use std::collections::BTreeMap;
use anyhow::{bail, Result};
use frink_gguf::GgmlType;
use super::arch::{self, Early, QuantArch};
use super::model_shape::{llama_cpp_weight_order, scan_layer, ModelShape};
use super::policy::Target;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
Output,
TokenEmbd,
AttnV,
AttnK,
AttnQ,
FfnDown,
AttnOutput,
AttnQkv,
AttnKvB,
FfnGate,
FfnUp,
FfnLatent,
AttnGate,
Other,
}
impl Role {
pub fn is_attn_v_like(self) -> bool {
matches!(self, Role::AttnV | Role::AttnQkv | Role::AttnKvB)
}
}
impl Role {
pub fn of(name: &str, has_output: bool) -> Role {
if name == "output.weight" {
return Role::Output;
}
let is_token_embd = name == "token_embd.weight" || name == "per_layer_token_embd.weight";
if is_token_embd {
return if has_output {
Role::TokenEmbd
} else {
Role::Output
};
}
for (needle, role) in [
("attn_qkv.weight", Role::AttnQkv),
("attn_qkv_gate.weight", Role::AttnQkv),
("attn_kv_b.weight", Role::AttnKvB),
("attn_v.weight", Role::AttnV),
("attn_k.weight", Role::AttnK),
("attn_q.weight", Role::AttnQ),
("attn_output.weight", Role::AttnOutput),
("ffn_up", Role::FfnUp),
("ffn_gate", Role::FfnGate),
("ffn_latent", Role::FfnLatent),
("attn_gate.weight", Role::AttnGate),
("ffn_down", Role::FfnDown),
] {
if name.contains(needle) {
return role;
}
}
Role::Other
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum When {
Always,
UseMoreBits,
FirstEighth,
FirstFour,
}
impl When {
fn holds(self, i: usize, n: usize) -> bool {
match self {
When::Always => true,
When::UseMoreBits => {
if i < n / 8 {
return true;
}
if n != 0 && i >= 7 * n / 8 {
return true;
}
(i - n / 8) % 3 == 2
}
When::FirstEighth => i < n / 8,
When::FirstFour => i < 4,
}
}
}
struct Promotion {
role: Role,
ftype: Target,
not_falcon: bool,
when: When,
to: GgmlType,
}
const PROMOTIONS: &[Promotion] = &[
Promotion {
role: Role::Output,
ftype: Target::Q4_K_S,
not_falcon: true,
when: When::Always,
to: GgmlType::Q6K,
},
Promotion {
role: Role::Output,
ftype: Target::Q4_K_M,
not_falcon: true,
when: When::Always,
to: GgmlType::Q6K,
},
Promotion {
role: Role::Output,
ftype: Target::Q5_K_S,
not_falcon: true,
when: When::Always,
to: GgmlType::Q6K,
},
Promotion {
role: Role::Output,
ftype: Target::Q5_K_M,
not_falcon: true,
when: When::Always,
to: GgmlType::Q6K,
},
Promotion {
role: Role::AttnV,
ftype: Target::Q4_K_M,
not_falcon: false,
when: When::UseMoreBits,
to: GgmlType::Q6K,
},
Promotion {
role: Role::AttnV,
ftype: Target::Q5_K_M,
not_falcon: false,
when: When::UseMoreBits,
to: GgmlType::Q6K,
},
Promotion {
role: Role::AttnV,
ftype: Target::Q4_K_S,
not_falcon: false,
when: When::FirstFour,
to: GgmlType::Q5K,
},
Promotion {
role: Role::FfnDown,
ftype: Target::Q4_K_M,
not_falcon: true,
when: When::UseMoreBits,
to: GgmlType::Q6K,
},
Promotion {
role: Role::FfnDown,
ftype: Target::Q5_K_M,
not_falcon: false,
when: When::UseMoreBits,
to: GgmlType::Q6K,
},
Promotion {
role: Role::FfnDown,
ftype: Target::Q4_K_S,
not_falcon: true,
when: When::FirstEighth,
to: GgmlType::Q5K,
},
];
const FALCON_Q4KM_FFN_DOWN_SIXTEENTH: GgmlType = GgmlType::Q6K;
pub struct Recipe {
target: Target,
shape: ModelShape,
n_attention_wv: usize,
has_output: bool,
i_attention_wv: usize,
i_ffn_down: usize,
i_ffn_gate: usize,
i_ffn_up: usize,
}
impl Recipe {
pub fn new(target: Target, shape: ModelShape, tensor_names: &[String]) -> Recipe {
let has_output = tensor_names.iter().any(|n| n == "output.weight");
let n_attention_wv = tensor_names
.iter()
.filter(|n| Role::of(n, has_output).is_attn_v_like())
.count();
Recipe {
target,
shape,
n_attention_wv,
has_output,
i_attention_wv: 0,
i_ffn_down: 0,
i_ffn_gate: 0,
i_ffn_up: 0,
}
}
pub fn tensor_type(&mut self, name: &str, shape: &[u64], source: GgmlType) -> Result<GgmlType> {
let role = Role::of(name, self.has_output);
let falcon = self.shape.arch == QuantArch::Falcon;
let default = match arch::early(
self.shape.arch,
self.target,
role,
name,
self.target.ggml_type(),
source,
) {
Early::Return(t) => return Ok(t),
Early::Start(t) => t,
};
let ty = match role {
Role::Output => self.output_head_type(shape, default),
Role::AttnV | Role::AttnQkv | Role::AttnKvB => {
let t = self.chain(
Role::AttnV,
self.i_attention_wv,
self.n_attention_wv,
default,
);
let t = if self.shape.is_70b && matches!(t, GgmlType::Q3K | GgmlType::Q4K) {
GgmlType::Q5K
} else {
t
};
let t = if self.shape.n_expert == 8 {
GgmlType::Q8_0
} else {
t
};
self.i_attention_wv += 1;
t
}
Role::AttnK => {
if self.shape.n_expert == 8 {
GgmlType::Q8_0
} else {
default
}
}
Role::FfnDown => {
let (i, n) = self.ffn_layer(name, self.i_ffn_down)?;
let t = if falcon && self.target == Target::Q4_K_M {
if i < n / 16 {
FALCON_Q4KM_FFN_DOWN_SIXTEENTH
} else if When::UseMoreBits.holds(i, n) {
GgmlType::Q5K
} else {
default
}
} else {
self.chain(role, i, n, default)
};
self.i_ffn_down += 1;
t
}
Role::AttnOutput => {
if !falcon
&& self.shape.n_expert == 8
&& matches!(self.target, Target::Q4_K_S | Target::Q4_K_M)
{
GgmlType::Q5K
} else {
default
}
}
Role::FfnGate => {
let (i, n) = self.ffn_layer(name, self.i_ffn_gate)?;
let t = self.chain(role, i, n, default);
self.i_ffn_gate += 1;
t
}
Role::FfnUp => {
let (i, n) = self.ffn_layer(name, self.i_ffn_up)?;
let t = self.chain(role, i, n, default);
self.i_ffn_up += 1;
t
}
Role::AttnQ | Role::TokenEmbd | Role::FfnLatent | Role::AttnGate | Role::Other => {
self.chain(role, 0, 0, default)
}
};
let ty = if self.shape.arch == QuantArch::Raon1Mini {
arch::raon_floor(self.target, role, name, ty)
} else {
ty
};
Ok(ty)
}
fn output_head_type(&self, shape: &[u64], default: GgmlType) -> GgmlType {
let nx = shape.first().copied().unwrap_or(0) as usize;
let qk_k = default.block_layout().1;
if self.shape.arch == QuantArch::Falcon || qk_k == 0 || !nx.is_multiple_of(qk_k) {
return GgmlType::Q8_0;
}
self.chain(Role::Output, 0, 0, default)
}
fn chain(&self, role: Role, i: usize, n: usize, default: GgmlType) -> GgmlType {
for p in PROMOTIONS {
if p.role != role || p.ftype != self.target {
continue;
}
if p.not_falcon && self.shape.arch == QuantArch::Falcon {
continue;
}
if p.when.holds(i, n) {
return p.to;
}
}
default
}
pub fn resolve_all<F>(
target: Target,
shape: ModelShape,
tensors: &[(String, Vec<u64>, GgmlType)],
eligible: F,
) -> Result<BTreeMap<String, GgmlType>>
where
F: Fn(&str, &[u64]) -> bool,
{
let names: Vec<String> = tensors.iter().map(|(n, _, _)| n.clone()).collect();
let mut recipe = Recipe::new(target, shape, &names);
let mut order: Vec<usize> = (0..tensors.len()).collect();
order.sort_by(|&a, &b| llama_cpp_weight_order(&tensors[a].0, &tensors[b].0));
let mut out = BTreeMap::new();
for i in order {
let (name, shape, source) = &tensors[i];
if eligible(name, shape) {
out.insert(name.clone(), recipe.tensor_type(name, shape, *source)?);
}
}
Ok(out)
}
fn ffn_layer(&self, name: &str, counter: usize) -> Result<(usize, usize)> {
let n = self.shape.n_layer;
if self.shape.n_expert.max(1) <= 1 {
return Ok((counter, n));
}
if let Some(i) = scan_layer(name, "blk.") {
if i < 0 || i >= n as i64 {
bail!(
"tensor {name} is in layer {i} of a {n}-layer mixture-of-experts checkpoint; \
llama-quantize stops here (`Bad layer {i} for tensor {name}. Must be in [0, \
{n})`), and so does frink"
);
}
return Ok((i as usize, n));
}
match scan_layer(name, "dec.blk.") {
Some(i) if i >= 0 => Ok((i as usize, n)),
_ => bail!(
"cannot tell which layer {name} is in, and on a mixture-of-experts checkpoint \
llama-quantize reads the FFN layer from the name (`Failed to determine layer \
for tensor {name}`); frink stops too"
),
}
}
}
#[cfg(test)]
mod tests;