Merge branch 'claude/size-cd-am' into claude/hexagonal-integ

# Conflicts:
#	limits-baseline.json
This commit is contained in:
Pavlo Ratushnyi
2026-11-06 14:45:48 +01:00
26 changed files with 3577 additions and 2617 deletions
+2
View File
@@ -105,3 +105,5 @@ mod impl_api_3;
mod impl_api_4;
mod impl_api_5;
mod impl_api_6;
mod mmq_group_symbols;
use mmq_group_symbols::MMQ_ORIGINAL_GROUP_SYMBOLS;
@@ -32,300 +32,11 @@ impl Api {
width: u32,
fixup: bool,
) -> Result<FunctionHandle> {
let name = match (kind, width, fixup) {
(0, 0, false) => c"leleka_original_mmq_swiglu",
(1, 0, false) => c"leleka_original_mmq_gather",
(2, 0, false) => c"leleka_original_mmq_gu_finite",
(18, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(18, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type18ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(18, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(22, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(22, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type22ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(22, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(21, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(21, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type21ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(21, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(23, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(23, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type23ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(23, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(20, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(20, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type20ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(20, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(42, 8, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 16, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 24, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 32, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 40, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 48, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 64, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 80, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 96, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42, 112, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 112, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
(42, 128, false) => {
c"_Z9mul_mat_qIL9ggml_type42ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_"
}
(42, 128, true) => {
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_"
}
_ => return Err(Error::InvalidProjectionShape),
};
let name = MMQ_ORIGINAL_GROUP_SYMBOLS
.iter()
.find(|(k, w, f, _)| (*k, *w, *f) == (kind, width, fixup))
.map(|(_, _, _, name)| *name)
.ok_or(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()) })?;
@@ -0,0 +1,142 @@
//! Mangled symbols of the Original MMQ group module (moved out of `Api::mmq_original_group_function`, STRA-338).
use std::ffi::CStr;
/// `(kind, width, fixup, symbol)`; the first entry matching `(kind, width, fixup)` is the kernel.
pub(super) const MMQ_ORIGINAL_GROUP_SYMBOLS: &[(u32, u32, bool, &CStr)] = &[
(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_"),
];
@@ -12,6 +12,62 @@ impl<'ctx> GrMicrobatchRead<'ctx> {
return Err(Error::InvalidQwenShape);
}
self.validate(&weights)?;
let (mut arguments, mut scans) = self.micro_arguments(weights, epsilon)?;
let zero = vec![0u8; 32 * self.tokens];
let mut readback = vec![0u8; 32 * self.tokens];
let guard = self.context.enter()?;
let kernels = match self.micro_kernels() {
Ok(kernels) => kernels,
Err(error) => {
let pop = guard.finish();
if pop.is_err() {
self.failed = true;
self.context.poison();
self.context.retain_driver();
}
return combine(Err(error), pop);
}
};
let status = self.buffer(10)?.handle.ok_or(Error::ContextPoisoned)?;
let finite = self.finite.ok_or(Error::ContextPoisoned)?;
let commands = self.context.driver.api.copy_from(status, &zero);
let initialized = commands.is_ok();
let (commands, completed_scans) = self.micro_launch(&kernels, finite, (&mut arguments, &mut scans), commands);
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();
let pop = guard.finish();
if commands.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((arguments, scans, zero, readback));
} else {
// A later enqueue failure cannot replace an earlier completed
// numeric refusal. Only actually enqueued scans, successful
// status readback and confirmed sync/pop authorize this ordering.
if status_read {
self.micro_check_flags(&readback, completed_scans)?;
}
combine(combine(commands, sync), pop)?;
let mixed = decode(self.buffer(6)?)?;
let inject = decode(self.buffer(7)?)?;
self.phase = 1;
return Ok(GrMicroValues { mixed, inject });
}
combine(combine(commands, sync), pop).map(|()| unreachable!("uncertain completion is an error"))
}
/// Per-row kernel arguments and the seven finite scans of every row.
#[allow(clippy::type_complexity)]
fn micro_arguments(
&self,
weights: [&DeviceBuffer<'_>; 4],
epsilon: f32,
) -> Result<(Vec<[Arguments; 6]>, Vec<ffi::MmqResidentArguments>)> {
let mut arguments = Vec::new();
arguments.try_reserve_exact(self.tokens).map_err(|_| Error::HostAllocation)?;
let mut scans = Vec::new();
@@ -29,37 +85,32 @@ impl<'ctx> GrMicrobatchRead<'ctx> {
));
}
}
let zero = vec![0u8; 32 * self.tokens];
let mut readback = vec![0u8; 32 * self.tokens];
let guard = self.context.enter()?;
let kernels = (|| {
let mut result = Vec::new();
result.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?;
for operation in OPS {
result.push(registered(
self.context,
&self.context.qwen_kernels,
qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?,
)?);
}
Ok(result)
})();
let kernels = match kernels {
Ok(kernels) => kernels,
Err(error) => {
let pop = guard.finish();
if pop.is_err() {
self.failed = true;
self.context.poison();
self.context.retain_driver();
}
return combine(Err(error), pop);
}
};
let status = self.buffer(10)?.handle.ok_or(Error::ContextPoisoned)?;
let finite = self.finite.ok_or(Error::ContextPoisoned)?;
let mut commands = self.context.driver.api.copy_from(status, &zero);
let initialized = commands.is_ok();
Ok((arguments, scans))
}
/// The six registered GR kernels, in `OPS` order.
fn micro_kernels(&self) -> Result<Vec<FixedKernel>> {
let mut result = Vec::new();
result.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?;
for operation in OPS {
result.push(registered(
self.context,
&self.context.qwen_kernels,
qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?,
)?);
}
Ok(result)
}
/// Enqueues every row's six kernels, each followed by its finite scan, stopping at the first failure; returns
/// the enqueue status and the number of scans actually enqueued.
fn micro_launch(
&self,
kernels: &[FixedKernel],
finite: ffi::FunctionHandle,
(arguments, scans): (&mut [[Arguments; 6]], &mut [ffi::MmqResidentArguments]),
mut commands: Result<()>,
) -> (Result<()>, usize) {
let mut completed_scans = 0usize;
for (row, row_args) in arguments.iter_mut().enumerate() {
for stage in 0..6 {
@@ -91,47 +142,28 @@ impl<'ctx> GrMicrobatchRead<'ctx> {
break;
}
}
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();
let pop = guard.finish();
if commands.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((arguments, scans, zero, readback));
} else {
// A later enqueue failure cannot replace an earlier completed
// numeric refusal. Only actually enqueued scans, successful
// status readback and confirmed sync/pop authorize this ordering.
if status_read {
let mut scan_index = 0usize;
for row in readback.chunks_exact(32) {
for (stage, bytes) in row.chunks_exact(4).take(7).enumerate() {
if scan_index >= completed_scans {
break;
}
scan_index += 1;
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"));
}
if flag != 0 {
return Err(Error::NonFiniteMmqOutput(STAGES[stage]));
}
}
(commands, completed_scans)
}
/// Reports the first non-zero finite status among the scans that were actually enqueued.
fn micro_check_flags(&mut self, readback: &[u8], completed_scans: usize) -> Result<()> {
let mut scan_index = 0usize;
for row in readback.chunks_exact(32) {
for (stage, bytes) in row.chunks_exact(4).take(7).enumerate() {
if scan_index >= completed_scans {
break;
}
scan_index += 1;
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"));
}
if flag != 0 {
return Err(Error::NonFiniteMmqOutput(STAGES[stage]));
}
}
combine(combine(commands, sync), pop)?;
let mixed = decode(self.buffer(6)?)?;
let inject = decode(self.buffer(7)?)?;
self.phase = 1;
return Ok(GrMicroValues { mixed, inject });
}
combine(combine(commands, sync), pop).map(|()| unreachable!("uncertain completion is an error"))
Ok(())
}
}
@@ -86,6 +86,31 @@ impl<'ctx> GrNativeBatch<'ctx> {
workspace.reject_alias(self.handle(i)?, buffer.bytes)?;
}
let blas = workspace.blas()?;
let w = self.native_weights(weights, workspace)?;
let flags = self.handle(14)?;
let mut args = Vec::with_capacity(10);
self.push_norm_args(&mut args, w[0], flags, epsilon)?;
self.push_mix_args(&mut args, w[0], flags)?;
let scalars = self.scalars.as_ref().ok_or(Error::ContextPoisoned)?;
let zero = vec![0u8; 32 * self.tokens];
let readback = vec![0u8; 32 * self.tokens];
let context = self.context;
let guard = context.enter()?;
let mut eligible = [false; 8];
let commands = self.native_commands(blas, (w, flags, scalars), (&zero, &mut args, &mut eligible));
self.finish(blas, commands, eligible, zero, args, readback, guard)?;
let mixed = decode(self.buffer(8)?)?;
let inject = decode(self.buffer(12)?)?;
self.phase = 1;
Ok(super::super::super::gr_batch_read::GrMicroValues { mixed, inject })
}
/// The four weight handles, checked for size, extent and overlap with the workspace.
fn native_weights(
&self,
weights: [&DeviceBuffer<'_>; 4],
workspace: &NativeBatchWorkspace<'ctx>,
) -> Result<[ffi::BufferHandle; 4]> {
let mut w = [self.handle(0)?; 4];
for (i, size) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() {
if weights[i].len() != size {
@@ -95,98 +120,168 @@ impl<'ctx> GrNativeBatch<'ctx> {
w[i].validate_projection_extent(size, if i == 0 { 4 } else { 2 })?;
workspace.reject_alias(w[i], size)?;
}
Ok(w)
}
/// Arguments of the norm, its finite scan, the low-precision conversion and the products (slots 0..=4).
fn push_norm_args(
&self,
args: &mut Vec<KernelArguments>,
w0: ffi::BufferHandle,
flags: ffi::BufferHandle,
epsilon: f32,
) -> Result<()> {
let t = self.tokens as i64;
let flags = self.handle(14)?;
let mut args = vec![
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(w[0]),
A::F32(epsilon),
A::Address(self.handle(1)?),
A::Address(self.handle(2)?),
self.low(3)?,
]),
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w[0]),
A::Address(flags),
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.scan(7, 10240, 3)?,
self.scan(12, 4, 6)?,
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w[0]),
A::Address(self.handle(7)?),
A::Address(self.handle(8)?),
A::Address(self.handle(9)?),
A::I64(t),
A::Address(self.handle(11)?),
self.low(10)?,
]),
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w[0]),
A::Address(self.handle(7)?),
A::Address(flags),
A::I64(t),
]),
self.scan(8, 2560, 5)?,
];
let scalars = self.scalars.as_ref().ok_or(Error::ContextPoisoned)?;
let alpha = &scalars[0];
let beta0 = &scalars[1];
let beta1 = &scalars[2];
let zero = vec![0u8; 32 * self.tokens];
let readback = vec![0u8; 32 * self.tokens];
let context = self.context;
let guard = context.enter()?;
let mut eligible = [false; 8];
let commands = (|| {
self.context.driver.api.copy_from(flags, &zero)?;
// The private vendor stream is NON_BLOCKING: drain all actual
// legacy uploads/reset before any stream consumer is enqueued.
self.context.driver.api.synchronize()?;
// Original gr_norm_rs block topology T*HC blocks, 256 threads.
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(
0,
(self.tokens * 4) as u32,
256,
blas.stream(),
&mut args[0],
)?;
self.launch(blas, 5, self.tokens * 10240, &mut args[1])?;
eligible[0] = true;
self.gemm(blas, 2, 3, w[1], 4, 320, 10240, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 320, &mut args[2])?;
eligible[1] = true;
self.launch(blas, 1, self.tokens * 320, &mut args[3])?;
self.launch(blas, 6, self.tokens * 320, &mut args[4])?;
eligible[2] = true;
self.gemm(blas, 5, 6, w[2], 7, 10240, 320, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 10240, &mut args[5])?;
eligible[3] = true;
// Literal Original executes inject GEMM BEFORE gr_mix_r.
self.gemm(blas, 2, 3, w[3], 12, 4, 10240, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 4, &mut args[6])?;
eligible[6] = true;
self.launch(blas, 2, self.tokens * 2560, &mut args[7])?;
self.launch(blas, 7, self.tokens * 10240, &mut args[8])?;
eligible[4] = true;
self.launch(blas, 4, self.tokens * 2560, &mut args[9])?;
eligible[5] = true;
Ok(())
})();
self.finish(blas, commands, eligible, zero, args, readback, guard)?;
let mixed = decode(self.buffer(8)?)?;
let inject = decode(self.buffer(12)?)?;
self.phase = 1;
Ok(super::super::super::gr_batch_read::GrMicroValues { mixed, inject })
args.push(Self::args(vec![
A::Address(self.handle(0)?),
A::Address(w0),
A::F32(epsilon),
A::Address(self.handle(1)?),
A::Address(self.handle(2)?),
self.low(3)?,
]));
args.push(Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w0),
A::Address(flags),
A::I64(t),
]));
args.push(self.scan(4, 320, 1)?);
self.push_product_args(args, flags)
}
/// Arguments of the products conversion and its finite flag kernel.
fn push_product_args(&self, args: &mut Vec<KernelArguments>, flags: ffi::BufferHandle) -> Result<()> {
let t = self.tokens as i64;
args.push(Self::args(vec![
A::Address(self.handle(4)?),
A::Address(self.handle(5)?),
self.low(6)?,
A::I64(t * 320),
]));
args.push(Self::args(vec![A::Address(self.handle(4)?), A::Address(flags), A::I64(t)]));
Ok(())
}
/// Arguments of the activation scans, the mix and the inject kernels (slots 5..=9).
fn push_mix_args(
&self,
args: &mut Vec<KernelArguments>,
w0: ffi::BufferHandle,
flags: ffi::BufferHandle,
) -> Result<()> {
let t = self.tokens as i64;
args.push(self.scan(7, 10240, 3)?);
args.push(self.scan(12, 4, 6)?);
self.push_mix_kernel_args(args, w0, flags)
}
/// Arguments of the mix kernel; the inject arguments follow.
fn push_mix_kernel_args(
&self,
args: &mut Vec<KernelArguments>,
w0: ffi::BufferHandle,
flags: ffi::BufferHandle,
) -> Result<()> {
let t = self.tokens as i64;
args.push(Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w0),
A::Address(self.handle(7)?),
A::Address(self.handle(8)?),
A::Address(self.handle(9)?),
A::I64(t),
A::Address(self.handle(11)?),
self.low(10)?,
]));
self.push_inject_args(args, w0, flags)
}
/// Arguments of the inject kernel and the scan of the mixed state.
fn push_inject_args(
&self,
args: &mut Vec<KernelArguments>,
w0: ffi::BufferHandle,
flags: ffi::BufferHandle,
) -> Result<()> {
let t = self.tokens as i64;
args.push(Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w0),
A::Address(self.handle(7)?),
A::Address(flags),
A::I64(t),
]));
args.push(self.scan(8, 2560, 5)?);
Ok(())
}
/// Resets the flags, then enqueues the GR kernels and GEMMs in the literal Original order; `eligible[i]`
/// records which stages were enqueued.
fn native_commands(
&self,
blas: &Blas,
(w, flags, scalars): ([ffi::BufferHandle; 4], ffi::BufferHandle, &[f32; 3]),
(zero, args, eligible): (&[u8], &mut [KernelArguments], &mut [bool; 8]),
) -> Result<()> {
self.native_commands_head(blas, (w, flags, scalars), (zero, &mut *args, &mut *eligible))?;
self.native_commands_tail(blas, (w, scalars), (args, eligible))
}
/// The flag reset, the norm and the first GEMM with its guards (stages 0..=2).
fn native_commands_head(
&self,
blas: &Blas,
(w, flags, scalars): ([ffi::BufferHandle; 4], ffi::BufferHandle, &[f32; 3]),
(zero, args, eligible): (&[u8], &mut [KernelArguments], &mut [bool; 8]),
) -> Result<()> {
let (alpha, beta0, beta1) = (&scalars[0], &scalars[1], &scalars[2]);
self.context.driver.api.copy_from(flags, zero)?;
// The private vendor stream is NON_BLOCKING: drain all actual
// legacy uploads/reset before any stream consumer is enqueued.
self.context.driver.api.synchronize()?;
// Original gr_norm_rs block topology T*HC blocks, 256 threads.
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(
0,
(self.tokens * 4) as u32,
256,
blas.stream(),
&mut args[0],
)?;
self.launch(blas, 5, self.tokens * 10240, &mut args[1])?;
eligible[0] = true;
self.gemm(blas, 2, 3, w[1], 4, 320, 10240, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 320, &mut args[2])?;
eligible[1] = true;
self.launch(blas, 1, self.tokens * 320, &mut args[3])?;
self.launch(blas, 6, self.tokens * 320, &mut args[4])?;
eligible[2] = true;
Ok(())
}
/// The remaining GEMMs and kernels (stages 3..=6) in the literal Original order.
fn native_commands_tail(
&self,
blas: &Blas,
(w, scalars): ([ffi::BufferHandle; 4], &[f32; 3]),
(args, eligible): (&mut [KernelArguments], &mut [bool; 8]),
) -> Result<()> {
let (alpha, beta0, beta1) = (&scalars[0], &scalars[1], &scalars[2]);
self.gemm(blas, 5, 6, w[2], 7, 10240, 320, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 10240, &mut args[5])?;
eligible[3] = true;
// Literal Original executes inject GEMM BEFORE gr_mix_r.
self.gemm(blas, 2, 3, w[3], 12, 4, 10240, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 4, &mut args[6])?;
eligible[6] = true;
self.launch(blas, 2, self.tokens * 2560, &mut args[7])?;
self.launch(blas, 7, self.tokens * 10240, &mut args[8])?;
eligible[4] = true;
self.launch(blas, 4, self.tokens * 2560, &mut args[9])?;
eligible[5] = true;
Ok(())
}
}
+166 -117
View File
@@ -7,6 +7,36 @@ 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]> {
let layouts = self.triplet_admit(formats, &raw)?;
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);
}
let mut buffers: [Option<DeviceBuffer<'_>>; 3] = std::array::from_fn(|_| None);
for (slot, layout) in layouts.iter().enumerate() {
match self.allocate(layout.weight) {
Ok(buffer) => buffers[slot] = Some(buffer),
Err(primary) => return combine(Err(primary), release_triplet(self, buffers)),
}
}
let operation = self.triplet_upload(&buffers, &mut staging);
if let Err(primary) = operation {
// Poisoned release retains uncertain native allocations/charges;
// completed failures attempt every owner, never publish a prefix.
return combine(Err(primary), release_triplet(self, buffers));
}
let [Some(gate), Some(up), Some(down)] = buffers else {
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) },
])
}
/// Format, source and budget admission of three host weight images; returns their layouts.
fn triplet_admit(&self, formats: [MmqFormat; 3], raw: &[&[u8]; 3]) -> Result<[Layout; 3]> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
@@ -33,55 +63,34 @@ impl Context<'_> {
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)?];
for (padded, source) in staging.iter_mut().zip(raw) {
padded[..source.len()].copy_from_slice(source);
}
let mut buffers: [Option<DeviceBuffer<'_>>; 3] = std::array::from_fn(|_| None);
for (slot, layout) in layouts.iter().enumerate() {
match self.allocate(layout.weight) {
Ok(buffer) => buffers[slot] = Some(buffer),
Err(primary) => return combine(Err(primary), release_triplet(self, buffers)),
Ok(layouts)
}
/// Copies the three padded staging images into their device buffers under one confirmed fence.
fn triplet_upload(&self, buffers: &[Option<DeviceBuffer<'_>>; 3], staging: &mut [Vec<u8>; 3]) -> Result<()> {
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)?,
];
let guard = self.enter()?;
let mut copy = Ok(());
for (handle, padded) in handles.into_iter().zip(staging.iter()) {
copy = self.driver.api.copy_from(handle, padded);
if copy.is_err() {
break;
}
}
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)?,
];
let guard = self.enter()?;
let mut copy = Ok(());
for (handle, padded) in handles.into_iter().zip(&staging) {
copy = self.driver.api.copy_from(handle, padded);
if copy.is_err() {
break;
}
}
// Drain every attempted copy, including reported command errors.
let sync = self.driver.api.synchronize();
let restored = guard.finish();
if sync.is_err() || restored.is_err() {
self.poisoned.set(true);
// Even successful synchronous-looking H2D calls are not a
// lifetime certificate after failed completion/restoration.
std::mem::forget(std::mem::take(&mut staging));
}
combine(combine(copy, sync), restored)
})();
if let Err(primary) = operation {
// Poisoned release retains uncertain native allocations/charges;
// completed failures attempt every owner, never publish a prefix.
return combine(Err(primary), release_triplet(self, buffers));
// Drain every attempted copy, including reported command errors.
let sync = self.driver.api.synchronize();
let restored = guard.finish();
if sync.is_err() || restored.is_err() {
self.poisoned.set(true);
// Even successful synchronous-looking H2D calls are not a
// lifetime certificate after failed completion/restoration.
std::mem::forget(std::mem::take(staging));
}
let [Some(gate), Some(up), Some(down)] = buffers else {
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) },
])
combine(combine(copy, sync), restored)
}
/// Byte transport from three actual immutable raw GPU owners into three
@@ -92,6 +101,41 @@ impl Context<'_> {
formats: [MmqFormat; 3],
raw: [&DeviceBuffer<'_>; 3],
) -> Result<[MmqWeights<'_>; 3]> {
let (layouts, sources) = self.device_triplet_admit(formats, &raw)?;
// Only the literal over-read tails have host staging; no raw GPU weight
// is read back or presented as borrowed padded/ready weights.
let mut tails = [
bytes(layouts[0].weight - layouts[0].raw_weight)?,
bytes(layouts[1].weight - layouts[1].raw_weight)?,
bytes(layouts[2].weight - layouts[2].raw_weight)?,
];
let mut buffers: [Option<DeviceBuffer<'_>>; 3] = std::array::from_fn(|_| None);
for i in 0..3 {
match self.allocate(layouts[i].weight) {
Ok(buffer) => buffers[i] = Some(buffer),
Err(primary) => return combine(Err(primary), release_triplet(self, buffers)),
}
}
let operation = self.device_triplet_operation(&buffers, &mut tails, (&layouts, &raw), sources);
if let Err(primary) = operation {
return combine(Err(primary), release_triplet(self, buffers));
}
let [Some(gate), Some(up), Some(down)] = buffers else {
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) },
])
}
/// Format, context, extent, alias and budget admission of three raw GPU owners; returns layouts and handles.
fn device_triplet_admit(
&self,
formats: [MmqFormat; 3],
raw: &[&DeviceBuffer<'_>; 3],
) -> Result<([Layout; 3], [ffi::BufferHandle; 3])> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
@@ -114,6 +158,20 @@ impl Context<'_> {
raw[1].handle.ok_or(Error::ContextPoisoned)?,
raw[2].handle.ok_or(Error::ContextPoisoned)?,
];
let charge = self.device_triplet_charge(formats, raw, (&layouts, &sources))?;
if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) {
return Err(Error::BudgetExceeded);
}
Ok((layouts, sources))
}
/// Checks each raw owner (context, size, extent, overlap with the earlier ones); returns the padded byte charge.
fn device_triplet_charge(
&self,
formats: [MmqFormat; 3],
raw: &[&DeviceBuffer<'_>; 3],
(layouts, sources): (&[Layout; 3], &[ffi::BufferHandle; 3]),
) -> Result<usize> {
let mut charge = 0usize;
for i in 0..3 {
if !std::ptr::eq(self, raw[i].context) {
@@ -131,87 +189,78 @@ impl Context<'_> {
}
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) {
return Err(Error::BudgetExceeded);
}
// Only the literal over-read tails have host staging; no raw GPU weight
// is read back or presented as borrowed padded/ready weights.
let mut tails = [
bytes(layouts[0].weight - layouts[0].raw_weight)?,
bytes(layouts[1].weight - layouts[1].raw_weight)?,
bytes(layouts[2].weight - layouts[2].raw_weight)?,
Ok(charge)
}
/// Validates the three padded targets against the sources and each other, then copies raw weights and tails.
fn device_triplet_operation(
&self,
buffers: &[Option<DeviceBuffer<'_>>; 3],
tails: &mut [Vec<u8>; 3],
(layouts, raw): (&[Layout; 3], &[&DeviceBuffer<'_>; 3]),
sources: [ffi::BufferHandle; 3],
) -> Result<()> {
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)?,
];
let mut buffers: [Option<DeviceBuffer<'_>>; 3] = std::array::from_fn(|_| None);
for i in 0..3 {
match self.allocate(layouts[i].weight) {
Ok(buffer) => buffers[i] = Some(buffer),
Err(primary) => return combine(Err(primary), release_triplet(self, buffers)),
let all = [
(sources[0], raw[0].bytes),
(sources[1], raw[1].bytes),
(sources[2], raw[2].bytes),
(targets[0], layouts[0].weight),
(targets[1], layouts[1].weight),
(targets[2], layouts[2].weight),
];
for i in 3..6 {
all[i].0.validate_projection_extent(all[i].1, 4)?;
for j in 0..i {
if all[i].0.overlaps(all[i].1, all[j].0, all[j].1) {
return Err(Error::OutputAliasesInput);
}
}
}
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)?,
];
let all = [
(sources[0], raw[0].bytes),
(sources[1], raw[1].bytes),
(sources[2], raw[2].bytes),
(targets[0], layouts[0].weight),
(targets[1], layouts[1].weight),
(targets[2], layouts[2].weight),
];
for i in 3..6 {
all[i].0.validate_projection_extent(all[i].1, 4)?;
for j in 0..i {
if all[i].0.overlaps(all[i].1, all[j].0, all[j].1) {
return Err(Error::OutputAliasesInput);
}
}
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())?);
}
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())?);
}
}
let guard = self.enter()?;
let mut copy = Ok(());
for i in 0..3 {
if let Some(tail) = tail_handles[i] {
copy = self.driver.api.copy_from(tail, &tails[i]);
if copy.is_err() {
break;
}
}
copy = self.driver.api.copy_mmq_weight(targets[i], sources[i], raw[i].bytes);
}
self.device_triplet_copy((targets, sources), (&tail_handles, tails), [raw[0].bytes, raw[1].bytes, raw[2].bytes])
}
/// One guarded sequence of tail uploads and device-to-device weight copies, drained by one synchronize.
fn device_triplet_copy(
&self,
(targets, sources): ([ffi::BufferHandle; 3], [ffi::BufferHandle; 3]),
(tail_handles, tails): (&[Option<ffi::BufferHandle>; 3], &mut [Vec<u8>; 3]),
raw_bytes: [usize; 3],
) -> Result<()> {
let guard = self.enter()?;
let mut copy = Ok(());
for i in 0..3 {
if let Some(tail) = tail_handles[i] {
copy = self.driver.api.copy_from(tail, &tails[i]);
if copy.is_err() {
break;
}
}
let sync = self.driver.api.synchronize();
let pop = guard.finish();
if copy.is_err() || sync.is_err() || pop.is_err() {
self.poisoned.set(true);
copy = self.driver.api.copy_mmq_weight(targets[i], sources[i], raw_bytes[i]);
if copy.is_err() {
break;
}
if sync.is_err() || pop.is_err() {
std::mem::forget(std::mem::take(&mut tails));
}
combine(combine(copy, sync), pop)
})();
if let Err(primary) = operation {
return combine(Err(primary), release_triplet(self, buffers));
}
let [Some(gate), Some(up), Some(down)] = buffers else {
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) },
])
let sync = self.driver.api.synchronize();
let pop = guard.finish();
if copy.is_err() || sync.is_err() || pop.is_err() {
self.poisoned.set(true);
}
if sync.is_err() || pop.is_err() {
std::mem::forget(std::mem::take(tails));
}
combine(combine(copy, sync), pop)
}
/// Closed owned cold Gate/Up upload; no tail padding, no module loading.
+150 -71
View File
@@ -168,6 +168,28 @@ impl<'ctx> MmqExperiment<'ctx> {
) -> Result<MmqObservation> {
self.check()?;
let l = weights.format.adaptive_layout(tokens, profile)?;
let hs = self.observed_admit(weights, input, output, &l)?;
self.observed_host_input(input, &l)?;
let (tiles, grid) = self.observed_grid(&l, profile);
let fixup = tiles % grid != 0;
let mut temporary = None;
let mut packed = self.context.allocate(l.packed)?;
let result = self.observed_run(weights, output, l, (grid, fixup), hs, (&mut packed, &mut temporary));
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));
combine(result, combine(cleanup, self.release_buffer(packed)))
}
/// Context, size and alias admission of the three buffers; returns their handles `[weights, input, output]`.
fn observed_admit(
&self,
weights: &MmqWeights<'_>,
input: &DeviceBuffer<'_>,
output: &DeviceBuffer<'_>,
l: &Layout,
) -> Result<[ffi::BufferHandle; 3]> {
let w = weights.buffer.as_ref().ok_or(Error::ContextPoisoned)?;
if !std::ptr::eq(self.context, weights.context)
|| !std::ptr::eq(self.context, w.context)
@@ -191,6 +213,10 @@ impl<'ctx> MmqExperiment<'ctx> {
{
return Err(Error::OutputAliasesInput);
}
Ok([wh, ih, oh])
}
fn observed_host_input(&self, input: &DeviceBuffer<'_>, l: &Layout) -> Result<()> {
let mut host = bytes(l.input)?;
if let Err(e) = input.copy_to(&mut host) {
self.context.poisoned.set(true);
@@ -199,6 +225,11 @@ impl<'ctx> MmqExperiment<'ctx> {
if !finite_f32(&host) {
return Err(Error::InvalidQ8Activation);
}
Ok(())
}
/// `(tiles, grid)`: complete tiles, or the stream-k grid when the tile count fills the SMs poorly.
fn observed_grid(&self, l: &Layout, profile: MmqProfile) -> (u32, u32) {
let tiles = l.rows / 128;
let efficiency = 100 * tiles / (self.sms * tiles.div_ceil(self.sms));
let grid = match profile {
@@ -210,83 +241,131 @@ impl<'ctx> MmqExperiment<'ctx> {
}
MmqProfile::OriginalStreamK | MmqProfile::OriginalAdaptive => self.sms,
};
let fixup = tiles % grid != 0;
let mut temporary = None;
let mut packed = self.context.allocate(l.packed)?;
let result = (|| {
let zeros = bytes(l.packed)?;
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)) {
return Err(Error::OutputAliasesInput);
}
let mut quant = ffi::MmqQuantArguments::new(ih, ph, l);
(tiles, grid)
}
fn observed_run(
&self,
weights: &MmqWeights<'_>,
output: &DeviceBuffer<'_>,
l: Layout,
(grid, fixup): (u32, bool),
hs: [ffi::BufferHandle; 3],
(packed, temporary): (&mut DeviceBuffer<'ctx>, &mut Option<DeviceBuffer<'ctx>>),
) -> Result<MmqObservation> {
let [wh, ih, oh] = hs;
let ph = self.observed_prepare_packed(l, hs, packed)?;
let q = self.observed_quantize(l, (ih, ph), packed)?;
if fixup {
self.observed_alloc_fixup(l, [wh, ih, oh, ph], grid, temporary)?;
}
let th = temporary.as_ref().and_then(|b| b.handle);
self.observed_project(weights, l, grid, ([wh, ph, oh], th))?;
let mut out = bytes(l.output)?;
output.copy_to(&mut out)?;
if !finite_f32(&out) {
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)));
Ok((values.into_boxed_slice(), q.into_boxed_slice()))
}
/// Zeroes the packed activation buffer and checks it overlaps none of the three buffers.
fn observed_prepare_packed(
&self,
l: Layout,
[wh, ih, oh]: [ffi::BufferHandle; 3],
packed: &mut DeviceBuffer<'ctx>,
) -> Result<ffi::BufferHandle> {
let zeros = bytes(l.packed)?;
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)) {
return Err(Error::OutputAliasesInput);
}
Ok(ph)
}
/// Launches the activation quantizer and returns the packed bytes after checking them.
fn observed_quantize(
&self,
l: Layout,
(ih, ph): (ffi::BufferHandle, ffi::BufferHandle),
packed: &DeviceBuffer<'ctx>,
) -> Result<Vec<u8>> {
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);
if launch.is_err() {
self.context.poisoned.set(true)
}
self.context.complete_launch(launch, quant, guard)?;
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]))
{
return Err(Error::InvalidQ8Activation);
}
Ok(q)
}
/// Allocates and zeroes the stream-k fixup scratch; it must overlap none of the four buffers.
fn observed_alloc_fixup(
&self,
l: Layout,
hs: [ffi::BufferHandle; 4],
grid: u32,
temporary: &mut Option<DeviceBuffer<'ctx>>,
) -> Result<()> {
let [wh, ih, oh, ph] = hs;
let extent =
(grid as usize).checked_mul(l.tile.width() as usize * 128 * 4).ok_or(Error::InvalidProjectionShape)?;
let b = self.context.allocate(extent)?;
*temporary = Some(b);
let b = temporary.as_mut().ok_or(Error::ContextPoisoned)?;
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))
{
return Err(Error::OutputAliasesInput);
}
Ok(())
}
/// The projection kernel, then the stream-k fixup kernel when a fixup scratch exists.
fn observed_project(
&self,
weights: &MmqWeights<'_>,
l: Layout,
grid: u32,
([wh, ph, oh], th): ([ffi::BufferHandle; 3], Option<ffi::BufferHandle>),
) -> Result<()> {
let mut args = ffi::MmqArguments::new(wh, ph, oh, th, l);
let guard = self.context.enter()?;
let f = self.function(weights.format, l.tile, false)?;
let launch = self.context.driver.api.project_mmq(f, l, grid, &mut args);
if launch.is_err() {
self.context.poisoned.set(true)
}
self.context.complete_launch(launch, args, guard)?;
if let Some(th) = th {
let mut args = ffi::MmqFixupArguments::new(oh, th, l);
let guard = self.context.enter()?;
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)
}
self.context.complete_launch(launch, quant, guard)?;
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]))
{
return Err(Error::InvalidQ8Activation);
}
if fixup {
let extent = (grid as usize)
.checked_mul(l.tile.width() as usize * 128 * 4)
.ok_or(Error::InvalidProjectionShape)?;
let b = self.context.allocate(extent)?;
temporary = Some(b);
let b = temporary.as_mut().ok_or(Error::ContextPoisoned)?;
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))
{
return Err(Error::OutputAliasesInput);
}
}
let th = temporary.as_ref().and_then(|b| b.handle);
let mut args = ffi::MmqArguments::new(wh, ph, oh, th, l);
let guard = self.context.enter()?;
let f = self.function(weights.format, l.tile, false)?;
let launch = self.context.driver.api.project_mmq(f, l, grid, &mut args);
let f = self.function(weights.format, l.tile, true)?;
let launch = self.context.driver.api.fixup_mmq(f, grid, &mut args);
if launch.is_err() {
self.context.poisoned.set(true)
}
self.context.complete_launch(launch, args, guard)?;
if let Some(th) = th {
let mut args = ffi::MmqFixupArguments::new(oh, th, l);
let guard = self.context.enter()?;
let f = self.function(weights.format, l.tile, true)?;
let launch = self.context.driver.api.fixup_mmq(f, grid, &mut args);
if launch.is_err() {
self.context.poisoned.set(true)
}
self.context.complete_launch(launch, args, guard)?;
}
let mut out = bytes(l.output)?;
output.copy_to(&mut out)?;
if !finite_f32(&out) {
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)));
Ok((values.into_boxed_slice(), q.into_boxed_slice()))
})();
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));
combine(result, combine(cleanup, self.release_buffer(packed)))
Ok(())
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
+118 -258
View File
@@ -3,6 +3,122 @@
#[allow(unused_imports)]
use super::*;
/// Original `mul_mat_q` entry symbols by `MmqFormat::index()` row and `Tile::index()` column.
const MMQ_ENTRIES: [[&CStr; 7]; 6] = [
[
c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
],
[
c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
],
[
c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
],
[
c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
],
[
c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
],
[
c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
],
];
/// Original stream-k fixup entry symbols, same indexing as `MMQ_ENTRIES`.
const MMQ_FIXUP_ENTRIES: [[&CStr; 7]; 6] = [
[
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
],
[
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
],
[
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
],
[
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
],
[
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
],
[
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
],
];
impl Tile {
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 {
@@ -50,266 +166,10 @@ 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),
}
MMQ_ENTRIES[self.index()][tile.index()]
}
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),
}
MMQ_FIXUP_ENTRIES[self.index()][tile.index()]
}
pub(crate) fn layout(self, tokens: u32) -> Result<Layout> {
if !(1..=64).contains(&tokens) {
@@ -55,17 +55,7 @@ impl<'ctx> OriginalGroupBank<'ctx> {
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)? };
if context
.allocated_bytes()
.checked_add(charge)
.and_then(|n| n.checked_add(128 * 1024 * 1024))
.is_none_or(|n| n > context.budget)
{
return Err(Error::BudgetExceeded);
}
if context.memory_info()?.0 < charge.checked_add(128 * 1024 * 1024).ok_or(Error::BudgetExceeded)? {
return Err(Error::BudgetExceeded);
}
Self::admit_charge(context, charge)?;
let mut bank = Self {
context,
capacity,
@@ -79,91 +69,109 @@ impl<'ctx> OriginalGroupBank<'ctx> {
fixups: [[None; 11]; 7],
failed: false,
};
let result = (|| {
let guard = context.enter()?;
crate::arch_ptx::latch_stream_k_policy();
let operation = (|| {
let limit = context.driver.api.mmq_original_group_shared_limit()?;
for k in 0..3 {
bank.modules[k] = Some(context.driver.api.load_mmq_original_group(k as u32)?);
}
bank.swiglu = Some(context.driver.api.mmq_original_group_function(
bank.modules[0].ok_or(Error::ContextPoisoned)?,
0,
0,
false,
)?);
bank.gather = Some(context.driver.api.mmq_original_group_function(
bank.modules[0].ok_or(Error::ContextPoisoned)?,
1,
0,
false,
)?);
bank.gu_finite = Some(context.driver.api.mmq_original_group_function(
bank.modules[0].ok_or(Error::ContextPoisoned)?,
2,
0,
false,
)?);
for (i, format) in FORMATS.into_iter().enumerate() {
for (j, width) in WIDTHS.into_iter().enumerate() {
let shared = shared(format, width);
if shared > limit {
continue;
}
let kind = kind(format);
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,
width,
false,
)?;
context.driver.api.mmq_shared(f, shared)?;
bank.functions[i][j] = Some(f);
bank.fixups[i][j] = Some(context.driver.api.mmq_original_group_function(
bank.modules[2].ok_or(Error::ContextPoisoned)?,
kind,
width,
true,
)?);
}
if bank.functions[i].iter().all(Option::is_none) {
return Err(Error::UnsupportedProjection);
}
}
Ok(())
})();
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);
}
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)?;
if context.memory_info()?.0 < required
|| context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget)
{
return Err(Error::BudgetExceeded);
}
for (i, bytes) in sizes.into_iter().enumerate() {
if !arena_only || i == TMP {
bank.buffers[i] = Some(context.allocate(bytes)?);
}
}
Ok(())
})();
if let Err(e) = result {
if let Err(e) = bank.init(sizes, charge) {
return combine(Err(e), bank.close());
}
Ok(bank)
}
/// The charge plus a 128 MiB reserve must fit the context budget and the physical free memory.
fn admit_charge(context: &'ctx Context<'ctx>, charge: usize) -> Result<()> {
if context
.allocated_bytes()
.checked_add(charge)
.and_then(|n| n.checked_add(128 * 1024 * 1024))
.is_none_or(|n| n > context.budget)
{
return Err(Error::BudgetExceeded);
}
if context.memory_info()?.0 < charge.checked_add(128 * 1024 * 1024).ok_or(Error::BudgetExceeded)? {
return Err(Error::BudgetExceeded);
}
Ok(())
}
/// Loads the modules and functions under one context guard, then allocates the buffers.
fn init(&mut self, sizes: [usize; 12], charge: usize) -> Result<()> {
let context = self.context;
let guard = context.enter()?;
crate::arch_ptx::latch_stream_k_policy();
let operation = self.load_functions();
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);
}
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)?;
if context.memory_info()?.0 < required
|| context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget)
{
return Err(Error::BudgetExceeded);
}
for (i, bytes) in sizes.into_iter().enumerate() {
if !self.arena_only || i == TMP {
self.buffers[i] = Some(context.allocate(bytes)?);
}
}
Ok(())
}
/// Loads the three modules, the helper kernels and every format/width kernel that fits the shared capacity.
fn load_functions(&mut self) -> Result<()> {
let context = self.context;
let limit = context.driver.api.mmq_original_group_shared_limit()?;
for k in 0..3 {
self.modules[k] = Some(context.driver.api.load_mmq_original_group(k as u32)?);
}
let helpers = self.modules[0].ok_or(Error::ContextPoisoned)?;
self.swiglu = Some(context.driver.api.mmq_original_group_function(helpers, 0, 0, false)?);
self.gather = Some(context.driver.api.mmq_original_group_function(helpers, 1, 0, false)?);
self.gu_finite = Some(context.driver.api.mmq_original_group_function(helpers, 2, 0, false)?);
for (i, format) in FORMATS.into_iter().enumerate() {
for (j, width) in WIDTHS.into_iter().enumerate() {
self.load_format_function((i, j), (format, width), limit)?;
}
if self.functions[i].iter().all(Option::is_none) {
return Err(Error::UnsupportedProjection);
}
}
Ok(())
}
fn load_format_function(
&mut self,
(i, j): (usize, usize),
(format, width): (MmqFormat, u32),
limit: u32,
) -> Result<()> {
let context = self.context;
let shared = shared(format, width);
if shared > limit {
return Ok(());
}
let kind = kind(format);
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(
self.modules[1].ok_or(Error::ContextPoisoned)?,
kind,
width,
false,
)?;
context.driver.api.mmq_shared(f, shared)?;
self.functions[i][j] = Some(f);
self.fixups[i][j] = Some(context.driver.api.mmq_original_group_function(
self.modules[2].ok_or(Error::ContextPoisoned)?,
kind,
width,
true,
)?);
Ok(())
}
pub(super) fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> {
if self.failed || self.context.is_poisoned() {
return Err(Error::ContextPoisoned);
@@ -16,160 +16,11 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
formats: [MmqFormat; 3],
sources: &[[leleka_model_format::qwen4exp::ResidentExpertBankSpan; 3]],
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
if self.next != 0
|| self.staged != 0
|| self.completed
|| self.formats.is_some()
|| sources.len() != self.counts.len()
|| self.arena.is_none()
|| !read.context_matches(self.workspace.context)
|| read.rows() as u32 != self.total / 10
{
return Err(Error::InvalidProjectionShape);
}
// Require the SAME genuine producer's group spans. A different arena with
// identical shapes is not a substitute for this layer's affine Mixed source.
for index in 0..TMP {
let (a, n) = self.span(index)?;
let (b, m) = GroupArena::span(read, index)?;
if n != m || a.qwen_address() != b.qwen_address() {
return Err(Error::ContextMismatch);
}
}
self.copy_ring_preflight(read, sources.len())?;
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 operation = (|| {
// The actual carved ring size determines the literal STAGE-1 lookahead.
let stages = read.lease().copy_ring_slots()?;
let lookahead = stages - 1;
let mut staged = 0usize;
for j in 0..sources.len() {
while staged < sources.len() && staged <= j + lookahead {
ring.stage_one(staged, formats)?;
staged += 1;
}
let b = self.bank()?;
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let wh = self.handle(WG, self.staged * gu * 2, gu * 2, 16)?;
let dh = self.handle(WD, self.staged * down, down, 16)?;
ring.gather(j, formats, b.gather.ok_or(Error::ContextPoisoned)?, wh, dh)?;
self.formats = Some(formats);
self.staged += 1;
if self.staged < 16 && j + 1 < sources.len() {
continue;
}
let group = self.next / 16;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
for stage in 0..4 {
let flag = ring.flag(group, stage)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(0)?,
1,
ffi::MmqResidentArguments::zero(flag, 1),
))?;
}
for (index, bytes) in [(WG, gu * 2 * self.staged), (WD, down * self.staged)] {
let h = self.handle(index, bytes, 4096, 4)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(0)?,
1024,
ffi::MmqResidentArguments::zero(h, 1024),
))?;
}
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_flag = ring.flag(group, 0)?;
ring.enqueue(Command::Helper(
b.gu_finite.ok_or(Error::ContextPoisoned)?,
nr * 1280,
ffi::MmqResidentArguments::finite(gu_source, gu_flag, 0, nr * 1280, 0),
))?;
let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?;
ring.enqueue(Command::Swiglu(
b.swiglu.ok_or(Error::ContextPoisoned)?,
nr,
ffi::MmqOriginalSwigluArguments::new(gu_source, h, nr),
))?;
let h_flag = ring.flag(group, 1)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(1)?,
nr * 640,
ffi::MmqResidentArguments::finite(h, h_flag, 0, nr * 640, 0),
))?;
let ql = layout(MmqFormat::Iq4NlDown, 2560, nr, 64)?;
let q = self.handle(HQ, 0, ql.packed, 16)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(0)?,
(ql.packed / 4) as u32,
ffi::MmqResidentArguments::zero(q, (ql.packed / 4) as u32),
))?;
ring.enqueue(Command::Quantize(
self.workspace
.experiment
.as_ref()
.ok_or(Error::ContextPoisoned)?
.quantizer
.ok_or(Error::ContextPoisoned)?,
ql,
ffi::MmqQuantArguments::original_indexed(h, None, q, ql),
))?;
let q_flag = ring.flag(group, 2)?;
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),
))?;
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(
self.workspace.kernel(1)?,
nr * 2560,
ffi::MmqResidentArguments::finite(d, d_flag, 0, nr * 2560, 0),
))?;
// These are private enqueue cursors, NOT ready/finite publication. All
// group flags remain independently owned until the final genuine drain.
self.next += self.staged;
self.staged = 0;
self.formats = None;
}
let flags = ring.finish_statuses()?;
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
let gu = u32::from_le_bytes(words[0]);
let h = u32::from_le_bytes(words[1]);
let q = u32::from_le_bytes(words[2]);
let down = u32::from_le_bytes(words[3]);
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
}
Ok(())
})();
let operation = self.stream_through_ring(&mut ring, read, formats, sources.len());
let close = ring.close();
if operation.is_err() || close.is_err() {
// A failed layer cannot masquerade as a completed output or resume midway.
@@ -179,6 +30,232 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
}
combine(operation, close)
}
fn copy_ring_preflight(&self, read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, sources: usize) -> Result<()> {
if self.next != 0
|| self.staged != 0
|| self.completed
|| self.formats.is_some()
|| sources != self.counts.len()
|| self.arena.is_none()
|| !read.context_matches(self.workspace.context)
|| read.rows() as u32 != self.total / 10
{
return Err(Error::InvalidProjectionShape);
}
self.copy_ring_same_spans(read)
}
// Require the SAME genuine producer's group spans. A different arena with
// identical shapes is not a substitute for this layer's affine Mixed source.
fn copy_ring_same_spans(&self, read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>) -> Result<()> {
for index in 0..TMP {
let (a, n) = self.span(index)?;
let (b, m) = GroupArena::span(read, index)?;
if n != m || a.qwen_address() != b.qwen_address() {
return Err(Error::ContextMismatch);
}
}
Ok(())
}
/// Stages, gathers and enqueues every group of 16 experts, then drains and checks the group statuses.
fn stream_through_ring(
&mut self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
formats: [MmqFormat; 3],
sources: usize,
) -> Result<()> {
// The actual carved ring size determines the literal STAGE-1 lookahead.
let stages = read.lease().copy_ring_slots()?;
let lookahead = stages - 1;
let mut staged = 0usize;
for j in 0..sources {
while staged < sources && staged <= j + lookahead {
ring.stage_one(staged, formats)?;
staged += 1;
}
self.ring_gather(ring, j, formats)?;
if self.staged < 16 && j + 1 < sources {
continue;
}
self.ring_enqueue_group(ring, formats)?;
}
Self::check_ring_statuses(ring.finish_statuses()?)
}
fn ring_gather(&mut self, ring: &mut copy_ring::Ring<'_, 'ctx>, j: usize, formats: [MmqFormat; 3]) -> Result<()> {
let b = self.bank()?;
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let wh = self.handle(WG, self.staged * gu * 2, gu * 2, 16)?;
let dh = self.handle(WD, self.staged * down, down, 16)?;
ring.gather(j, formats, b.gather.ok_or(Error::ContextPoisoned)?, wh, dh)?;
self.formats = Some(formats);
self.staged += 1;
Ok(())
}
/// Enqueues the whole Gate/Up, SwiGLU and Down chain of the staged group with its finite guards.
fn ring_enqueue_group(&mut self, ring: &mut copy_ring::Ring<'_, 'ctx>, formats: [MmqFormat; 3]) -> Result<()> {
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let group = self.next / 16;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
self.ring_enqueue_zeroes(ring, group, (gu, down))?;
self.enqueue_ring_project(ring, formats[0], WG, XQ, GU, false, self.width(formats[0])?)?;
let h = self.ring_enqueue_swiglu(ring, group, nr)?;
self.ring_enqueue_down(ring, formats, (group, nr, h))?;
// These are private enqueue cursors, NOT ready/finite publication. All
// group flags remain independently owned until the final genuine drain.
self.next += self.staged;
self.staged = 0;
self.formats = None;
Ok(())
}
/// Clears the four group flags and the Gate/Up and Down weight scratch.
fn ring_enqueue_zeroes(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
group: usize,
(gu, down): (usize, usize),
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
for stage in 0..4 {
let flag = ring.flag(group, stage)?;
ring.enqueue(Command::Helper(self.workspace.kernel(0)?, 1, ffi::MmqResidentArguments::zero(flag, 1)))?;
}
for (index, bytes) in [(WG, gu * 2 * self.staged), (WD, down * self.staged)] {
let h = self.handle(index, bytes, 4096, 4)?;
ring.enqueue(Command::Helper(self.workspace.kernel(0)?, 1024, ffi::MmqResidentArguments::zero(h, 1024)))?;
}
Ok(())
}
/// Gate/Up finite guard, SwiGLU and its finite guard; returns the SwiGLU output handle.
fn ring_enqueue_swiglu(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
group: usize,
nr: u32,
) -> Result<ffi::BufferHandle> {
use crate::ffi::original_enqueue::Command;
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_flag = ring.flag(group, 0)?;
ring.enqueue(Command::Helper(
b.gu_finite.ok_or(Error::ContextPoisoned)?,
nr * 1280,
ffi::MmqResidentArguments::finite(gu_source, gu_flag, 0, nr * 1280, 0),
))?;
let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?;
ring.enqueue(Command::Swiglu(
b.swiglu.ok_or(Error::ContextPoisoned)?,
nr,
ffi::MmqOriginalSwigluArguments::new(gu_source, h, nr),
))?;
let h_flag = ring.flag(group, 1)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(1)?,
nr * 640,
ffi::MmqResidentArguments::finite(h, h_flag, 0, nr * 640, 0),
))?;
Ok(h)
}
/// Quantizes the SwiGLU output `h`, projects Down and guards both results.
fn ring_enqueue_down(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
formats: [MmqFormat; 3],
(group, nr, h): (usize, u32, ffi::BufferHandle),
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
self.ring_enqueue_quantize(ring, group, (nr, h))?;
self.enqueue_ring_project(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(
self.workspace.kernel(1)?,
nr * 2560,
ffi::MmqResidentArguments::finite(d, d_flag, 0, nr * 2560, 0),
))
}
/// Zeroes the Q8 scratch, quantizes the SwiGLU output `h` into it and guards the result.
fn ring_enqueue_quantize(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
group: usize,
(nr, h): (u32, ffi::BufferHandle),
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
let ql = layout(MmqFormat::Iq4NlDown, 2560, nr, 64)?;
let q = self.handle(HQ, 0, ql.packed, 16)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(0)?,
(ql.packed / 4) as u32,
ffi::MmqResidentArguments::zero(q, (ql.packed / 4) as u32),
))?;
let quantizer = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.quantizer;
ring.enqueue(Command::Quantize(
quantizer.ok_or(Error::ContextPoisoned)?,
ql,
ffi::MmqQuantArguments::original_indexed(h, None, q, ql),
))?;
let q_flag = ring.flag(group, 2)?;
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),
))
}
/// Maps the finite/Q8 witness words of every group to the first refusal.
fn check_ring_statuses(flags: &[u8]) -> Result<()> {
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
Self::check_group_status([0, 1, 2, 3].map(|i| u32::from_le_bytes(words[i])))?;
}
Ok(())
}
fn check_group_status([gu, h, q, down]: [u32; 4]) -> Result<()> {
Self::check_gate_up_status(gu, h)?;
Self::check_q8_down_status(q, down)
}
fn check_gate_up_status(gu: u32, h: u32) -> Result<()> {
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
fn check_q8_down_status(q: u32, down: u32) -> Result<()> {
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
pub(super) fn enqueue_ring_project(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
@@ -60,15 +60,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
bytes_per_second: f64,
) -> 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
|| !read.context_matches(self.context)
{
return Err(Error::InvalidProjectionShape);
}
self.stream_admit(read, bank, first)?;
let lease = read.lease();
let ring = lease.copy_ring_slots()?;
let mut targets = Vec::new();
@@ -76,111 +68,11 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
for index in 0..ring {
targets.push(lease.copy_ring_span(index)?);
}
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)?;
for layer in first..48 {
for expert in 0..512u32 {
if lease.cache_expert_span(usize::from(layer), expert as usize)?.is_some() {
continue;
}
let exact = bank.expert_pieces(layer, expert)?;
let slot_bytes = targets.iter().map(|t| t.1).min().unwrap_or(0);
// page-aligned supersets side by side at page offsets when they fit the slot (claude/ledger), else the
// exact pieces back to back
let mut entry = None;
if aligned_copy {
let sup = bank.expert_pieces_aligned(layer, expert)?;
let mut dest = [0usize; 3];
let mut at = [0usize; 3];
let mut off = 0usize;
for i in 0..3 {
dest[i] = off;
at[i] = off + sup[i].2;
off += sup[i].1.div_ceil(4096) * 4096;
}
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,
});
}
}
let entry = match entry {
Some(e) => e,
None => {
let bytes: usize = exact.iter().map(|p| p.1).sum();
if bytes > slot_bytes {
return Err(Error::InvalidSize);
}
let dest = [0, exact[0].1, exact[0].1 + exact[1].1];
StreamEntry { layer, expert, pieces: exact, exact, dest, at: dest }
}
};
entries.push(entry);
}
}
let entries = Self::stream_entries(lease, bank, first, &targets)?;
let api = StagerApi::load()?;
let guard = self.context.enter()?;
let mut events = Vec::new();
let stats = std::env::var_os("LELEKA_PREFILL_COPY_STATS").is_some_and(|v| v == "1");
let per_slot = if stats { 3 } else { 2 };
let created = (|| -> Result<()> {
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()?
});
}
Ok(())
})();
let pop = guard.finish();
if let Err(primary) = combine(created, pop) {
let guard = self.context.enter()?;
for e in &events {
let _ = api.event_destroy(*e);
}
let _ = guard.finish();
return Err(primary);
}
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::<usize>().ok()).unwrap_or(48);
let events = self.stream_make_events(&api, ring)?;
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
self.context.synchronize()?;
let context_token = StagerApi::context_token(self.context.handle.ok_or(Error::ContextPoisoned)?);
match ChunkStream::start(api, copy, first, entries, targets, copied, used, starts, topup, context_token) {
Ok(stream) => {
// from here the compute path's drains stop waiting for the copy stream (end_prompt_stream restores them)
crate::compute_drain::set_background(copy);
self.stream_started = Some(std::time::Instant::now());
self.stream = Some(stream);
self.stream_bank = Some(Rc::clone(bank));
self.stream_events = events;
Ok(())
}
Err(primary) => {
let guard = self.context.enter()?;
let loaded = StagerApi::load();
if let Ok(api) = loaded {
for e in &events {
let _ = api.event_destroy(*e);
}
}
let _ = guard.finish();
Err(primary)
}
}
self.stream_launch(api, bank, (first, ring), (entries, targets), events)
}
/// End the chunk's expert stream: stop and join the issuer, drain the copy and compute streams, release the
/// raw events. Idempotent; a failure poisons the schedule.
@@ -299,3 +191,184 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
result
}
}
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
impl<'ctx> OriginalMmqCopySchedule<'ctx> {
fn stream_admit(
&self,
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
bank: &Rc<crate::MappedExpertBank<'ctx>>,
first: u8,
) -> Result<()> {
self.validate_context(self.context)?;
if self.stream.is_some()
|| bank.pageable()
|| !bank.cache_context_matches(self.context)
|| first >= 48
|| !read.context_matches(self.context)
{
return Err(Error::InvalidProjectionShape);
}
Ok(())
}
/// One stream entry per expert of layers `first..48` that the arena cache does not already hold.
fn stream_entries(
lease: &crate::OriginalPromptRows<'_, '_, 'ctx>,
bank: &Rc<crate::MappedExpertBank<'ctx>>,
first: u8,
targets: &[(ffi::BufferHandle, usize)],
) -> Result<Vec<StreamEntry>> {
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)?;
for layer in first..48 {
for expert in 0..512u32 {
if lease.cache_expert_span(usize::from(layer), expert as usize)?.is_some() {
continue;
}
entries.push(Self::stream_entry(bank, (layer, expert), aligned_copy, targets)?);
}
}
Ok(entries)
}
/// The entry of one expert: its page-aligned supersets side by side at page offsets when they fit the slot
/// (claude/ledger), else the exact pieces back to back.
fn stream_entry(
bank: &Rc<crate::MappedExpertBank<'ctx>>,
(layer, expert): (u8, u32),
aligned_copy: bool,
targets: &[(ffi::BufferHandle, usize)],
) -> Result<StreamEntry> {
let exact = bank.expert_pieces(layer, expert)?;
let slot_bytes = targets.iter().map(|t| t.1).min().unwrap_or(0);
let mut entry = None;
if aligned_copy {
entry = Self::aligned_entry(bank, (layer, expert), exact, slot_bytes)?;
}
match entry {
Some(e) => Ok(e),
None => Self::exact_entry((layer, expert), exact, slot_bytes),
}
}
/// The expert's page-aligned supersets side by side, or none when they do not fit the slot.
fn aligned_entry(
bank: &Rc<crate::MappedExpertBank<'ctx>>,
(layer, expert): (u8, u32),
exact: [(usize, usize); 3],
slot_bytes: usize,
) -> Result<Option<StreamEntry>> {
let sup = bank.expert_pieces_aligned(layer, expert)?;
let mut dest = [0usize; 3];
let mut at = [0usize; 3];
let mut off = 0usize;
for i in 0..3 {
dest[i] = off;
at[i] = off + sup[i].2;
off += sup[i].1.div_ceil(4096) * 4096;
}
if off <= slot_bytes {
return Ok(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,
}));
}
Ok(None)
}
/// The expert's exact pieces back to back.
fn exact_entry((layer, expert): (u8, u32), exact: [(usize, usize); 3], slot_bytes: usize) -> Result<StreamEntry> {
let bytes: usize = exact.iter().map(|p| p.1).sum();
if bytes > slot_bytes {
return Err(Error::InvalidSize);
}
let dest = [0, exact[0].1, exact[0].1 + exact[1].1];
Ok(StreamEntry { layer, expert, pieces: exact, exact, dest, at: dest })
}
/// Starts the issuer thread on the copy stream; on failure destroys the events.
fn stream_launch(
&mut self,
api: crate::ffi::original_stager::Api,
bank: &Rc<crate::MappedExpertBank<'ctx>>,
(first, ring): (u8, usize),
(entries, targets): (Vec<StreamEntry>, Vec<(ffi::BufferHandle, usize)>),
events: Vec<usize>,
) -> Result<()> {
use crate::ffi::original_stager::Api as StagerApi;
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::<usize>().ok()).unwrap_or(48);
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
self.context.synchronize()?;
let context_token = StagerApi::context_token(self.context.handle.ok_or(Error::ContextPoisoned)?);
match ChunkStream::start(api, copy, first, entries, targets, copied, used, starts, topup, context_token) {
Ok(stream) => {
// from here the compute path's drains stop waiting for the copy stream (end_prompt_stream restores them)
crate::compute_drain::set_background(copy);
self.stream_started = Some(std::time::Instant::now());
self.stream = Some(stream);
self.stream_bank = Some(Rc::clone(bank));
self.stream_events = events;
Ok(())
}
Err(primary) => {
let guard = self.context.enter()?;
let loaded = StagerApi::load();
if let Ok(api) = loaded {
for e in &events {
let _ = api.event_destroy(*e);
}
}
let _ = guard.finish();
Err(primary)
}
}
}
/// Creates the `copied`, `used` and `start` event blocks (`ring` events each; timing events when the
/// statistics are on); on failure destroys the events already created.
/// Pushes `count` events; with the statistics on, `copied` (first block) and `start` (third block) carry
/// timestamps.
fn create_events(
api: &crate::ffi::original_stager::Api,
events: &mut Vec<usize>,
(count, ring, stats): (usize, usize, bool),
) -> Result<()> {
events.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?;
for i in 0..count {
events.push(if stats && (i < ring || i >= 2 * ring) {
api.event_create_timing()?
} else {
api.event_create()?
});
}
Ok(())
}
fn stream_make_events(&self, api: &crate::ffi::original_stager::Api, ring: usize) -> Result<Vec<usize>> {
let guard = self.context.enter()?;
let mut events = Vec::new();
let stats = std::env::var_os("LELEKA_PREFILL_COPY_STATS").is_some_and(|v| v == "1");
let per_slot = if stats { 3 } else { 2 };
let created = Self::create_events(api, &mut events, (per_slot * ring, ring, stats));
let pop = guard.finish();
if let Err(primary) = combine(created, pop) {
let guard = self.context.enter()?;
for e in &events {
let _ = api.event_destroy(*e);
}
let _ = guard.finish();
return Err(primary);
}
Ok(events)
}
}
@@ -9,3 +9,5 @@ mod impl_ring_2;
mod impl_ring_2_2;
#[path = "impl_ring/impl_ring_3.rs"]
mod impl_ring_3;
mod ring_init;
use ring_init::RingPlan;
@@ -14,205 +14,17 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
spans: &'read [[ResidentExpertBankSpan; 3]],
groups: usize,
) -> Result<Self> {
if !read.context_matches(context)
|| !bank.cache_context_matches(context)
|| layer >= 48
|| spans.is_empty()
|| spans.len() > 512
|| groups != spans.len().div_ceil(16)
|| formats[0] != formats[1]
|| !FORMATS[..5].contains(&formats[0])
|| !FORMATS[5..].contains(&formats[2])
{
return Err(Error::InvalidProjectionShape);
}
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)?;
Self::validate_new(context, read, &bank, (layer, groups, spans.len()), &formats)?;
let (gu, down, blob) = Self::blob_geometry(&formats)?;
let admitted: &dyn RingArena = read;
let count = admitted.stage_slots()?;
schedule.validate_context(context)?;
if schedule.ring_slots() != count {
return Err(Error::InvalidProjectionShape);
}
let mut owner = Self {
context,
read,
bank: Some(bank),
schedule,
slots: Vec::new(),
sources: Vec::new(),
commands: Vec::new(),
status: None,
flags: Vec::new(),
stage_next: 0,
staging: false,
streamed: false,
layer: layer as u8,
stage_done: 0,
submitted: false,
drained: false,
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.flags.resize(groups * 16, 0);
// Includes actual fixed ABI storage conservatively (<=512B each),
// plus actual vector capacities; no second unbounded launch list.
if owner
.metadata_bytes()?
.checked_add(owner.schedule.metadata_bytes()?)
.and_then(|n| n.checked_add(owner.schedule.host_metadata_outside))
.is_none_or(|n| n > 16 * 1024 * 1024)
{
return Err(Error::BudgetExceeded);
}
for index in 0..count {
let (h, n) = admitted.stage_span(index)?;
if n < blob {
return Err(Error::InvalidSize);
}
h.validate_projection_extent(n, 256)?;
for slot in &owner.slots {
if h.overlaps(n, slot.span, slot.bytes) {
return Err(Error::OutputAliasesInput);
}
}
for role in 0..TMP {
let (a, n) = GroupArena::span(read, role)?;
if h.overlaps(blob, a, n) {
return Err(Error::OutputAliasesInput);
}
}
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() {
if !bank.eligible(spans)
|| !matches!(spans[0].role(),TensorRole::Layer{layer:l,..} if usize::from(l)==layer)
|| i > 0 && spans[0].expert() <= owner.sources[i - 1].spans[0].expert()
{
return Err(Error::InvalidProjectionShape);
}
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 } {
return Err(Error::InvalidProjectionShape);
}
}
let resident = admitted
.cache_span(layer, spans[0].expert() as usize)?
.map(|(h, n)| {
if n < blob {
return Err(Error::InvalidSize);
}
Ok([
h.checked_subspan(n, 0, gu)?,
h.checked_subspan(n, gu, gu)?,
h.checked_subspan(n, gu * 2, down)?,
])
})
.transpose()?;
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() {
if stream.next_layer_is(layer as u8) {
for source in &mut owner.sources {
if source.resident.is_some() {
continue;
}
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])?,
],
) {
return Err(Error::InvalidProjectionShape);
}
source.entry = Some(entry);
}
owner.streamed = true;
} else {
return Err(Error::InvalidProjectionShape);
}
}
// Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked
// buffers, in launch order, ahead of their DMAs.
let mut jobs = Vec::new();
for source in &mut owner.sources {
if source.resident.is_none() && source.entry.is_none() && bank.host_staged(source.spans) {
let mut pieces = [(0usize, 0usize, 0u32); 3];
for (role, span) in source.spans.iter().enumerate() {
let bytes = bank.cache_source(span)?;
pieces[role] = (bytes.as_ptr() as usize, bytes.len(), span.raw_kind());
}
source.job = Some(jobs.len());
jobs.push(Job { pieces, priority: 0 });
}
}
if !jobs.is_empty() {
let priority = host_stage::layer_priority(layer, jobs.len().saturating_mul(blob));
for job in &mut jobs {
job.priority = priority;
}
}
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)
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
owner.status = match owner.schedule.status_pool.take() {
Some((bytes, buffer)) if bytes >= charge => Some(buffer),
Some((_, other)) => {
other.release()?;
Some(context.allocate(charge.max(512))?)
}
None => Some(context.allocate(charge.max(512))?),
};
// The old input quantization/metadata upload used default stream.
// Admit that dependency once before starting nonblocking producers.
context.synchronize()?;
if !jobs.is_empty() {
let pageable = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?.pageable();
let schedule = &mut *owner.schedule;
if schedule.host.as_ref().is_some_and(|h| h.buffer_bytes() < blob) {
// a larger blob than the buffers: every earlier DMA from them was drained with its layer
let mut old = schedule.host.take().ok_or(Error::ContextPoisoned)?;
old.close()?;
for event in schedule.host_events.drain(..) {
event.close()?;
}
}
if schedule.host.is_none() {
let guard = context.enter()?;
let created = HostStage::new(blob, pageable);
let pop = guard.finish();
let host = match (created, pop) {
(Ok(host), Ok(())) => host,
(Err(e), _) | (Ok(_), Err(e)) => return Err(e),
};
for _ in 0..host.ring() {
schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?);
}
schedule.host = Some(host);
}
schedule.host.as_mut().ok_or(Error::ContextPoisoned)?.start(jobs)?;
owner.staging = true;
}
Ok(())
})();
if let Err(primary) = result {
let mut owner = Self::empty(context, read, bank, schedule, layer);
let plan = RingPlan { layer, groups, formats, gu, down, blob, count };
if let Err(primary) = owner.init(spans, &plan) {
return combine(Err(primary), owner.close_inner());
}
Ok(owner)
@@ -0,0 +1,334 @@
//! Construction phases of `Ring::new`, split out by STRA-338 (size). Every phase keeps the original statement
//! order and error handling; `Ring::init` runs them in the order the former closure ran them.
#[allow(unused_imports)]
use super::*;
/// Layer-wide numbers every construction phase needs.
pub(super) struct RingPlan {
pub(super) layer: usize,
pub(super) groups: usize,
pub(super) formats: [MmqFormat; 3],
/// raw bytes of one gate or up matrix
pub(super) gu: usize,
/// raw bytes of one down matrix
pub(super) down: usize,
/// bytes of one expert blob (gate + up + down)
pub(super) blob: usize,
/// number of stage slots of the arena
pub(super) count: usize,
}
impl<'read, 'ctx> Ring<'read, 'ctx> {
/// Rejects a read, bank, layer, span list or format set the literal ring cannot serve.
pub(super) fn validate_new(
context: &'ctx Context<'ctx>,
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
bank: &crate::MappedExpertBank<'ctx>,
(layer, groups, nspans): (usize, usize, usize),
formats: &[MmqFormat; 3],
) -> Result<()> {
if !read.context_matches(context)
|| !bank.cache_context_matches(context)
|| layer >= 48
|| nspans == 0
|| nspans > 512
|| groups != nspans.div_ceil(16)
|| formats[0] != formats[1]
|| !FORMATS[..5].contains(&formats[0])
|| !FORMATS[5..].contains(&formats[2])
{
return Err(Error::InvalidProjectionShape);
}
Ok(())
}
/// `(gate/up bytes, down bytes, blob bytes)` of one expert.
pub(super) fn blob_geometry(formats: &[MmqFormat; 3]) -> Result<(usize, usize, usize)> {
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)?;
Ok((gu, down, blob))
}
/// An owner with no slots, sources or commands yet.
pub(super) fn empty(
context: &'ctx Context<'ctx>,
read: &'read crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
bank: Rc<crate::MappedExpertBank<'ctx>>,
schedule: &'read mut OriginalMmqCopySchedule<'ctx>,
layer: usize,
) -> Self {
Self {
context,
read,
bank: Some(bank),
schedule,
slots: Vec::new(),
sources: Vec::new(),
commands: Vec::new(),
status: None,
flags: Vec::new(),
stage_next: 0,
staging: false,
streamed: false,
layer: layer as u8,
stage_done: 0,
submitted: false,
drained: false,
closed: false,
}
}
/// Everything the former construction closure did after the owner existed; on error the caller closes the owner.
pub(super) fn init(&mut self, spans: &'read [[ResidentExpertBankSpan; 3]], plan: &RingPlan) -> Result<()> {
self.reserve_buffers(spans.len(), plan)?;
self.check_metadata_budget()?;
self.admit_slots(plan)?;
self.admit_sources(spans, plan)?;
self.attach_stream(plan)?;
let jobs = self.plan_host_jobs(plan)?;
self.admit_status(plan)?;
self.start_jobs(jobs, plan)
}
fn start_jobs(&mut self, jobs: Vec<Job>, plan: &RingPlan) -> Result<()> {
// The old input quantization/metadata upload used default stream.
// Admit that dependency once before starting nonblocking producers.
self.context.synchronize()?;
if !jobs.is_empty() {
self.start_host_stage(jobs, plan)?;
}
Ok(())
}
fn reserve_buffers(&mut self, nspans: usize, plan: &RingPlan) -> Result<()> {
self.slots.try_reserve_exact(plan.count).map_err(|_| Error::HostAllocation)?;
self.sources.try_reserve_exact(nspans).map_err(|_| Error::HostAllocation)?;
self.commands.try_reserve_exact(COMMAND_CAP).map_err(|_| Error::HostAllocation)?;
self.flags.try_reserve_exact(plan.groups * 16).map_err(|_| Error::HostAllocation)?;
self.flags.resize(plan.groups * 16, 0);
Ok(())
}
fn check_metadata_budget(&self) -> Result<()> {
// Includes actual fixed ABI storage conservatively (<=512B each),
// plus actual vector capacities; no second unbounded launch list.
if self
.metadata_bytes()?
.checked_add(self.schedule.metadata_bytes()?)
.and_then(|n| n.checked_add(self.schedule.host_metadata_outside))
.is_none_or(|n| n > 16 * 1024 * 1024)
{
return Err(Error::BudgetExceeded);
}
Ok(())
}
/// Every stage slot must hold a blob, be GPU-addressable, and overlap neither another slot nor a temporary role.
fn admit_slots(&mut self, plan: &RingPlan) -> Result<()> {
let read = self.read;
for index in 0..plan.count {
let (h, n) = read.stage_span(index)?;
if n < plan.blob {
return Err(Error::InvalidSize);
}
h.validate_projection_extent(n, 256)?;
for slot in &self.slots {
if h.overlaps(n, slot.span, slot.bytes) {
return Err(Error::OutputAliasesInput);
}
}
for role in 0..TMP {
let (a, n) = GroupArena::span(read, role)?;
if h.overlaps(plan.blob, a, n) {
return Err(Error::OutputAliasesInput);
}
}
self.slots.push(Slot { span: h, bytes: n, live: false, gathered: false });
}
Ok(())
}
fn admit_sources(&mut self, spans: &'read [[ResidentExpertBankSpan; 3]], plan: &RingPlan) -> Result<()> {
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
for (i, spans) in spans.iter().enumerate() {
let ordered = i == 0 || spans[0].expert() > self.sources[i - 1].spans[0].expert();
Self::check_source_spans(bank, spans, ordered, plan)?;
let resident = self.resident_blob(spans[0].expert() as usize, plan)?;
self.sources.push(Source { spans, resident, slot: None, job: None, entry: None, dest: None });
}
Ok(())
}
fn check_source_spans(
bank: &crate::MappedExpertBank<'ctx>,
spans: &[ResidentExpertBankSpan; 3],
ordered: bool,
plan: &RingPlan,
) -> Result<()> {
if !bank.eligible(spans)
|| !matches!(spans[0].role(),TensorRole::Layer{layer:l,..} if usize::from(l)==plan.layer)
|| !ordered
{
return Err(Error::InvalidProjectionShape);
}
for (role, span) in spans.iter().enumerate() {
let actual = bank.cache_source(span)?;
if span.raw_kind() != kind(plan.formats[role]) || actual.len() != if role < 2 { plan.gu } else { plan.down }
{
return Err(Error::InvalidProjectionShape);
}
}
Ok(())
}
/// The gate, up and down spans of an expert that already sits in the arena cache.
fn resident_blob(&self, expert: usize, plan: &RingPlan) -> Result<Option<[ffi::BufferHandle; 3]>> {
self.read
.cache_span(plan.layer, expert)?
.map(|(h, n)| {
if n < plan.blob {
return Err(Error::InvalidSize);
}
Ok([
h.checked_subspan(n, 0, plan.gu)?,
h.checked_subspan(n, plan.gu, plan.gu)?,
h.checked_subspan(n, plan.gu * 2, plan.down)?,
])
})
.transpose()
}
/// With an active chunk stream for this layer, every non-resident expert is the stream's entry.
fn attach_stream(&mut self, plan: &RingPlan) -> Result<()> {
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
if let Some(stream) = self.schedule.stream.as_ref() {
if !stream.next_layer_is(plan.layer as u8) {
return Err(Error::InvalidProjectionShape);
}
for source in &mut self.sources {
if source.resident.is_some() {
continue;
}
let entry =
stream.entry(plan.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, Self::source_pieces(bank, source.spans)?) {
return Err(Error::InvalidProjectionShape);
}
source.entry = Some(entry);
}
self.streamed = true;
}
Ok(())
}
/// The gate, up and down host ranges of one expert.
fn source_pieces<'b>(
bank: &'b crate::MappedExpertBank<'ctx>,
spans: &[ResidentExpertBankSpan; 3],
) -> Result<[&'b [u8]; 3]> {
Ok([bank.cache_source(&spans[0])?, bank.cache_source(&spans[1])?, bank.cache_source(&spans[2])?])
}
/// Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked
/// buffers, in launch order, ahead of their DMAs.
fn plan_host_jobs(&mut self, plan: &RingPlan) -> Result<Vec<Job>> {
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
let mut jobs = Vec::new();
for source in &mut self.sources {
if source.resident.is_none() && source.entry.is_none() && bank.host_staged(source.spans) {
let mut pieces = [(0usize, 0usize, 0u32); 3];
for (role, span) in source.spans.iter().enumerate() {
let bytes = bank.cache_source(span)?;
pieces[role] = (bytes.as_ptr() as usize, bytes.len(), span.raw_kind());
}
source.job = Some(jobs.len());
jobs.push(Job { pieces, priority: 0 });
}
}
if !jobs.is_empty() {
let priority = host_stage::layer_priority(plan.layer, jobs.len().saturating_mul(plan.blob));
for job in &mut jobs {
job.priority = priority;
}
}
Ok(jobs)
}
/// Checks the device budget for the status words and takes (or allocates) their buffer.
fn admit_status(&mut self, plan: &RingPlan) -> Result<()> {
let context = self.context;
let charge = plan.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)
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
self.status = Some(self.status_buffer(charge)?);
Ok(())
}
/// The pooled status buffer when it is large enough, else a fresh one (the pooled one is released).
fn status_buffer(&mut self, charge: usize) -> Result<DeviceBuffer<'ctx>> {
match self.schedule.status_pool.take() {
Some((bytes, buffer)) if bytes >= charge => Ok(buffer),
Some((_, other)) => {
other.release()?;
self.context.allocate(charge.max(512))
}
None => self.context.allocate(charge.max(512)),
}
}
fn start_host_stage(&mut self, jobs: Vec<Job>, plan: &RingPlan) -> Result<()> {
let pageable = self.bank.as_ref().ok_or(Error::ContextPoisoned)?.pageable();
Self::ensure_host_stage(self.context, &mut *self.schedule, plan.blob, pageable)?;
self.schedule.host.as_mut().ok_or(Error::ContextPoisoned)?.start(jobs)?;
self.staging = true;
Ok(())
}
/// Replaces a host stage whose buffers are smaller than `blob` and creates one when none exists.
fn ensure_host_stage(
context: &'ctx Context<'ctx>,
schedule: &mut OriginalMmqCopySchedule<'ctx>,
blob: usize,
pageable: bool,
) -> Result<()> {
if schedule.host.as_ref().is_some_and(|h| h.buffer_bytes() < blob) {
// a larger blob than the buffers: every earlier DMA from them was drained with its layer
let mut old = schedule.host.take().ok_or(Error::ContextPoisoned)?;
old.close()?;
for event in schedule.host_events.drain(..) {
event.close()?;
}
}
if schedule.host.is_none() {
Self::create_host_stage(context, schedule, blob, pageable)?;
}
Ok(())
}
fn create_host_stage(
context: &'ctx Context<'ctx>,
schedule: &mut OriginalMmqCopySchedule<'ctx>,
blob: usize,
pageable: bool,
) -> Result<()> {
let guard = context.enter()?;
let created = HostStage::new(blob, pageable);
let pop = guard.finish();
let host = match (created, pop) {
(Ok(host), Ok(())) => host,
(Err(e), _) | (Ok(_), Err(e)) => return Err(e),
};
for _ in 0..host.ring() {
schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?);
}
schedule.host = Some(host);
Ok(())
}
}
@@ -20,6 +20,87 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
direct_window: bool,
after: Option<&mut OriginalGpuEvent<'ctx>>,
) -> Result<()> {
let cp = coupled.is_some();
let (rows, first, policy_key) =
self.launch_admit(ring, prior, (&window, &selection), (a, first_rows, direct_window, cp), policy)?;
let window = Rc::new(window);
let mut selection = Some(selection);
if first_rows.is_some() {
self.launch_stage_first(&window, &mut selection, rows, direct_window)?;
}
let pol = policy.for_capture(0, 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)?;
let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?;
let span_record = crate::host_profile::span("mtp.launch_record");
let first_capture = graphs.find_mut(key)?.is_none();
let graph = graphs.record(
key,
stream,
|| {
Self::prepare_launch_round(
(full, scalar, &mut *ring),
&window,
(rows, first_rows.is_some(), direct_window),
&pol,
)
},
|c, r| r.capture(c),
)?;
drop(span_record);
if first_capture {
Self::note_first_capture(&mut self.graph_metadata, graph, (rows, cp))?;
}
let _span_stage = crate::host_profile::span("mtp.launch_stage_enqueue");
Self::launch_stage_graph(graph, stream, (&window, &mut selection, a), (first_rows.is_some(), coupled, after))?;
let generation = ring.begin_original_graph_mutation(prior)?;
Self::enqueue_round(self.context, &mut self.failed, graph, stream)?;
self.in_flight =
Some(InFlightDraft { window, key, generation, a, rows, first, max_drafts, min_p, coupled: cp, policy_key });
Ok(())
}
/// Charges the metadata of a newly captured round graph to the draft budget.
fn note_first_capture(
graph_metadata: &mut usize,
graph: &crate::original_gpu_schedule::OriginalGpuGraph<'ctx, OriginalMtpDraftProgram<'ctx>>,
(rows, cp): (usize, bool),
) -> Result<()> {
*graph_metadata = 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());
}
Ok(())
}
/// Enqueues the staged round graph; a failure that poisoned the context fails the drafter.
fn enqueue_round(
context: &'ctx Context<'ctx>,
failed: &mut bool,
graph: &mut crate::original_gpu_schedule::OriginalGpuGraph<'ctx, OriginalMtpDraftProgram<'ctx>>,
stream: &mut OriginalGpuStream<'ctx>,
) -> Result<()> {
if let Err(error) = graph.enqueue(stream) {
if context.is_poisoned() {
*failed = true;
}
return Err(error);
}
Ok(())
}
/// Validates the draft request against the ring, window and prior state; latches the owner, policy and window
/// mode. Returns `(rows, first position, policy key)`.
fn launch_admit(
&mut self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
(window, selection): (&OriginalVerifyWindow<'ctx>, &NativeHeadSelection),
(a, first_rows, direct_window, cp): (usize, Option<usize>, bool, bool),
policy: &OriginalMtpFullPolicy,
) -> Result<(usize, usize, [u32; 23])> {
if self.in_flight.is_some() {
return Err(Error::InvalidQwenShape);
}
@@ -27,7 +108,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
policy.validate_selected()?;
ring.validate_snapshot(prior)?;
window.validate_context(self.context)?;
window.validate_selection(&selection)?;
window.validate_selection(selection)?;
let rows = first_rows.unwrap_or(window.rows());
let first = window.first_position();
if first_rows.is_some() && window.rows() != 1 {
@@ -45,6 +126,15 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
return Err(Error::InvalidQwenShape);
}
self.direct_window_mode = Some(direct_window);
let policy_key = self.launch_latch(prior, policy)?;
if cp && !self.full.as_ref().ok_or(Error::ContextPoisoned)?.inner.coupled {
return Err(Error::InvalidQwenShape);
}
Ok((rows, first, policy_key))
}
/// The ring owner and policy key may not change between rounds.
fn launch_latch(&mut self, prior: &MtpInt8Snapshot, policy: &OriginalMtpFullPolicy) -> Result<[u32; 23]> {
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))
@@ -54,60 +144,59 @@ 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 {
return Err(Error::InvalidQwenShape);
}
let window = Rc::new(window);
let mut selection = Some(selection);
if first_rows.is_some() {
let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?;
if direct_window {
full.stage_first_residual_direct(
Rc::clone(&window),
selection.take().ok_or(Error::InvalidQwenShape)?,
rows,
)?;
} else {
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 };
Ok(policy_key)
}
/// Stages the first residual of the verifier window for a one-row first draft.
fn launch_stage_first(
&self,
window: &Rc<OriginalVerifyWindow<'ctx>>,
selection: &mut Option<NativeHeadSelection>,
rows: usize,
direct_window: bool,
) -> Result<()> {
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)?;
let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?;
let span_record = crate::host_profile::span("mtp.launch_record");
let first_capture = graphs.find_mut(key)?.is_none();
let graph = graphs.record(
key,
stream,
|| {
if direct_window {
full.prepare_round_from_verifier_rows(
scalar,
ring,
Rc::clone(&window),
rows,
first_rows.is_some(),
&pol,
)
} else {
full.prepare_round(scalar, ring, rows, &pol)
}
},
|c, r| r.capture(c),
)?;
drop(span_record);
if first_capture {
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());
}
if direct_window {
full.stage_first_residual_direct(
Rc::clone(window),
selection.take().ok_or(Error::InvalidQwenShape)?,
rows,
)?;
} else {
full.stage_first_residual(Rc::clone(window), selection.take().ok_or(Error::InvalidQwenShape)?, rows)?;
}
let _span_stage = crate::host_profile::span("mtp.launch_stage_enqueue");
Ok(())
}
/// The program the round graph captures: from verifier rows when the window is direct, else from scratch.
fn prepare_launch_round(
(full, scalar, ring): (
&OriginalMtpFullForward<'ctx>,
&OriginalMtpScalarPrefill<'ctx>,
&mut MtpOriginalInt8<'ctx>,
),
window: &Rc<OriginalVerifyWindow<'ctx>>,
(rows, first_rows, direct_window): (usize, bool, bool),
pol: &OriginalMtpFullPolicy,
) -> Result<OriginalMtpDraftProgram<'ctx>> {
if direct_window {
full.prepare_round_from_verifier_rows(scalar, ring, Rc::clone(window), rows, first_rows, pol)
} else {
full.prepare_round(scalar, ring, rows, pol)
}
}
/// Waits the commit event, then stages the window (or the first residual) and the sampling state.
fn launch_stage_graph(
graph: &mut crate::original_gpu_schedule::OriginalGpuGraph<'ctx, OriginalMtpDraftProgram<'ctx>>,
stream: &mut OriginalGpuStream<'ctx>,
(window, selection, a): (&Rc<OriginalVerifyWindow<'ctx>>, &mut Option<NativeHeadSelection>, usize),
(first_rows, coupled, after): (
bool,
Option<(SamplerParams, &[i32; 4096])>,
Option<&mut OriginalGpuEvent<'ctx>>,
),
) -> Result<()> {
// generate.cpp enqueues the draft on the commit's stream: here the draft stream waits the verifier's
// commit event before its first command, so the GPU orders them without a host wait.
if let Some(event) = after {
@@ -115,23 +204,14 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
}
// Literal capture happens before h_tok/h_step/h_pos/h_row writes. Its real
// mapped residual staging retains the completed verifier window before DMA.
if first_rows.is_some() {
if first_rows {
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)?;
}
let generation = ring.begin_original_graph_mutation(prior)?;
if let Err(error) = graph.enqueue(stream) {
if self.context.is_poisoned() {
self.failed = true;
}
return Err(error);
}
self.in_flight =
Some(InFlightDraft { window, key, generation, a, rows, first, max_drafts, min_p, coupled: cp, policy_key });
Ok(())
}
}
@@ -14,14 +14,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
) -> Result<CompletedOriginalMtpDraft<'ctx>> {
let InFlightDraft { window, key, generation, a, rows, first, max_drafts, min_p, coupled: cp, policy_key } =
self.in_flight.take().ok_or(Error::InvalidQwenShape)?;
self.validate_context(self.context)?;
policy.validate_selected()?;
ring.validate_snapshot(prior)?;
if policy.capture_key() != policy_key
|| self.ring_owner.as_ref().is_none_or(|old| !old.same_owner(&prior.owner_id()))
{
return Err(Error::InvalidQwenShape);
}
self.finish_admit(ring, prior, policy, policy_key)?;
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)?;
@@ -29,22 +22,17 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
let graph = graphs.find_mut(key)?.ok_or(Error::InvalidQwenShape)?;
let mut ids = [0i32; 8];
let mut probabilities = [0f32; 8];
let mut count;
let span_first = crate::host_profile::span("mtp.finish_first_step");
let first_result = graph.mtp_finish_step(stream);
drop(span_first);
let output = match first_result {
Ok(o) => o,
Err(error) => {
if self.context.is_poisoned() {
self.failed = true;
}
return Err(error);
let output = first_result.inspect_err(|_| {
if self.context.is_poisoned() {
self.failed = true;
}
};
})?;
ids[0] = output.token;
probabilities[0] = output.probability;
count = 1;
let mut count = 1;
// draft j writes the cell first + a + j, and the ring ends at MTP_ORIGINAL_MAX_CELLS (upstream `max_steps`)
let limit = crate::original_mtp_actor::chain_end_within_cells(
(self.max_t as i32 - 1).min(max_drafts),
@@ -53,54 +41,17 @@ 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 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))?;
if first_capture {
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());
let step = Self::chain_step(
self.context,
(full, scalar, &mut *graphs, &mut *stream),
(&mut self.graph_metadata, &mut *ring),
(j, cp, policy),
)?;
let output = step.inspect_err(|_| {
if self.context.is_poisoned() {
self.failed = true;
}
}
graph.mtp_stage_chain()?;
// LELEKA_SERVE_PROFILE: the GPU time of the step's graph (events around the launch), next to its wall time
let mut timing = if crate::host_profile::enabled() {
match (
self.context.original_gpu_event(crate::OriginalEventKind::Timing),
self.context.original_gpu_event(crate::OriginalEventKind::Timing),
) {
(Ok(a), Ok(b)) => Some((a, b)),
_ => None,
}
} else {
None
};
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)
});
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));
}
}
let output = match step_result {
Ok(o) => o,
Err(error) => {
if self.context.is_poisoned() {
self.failed = true;
}
return Err(error);
}
};
})?;
ids[j] = output.token;
probabilities[j] = output.probability;
count += 1;
@@ -121,6 +72,91 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
accepted_row: a,
})
}
fn finish_admit(
&self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
policy: &OriginalMtpFullPolicy,
policy_key: [u32; 23],
) -> Result<()> {
self.validate_context(self.context)?;
policy.validate_selected()?;
ring.validate_snapshot(prior)?;
if policy.capture_key() != policy_key
|| self.ring_owner.as_ref().is_none_or(|old| !old.same_owner(&prior.owner_id()))
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
/// Records (once) and runs the chain-step graph `j`; the outer error is a setup failure, the inner one the
/// step's own (which fails the drafter when it poisoned the context).
#[allow(clippy::type_complexity)]
fn chain_step(
context: &'ctx Context<'ctx>,
(full, scalar, graphs, stream): (
&OriginalMtpFullForward<'ctx>,
&OriginalMtpScalarPrefill<'ctx>,
&mut OriginalGraphRegistry<'ctx, OriginalMtpDraftProgram<'ctx>>,
&mut OriginalGpuStream<'ctx>,
),
(graph_metadata, ring): (&mut usize, &mut MtpOriginalInt8<'ctx>),
(j, cp, policy): (usize, bool, &OriginalMtpFullPolicy),
) -> Result<Result<OriginalMtpStepOutput>> {
let _span_chain = crate::host_profile::span("mtp.chain_step");
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))?;
if first_capture {
*graph_metadata =
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());
}
}
graph.mtp_stage_chain()?;
Ok(Self::chain_step_run(context, graph, stream))
}
/// Enqueues the staged step graph and reads its token back; with the serve profile on, the GPU time of the
/// graph is measured with events around the launch.
fn chain_step_run(
context: &'ctx Context<'ctx>,
graph: &mut crate::original_gpu_schedule::OriginalGpuGraph<'ctx, OriginalMtpDraftProgram<'ctx>>,
stream: &mut OriginalGpuStream<'ctx>,
) -> Result<OriginalMtpStepOutput> {
// LELEKA_SERVE_PROFILE: the GPU time of the step's graph (events around the launch), next to its wall time
let mut timing = if crate::host_profile::enabled() {
match (
context.original_gpu_event(crate::OriginalEventKind::Timing),
context.original_gpu_event(crate::OriginalEventKind::Timing),
) {
(Ok(a), Ok(b)) => Some((a, b)),
_ => None,
}
} else {
None
};
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)
});
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));
}
}
step_result
}
/// End of a verifier's life (the serve stack assembles a NEW verifier bank per request). The cached round programs of the
/// direct mode captured the OLD bank's final-R span and keep its completed window alive, and the tail owner keeps the last
/// staged window: that blocks `OriginalVerifyBank::close` (the bank is still shared) and makes the next request's first
@@ -250,6 +250,7 @@ mod impl_fullowned;
mod impl_originalmtpfullforward;
#[path = "mtp_original_full_forward/impl_originalmtpretainedprefix.rs"]
mod impl_originalmtpretainedprefix;
mod mtp_original_full_init;
#[path = "mtp_original_full_forward/validate_scalar_prefix_fn.rs"]
mod validate_scalar_prefix_fn;
#[allow(unused_imports)]
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: impl OriginalMtpFullForward.
use super::mtp_original_full_init::FullGeometry;
#[allow(unused_imports)]
use super::*;
@@ -25,24 +26,8 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
coupled: bool,
original: bool,
) -> Result<Self> {
weights.validate_context(c)?;
if !(1..=8).contains(&max_t) {
return Err(Error::InvalidQwenShape);
}
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 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))?,
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 {
return Err(Error::BudgetExceeded);
}
let FullGeometry { layout, original_layout, sizes } =
FullGeometry::admit(c, &weights, max_t, (coupled, original))?;
let mut o = FullOwned {
context: c,
modules: Vec::new(),
@@ -58,121 +43,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
source: RefCell::new(None),
};
o.modules.try_reserve_exact(symbols::ASSETS.len()).map_err(|_| Error::HostAllocation)?;
let op = (|| {
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
let load = (|| {
for (p, e) in &symbols::ASSETS[..symbols::CHAIN_ASSET] {
o.modules.push(Rc::new(FM::load(p, e)?));
}
if chain_mtp_assets() || daily_mtp() {
// chain_window.ptx: loaded only when selected, and only if it is the sealed one
crate::original_verify::chain::CHAIN.sealed()?;
let (p, e) = &symbols::ASSETS[symbols::CHAIN_ASSET];
o.modules.push(Rc::new(FM::load(p, e)?));
}
if daily_mtp() {
// sm120_attn_daily.ptx: the draft step's attention (opt-in, LELEKA_SM120_ATTN_DAILY_MTP=1); slot 22 follows the chain slot
crate::original_verify::sm120::ATTN_DAILY.sealed()?;
let (p, e) = &symbols::ASSETS[symbols::DAILY_ASSET];
o.modules.push(Rc::new(FM::load(p, e)?));
}
Ok(())
})();
let pop = g.finish();
if pop.is_err() {
c.poison();
c.retain_driver();
}
combine(load, pop)?;
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
let config = o.modules[17].configure_gr();
let pop = g.finish();
if pop.is_err() {
c.poison();
c.retain_driver();
}
let _actual = combine(config, pop)?;
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
let mapped = if original {
full_mapped::MappedOwner::original(max_t, coupled)
} else {
full_mapped::MappedOwner::new(max_t, coupled)
};
let pop = g.finish();
if pop.is_err() {
c.poison();
c.retain_driver();
let primary = match mapped {
Ok(actual) => {
std::mem::forget(actual);
Ok(())
}
Err(error) => Err(error),
};
return combine(primary, pop);
}
if original && mapped.is_err() {
c.poison();
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))?));
if original {
for (i, n) in sizes.into_iter().enumerate() {
if n != 0 {
o.extras[i] = Some(c.allocate(n)?);
}
}
}
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
// cuMemsetD8_v2 on device memory is asynchronous with respect to the host (it only orders on the legacy
// default stream). Fence it inside the same guard: the non-original layout has no later synchronous copy
// (the original one does, `copy_from_range` below), and the first kernel of a non-blocking stream must not
// race the zeroing. Same pattern as `zero_state` + `synchronize` in mtp_original_ring_state.rs.
let zero = o.modules[0]
.zero(
o.scratch
.as_ref()
.ok_or(Error::ContextPoisoned)?
.handle
.ok_or(Error::ContextPoisoned)?
.qwen_address(),
o.original_layout.as_ref().map_or(o.layout.bytes, |l| l.bytes),
)
.and_then(|()| c.driver.api.synchronize());
let pop = g.finish();
if zero.is_err() || pop.is_err() {
c.poison();
c.retain_driver();
}
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)?;
for _ in 0..l.t {
for i in 0..l.cap {
ids.extend_from_slice(&(i as i32).to_le_bytes());
}
}
Rc::get_mut(o.scratch.as_mut().ok_or(Error::ContextPoisoned)?)
.ok_or(Error::InvalidQwenShape)?
.copy_from_range(l.offsets[4], &ids)?;
}
Ok(())
})();
if let Err(e) = op {
if let Err(e) = o.init_device(c, (original, max_t, coupled), sizes) {
return combine(Err(e), o.close());
}
Ok(Self { inner: Rc::new(o) })
@@ -3,6 +3,9 @@
#[allow(unused_imports)]
use super::*;
mod prefix_parts;
mod prefix_rows;
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;
@@ -15,317 +18,21 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
t: usize,
step_row: usize,
) -> Result<(Vec<ScalarCommand>, Option<OriginalMtpNativeGather<'ctx>>)> {
self.validate_context(scalar.context)?;
validate_scalar_prefix(scalar)?;
ring.validate_context(scalar.context)?;
policy.validate_selected()?;
if scalar.has_pending {
return Err(Error::InvalidQwenShape);
}
if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) {
return Err(Error::InvalidQwenShape);
}
self.prefix_preflight(scalar, ring, policy)?;
let retained = Rc::clone(&self.inner.weights.prefix);
retained.validate_context(scalar.context)?;
let weights = &retained.roles;
let embedding = match &retained.embedding {
PrefixEmbedding::Device { bank } => Some(bank.loans(scalar.context)?.1),
PrefixEmbedding::Native(_) => None,
};
let wr = weights.each_ref().map(|b| Rc::as_ref(b));
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,
];
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 mut wh = [eh; 11];
for i in 0..11 {
checked(scalar.context, wr[i], extents[i])?;
wh[i] = wr[i].handle.ok_or(Error::ContextPoisoned)?;
}
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) {
return Err(Error::OutputAliasesInput);
}
}
for output in ring.buffers()?.iter().flatten() {
if h.overlaps(b.bytes, output.handle.ok_or(Error::ContextPoisoned)?, output.bytes) {
return Err(Error::OutputAliasesInput);
}
}
}
if t == 0
|| t > self.inner.max_t
|| t > scalar.max_t
|| t > ring.max_t
// Window ring (mtp.cpp: ring = window + 4 * max_t + 64 cells, 4 per
// slot) or the Original fully-resident retry (one slot per page).
|| (ring.slots != (MTP_ORIGINAL_WINDOW + 4 * ring.max_t + 64).div_ceil(4)
&& ring.slots != MTP_ORIGINAL_MAX_CELLS / 4)
|| step_row
.checked_add(t)
.is_none_or(|n| n > 2 * self.inner.max_t)
{
return Err(Error::InvalidQwenShape);
}
let kv = &policy.kv;
let group = 0usize;
let prefix_policy = OriginalMtpScalarPolicy {
gr: policy.gr,
per_group_sync: false,
kv: DraftKvPolicy {
disabled: kv.disabled,
hybrid: kv.hybrid,
rotated: kv.rotated,
q4: kv.q4,
alternate_f16: kv.alternate_f16,
mode: kv.mode,
rope_table_enabled: kv.rope_table_enabled,
multimodal_positions: kv.multimodal_positions,
theta_scale: kv.theta_scale,
freq_scale: kv.freq_scale,
corr_low: kv.corr_low,
corr_high: kv.corr_high,
ext_factor: kv.ext_factor,
mscale: kv.mscale,
},
};
let rin = scalar.address(0, t * 40960)?;
let emb = scalar.address(2, t * 10240)?;
let en = scalar.address(3, t * 10240)?;
let e2 = scalar.address(4, t * 10240)?;
let hn = scalar.address(5, t * 40960)?;
let h2 = scalar.address(6, t * 40960)?;
let r = scalar.address(1, t * 40960)?;
let mixed = scalar.address(11, t * 10240)?;
let tok = scalar.address(12, t * 4)?;
let step = self.inner.address(31)? + (step_row * 16) as u64;
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)?;
OriginalMtpScalarPrefill::kernel(
&mut cmds,
0,
11,
[1, 1, 1],
[256, 1, 1],
0,
vec![Arg::U64(scalar.flag(0, 0)?), Arg::I32(16)],
)?;
let mut native_embedding = None;
if let PrefixEmbedding::Native(e) = &retained.embedding {
let scratch = scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?;
let h = scratch.handle.ok_or(Error::ContextPoisoned)?;
native_embedding = Some(e.gather_plan(
scalar.context,
h.checked_subspan(scratch.bytes, scalar.layout.offsets[12], t * 4)?,
h.checked_subspan(scratch.bytes, scalar.layout.offsets[2], t * 10240)?,
t,
)?);
}
let (wh, embedding) = Self::prefix_roles(scalar, ring, &retained)?;
self.prefix_check_shape(scalar, ring, t, step_row)?;
let prefix_policy = Self::prefix_scalar_policy(policy);
let a = self.prefix_addresses(scalar, t, step_row)?;
let mut cmds = Self::prefix_start(scalar)?;
let native_embedding = Self::prefix_native_embedding(scalar, &retained, t)?;
if let Some(embedding) = embedding {
let eh = embedding.table.handle.ok_or(Error::ContextPoisoned)?;
match embedding.kind {
EmbeddingKind::Native { kind, row_bytes, .. } => OriginalMtpScalarPrefill::kernel(
&mut cmds,
1,
0,
[10, t as u32, 1],
[32, 1, 1],
0,
vec![
Arg::I32(kind),
Arg::U64(eh.qwen_address()),
Arg::U64(row_bytes as u64),
Arg::U64(tok),
Arg::I64(2560),
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),
],
)?
}
}
Self::prefix_embedding_lookup(&mut cmds, embedding, &a, t)?;
}
scalar.finite(&mut cmds, emb, t * 2560, group, 0)?;
OriginalMtpScalarPrefill::kernel(
&mut cmds,
3,
0,
[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)],
)?;
scalar.finite(&mut cmds, en, t * 2560, group, 1)?;
let q = scalar.address(15, 8 * 80 * 36)?;
OriginalMtpScalarPrefill::quant(&mut cmds, en, q, t)?;
scalar.q8_guard(&mut cmds, q, t, group, 2)?;
OriginalMtpScalarPrefill::project(&mut cmds, wh[1].qwen_address(), q, e2, t, 2560)?;
scalar.finite(&mut cmds, e2, t * 2560, group, 2)?;
OriginalMtpScalarPrefill::kernel(
&mut cmds,
3,
0,
[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)],
)?;
scalar.finite(&mut cmds, hn, t * 10240, group, 3)?;
for hc in (0..t * 4).step_by(8) {
let cols = 8.min(t * 4 - hc);
OriginalMtpScalarPrefill::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?;
scalar.q8_guard(&mut cmds, q, cols, group, 4)?;
OriginalMtpScalarPrefill::project(
&mut cmds,
wh[3].qwen_address(),
q,
h2 + (hc * 10240) as u64,
cols,
2560,
)?;
}
scalar.finite(&mut cmds, h2, t * 10240, group, 4)?;
OriginalMtpScalarPrefill::kernel(
&mut cmds,
0,
4,
[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)],
)?;
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(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)?;
OriginalMtpScalarPrefill::quant(&mut cmds, mixed, q, t)?;
scalar.q8_guard(&mut cmds, q, t, group, 9)?;
let (kc, vc) = scalar.current_kv(ring)?;
OriginalMtpScalarPrefill::project(&mut cmds, wh[7].qwen_address(), q, kc, t, 512)?;
scalar.finite(&mut cmds, kc, t * 512, group, 10)?;
OriginalMtpScalarPrefill::project(&mut cmds, wh[8].qwen_address(), q, vc, t, 512)?;
scalar.finite(&mut cmds, vc, t * 512, group, 11)?;
for row in 0..t {
let k = kc + (row * 2048) as u64;
OriginalMtpScalarPrefill::kernel(
&mut cmds,
2,
9,
[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)],
)?;
scalar.finite(&mut cmds, k, 512, group, 12)?;
OriginalMtpScalarPrefill::kernel(
&mut cmds,
3,
1,
[4, 2, 1],
[32, 1, 1],
0,
vec![
Arg::U64(k),
Arg::U64(k),
Arg::I32(2),
Arg::I32(256),
Arg::I32(64),
Arg::F32(kv.theta_scale),
Arg::F32(kv.freq_scale),
Arg::F32(kv.corr_low),
Arg::F32(kv.corr_high),
Arg::F32(kv.ext_factor),
Arg::F32(kv.mscale),
Arg::U64(pos + (row * 96) as u64),
Arg::U64(0),
Arg::Words3([0; 3]),
],
)?;
scalar.finite(&mut cmds, k, 512, group, 13)?;
let mut host = [0u64; 8];
host[2..6].copy_from_slice(&ring.host_addresses()?);
// Literal step append kernel and actual private step record, not batched prompt arithmetic.
OriginalMtpScalarPrefill::kernel(
&mut cmds,
5,
0,
[2, 4, 2],
[64, 1, 1],
0,
vec![
Arg::U64(ring.address(0)?),
Arg::U64(ring.address(1)?),
Arg::U64(ring.address(2)?),
Arg::U64(ring.address(3)?),
Arg::U64(ring.address(4)?),
Arg::U64(step + (row * 16) as u64),
Arg::U64(k),
Arg::U64(vc + (row * 2048) as u64),
Arg::I32(2),
Arg::I32(256),
Arg::I32(4),
Arg::U64(host[2]),
Arg::U64(host[3]),
Arg::U64(host[4]),
Arg::U64(host[5]),
],
)?;
}
OriginalMtpScalarPrefill::kernel(
&mut cmds,
3,
3,
[64, 1, 1],
[256, 1, 1],
0,
vec![
Arg::U64(ring.address(2)?),
Arg::U64(ring.address(3)?),
Arg::U64(ring.address(4)?),
Arg::U64(step),
Arg::I32(t as i32),
Arg::U64(scalar.flag(0, 14)?),
],
)?;
let q = Self::prefix_embedding_branch(scalar, &mut cmds, &a, &wh, t)?;
Self::prefix_hidden_branch(scalar, &mut cmds, &a, &wh, (q, t))?;
Self::prefix_mix_and_gr(scalar, &mut cmds, &a, &wh, (t, &prefix_policy))?;
Self::prefix_tail(scalar, ring, &mut cmds, &a, (&policy.kv, &wh, q, t))?;
Ok((cmds, native_embedding))
}
}
@@ -15,70 +15,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
native_embedding: Option<OriginalMtpNativeGather<'ctx>>,
step_row: usize,
) -> Result<OriginalMtpForwardProgram<'ctx>> {
validate_scalar_prefix(scalar)?;
ring.validate_context(self.inner.context)?;
self.validate_context(scalar.context)?;
let scratch = self.inner.scratch.as_ref().ok_or(Error::ContextPoisoned)?;
ring.reject_state_alias(scratch)?;
let sh = scratch.handle.ok_or(Error::ContextPoisoned)?;
for b in self
.inner
.weights
.prefix
.roles
.iter()
.chain(self.inner.weights.roles.iter())
.chain([&self.inner.weights.experts, &self.inner.weights.head])
.chain([
scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?,
scalar.status.as_ref().ok_or(Error::ContextPoisoned)?,
scalar.records.as_ref().ok_or(Error::ContextPoisoned)?,
])
{
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 {
return Err(Error::OutputAliasesInput);
}
}
}
if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) {
return Err(Error::InvalidQwenShape);
}
for extra in self.inner.extras.iter().flatten() {
ring.reject_state_alias(extra)?;
let h = extra.handle.ok_or(Error::ContextPoisoned)?;
for b in self
.inner
.weights
.prefix
.roles
.iter()
.chain(self.inner.weights.roles.iter())
.chain([&self.inner.weights.experts, &self.inner.weights.head])
.chain([
scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?,
scalar.status.as_ref().ok_or(Error::ContextPoisoned)?,
scalar.records.as_ref().ok_or(Error::ContextPoisoned)?,
])
{
ring.reject_state_alias(b)?;
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) {
return Err(Error::OutputAliasesInput);
}
}
}
for b in ring.buffers()?.iter().flatten() {
if sh.overlaps(scratch.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) {
return Err(Error::OutputAliasesInput);
}
}
self.program_reject_aliases(scalar, ring)?;
let p = ForwardPrefix {
scalar,
ring,
@@ -90,32 +27,17 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
inj: scalar.address(10, 16)?,
};
let commands = self.plan(&p, policy)?;
let mut modules = Vec::new();
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)?));
}
let modules = Self::program_modules(scalar)?;
let window = abi::Arguments::new(vec![
abi::Arg::U64(p.step),
abi::Arg::I32(32768),
abi::Arg::U64(self.inner.attention(ring)?.3),
abi::Arg::I64(32768),
])?;
let coupled_stage = if policy.coupled_j == Some(0) {
let base = self.inner.max_t * 236 + 384;
Some(FA::new(vec![
F::U64(self.inner.mapped_address(base, 64)?),
F::U64(self.inner.mapped_address(base + 64, 4096 * 4)?),
F::U64(self.inner.address(28)?),
F::U64(self.inner.address(29)?),
F::I32(4096),
])?)
} else {
None
};
let coupled_stage = self.program_coupled_stage(policy)?;
Ok(OriginalMtpForwardProgram {
context: scalar.context,
prefix_modules: modules.try_into().map_err(|_| Error::InvalidSize)?,
prefix_modules: modules,
prefix_scratch: Rc::clone(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?),
prefix_status: Rc::clone(scalar.status.as_ref().ok_or(Error::ContextPoisoned)?),
prefix_records: Rc::clone(scalar.records.as_ref().ok_or(Error::ContextPoisoned)?),
@@ -134,4 +56,107 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
token_address: scalar.address(12, 4)?,
})
}
/// Every buffer the full-forward scratch must not alias: all prefix and tail weights, the expert bank, the head
/// and the scalar scratch, status and records.
fn program_buffers<'a>(
&'a self,
scalar: &'a OriginalMtpScalarPrefill<'ctx>,
) -> Result<impl Iterator<Item = &'a Rc<DeviceBuffer<'ctx>>> + 'a> {
Ok(self
.inner
.weights
.prefix
.roles
.iter()
.chain(self.inner.weights.roles.iter())
.chain([&self.inner.weights.experts, &self.inner.weights.head])
.chain([
scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?,
scalar.status.as_ref().ok_or(Error::ContextPoisoned)?,
scalar.records.as_ref().ok_or(Error::ContextPoisoned)?,
]))
}
/// The tail scratch, the extra banks and the ring state may overlap nothing but the genuinely shared scalar
/// scratch.
fn program_reject_aliases(
&self,
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
) -> Result<()> {
validate_scalar_prefix(scalar)?;
ring.validate_context(self.inner.context)?;
self.validate_context(scalar.context)?;
let scratch = self.inner.scratch.as_ref().ok_or(Error::ContextPoisoned)?;
ring.reject_state_alias(scratch)?;
let sh = scratch.handle.ok_or(Error::ContextPoisoned)?;
for b in self.program_buffers(scalar)? {
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 {
return Err(Error::OutputAliasesInput);
}
}
}
if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) {
return Err(Error::InvalidQwenShape);
}
for extra in self.inner.extras.iter().flatten() {
self.program_reject_extra_alias(scalar, ring, extra)?;
}
for b in ring.buffers()?.iter().flatten() {
if sh.overlaps(scratch.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) {
return Err(Error::OutputAliasesInput);
}
}
Ok(())
}
fn program_reject_extra_alias(
&self,
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
extra: &DeviceBuffer<'ctx>,
) -> Result<()> {
ring.reject_state_alias(extra)?;
let h = extra.handle.ok_or(Error::ContextPoisoned)?;
for b in self.program_buffers(scalar)? {
ring.reject_state_alias(b)?;
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) {
return Err(Error::OutputAliasesInput);
}
}
Ok(())
}
/// The six scalar-prefix modules the program retains.
fn program_modules(scalar: &OriginalMtpScalarPrefill<'ctx>) -> Result<[Rc<Module>; 6]> {
let mut modules = Vec::new();
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)?));
}
modules.try_into().map_err(|_| Error::InvalidSize)
}
/// The staging arguments of a coupled draft whose sampler runs at step 0.
fn program_coupled_stage(&self, policy: &OriginalMtpFullPolicy) -> Result<Option<FA>> {
if policy.coupled_j != Some(0) {
return Ok(None);
}
let base = self.inner.max_t * 236 + 384;
Ok(Some(FA::new(vec![
F::U64(self.inner.mapped_address(base, 64)?),
F::U64(self.inner.mapped_address(base + 64, 4096 * 4)?),
F::U64(self.inner.address(28)?),
F::U64(self.inner.address(29)?),
F::I32(4096),
])?))
}
}
@@ -0,0 +1,345 @@
//! Phases of `OriginalMtpFullForward::prefix_commands`, split out by STRA-338 (size). Each helper keeps the
//! original statement order, so the command list and the error precedence are unchanged.
#[allow(unused_imports)]
use super::*;
/// Device addresses of the scratch regions and step records that one prefix build touches.
pub(super) struct PrefixAddrs {
pub(super) rin: u64,
pub(super) emb: u64,
pub(super) en: u64,
pub(super) e2: u64,
pub(super) hn: u64,
pub(super) h2: u64,
pub(super) r: u64,
pub(super) mixed: u64,
pub(super) tok: u64,
pub(super) step: u64,
pub(super) pos: u64,
}
const PREFIX_WEIGHT_EXTENTS: [usize; 11] = [
10240,
2560 * 80 * 34,
40960,
2560 * 80 * 34,
40960,
320 * 10240 * 2,
10240 * 320 * 2,
512 * 80 * 34,
512 * 80 * 34,
1024,
4 * 10240 * 2,
];
impl<'ctx> OriginalMtpFullForward<'ctx> {
pub(super) fn prefix_preflight(
&self,
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
policy: &OriginalMtpFullPolicy,
) -> Result<()> {
self.validate_context(scalar.context)?;
validate_scalar_prefix(scalar)?;
ring.validate_context(scalar.context)?;
policy.validate_selected()?;
if scalar.has_pending {
return Err(Error::InvalidQwenShape);
}
if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) {
return Err(Error::InvalidQwenShape);
}
Ok(())
}
/// Validates the main ring and every prefix weight against its extent; returns the weight handles.
fn prefix_weight_handles(
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
wr: &[&DeviceBuffer<'ctx>; 11],
) -> Result<[BufferHandle; 11]> {
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 mut wh = [eh; 11];
for i in 0..11 {
checked(scalar.context, wr[i], PREFIX_WEIGHT_EXTENTS[i])?;
wh[i] = wr[i].handle.ok_or(Error::ContextPoisoned)?;
}
Ok(wh)
}
/// No weight (or the embedding table) may overlap a scratch, status, record or ring-state output.
fn prefix_reject_aliases(
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
wr: [&DeviceBuffer<'ctx>; 11],
embedding: Option<&OriginalMtpEmbedding<'_, 'ctx>>,
) -> Result<()> {
for b in wr.into_iter().chain(embedding.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) {
return Err(Error::OutputAliasesInput);
}
}
Self::prefix_reject_ring_overlap(ring, h, b.bytes)?;
}
Ok(())
}
fn prefix_reject_ring_overlap(ring: &MtpOriginalInt8<'ctx>, h: BufferHandle, bytes: usize) -> Result<()> {
for output in ring.buffers()?.iter().flatten() {
if h.overlaps(bytes, output.handle.ok_or(Error::ContextPoisoned)?, output.bytes) {
return Err(Error::OutputAliasesInput);
}
}
Ok(())
}
/// Validates the retained prefix roles against the scalar scratch and ring; returns their handles and the
/// device embedding loan (none for a native mapped embedding).
pub(super) fn prefix_roles<'a>(
scalar: &'a OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
retained: &'a OriginalMtpRetainedPrefix<'ctx>,
) -> Result<([BufferHandle; 11], Option<OriginalMtpEmbedding<'a, 'ctx>>)> {
retained.validate_context(scalar.context)?;
let weights = &retained.roles;
let embedding = match &retained.embedding {
PrefixEmbedding::Device { bank } => Some(bank.loans(scalar.context)?.1),
PrefixEmbedding::Native(_) => None,
};
let wr = weights.each_ref().map(|b| Rc::as_ref(b));
let wh = Self::prefix_weight_handles(scalar, ring, &wr)?;
Self::prefix_reject_aliases(scalar, ring, wr, embedding.as_ref())?;
Ok((wh, embedding))
}
/// Command list with its reserved capacity and the leading flag-clearing kernel.
pub(super) fn prefix_start(scalar: &OriginalMtpScalarPrefill<'ctx>) -> Result<Vec<ScalarCommand>> {
let mut cmds = Vec::new();
cmds.try_reserve_exact(128).map_err(|_| Error::HostAllocation)?;
OriginalMtpScalarPrefill::kernel(
&mut cmds,
0,
11,
[1, 1, 1],
[256, 1, 1],
0,
vec![Arg::U64(scalar.flag(0, 0)?), Arg::I32(16)],
)?;
Ok(cmds)
}
pub(super) fn prefix_check_shape(
&self,
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
t: usize,
step_row: usize,
) -> Result<()> {
if t == 0
|| t > self.inner.max_t
|| t > scalar.max_t
|| t > ring.max_t
// Window ring (mtp.cpp: ring = window + 4 * max_t + 64 cells, 4 per
// slot) or the Original fully-resident retry (one slot per page).
|| (ring.slots != (MTP_ORIGINAL_WINDOW + 4 * ring.max_t + 64).div_ceil(4)
&& ring.slots != MTP_ORIGINAL_MAX_CELLS / 4)
|| step_row
.checked_add(t)
.is_none_or(|n| n > 2 * self.inner.max_t)
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
pub(super) fn prefix_scalar_policy(policy: &OriginalMtpFullPolicy) -> OriginalMtpScalarPolicy {
let kv = &policy.kv;
OriginalMtpScalarPolicy {
gr: policy.gr,
per_group_sync: false,
kv: DraftKvPolicy {
disabled: kv.disabled,
hybrid: kv.hybrid,
rotated: kv.rotated,
q4: kv.q4,
alternate_f16: kv.alternate_f16,
mode: kv.mode,
rope_table_enabled: kv.rope_table_enabled,
multimodal_positions: kv.multimodal_positions,
theta_scale: kv.theta_scale,
freq_scale: kv.freq_scale,
corr_low: kv.corr_low,
corr_high: kv.corr_high,
ext_factor: kv.ext_factor,
mscale: kv.mscale,
},
}
}
pub(super) fn prefix_addresses(
&self,
scalar: &OriginalMtpScalarPrefill<'ctx>,
t: usize,
step_row: usize,
) -> Result<PrefixAddrs> {
let [rin, emb, en, e2, hn, h2, r, mixed, tok] = Self::prefix_scalar_addresses(scalar, t)?;
let step = self.inner.address(31)? + (step_row * 16) as u64;
let pos = self.inner.address(32)? + (step_row * 96) as u64;
Ok(PrefixAddrs { rin, emb, en, e2, hn, h2, r, mixed, tok, step, pos })
}
/// `[rin, emb, en, e2, hn, h2, r, mixed, tok]` scratch addresses of the scalar owner.
fn prefix_scalar_addresses(scalar: &OriginalMtpScalarPrefill<'ctx>, t: usize) -> Result<[u64; 9]> {
Ok([
scalar.address(0, t * 40960)?,
scalar.address(2, t * 10240)?,
scalar.address(3, t * 10240)?,
scalar.address(4, t * 10240)?,
scalar.address(5, t * 40960)?,
scalar.address(6, t * 40960)?,
scalar.address(1, t * 40960)?,
scalar.address(11, t * 10240)?,
scalar.address(12, t * 4)?,
])
}
pub(super) fn prefix_native_embedding(
scalar: &OriginalMtpScalarPrefill<'ctx>,
retained: &OriginalMtpRetainedPrefix<'ctx>,
t: usize,
) -> Result<Option<OriginalMtpNativeGather<'ctx>>> {
let mut native_embedding = None;
if let PrefixEmbedding::Native(e) = &retained.embedding {
let scratch = scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?;
let h = scratch.handle.ok_or(Error::ContextPoisoned)?;
native_embedding = Some(e.gather_plan(
scalar.context,
h.checked_subspan(scratch.bytes, scalar.layout.offsets[12], t * 4)?,
h.checked_subspan(scratch.bytes, scalar.layout.offsets[2], t * 10240)?,
t,
)?);
}
Ok(native_embedding)
}
/// RMS norm of `rows` rows of `width` floats (eps 1e-6).
fn prefix_rms_norm(
cmds: &mut Vec<ScalarCommand>,
rows: usize,
(input, weight, out): (u64, u64, u64),
width: i32,
) -> Result<()> {
OriginalMtpScalarPrefill::kernel(
cmds,
3,
0,
[rows as u32, 1, 1],
[1024, 1, 1],
0,
vec![Arg::U64(input), Arg::U64(weight), Arg::U64(out), Arg::I32(width), Arg::F32(1e-6)],
)
}
/// Embedding norm and its projection into `e2`; returns the Q8 scratch address.
pub(super) fn prefix_embedding_branch(
scalar: &OriginalMtpScalarPrefill<'ctx>,
cmds: &mut Vec<ScalarCommand>,
a: &PrefixAddrs,
wh: &[BufferHandle; 11],
t: usize,
) -> Result<u64> {
let group = 0usize;
scalar.finite(cmds, a.emb, t * 2560, group, 0)?;
Self::prefix_rms_norm(cmds, t, (a.emb, wh[0].qwen_address(), a.en), 2560)?;
scalar.finite(cmds, a.en, t * 2560, group, 1)?;
let q = scalar.address(15, 8 * 80 * 36)?;
OriginalMtpScalarPrefill::quant(cmds, a.en, q, t)?;
scalar.q8_guard(cmds, q, t, group, 2)?;
OriginalMtpScalarPrefill::project(cmds, wh[1].qwen_address(), q, a.e2, t, 2560)?;
scalar.finite(cmds, a.e2, t * 2560, group, 2)?;
Ok(q)
}
/// Hidden-state norm and its projection into `h2`, eight columns at a time.
pub(super) fn prefix_hidden_branch(
scalar: &OriginalMtpScalarPrefill<'ctx>,
cmds: &mut Vec<ScalarCommand>,
a: &PrefixAddrs,
wh: &[BufferHandle; 11],
(q, t): (u64, usize),
) -> Result<()> {
let group = 0usize;
Self::prefix_rms_norm(cmds, t, (a.rin, wh[2].qwen_address(), a.hn), 10240)?;
scalar.finite(cmds, a.hn, t * 10240, group, 3)?;
for hc in (0..t * 4).step_by(8) {
let cols = 8.min(t * 4 - hc);
OriginalMtpScalarPrefill::quant(cmds, a.hn + (hc * 10240) as u64, q, cols)?;
scalar.q8_guard(cmds, q, cols, group, 4)?;
OriginalMtpScalarPrefill::project(cmds, wh[3].qwen_address(), q, a.h2 + (hc * 10240) as u64, cols, 2560)?;
}
scalar.finite(cmds, a.h2, t * 10240, group, 4)?;
Ok(())
}
/// Residual mix of the two branches, the GR block and the finite guards over its outputs.
pub(super) fn prefix_mix_and_gr(
scalar: &OriginalMtpScalarPrefill<'ctx>,
cmds: &mut Vec<ScalarCommand>,
a: &PrefixAddrs,
wh: &[BufferHandle; 11],
(t, policy): (usize, &OriginalMtpScalarPolicy),
) -> Result<()> {
let group = 0usize;
OriginalMtpScalarPrefill::kernel(
cmds,
0,
4,
[40, t as u32, 1],
[256, 1, 1],
0,
vec![Arg::U64(a.h2), Arg::U64(a.e2), Arg::U64(a.r), Arg::I64(2560), Arg::I32(4)],
)?;
scalar.finite(cmds, a.r, t * 10240, group, 5)?;
scalar.gr(cmds, t, wh, policy)?;
Self::prefix_gr_guards(scalar, cmds, a.mixed, t)
}
/// Finite guards over the GR outputs and the mixed state.
fn prefix_gr_guards(
scalar: &OriginalMtpScalarPrefill<'ctx>,
cmds: &mut Vec<ScalarCommand>,
mixed: u64,
t: usize,
) -> Result<()> {
let group = 0usize;
scalar.finite(cmds, scalar.address(9, t * 16)?, t * 4, group, 6)?;
scalar.finite(cmds, scalar.address(7, t * 40960)?, t * 10240, group, 6)?;
scalar.finite(cmds, scalar.address(8, t * 1280)?, t * 320, group, 7)?;
scalar.finite(cmds, scalar.address(10, t * 16)?, t * 4, group, 7)?;
scalar.finite(cmds, mixed, t * 2560, group, 8)
}
/// K and V projections of the mixed state into the current KV cells; returns `(k, v)` addresses.
pub(super) fn prefix_kv_projection(
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
cmds: &mut Vec<ScalarCommand>,
a: &PrefixAddrs,
(wh, q, t): (&[BufferHandle; 11], u64, usize),
) -> Result<(u64, u64)> {
let group = 0usize;
OriginalMtpScalarPrefill::quant(cmds, a.mixed, q, t)?;
scalar.q8_guard(cmds, q, t, group, 9)?;
let (kc, vc) = scalar.current_kv(ring)?;
OriginalMtpScalarPrefill::project(cmds, wh[7].qwen_address(), q, kc, t, 512)?;
scalar.finite(cmds, kc, t * 512, group, 10)?;
OriginalMtpScalarPrefill::project(cmds, wh[8].qwen_address(), q, vc, t, 512)?;
scalar.finite(cmds, vc, t * 512, group, 11)?;
Ok((kc, vc))
}
}
@@ -0,0 +1,207 @@
//! Embedding lookup, per-row and closing commands of `OriginalMtpFullForward::prefix_commands` (STRA-338 size).
use super::prefix_parts::PrefixAddrs;
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalMtpFullForward<'ctx> {
/// Embedding row lookup of the `t` token ids into `emb`, for a device-resident embedding table.
pub(super) fn prefix_embedding_lookup(
cmds: &mut Vec<ScalarCommand>,
embedding: OriginalMtpEmbedding<'_, 'ctx>,
a: &PrefixAddrs,
t: usize,
) -> Result<()> {
let eh = embedding.table.handle.ok_or(Error::ContextPoisoned)?;
match embedding.kind {
EmbeddingKind::Native { kind, row_bytes, .. } => {
Self::prefix_lookup_native(cmds, a, (eh.qwen_address(), kind, row_bytes), t)
}
EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => {
let layout = (eh.qwen_address(), codes, if offsets { Some(scales) } else { None });
Self::prefix_lookup_compressed(cmds, a, (layout, bits, bias, group), t)
}
}
}
fn prefix_lookup_native(
cmds: &mut Vec<ScalarCommand>,
a: &PrefixAddrs,
(table, kind, row_bytes): (u64, i32, usize),
t: usize,
) -> Result<()> {
OriginalMtpScalarPrefill::kernel(
cmds,
1,
0,
[10, t as u32, 1],
[32, 1, 1],
0,
vec![
Arg::I32(kind),
Arg::U64(table),
Arg::U64(row_bytes as u64),
Arg::U64(a.tok),
Arg::I64(2560),
Arg::U64(a.emb),
],
)
}
/// `layout` is `(table address, code bytes, scale bytes when offsets follow)`.
fn prefix_lookup_compressed(
cmds: &mut Vec<ScalarCommand>,
a: &PrefixAddrs,
((table, codes, offsets), bits, bias, group): ((u64, usize, Option<usize>), i32, i32, usize),
t: usize,
) -> Result<()> {
OriginalMtpScalarPrefill::kernel(
cmds,
0,
5,
[10, t as u32, 1],
[256, 1, 1],
0,
vec![
Arg::U64(table),
Arg::U64(table + codes as u64),
Arg::U64(if let Some(scales) = offsets { table + (codes + scales) as u64 } else { 0 }),
Arg::U64(a.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(a.emb),
],
)
}
/// K/V projection, the per-row commands and the closing step publication.
pub(super) fn prefix_tail(
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
cmds: &mut Vec<ScalarCommand>,
a: &PrefixAddrs,
(kv, wh, q, t): (&DraftKvPolicy, &[BufferHandle; 11], u64, usize),
) -> Result<()> {
let (kc, vc) = Self::prefix_kv_projection(scalar, ring, cmds, a, (wh, q, t))?;
for row in 0..t {
Self::prefix_row_commands(scalar, ring, cmds, a, (kv, wh, kc, vc, row))?;
}
Self::prefix_publish_steps(scalar, ring, cmds, (a.step, t))
}
/// Per-row K norm, K rope, and the literal step append kernel on the actual private step record.
pub(super) fn prefix_row_commands(
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
cmds: &mut Vec<ScalarCommand>,
a: &PrefixAddrs,
(kv, wh, kc, vc, row): (&DraftKvPolicy, &[BufferHandle; 11], u64, u64, usize),
) -> Result<()> {
let group = 0usize;
let k = kc + (row * 2048) as u64;
OriginalMtpScalarPrefill::kernel(
cmds,
2,
9,
[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)],
)?;
scalar.finite(cmds, k, 512, group, 12)?;
Self::prefix_row_rope(cmds, kv, k, a.pos + (row * 96) as u64)?;
scalar.finite(cmds, k, 512, group, 13)?;
Self::prefix_step_append(cmds, ring, (a.step + (row * 16) as u64, k, vc + (row * 2048) as u64))
}
fn prefix_step_append(
cmds: &mut Vec<ScalarCommand>,
ring: &MtpOriginalInt8<'ctx>,
(step, k, v): (u64, u64, u64),
) -> Result<()> {
let mut host = [0u64; 8];
host[2..6].copy_from_slice(&ring.host_addresses()?);
// Literal step append kernel and actual private step record, not batched prompt arithmetic.
OriginalMtpScalarPrefill::kernel(
cmds,
5,
0,
[2, 4, 2],
[64, 1, 1],
0,
vec![
Arg::U64(ring.address(0)?),
Arg::U64(ring.address(1)?),
Arg::U64(ring.address(2)?),
Arg::U64(ring.address(3)?),
Arg::U64(ring.address(4)?),
Arg::U64(step),
Arg::U64(k),
Arg::U64(v),
Arg::I32(2),
Arg::I32(256),
Arg::I32(4),
Arg::U64(host[2]),
Arg::U64(host[3]),
Arg::U64(host[4]),
Arg::U64(host[5]),
],
)
}
fn prefix_row_rope(cmds: &mut Vec<ScalarCommand>, kv: &DraftKvPolicy, k: u64, position: u64) -> Result<()> {
OriginalMtpScalarPrefill::kernel(
cmds,
3,
1,
[4, 2, 1],
[32, 1, 1],
0,
vec![
Arg::U64(k),
Arg::U64(k),
Arg::I32(2),
Arg::I32(256),
Arg::I32(64),
Arg::F32(kv.theta_scale),
Arg::F32(kv.freq_scale),
Arg::F32(kv.corr_low),
Arg::F32(kv.corr_high),
Arg::F32(kv.ext_factor),
Arg::F32(kv.mscale),
Arg::U64(position),
Arg::U64(0),
Arg::Words3([0; 3]),
],
)
}
/// Final step-record kernel that publishes the `t` appended rows.
pub(super) fn prefix_publish_steps(
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
cmds: &mut Vec<ScalarCommand>,
(step, t): (u64, usize),
) -> Result<()> {
OriginalMtpScalarPrefill::kernel(
cmds,
3,
3,
[64, 1, 1],
[256, 1, 1],
0,
vec![
Arg::U64(ring.address(2)?),
Arg::U64(ring.address(3)?),
Arg::U64(ring.address(4)?),
Arg::U64(step),
Arg::I32(t as i32),
Arg::U64(scalar.flag(0, 14)?),
],
)
}
}
@@ -1,5 +1,349 @@
use super::*;
use crate::NativeHeadDispatch;
/// Kernel names of the IQ head kernels: `[old, c1, c2, c4, c8]` (kind 7 has the old kernel only).
const IQ_NAMES: [(u32, &[&str]); 7] = [
(7, &["head_i7_old"]),
(16, &["head_i16_old", "head_i16_c1", "head_i16_c2", "head_i16_c4", "head_i16_c8"]),
(17, &["head_i17_old", "head_i17_c1", "head_i17_c2", "head_i17_c4", "head_i17_c8"]),
(18, &["head_i18_old", "head_i18_c1", "head_i18_c2", "head_i18_c4", "head_i18_c8"]),
(21, &["head_i21_old", "head_i21_c1", "head_i21_c2", "head_i21_c4", "head_i21_c8"]),
(22, &["head_i22_old", "head_i22_c1", "head_i22_c2", "head_i22_c4", "head_i22_c8"]),
(29, &["head_i29_old", "head_i29_c1", "head_i29_c2", "head_i29_c4", "head_i29_c8"]),
];
/// Kernel names of the native head kernels per kind: `[s1, s0]` for one token, then
/// `[upstream, small, large]` for each token count 2..=8 (index `2 + (t - 2) * 3 + mode - 2`).
const HEAD_NAMES_PER_KIND: usize = 23;
const HEAD_N2: [&str; HEAD_NAMES_PER_KIND] = [
"head_n2_s1",
"head_n2_s0",
"head_n2_t2_upstream",
"head_n2_t2_small",
"head_n2_t2_large",
"head_n2_t3_upstream",
"head_n2_t3_small",
"head_n2_t3_large",
"head_n2_t4_upstream",
"head_n2_t4_small",
"head_n2_t4_large",
"head_n2_t5_upstream",
"head_n2_t5_small",
"head_n2_t5_large",
"head_n2_t6_upstream",
"head_n2_t6_small",
"head_n2_t6_large",
"head_n2_t7_upstream",
"head_n2_t7_small",
"head_n2_t7_large",
"head_n2_t8_upstream",
"head_n2_t8_small",
"head_n2_t8_large",
];
const HEAD_N6: [&str; HEAD_NAMES_PER_KIND] = [
"head_n6_s1",
"head_n6_s0",
"head_n6_t2_upstream",
"head_n6_t2_small",
"head_n6_t2_large",
"head_n6_t3_upstream",
"head_n6_t3_small",
"head_n6_t3_large",
"head_n6_t4_upstream",
"head_n6_t4_small",
"head_n6_t4_large",
"head_n6_t5_upstream",
"head_n6_t5_small",
"head_n6_t5_large",
"head_n6_t6_upstream",
"head_n6_t6_small",
"head_n6_t6_large",
"head_n6_t7_upstream",
"head_n6_t7_small",
"head_n6_t7_large",
"head_n6_t8_upstream",
"head_n6_t8_small",
"head_n6_t8_large",
];
const HEAD_N8: [&str; HEAD_NAMES_PER_KIND] = [
"head_n8_s1",
"head_n8_s0",
"head_n8_t2_upstream",
"head_n8_t2_small",
"head_n8_t2_large",
"head_n8_t3_upstream",
"head_n8_t3_small",
"head_n8_t3_large",
"head_n8_t4_upstream",
"head_n8_t4_small",
"head_n8_t4_large",
"head_n8_t5_upstream",
"head_n8_t5_small",
"head_n8_t5_large",
"head_n8_t6_upstream",
"head_n8_t6_small",
"head_n8_t6_large",
"head_n8_t7_upstream",
"head_n8_t7_small",
"head_n8_t7_large",
"head_n8_t8_upstream",
"head_n8_t8_small",
"head_n8_t8_large",
];
const HEAD_N20: [&str; HEAD_NAMES_PER_KIND] = [
"head_n20_s1",
"head_n20_s0",
"head_n20_t2_upstream",
"head_n20_t2_small",
"head_n20_t2_large",
"head_n20_t3_upstream",
"head_n20_t3_small",
"head_n20_t3_large",
"head_n20_t4_upstream",
"head_n20_t4_small",
"head_n20_t4_large",
"head_n20_t5_upstream",
"head_n20_t5_small",
"head_n20_t5_large",
"head_n20_t6_upstream",
"head_n20_t6_small",
"head_n20_t6_large",
"head_n20_t7_upstream",
"head_n20_t7_small",
"head_n20_t7_large",
"head_n20_t8_upstream",
"head_n20_t8_small",
"head_n20_t8_large",
];
const HEAD_N11: [&str; HEAD_NAMES_PER_KIND] = [
"head_n11_s1",
"head_n11_s0",
"head_n11_t2_upstream",
"head_n11_t2_small",
"head_n11_t2_large",
"head_n11_t3_upstream",
"head_n11_t3_small",
"head_n11_t3_large",
"head_n11_t4_upstream",
"head_n11_t4_small",
"head_n11_t4_large",
"head_n11_t5_upstream",
"head_n11_t5_small",
"head_n11_t5_large",
"head_n11_t6_upstream",
"head_n11_t6_small",
"head_n11_t6_large",
"head_n11_t7_upstream",
"head_n11_t7_small",
"head_n11_t7_large",
"head_n11_t8_upstream",
"head_n11_t8_small",
"head_n11_t8_large",
];
const HEAD_N12: [&str; HEAD_NAMES_PER_KIND] = [
"head_n12_s1",
"head_n12_s0",
"head_n12_t2_upstream",
"head_n12_t2_small",
"head_n12_t2_large",
"head_n12_t3_upstream",
"head_n12_t3_small",
"head_n12_t3_large",
"head_n12_t4_upstream",
"head_n12_t4_small",
"head_n12_t4_large",
"head_n12_t5_upstream",
"head_n12_t5_small",
"head_n12_t5_large",
"head_n12_t6_upstream",
"head_n12_t6_small",
"head_n12_t6_large",
"head_n12_t7_upstream",
"head_n12_t7_small",
"head_n12_t7_large",
"head_n12_t8_upstream",
"head_n12_t8_small",
"head_n12_t8_large",
];
const HEAD_N13: [&str; HEAD_NAMES_PER_KIND] = [
"head_n13_s1",
"head_n13_s0",
"head_n13_t2_upstream",
"head_n13_t2_small",
"head_n13_t2_large",
"head_n13_t3_upstream",
"head_n13_t3_small",
"head_n13_t3_large",
"head_n13_t4_upstream",
"head_n13_t4_small",
"head_n13_t4_large",
"head_n13_t5_upstream",
"head_n13_t5_small",
"head_n13_t5_large",
"head_n13_t6_upstream",
"head_n13_t6_small",
"head_n13_t6_large",
"head_n13_t7_upstream",
"head_n13_t7_small",
"head_n13_t7_large",
"head_n13_t8_upstream",
"head_n13_t8_small",
"head_n13_t8_large",
];
const HEAD_N14: [&str; HEAD_NAMES_PER_KIND] = [
"head_n14_s1",
"head_n14_s0",
"head_n14_t2_upstream",
"head_n14_t2_small",
"head_n14_t2_large",
"head_n14_t3_upstream",
"head_n14_t3_small",
"head_n14_t3_large",
"head_n14_t4_upstream",
"head_n14_t4_small",
"head_n14_t4_large",
"head_n14_t5_upstream",
"head_n14_t5_small",
"head_n14_t5_large",
"head_n14_t6_upstream",
"head_n14_t6_small",
"head_n14_t6_large",
"head_n14_t7_upstream",
"head_n14_t7_small",
"head_n14_t7_large",
"head_n14_t8_upstream",
"head_n14_t8_small",
"head_n14_t8_large",
];
const HEAD_N23: [&str; HEAD_NAMES_PER_KIND] = [
"head_n23_s1",
"head_n23_s0",
"head_n23_t2_upstream",
"head_n23_t2_small",
"head_n23_t2_large",
"head_n23_t3_upstream",
"head_n23_t3_small",
"head_n23_t3_large",
"head_n23_t4_upstream",
"head_n23_t4_small",
"head_n23_t4_large",
"head_n23_t5_upstream",
"head_n23_t5_small",
"head_n23_t5_large",
"head_n23_t6_upstream",
"head_n23_t6_small",
"head_n23_t6_large",
"head_n23_t7_upstream",
"head_n23_t7_small",
"head_n23_t7_large",
"head_n23_t8_upstream",
"head_n23_t8_small",
"head_n23_t8_large",
];
const HEAD_N42: [&str; HEAD_NAMES_PER_KIND] = [
"head_n42_s1",
"head_n42_s0",
"head_n42_t2_upstream",
"head_n42_t2_small",
"head_n42_t2_large",
"head_n42_t3_upstream",
"head_n42_t3_small",
"head_n42_t3_large",
"head_n42_t4_upstream",
"head_n42_t4_small",
"head_n42_t4_large",
"head_n42_t5_upstream",
"head_n42_t5_small",
"head_n42_t5_large",
"head_n42_t6_upstream",
"head_n42_t6_small",
"head_n42_t6_large",
"head_n42_t7_upstream",
"head_n42_t7_small",
"head_n42_t7_large",
"head_n42_t8_upstream",
"head_n42_t8_small",
"head_n42_t8_large",
];
fn iq_kernel_name(kind: u32, columns: usize, old: bool) -> Result<&'static str> {
let sel = match (old, columns) {
(true, _) => 0,
(false, 1) => 1,
(false, 2) => 2,
(false, 4) => 3,
(false, 8) => 4,
_ => return Err(Error::UnsupportedQwenOperation),
};
let names = IQ_NAMES.iter().find(|(k, _)| *k == kind).map(|(_, names)| *names);
names.and_then(|names| names.get(sel)).copied().ok_or(Error::UnsupportedQwenOperation)
}
/// `(div, bytes per item)` of the native head kernel family for `kind`.
fn native_head_geometry(kind: u32) -> Result<(usize, usize)> {
Ok(match kind {
2 | 6 | 20 => (32, 64),
8 => (32, 32),
11..=13 => (256, 8),
14 => (256, 4),
23 => (256, 16),
42 => (64, 64),
_ => return Err(Error::UnsupportedQwenOperation),
})
}
const HEAD_TABLES: [(u32, &[&str; HEAD_NAMES_PER_KIND]); 10] = [
(2, &HEAD_N2),
(6, &HEAD_N6),
(8, &HEAD_N8),
(20, &HEAD_N20),
(11, &HEAD_N11),
(12, &HEAD_N12),
(13, &HEAD_N13),
(14, &HEAD_N14),
(23, &HEAD_N23),
(42, &HEAD_N42),
];
fn native_kernel_name(kind: u32, t: usize, mode: usize) -> Result<&'static str> {
let names = HEAD_TABLES.iter().find(|(k, _)| *k == kind).map(|(_, names)| *names);
let names = names.ok_or(Error::UnsupportedQwenOperation)?;
let index = if t == 1 { mode } else { 2 + (t - 2) * 3 + (mode - 2) };
Ok(names[index])
}
fn iq_columns(t: usize) -> usize {
if t <= 2 {
t
} else if t <= 4 {
4
} else {
8
}
}
fn native_head_mode(t: usize, small: bool, upstream: bool) -> usize {
if t == 1 {
usize::from(!small)
} else if upstream {
2
} else if small {
3
} else {
4
}
}
fn native_head_rows(small: bool, upstream: bool) -> usize {
if upstream {
2
} else if small {
4
} else {
1
}
}
pub(super) fn head_dispatch(
kind: u32,
n: usize,
@@ -11,315 +355,14 @@ pub(super) fn head_dispatch(
return Err(Error::InvalidQwenShape);
}
if matches!(kind, 7 | 16 | 17 | 18 | 21 | 22 | 29) {
let columns = if t == 1 {
1
} else if t == 2 {
2
} else if t <= 4 {
4
} else {
8
};
let name = match (kind, if p.old_iq || kind == 7 { 0 } else { columns }) {
(7, 0) => "head_i7_old",
(16, 0) => "head_i16_old",
(16, 1) => "head_i16_c1",
(16, 2) => "head_i16_c2",
(16, 4) => "head_i16_c4",
(16, 8) => "head_i16_c8",
(17, 0) => "head_i17_old",
(17, 1) => "head_i17_c1",
(17, 2) => "head_i17_c2",
(17, 4) => "head_i17_c4",
(17, 8) => "head_i17_c8",
(18, 0) => "head_i18_old",
(18, 1) => "head_i18_c1",
(18, 2) => "head_i18_c2",
(18, 4) => "head_i18_c4",
(18, 8) => "head_i18_c8",
(21, 0) => "head_i21_old",
(21, 1) => "head_i21_c1",
(21, 2) => "head_i21_c2",
(21, 4) => "head_i21_c4",
(21, 8) => "head_i21_c8",
(22, 0) => "head_i22_old",
(22, 1) => "head_i22_c1",
(22, 2) => "head_i22_c2",
(22, 4) => "head_i22_c4",
(22, 8) => "head_i22_c8",
(29, 0) => "head_i29_old",
(29, 1) => "head_i29_c1",
(29, 2) => "head_i29_c2",
(29, 4) => "head_i29_c4",
(29, 8) => "head_i29_c8",
_ => return Err(Error::UnsupportedQwenOperation),
};
let name = iq_kernel_name(kind, iq_columns(t), p.old_iq || kind == 7)?;
return Ok((name, [v.div_ceil(4) as u32, 1, 1], [32, 4, 1], true));
}
let (div, bpi) = match kind {
2 => (32, 64),
6 => (32, 64),
8 => (32, 32),
20 => (32, 64),
11 => (256, 8),
12 => (256, 8),
13 => (256, 8),
14 => (256, 4),
23 => (256, 16),
42 => (64, 64),
_ => return Err(Error::UnsupportedQwenOperation),
};
let (div, bpi) = native_head_geometry(kind)?;
let small = n / div < bpi;
let upstream = t > 1 && !p.multi_exact;
let mode = if t == 1 {
if small { 0 } else { 1 }
} else if upstream {
2
} else if small {
3
} else {
4
};
let name = match (kind, t, mode) {
(2, 1, 0) => "head_n2_s1",
(2, 1, 1) => "head_n2_s0",
(2, 2, 2) => "head_n2_t2_upstream",
(2, 2, 3) => "head_n2_t2_small",
(2, 2, 4) => "head_n2_t2_large",
(2, 3, 2) => "head_n2_t3_upstream",
(2, 3, 3) => "head_n2_t3_small",
(2, 3, 4) => "head_n2_t3_large",
(2, 4, 2) => "head_n2_t4_upstream",
(2, 4, 3) => "head_n2_t4_small",
(2, 4, 4) => "head_n2_t4_large",
(2, 5, 2) => "head_n2_t5_upstream",
(2, 5, 3) => "head_n2_t5_small",
(2, 5, 4) => "head_n2_t5_large",
(2, 6, 2) => "head_n2_t6_upstream",
(2, 6, 3) => "head_n2_t6_small",
(2, 6, 4) => "head_n2_t6_large",
(2, 7, 2) => "head_n2_t7_upstream",
(2, 7, 3) => "head_n2_t7_small",
(2, 7, 4) => "head_n2_t7_large",
(2, 8, 2) => "head_n2_t8_upstream",
(2, 8, 3) => "head_n2_t8_small",
(2, 8, 4) => "head_n2_t8_large",
(6, 1, 0) => "head_n6_s1",
(6, 1, 1) => "head_n6_s0",
(6, 2, 2) => "head_n6_t2_upstream",
(6, 2, 3) => "head_n6_t2_small",
(6, 2, 4) => "head_n6_t2_large",
(6, 3, 2) => "head_n6_t3_upstream",
(6, 3, 3) => "head_n6_t3_small",
(6, 3, 4) => "head_n6_t3_large",
(6, 4, 2) => "head_n6_t4_upstream",
(6, 4, 3) => "head_n6_t4_small",
(6, 4, 4) => "head_n6_t4_large",
(6, 5, 2) => "head_n6_t5_upstream",
(6, 5, 3) => "head_n6_t5_small",
(6, 5, 4) => "head_n6_t5_large",
(6, 6, 2) => "head_n6_t6_upstream",
(6, 6, 3) => "head_n6_t6_small",
(6, 6, 4) => "head_n6_t6_large",
(6, 7, 2) => "head_n6_t7_upstream",
(6, 7, 3) => "head_n6_t7_small",
(6, 7, 4) => "head_n6_t7_large",
(6, 8, 2) => "head_n6_t8_upstream",
(6, 8, 3) => "head_n6_t8_small",
(6, 8, 4) => "head_n6_t8_large",
(8, 1, 0) => "head_n8_s1",
(8, 1, 1) => "head_n8_s0",
(8, 2, 2) => "head_n8_t2_upstream",
(8, 2, 3) => "head_n8_t2_small",
(8, 2, 4) => "head_n8_t2_large",
(8, 3, 2) => "head_n8_t3_upstream",
(8, 3, 3) => "head_n8_t3_small",
(8, 3, 4) => "head_n8_t3_large",
(8, 4, 2) => "head_n8_t4_upstream",
(8, 4, 3) => "head_n8_t4_small",
(8, 4, 4) => "head_n8_t4_large",
(8, 5, 2) => "head_n8_t5_upstream",
(8, 5, 3) => "head_n8_t5_small",
(8, 5, 4) => "head_n8_t5_large",
(8, 6, 2) => "head_n8_t6_upstream",
(8, 6, 3) => "head_n8_t6_small",
(8, 6, 4) => "head_n8_t6_large",
(8, 7, 2) => "head_n8_t7_upstream",
(8, 7, 3) => "head_n8_t7_small",
(8, 7, 4) => "head_n8_t7_large",
(8, 8, 2) => "head_n8_t8_upstream",
(8, 8, 3) => "head_n8_t8_small",
(8, 8, 4) => "head_n8_t8_large",
(20, 1, 0) => "head_n20_s1",
(20, 1, 1) => "head_n20_s0",
(20, 2, 2) => "head_n20_t2_upstream",
(20, 2, 3) => "head_n20_t2_small",
(20, 2, 4) => "head_n20_t2_large",
(20, 3, 2) => "head_n20_t3_upstream",
(20, 3, 3) => "head_n20_t3_small",
(20, 3, 4) => "head_n20_t3_large",
(20, 4, 2) => "head_n20_t4_upstream",
(20, 4, 3) => "head_n20_t4_small",
(20, 4, 4) => "head_n20_t4_large",
(20, 5, 2) => "head_n20_t5_upstream",
(20, 5, 3) => "head_n20_t5_small",
(20, 5, 4) => "head_n20_t5_large",
(20, 6, 2) => "head_n20_t6_upstream",
(20, 6, 3) => "head_n20_t6_small",
(20, 6, 4) => "head_n20_t6_large",
(20, 7, 2) => "head_n20_t7_upstream",
(20, 7, 3) => "head_n20_t7_small",
(20, 7, 4) => "head_n20_t7_large",
(20, 8, 2) => "head_n20_t8_upstream",
(20, 8, 3) => "head_n20_t8_small",
(20, 8, 4) => "head_n20_t8_large",
(11, 1, 0) => "head_n11_s1",
(11, 1, 1) => "head_n11_s0",
(11, 2, 2) => "head_n11_t2_upstream",
(11, 2, 3) => "head_n11_t2_small",
(11, 2, 4) => "head_n11_t2_large",
(11, 3, 2) => "head_n11_t3_upstream",
(11, 3, 3) => "head_n11_t3_small",
(11, 3, 4) => "head_n11_t3_large",
(11, 4, 2) => "head_n11_t4_upstream",
(11, 4, 3) => "head_n11_t4_small",
(11, 4, 4) => "head_n11_t4_large",
(11, 5, 2) => "head_n11_t5_upstream",
(11, 5, 3) => "head_n11_t5_small",
(11, 5, 4) => "head_n11_t5_large",
(11, 6, 2) => "head_n11_t6_upstream",
(11, 6, 3) => "head_n11_t6_small",
(11, 6, 4) => "head_n11_t6_large",
(11, 7, 2) => "head_n11_t7_upstream",
(11, 7, 3) => "head_n11_t7_small",
(11, 7, 4) => "head_n11_t7_large",
(11, 8, 2) => "head_n11_t8_upstream",
(11, 8, 3) => "head_n11_t8_small",
(11, 8, 4) => "head_n11_t8_large",
(12, 1, 0) => "head_n12_s1",
(12, 1, 1) => "head_n12_s0",
(12, 2, 2) => "head_n12_t2_upstream",
(12, 2, 3) => "head_n12_t2_small",
(12, 2, 4) => "head_n12_t2_large",
(12, 3, 2) => "head_n12_t3_upstream",
(12, 3, 3) => "head_n12_t3_small",
(12, 3, 4) => "head_n12_t3_large",
(12, 4, 2) => "head_n12_t4_upstream",
(12, 4, 3) => "head_n12_t4_small",
(12, 4, 4) => "head_n12_t4_large",
(12, 5, 2) => "head_n12_t5_upstream",
(12, 5, 3) => "head_n12_t5_small",
(12, 5, 4) => "head_n12_t5_large",
(12, 6, 2) => "head_n12_t6_upstream",
(12, 6, 3) => "head_n12_t6_small",
(12, 6, 4) => "head_n12_t6_large",
(12, 7, 2) => "head_n12_t7_upstream",
(12, 7, 3) => "head_n12_t7_small",
(12, 7, 4) => "head_n12_t7_large",
(12, 8, 2) => "head_n12_t8_upstream",
(12, 8, 3) => "head_n12_t8_small",
(12, 8, 4) => "head_n12_t8_large",
(13, 1, 0) => "head_n13_s1",
(13, 1, 1) => "head_n13_s0",
(13, 2, 2) => "head_n13_t2_upstream",
(13, 2, 3) => "head_n13_t2_small",
(13, 2, 4) => "head_n13_t2_large",
(13, 3, 2) => "head_n13_t3_upstream",
(13, 3, 3) => "head_n13_t3_small",
(13, 3, 4) => "head_n13_t3_large",
(13, 4, 2) => "head_n13_t4_upstream",
(13, 4, 3) => "head_n13_t4_small",
(13, 4, 4) => "head_n13_t4_large",
(13, 5, 2) => "head_n13_t5_upstream",
(13, 5, 3) => "head_n13_t5_small",
(13, 5, 4) => "head_n13_t5_large",
(13, 6, 2) => "head_n13_t6_upstream",
(13, 6, 3) => "head_n13_t6_small",
(13, 6, 4) => "head_n13_t6_large",
(13, 7, 2) => "head_n13_t7_upstream",
(13, 7, 3) => "head_n13_t7_small",
(13, 7, 4) => "head_n13_t7_large",
(13, 8, 2) => "head_n13_t8_upstream",
(13, 8, 3) => "head_n13_t8_small",
(13, 8, 4) => "head_n13_t8_large",
(14, 1, 0) => "head_n14_s1",
(14, 1, 1) => "head_n14_s0",
(14, 2, 2) => "head_n14_t2_upstream",
(14, 2, 3) => "head_n14_t2_small",
(14, 2, 4) => "head_n14_t2_large",
(14, 3, 2) => "head_n14_t3_upstream",
(14, 3, 3) => "head_n14_t3_small",
(14, 3, 4) => "head_n14_t3_large",
(14, 4, 2) => "head_n14_t4_upstream",
(14, 4, 3) => "head_n14_t4_small",
(14, 4, 4) => "head_n14_t4_large",
(14, 5, 2) => "head_n14_t5_upstream",
(14, 5, 3) => "head_n14_t5_small",
(14, 5, 4) => "head_n14_t5_large",
(14, 6, 2) => "head_n14_t6_upstream",
(14, 6, 3) => "head_n14_t6_small",
(14, 6, 4) => "head_n14_t6_large",
(14, 7, 2) => "head_n14_t7_upstream",
(14, 7, 3) => "head_n14_t7_small",
(14, 7, 4) => "head_n14_t7_large",
(14, 8, 2) => "head_n14_t8_upstream",
(14, 8, 3) => "head_n14_t8_small",
(14, 8, 4) => "head_n14_t8_large",
(23, 1, 0) => "head_n23_s1",
(23, 1, 1) => "head_n23_s0",
(23, 2, 2) => "head_n23_t2_upstream",
(23, 2, 3) => "head_n23_t2_small",
(23, 2, 4) => "head_n23_t2_large",
(23, 3, 2) => "head_n23_t3_upstream",
(23, 3, 3) => "head_n23_t3_small",
(23, 3, 4) => "head_n23_t3_large",
(23, 4, 2) => "head_n23_t4_upstream",
(23, 4, 3) => "head_n23_t4_small",
(23, 4, 4) => "head_n23_t4_large",
(23, 5, 2) => "head_n23_t5_upstream",
(23, 5, 3) => "head_n23_t5_small",
(23, 5, 4) => "head_n23_t5_large",
(23, 6, 2) => "head_n23_t6_upstream",
(23, 6, 3) => "head_n23_t6_small",
(23, 6, 4) => "head_n23_t6_large",
(23, 7, 2) => "head_n23_t7_upstream",
(23, 7, 3) => "head_n23_t7_small",
(23, 7, 4) => "head_n23_t7_large",
(23, 8, 2) => "head_n23_t8_upstream",
(23, 8, 3) => "head_n23_t8_small",
(23, 8, 4) => "head_n23_t8_large",
(42, 1, 0) => "head_n42_s1",
(42, 1, 1) => "head_n42_s0",
(42, 2, 2) => "head_n42_t2_upstream",
(42, 2, 3) => "head_n42_t2_small",
(42, 2, 4) => "head_n42_t2_large",
(42, 3, 2) => "head_n42_t3_upstream",
(42, 3, 3) => "head_n42_t3_small",
(42, 3, 4) => "head_n42_t3_large",
(42, 4, 2) => "head_n42_t4_upstream",
(42, 4, 3) => "head_n42_t4_small",
(42, 4, 4) => "head_n42_t4_large",
(42, 5, 2) => "head_n42_t5_upstream",
(42, 5, 3) => "head_n42_t5_small",
(42, 5, 4) => "head_n42_t5_large",
(42, 6, 2) => "head_n42_t6_upstream",
(42, 6, 3) => "head_n42_t6_small",
(42, 6, 4) => "head_n42_t6_large",
(42, 7, 2) => "head_n42_t7_upstream",
(42, 7, 3) => "head_n42_t7_small",
(42, 7, 4) => "head_n42_t7_large",
(42, 8, 2) => "head_n42_t8_upstream",
(42, 8, 3) => "head_n42_t8_small",
(42, 8, 4) => "head_n42_t8_large",
_ => return Err(Error::UnsupportedQwenOperation),
};
let rows = if upstream {
2
} else if small {
4
} else {
1
};
let name = native_kernel_name(kind, t, native_head_mode(t, small, upstream))?;
let rows = native_head_rows(small, upstream);
let nw = if upstream && t > 4 { 2 } else { 4 };
Ok((name, [v.div_ceil(rows) as u32, 1, 1], [32, nw, 1], false))
}
@@ -0,0 +1,200 @@
//! Construction phases of `OriginalMtpFullForward::new_internal`, split out by STRA-338 (size). Each phase keeps the
//! original context-guard, poison and error ordering; `FullOwned::init_device` runs them in the former closure order.
#[allow(unused_imports)]
use super::*;
/// What `new_internal` decides before any device memory exists.
pub(super) struct FullGeometry {
pub(super) layout: TailLayout,
pub(super) original_layout: Option<physical_layout::Layout>,
pub(super) sizes: [usize; 7],
}
impl FullGeometry {
/// Validates the weights, shape and sealed assets and charges the device budget for the owner.
pub(super) fn admit<'ctx>(
c: &'ctx Context<'ctx>,
weights: &OriginalMtpRetainedFullWeights<'ctx>,
max_t: usize,
(coupled, original): (bool, bool),
) -> Result<Self> {
weights.validate_context(c)?;
if !(1..=8).contains(&max_t) {
return Err(Error::InvalidQwenShape);
}
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 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))?,
None => layout.bytes,
};
Self::admit_charge(c, own_bytes)?;
Ok(Self { layout, original_layout, sizes })
}
/// The owner's bytes plus the reserve must fit the context budget and the physical free memory.
fn admit_charge(c: &Context<'_>, own_bytes: usize) -> Result<()> {
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);
}
Ok(())
}
}
impl<'ctx> FullOwned<'ctx> {
pub(super) fn init_device(
&mut self,
c: &'ctx Context<'ctx>,
(original, max_t, coupled): (bool, usize, bool),
sizes: [usize; 7],
) -> Result<()> {
self.init_modules(c)?;
self.init_gr_config(c)?;
self.init_mapped(c, (original, max_t, coupled))?;
self.init_scratch(c, original, sizes)?;
self.zero_scratch(c)?;
self.init_step_ids()
}
fn init_modules(&mut self, c: &'ctx Context<'ctx>) -> Result<()> {
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
let load = self.load_modules();
let pop = g.finish();
if pop.is_err() {
c.poison();
c.retain_driver();
}
combine(load, pop)
}
fn load_modules(&mut self) -> Result<()> {
for (p, e) in &symbols::ASSETS[..symbols::CHAIN_ASSET] {
self.modules.push(Rc::new(FM::load(p, e)?));
}
if chain_mtp_assets() || daily_mtp() {
// chain_window.ptx: loaded only when selected, and only if it is the sealed one
crate::original_verify::chain::CHAIN.sealed()?;
let (p, e) = &symbols::ASSETS[symbols::CHAIN_ASSET];
self.modules.push(Rc::new(FM::load(p, e)?));
}
if daily_mtp() {
// sm120_attn_daily.ptx: the draft step's attention (opt-in, LELEKA_SM120_ATTN_DAILY_MTP=1); slot 22 follows the chain slot
crate::original_verify::sm120::ATTN_DAILY.sealed()?;
let (p, e) = &symbols::ASSETS[symbols::DAILY_ASSET];
self.modules.push(Rc::new(FM::load(p, e)?));
}
Ok(())
}
fn init_gr_config(&self, c: &'ctx Context<'ctx>) -> Result<()> {
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
let config = self.modules[17].configure_gr();
let pop = g.finish();
if pop.is_err() {
c.poison();
c.retain_driver();
}
let _actual = combine(config, pop)?;
Ok(())
}
fn init_mapped(&mut self, c: &'ctx Context<'ctx>, (original, max_t, coupled): (bool, usize, bool)) -> Result<()> {
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
let mapped = if original {
full_mapped::MappedOwner::original(max_t, coupled)
} else {
full_mapped::MappedOwner::new(max_t, coupled)
};
let pop = g.finish();
if pop.is_err() {
c.poison();
c.retain_driver();
let primary = match mapped {
Ok(actual) => {
std::mem::forget(actual);
Ok(())
}
Err(error) => Err(error),
};
return combine(primary, pop);
}
if original && mapped.is_err() {
c.poison();
c.retain_driver();
}
*self.mapped.get_mut() = Some(mapped?);
Ok(())
}
fn init_scratch(&mut self, c: &'ctx Context<'ctx>, original: bool, sizes: [usize; 7]) -> Result<()> {
self.scratch = Some(Rc::new(c.allocate(self.original_layout.as_ref().map_or(self.layout.bytes, |l| l.bytes))?));
if original {
for (i, n) in sizes.into_iter().enumerate() {
if n != 0 {
self.extras[i] = Some(c.allocate(n)?);
}
}
}
Ok(())
}
fn zero_scratch(&self, c: &'ctx Context<'ctx>) -> Result<()> {
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
// cuMemsetD8_v2 on device memory is asynchronous with respect to the host (it only orders on the legacy
// default stream). Fence it inside the same guard: the non-original layout has no later synchronous copy
// (the original one does, `copy_from_range` below), and the first kernel of a non-blocking stream must not
// race the zeroing. Same pattern as `zero_state` + `synchronize` in mtp_original_ring_state.rs.
let zero = self.modules[0]
.zero(
self.scratch
.as_ref()
.ok_or(Error::ContextPoisoned)?
.handle
.ok_or(Error::ContextPoisoned)?
.qwen_address(),
self.original_layout.as_ref().map_or(self.layout.bytes, |l| l.bytes),
)
.and_then(|()| c.driver.api.synchronize());
let pop = g.finish();
if zero.is_err() || pop.is_err() {
c.poison();
c.retain_driver();
}
combine(zero, pop)
}
/// Uploads the identity step ids of the original layout.
fn init_step_ids(&mut self) -> Result<()> {
if let Some(l) = &self.original_layout {
let mut ids = Vec::new();
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());
}
}
Rc::get_mut(self.scratch.as_mut().ok_or(Error::ContextPoisoned)?)
.ok_or(Error::InvalidQwenShape)?
.copy_from_range(l.offsets[4], &ids)?;
}
Ok(())
}
}
@@ -13,6 +13,35 @@ impl<'ctx> MtpOriginalInt8<'ctx> {
input: &'loan MtpOriginalMixed<'loan, 'buffers>,
weights: [&'loan DeviceBuffer<'weights>; 3],
) -> Result<CompletedMtpKvReplay<'loan, 'ctx, 'buffers, 'weights>> {
let addresses = self.kv_only_admit(w, prior, input, &weights)?;
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, changed) = Self::kv_only_pages(prior, first_page, n_pages)?;
self.kv_only_stage(w, prior, input)?;
self.kv_only_run(w, input.rows, addresses)?;
self.kv_only_read_pages(&mut pages, changed, first_page)?;
let snapshot = self.kv_only_snapshot(pages, end, generation);
Ok(CompletedMtpKvReplay {
owner: self,
snapshot,
_mixed: input,
_weights: weights,
first: input.first,
rows: input.rows,
})
}
/// Validates the prior snapshot, workspace and rows; returns the `[mixed, wk, wv, gamma]` device addresses.
fn kv_only_admit(
&self,
w: &mut NativeBatchWorkspace<'ctx>,
prior: &MtpInt8Snapshot,
input: &MtpOriginalMixed<'_, '_>,
weights: &[&DeviceBuffer<'_>; 3],
) -> Result<[u64; 4]> {
self.validate_snapshot(prior)?;
w.validate_context(self.context)?;
rows_range(input.first, input.rows, self.max_t)?;
@@ -23,6 +52,76 @@ impl<'ctx> MtpOriginalInt8<'ctx> {
let wk = self.external(w, weights[0], 512 * 80 * 34)?;
let wv = self.external(w, weights[1], 512 * 80 * 34)?;
let gamma = self.external(w, weights[2], 256 * 4)?;
Self::kv_only_reject_aliases(input, weights)?;
Ok([mixed, wk, wv, gamma])
}
/// Rewinds the ring to the genuine prior and uploads the position, step and status words of the replay.
fn kv_only_stage(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
prior: &MtpInt8Snapshot,
input: &MtpOriginalMixed<'_, '_>,
) -> Result<()> {
let (pos, steps) = self.kv_only_positions(input)?;
let replay_prior = Self::kv_only_replay_prior(prior, input.first);
self.restore(w, &replay_prior)?;
self.copy_from_physical(8, &pos)?;
self.copy_from_physical(9, &steps)?;
self.copy_from_physical(10, &[0; STATUS_WORDS * 4])
}
/// Runs the numeric admission, then the append that mutates the ring.
fn kv_only_run(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
rows: usize,
[mixed, wk, wv, gamma]: [u64; 4],
) -> Result<()> {
let commands = self.kv_only_commands(rows, (mixed, wk, wv, gamma))?;
// First failed upstream full scan/quant wins. No host/ring write before
// successful numeric admission of all real K/V rows.
self.execute(w, commands)?;
self.kv_only_check_flags(rows)?;
let append = self.kv_only_append_commands(rows)?;
self.current = None; // source pages and resident ring mutate only after invalidation
self.execute(w, append)?;
if self.flags()?[4 + 2 * self.max_t] != 0 {
return Err(Error::NonFiniteMmqOutput("mtp-int8-scale"));
}
Ok(())
}
/// Reads the rewritten pages back from the ring and appends them to `pages`.
fn kv_only_read_pages(
&self,
pages: &mut Vec<Rc<Page>>,
mut changed: Vec<[Vec<u8>; 4]>,
first_page: usize,
) -> Result<()> {
for (p, runs) in changed.iter_mut().enumerate() {
self.read_encoded_page(p + first_page, runs)?;
}
for runs in changed {
pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) }));
}
Ok(())
}
fn kv_only_snapshot(&mut self, pages: Vec<Rc<Page>>, end: usize, generation: u64) -> MtpInt8Snapshot {
let snapshot = MtpInt8Snapshot(Rc::new(Snapshot {
origin: self.origin.clone(),
pages: Pages::from_vec(pages),
end,
checked: std::cell::Cell::new(false),
}));
self.current = Some(snapshot.clone());
self.generation = generation;
snapshot
}
/// The mixed input and the three weights must not partially overlap one another.
fn kv_only_reject_aliases(input: &MtpOriginalMixed<'_, '_>, weights: &[&DeviceBuffer<'_>; 3]) -> Result<()> {
let spans = [
(input.mixed.handle.ok_or(Error::ContextPoisoned)?, input.mixed.bytes),
(weights[0].handle.ok_or(Error::ContextPoisoned)?, weights[0].bytes),
@@ -37,11 +136,16 @@ impl<'ctx> MtpOriginalInt8<'ctx> {
}
}
}
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.
Ok(())
}
/// Unchanged prior pages, and zeroed-then-copied run buffers for the pages the replay rewrites.
#[allow(clippy::type_complexity)]
fn kv_only_pages(
prior: &MtpInt8Snapshot,
first_page: usize,
n_pages: usize,
) -> Result<(Vec<Rc<Page>>, Vec<[Vec<u8>; 4]>)> {
let mut pages = Vec::new();
pages.try_reserve_exact(n_pages).map_err(|_| Error::HostAllocation)?;
for page in prior.0.pages.iter().take(first_page) {
@@ -59,6 +163,11 @@ impl<'ctx> MtpOriginalInt8<'ctx> {
}
changed.push(runs);
}
Ok((pages, changed))
}
/// Host images of the position and step records for the replayed rows.
fn kv_only_positions(&self, input: &MtpOriginalMixed<'_, '_>) -> Result<(Vec<u8>, Vec<u8>)> {
let mut pos = zero_bytes(self.sizes[8])?;
let mut steps = zero_bytes(self.sizes[9])?;
for t in 0..input.rows {
@@ -70,124 +179,128 @@ impl<'ctx> MtpOriginalInt8<'ctx> {
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
// longer prior's ring would keep future blocks after a shorter replay.
// This private prefix is bounded by that genuine prior, never caller-minted.
let replay_prior = if input.first == prior.0.end {
Ok((pos, steps))
}
// The real mixed producer supplies the rewind position. Restoring the
// longer prior's ring would keep future blocks after a shorter replay.
// This private prefix is bounded by that genuine prior, never caller-minted.
fn kv_only_replay_prior(prior: &MtpInt8Snapshot, first: usize) -> MtpInt8Snapshot {
if first == prior.0.end {
prior.clone()
} else {
MtpInt8Snapshot(Rc::new(Snapshot {
origin: prior.0.origin.clone(),
pages: prior.0.pages.clone(),
end: input.first,
end: first,
checked: std::cell::Cell::new(prior.0.checked.get()),
}))
};
self.restore(w, &replay_prior)?;
self.copy_from_physical(8, &pos)?;
self.copy_from_physical(9, &steps)?;
self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?;
}
}
/// Quantize, K/V projections, K norm and rope with a finite guard after every stage.
fn kv_only_commands(&self, rows: usize, (mixed, wk, wv, gamma): (u64, u64, u64, u64)) -> Result<Vec<Command>> {
let mut commands = Vec::new();
commands.try_reserve_exact(32 + input.rows * 5).map_err(|_| Error::HostAllocation)?;
self.finite(&mut commands, mixed, input.rows * 2560, 0)?;
commands.try_reserve_exact(32 + rows * 5).map_err(|_| Error::HostAllocation)?;
self.kv_only_quantize(&mut commands, rows, mixed)?;
for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] {
self.kv_only_project(&mut commands, rows, (weight, out, status))?;
}
for t in 0..rows {
self.kv_only_norm_rope(&mut commands, gamma, t)?;
}
Ok(commands)
}
fn kv_only_quantize(&self, commands: &mut Vec<Command>, rows: usize, mixed: u64) -> Result<()> {
self.finite(commands, mixed, rows * 2560, 0)?;
Self::push(
&mut commands,
commands,
0,
0,
[(input.rows * 2560).div_ceil(256) as u32, 1, 1],
[(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((rows * 2560) as i32)],
)?;
Self::push(
&mut commands,
commands,
0,
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((rows * 80) as i32), Arg::U64(self.sub(10, 4, 4)?)],
)
}
fn kv_only_project(
&self,
commands: &mut Vec<Command>,
rows: usize,
(weight, out, status): (u64, usize, usize),
) -> Result<()> {
Self::push(
commands,
0,
rows,
[512, 1, 1],
[32, 4, 1],
vec![
Arg::U64(weight),
Arg::U64(self.address(5)?),
Arg::U64(self.address(out)?),
Arg::I32(2560),
Arg::I32(512),
],
)?;
for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] {
Self::push(
&mut commands,
0,
input.rows,
[512, 1, 1],
[32, 4, 1],
vec![
Arg::U64(weight),
Arg::U64(self.address(5)?),
Arg::U64(self.address(out)?),
Arg::I32(2560),
Arg::I32(512),
],
)?;
self.finite(&mut commands, self.address(out)?, input.rows * 512, status)?;
}
for t in 0..input.rows {
let k = self.sub(6, t * 2048, 2048)?;
Self::push(
&mut commands,
0,
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)],
)?;
self.finite(&mut commands, k, 512, 4 + 2 * t)?;
Self::push(
&mut commands,
0,
10,
[1, 2, 1],
[128, 1, 1],
vec![
Arg::U64(k),
Arg::U64(k),
Arg::I32(2),
Arg::I32(256),
Arg::F32(crate::qsa_index_ffi::theta()),
Arg::U64(self.sub(8, t * 96, 8)?),
],
)?;
self.finite(&mut commands, k, 512, 5 + 2 * t)?;
}
// First failed upstream full scan/quant wins. No host/ring write before
// successful numeric admission of all real K/V rows.
self.execute(w, commands)?;
self.finite(commands, self.address(out)?, rows * 512, status)
}
fn kv_only_norm_rope(&self, commands: &mut Vec<Command>, gamma: u64, t: usize) -> Result<()> {
let k = self.sub(6, t * 2048, 2048)?;
Self::push(
commands,
0,
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)],
)?;
self.finite(commands, k, 512, 4 + 2 * t)?;
Self::push(
commands,
0,
10,
[1, 2, 1],
[128, 1, 1],
vec![
Arg::U64(k),
Arg::U64(k),
Arg::I32(2),
Arg::I32(256),
Arg::F32(crate::qsa_index_ffi::theta()),
Arg::U64(self.sub(8, t * 96, 8)?),
],
)?;
self.finite(commands, k, 512, 5 + 2 * t)
}
fn kv_only_check_flags(&mut self, rows: usize) -> Result<()> {
let flags = self.flags()?;
for (i, v) in flags.iter().enumerate().take(4 + 2 * input.rows) {
for (i, v) in flags.iter().enumerate().take(4 + 2 * rows) {
if *v != 0 {
return Err(if i == 1 { Error::InvalidQ8Activation } else { Error::NonFiniteMmqOutput("mtp-kv-only") });
}
}
Ok(())
}
/// One literal int8 append kernel per row and the closing scale publication.
fn kv_only_append_commands(&self, rows: usize) -> Result<Vec<Command>> {
let mut append = Vec::new();
append.try_reserve_exact(input.rows * 2).map_err(|_| Error::HostAllocation)?;
append.try_reserve_exact(rows * 2).map_err(|_| Error::HostAllocation)?;
let host = self.host_addresses()?;
for t in 0..input.rows {
Self::push(
&mut append,
1,
0,
[2, 4, 2],
[64, 1, 1],
vec![
Arg::U64(self.address(0)?),
Arg::U64(self.address(1)?),
Arg::U64(self.address(2)?),
Arg::U64(self.address(3)?),
Arg::U64(self.address(4)?),
Arg::U64(self.sub(9, t * 16, 16)?),
Arg::U64(self.sub(6, t * 2048, 2048)?),
Arg::U64(self.sub(7, t * 2048, 2048)?),
Arg::I32(2),
Arg::I32(256),
Arg::I32(4),
Arg::U64(host[0]),
Arg::U64(host[1]),
Arg::U64(host[2]),
Arg::U64(host[3]),
],
)?;
for t in 0..rows {
self.kv_only_append_row(&mut append, host, t)?;
}
Self::push(
&mut append,
@@ -202,32 +315,33 @@ impl<'ctx> MtpOriginalInt8<'ctx> {
Arg::U64(self.sub(10, (4 + 2 * self.max_t) * 4, 4)?),
],
)?;
self.current = None; // source pages and resident ring mutate only after invalidation
self.execute(w, append)?;
if self.flags()?[4 + 2 * self.max_t] != 0 {
return Err(Error::NonFiniteMmqOutput("mtp-int8-scale"));
}
for (p, runs) in changed.iter_mut().enumerate() {
self.read_encoded_page(p + first_page, runs)?;
}
for runs in changed {
pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) }));
}
let snapshot = MtpInt8Snapshot(Rc::new(Snapshot {
origin: self.origin.clone(),
pages: Pages::from_vec(pages),
end,
checked: std::cell::Cell::new(false),
}));
self.current = Some(snapshot.clone());
self.generation = generation;
Ok(CompletedMtpKvReplay {
owner: self,
snapshot,
_mixed: input,
_weights: weights,
first: input.first,
rows: input.rows,
})
Ok(append)
}
fn kv_only_append_row(&self, append: &mut Vec<Command>, host: [u64; 4], t: usize) -> Result<()> {
Self::push(
append,
1,
0,
[2, 4, 2],
[64, 1, 1],
vec![
Arg::U64(self.address(0)?),
Arg::U64(self.address(1)?),
Arg::U64(self.address(2)?),
Arg::U64(self.address(3)?),
Arg::U64(self.address(4)?),
Arg::U64(self.sub(9, t * 16, 16)?),
Arg::U64(self.sub(6, t * 2048, 2048)?),
Arg::U64(self.sub(7, t * 2048, 2048)?),
Arg::I32(2),
Arg::I32(256),
Arg::I32(4),
Arg::U64(host[0]),
Arg::U64(host[1]),
Arg::U64(host[2]),
Arg::U64(host[3]),
],
)
}
}
@@ -60,29 +60,34 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
prompt_cap: usize,
exact: Option<OriginalLayoutSetup<'ctx>>,
) -> Result<Self> {
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)?
} else {
legacy_charge
};
if let Some(e) = &exact {
if e.layout.t != max_t {
return Err(Error::InvalidQwenShape);
}
checked(c, &e.bank, e.layout.bytes)?;
Self::admit_new(c, max_t, prompt_cap, exact.as_ref())?;
let mut o = Self::empty(c, max_t, prompt_cap, exact.as_ref())?;
if let Err(e) = o.init_device(c, exact.as_ref()) {
return combine(Err(e), o.close());
}
let assets = [
Ok(o)
}
/// The six sealed prefill assets, in module-slot order.
fn scalar_assets() -> [&'static [u8]; 6] {
[
include_bytes!("../../mtp_original_prefill.ptx").as_slice(),
include_bytes!("../../mtp_original_prefill_embedding.ptx").as_slice(),
include_bytes!("../../mtp_original_tail.ptx").as_slice(),
include_bytes!("../../mtp_original_scalar_norm.ptx").as_slice(),
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")) {
return Err(Error::UnsupportedQwenOperation);
}
]
}
/// Shape, sealed-asset, context and budget admission before any device memory exists.
fn admit_new(
c: &'ctx Context<'ctx>,
max_t: usize,
prompt_cap: usize,
exact: Option<&OriginalLayoutSetup<'ctx>>,
) -> Result<()> {
let charge = Self::admit_layout(c, max_t, prompt_cap, exact)?;
let required = charge.checked_add(RESERVE_BYTES).ok_or(Error::BudgetExceeded)?;
if c.is_poisoned() || c.handle.is_none() {
return Err(Error::ContextPoisoned);
@@ -92,7 +97,42 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
{
return Err(Error::BudgetExceeded);
}
let mut o = Self {
Ok(())
}
/// Shape and sealed-asset admission; returns the device bytes the owner will charge.
fn admit_layout(
c: &'ctx Context<'ctx>,
max_t: usize,
prompt_cap: usize,
exact: Option<&OriginalLayoutSetup<'ctx>>,
) -> Result<usize> {
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)?
} else {
legacy_charge
};
if let Some(e) = exact {
if e.layout.t != max_t {
return Err(Error::InvalidQwenShape);
}
checked(c, &e.bank, e.layout.bytes)?;
}
if Self::scalar_assets().iter().any(|p| p.windows(8).any(|w| w == b"UNSEALED")) {
return Err(Error::UnsupportedQwenOperation);
}
Ok(charge)
}
/// An owner with no device memory, modules or stream yet.
fn empty(
c: &'ctx Context<'ctx>,
max_t: usize,
prompt_cap: usize,
exact: Option<&OriginalLayoutSetup<'ctx>>,
) -> Result<Self> {
Ok(Self {
context: c,
max_t,
prompt_cap,
@@ -100,11 +140,11 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
scratch: None,
records: None,
status: None,
layout: match &exact {
layout: match exact {
Some(e) => e.layout.scalar(),
None => Scratch::new(max_t)?,
},
original_layout: exact.as_ref().map(|e| e.layout.clone()),
original_layout: exact.map(|e| e.layout.clone()),
shared_limit: 0,
plain_tile: 0,
stream: None,
@@ -117,74 +157,89 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
pending_host: Vec::new(),
graph_metadata_bytes: 0,
has_pending: false,
};
let operation = (|| {
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
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[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"],
)?));
o.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?));
o.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?));
let (shared, tile) = o.module(4)?.configure_gr()?;
o.shared_limit = shared;
o.plain_tile = tile;
Ok(())
})();
let pop = g.finish();
if load.is_err() || pop.is_err() {
o.poison();
}
combine(load, pop)?;
o.scratch = Some(match &exact {
Some(e) => Rc::clone(&e.bank),
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.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))),
None => mapped_records::MappedOwner::new(max_t),
};
let pop = g.finish();
if pop.is_err() {
o.poison();
let original = match allocation {
Ok(owner) => {
std::mem::forget(owner);
Ok(())
}
Err(e) => Err(e),
};
return combine(original, pop);
}
if allocation.is_err() {
o.poison();
}
*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)?;
if c.memory_info()?.0 < RESERVE_BYTES {
return Err(Error::BudgetExceeded);
}
Ok(())
})();
if let Err(e) = operation {
return combine(Err(e), o.close());
})
}
fn init_device(&mut self, c: &'ctx Context<'ctx>, exact: Option<&OriginalLayoutSetup<'ctx>>) -> Result<()> {
self.init_modules(c)?;
self.init_buffers(c, exact)?;
self.init_mapped(c, exact)?;
self.graphs = Some(OriginalGraphRegistry::new(c, 2 * self.max_t)?);
self.pending_host.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?;
if c.memory_info()?.0 < RESERVE_BYTES {
return Err(Error::BudgetExceeded);
}
Ok(o)
Ok(())
}
/// The scratch bank (shared when `exact`), the record and status buffers, and the private stream.
fn init_buffers(&mut self, c: &'ctx Context<'ctx>, exact: Option<&OriginalLayoutSetup<'ctx>>) -> Result<()> {
self.scratch = Some(match exact {
Some(e) => Rc::clone(&e.bank),
None => Rc::new(c.allocate(self.layout.bytes)?),
});
self.records = Some(Rc::new(c.allocate(self.prompt_cap * 29 * 4)?));
self.status = Some(Rc::new(c.allocate((self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4)?));
self.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
Ok(())
}
fn init_modules(&mut self, c: &'ctx Context<'ctx>) -> Result<()> {
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
let load = self.load_modules();
let pop = g.finish();
if load.is_err() || pop.is_err() {
self.poison();
}
combine(load, pop)
}
fn load_modules(&mut self) -> Result<()> {
let assets = Self::scalar_assets();
self.modules[0] = Some(Rc::new(Module::load(assets[0], ENTRIES)?));
self.modules[1] = Some(Rc::new(Module::load(assets[1], &[c"mtp_prefill_native_embedding"])?));
self.modules[2] = Some(Rc::new(Module::load(assets[2], TAIL_ENTRIES)?));
self.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"],
)?));
self.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?));
self.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?));
let (shared, tile) = self.module(4)?.configure_gr()?;
self.shared_limit = shared;
self.plain_tile = tile;
Ok(())
}
fn init_mapped(&mut self, c: &'ctx Context<'ctx>, exact: Option<&OriginalLayoutSetup<'ctx>>) -> Result<()> {
let g = c.enter().inspect_err(|_| {
c.poison();
c.retain_driver();
})?;
let allocation = match exact {
Some(e) => Ok(mapped_records::MappedOwner::original(self.max_t, Rc::clone(&e.mapped))),
None => mapped_records::MappedOwner::new(self.max_t),
};
let pop = g.finish();
if pop.is_err() {
self.poison();
let original = match allocation {
Ok(owner) => {
std::mem::forget(owner);
Ok(())
}
Err(e) => Err(e),
};
return combine(original, pop);
}
if allocation.is_err() {
self.poison();
}
*self.mapped.borrow_mut() = Some(allocation?);
Ok(())
}
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()