250 lines
9.5 KiB
Rust
250 lines
9.5 KiB
Rust
//! Conversion of one dense tensor into the form the engine reads (exact or rounded BF16, F16, F32) while it streams
|
|
//! into `dense.bin`, with the digest of the source bytes and the error of each rounding.
|
|
//! Separate from `dense_files`, which walks the tensors, because it holds the per-kind conversion rules.
|
|
|
|
use super::{
|
|
Converted, Digest, Error64, File, Result, Sha256, Shard, Write, bf16_round_nearest_even, gguf, kar_codec,
|
|
kind_name, stream_f32, values_of,
|
|
};
|
|
|
|
/// A tensor to convert and the shard it is read from.
|
|
#[derive(Clone, Copy)]
|
|
pub(super) struct SourceTensor<'a> {
|
|
pub(super) shard: &'a Shard,
|
|
pub(super) tensor: &'a gguf::TensorInfo,
|
|
}
|
|
|
|
/// The pack form of one tensor the engine reads from `dense.bin` when it is stored otherwise. Mirrors
|
|
/// `tools/iq_pack.py::convert` for every source kind: same accept/reject decision, same bytes, same record.
|
|
pub(super) fn convert_tensor(
|
|
input: &mut File,
|
|
source: SourceTensor<'_>,
|
|
target: u32,
|
|
compat_bf16: bool,
|
|
dense: &mut File,
|
|
) -> Result<Converted> {
|
|
let mut conv = Conv::new(source.shard, source.tensor, target, compat_bf16);
|
|
match target {
|
|
30 => conv.convert_bf16(input, dense),
|
|
1 => conv.convert_f16(input, dense),
|
|
0 => conv.convert_f32(input, dense),
|
|
_ => Err("unsupported native pack conversion target".into()),
|
|
}
|
|
}
|
|
|
|
/// One conversion in flight: the source, the digest of the bytes read and the count of bytes written.
|
|
struct Conv<'a> {
|
|
shard: &'a Shard,
|
|
tensor: &'a gguf::TensorInfo,
|
|
target: u32,
|
|
compat_bf16: bool,
|
|
src: u32,
|
|
digest: Sha256,
|
|
written: u64,
|
|
out: Vec<u8>,
|
|
}
|
|
|
|
type Step = std::result::Result<(), String>;
|
|
|
|
fn write_counted(dense: &mut File, written: &mut u64, bytes: &[u8]) -> Step {
|
|
dense.write_all(bytes).map_err(|e| e.to_string())?;
|
|
*written += bytes.len() as u64;
|
|
Ok(())
|
|
}
|
|
|
|
impl<'a> Conv<'a> {
|
|
fn new(shard: &'a Shard, tensor: &'a gguf::TensorInfo, target: u32, compat_bf16: bool) -> Self {
|
|
Self {
|
|
shard,
|
|
tensor,
|
|
target,
|
|
compat_bf16,
|
|
src: tensor.kind,
|
|
digest: Sha256::new(),
|
|
written: 0,
|
|
out: Vec::new(),
|
|
}
|
|
}
|
|
|
|
fn src_lower(&self) -> String {
|
|
kind_name(self.src).to_ascii_lowercase()
|
|
}
|
|
|
|
fn need_compat(&self, what: &str) -> Result<()> {
|
|
if self.compat_bf16 {
|
|
Ok(())
|
|
} else {
|
|
Err(format!(
|
|
"{}: stored as {what} but the engine reads {}; use --compat-bf16",
|
|
self.tensor.name,
|
|
kind_name(self.target)
|
|
)
|
|
.into())
|
|
}
|
|
}
|
|
|
|
fn finish(&self, index_kind: u32, dst: u64, record: (String, bool, f64)) -> Converted {
|
|
Converted {
|
|
index_kind,
|
|
written: self.written,
|
|
dst,
|
|
record: Some(record),
|
|
source_sha256: hex::encode(self.digest.clone().finalize()),
|
|
}
|
|
}
|
|
|
|
fn convert_bf16(&mut self, input: &mut File, dense: &mut File) -> Result<Converted> {
|
|
// F32 whose values are all exactly BF16 (low 16 bits zero): the exact path, whole tensor or nothing.
|
|
if self.src == 0 && self.values_all_bf16(input)? {
|
|
return self.bf16_exact(input, dense);
|
|
}
|
|
self.need_compat(if self.src == 0 { "F32 with values that are not BF16" } else { kind_name(self.src) })?;
|
|
self.bf16_rounded(input, dense)
|
|
}
|
|
|
|
fn values_all_bf16(&self, input: &mut File) -> Result<bool> {
|
|
let mut all = true;
|
|
stream_f32(input, self.shard, self.tensor, |_, values| {
|
|
all &= values_of(values).all(|v| v.to_bits() & 0xffff == 0);
|
|
Ok(())
|
|
})?;
|
|
Ok(all)
|
|
}
|
|
|
|
fn bf16_exact(&mut self, input: &mut File, dense: &mut File) -> Result<Converted> {
|
|
let (shard, tensor) = (self.shard, self.tensor);
|
|
stream_f32(input, shard, tensor, |raw, values| {
|
|
self.digest.update(raw);
|
|
self.out.clear();
|
|
for v in values_of(values) {
|
|
exact_bf16_value(&tensor.name, v, &mut self.out)?;
|
|
}
|
|
write_counted(dense, &mut self.written, &self.out)
|
|
})?;
|
|
let written = self.written;
|
|
let record = ("f32->bf16: the values are BF16's (low 16 bits zero)".to_owned(), true, 0.0);
|
|
Ok(self.finish(4, written, record))
|
|
}
|
|
|
|
fn bf16_rounded(&mut self, input: &mut File, dense: &mut File) -> Result<Converted> {
|
|
let mut stats = Error64::new();
|
|
let (shard, tensor) = (self.shard, self.tensor);
|
|
stream_f32(input, shard, tensor, |raw, values| {
|
|
self.digest.update(raw);
|
|
self.out.clear();
|
|
for v in values_of(values) {
|
|
rounded_bf16_value(&tensor.name, v, &mut stats, &mut self.out)?;
|
|
}
|
|
write_counted(dense, &mut self.written, &self.out)
|
|
})?;
|
|
let method = if matches!(self.src, 0 | 1 | 30) {
|
|
format!("{}->bf16 round-to-nearest-even (--compat-bf16)", self.src_lower())
|
|
} else {
|
|
"dequantize->bf16 round-to-nearest-even (--compat-bf16)".to_owned()
|
|
};
|
|
let written = self.written;
|
|
Ok(self.finish(4, written, (method, stats.exact, stats.max_abs_err)))
|
|
}
|
|
|
|
fn convert_f16(&mut self, input: &mut File, dense: &mut File) -> Result<Converted> {
|
|
// The PLE conv kernel reads F16. F32 goes in as index kind 3 (the loader narrows it); anything else
|
|
// is narrowed here, which only --compat-bf16 allows.
|
|
if self.src != 0 {
|
|
self.need_compat(kind_name(self.src))?;
|
|
}
|
|
let mut stats = Error64::new();
|
|
let (shard, tensor, src) = (self.shard, self.tensor, self.src);
|
|
stream_f32(input, shard, tensor, |raw, values| {
|
|
self.digest.update(raw);
|
|
self.out.clear();
|
|
for v in values_of(values) {
|
|
f16_value(&tensor.name, v, src, &mut stats, &mut self.out)?;
|
|
}
|
|
write_counted(dense, &mut self.written, &self.out)
|
|
})?;
|
|
let (index_kind, dst, method) = self.f16_layout();
|
|
Ok(self.finish(index_kind, dst, (method, stats.exact, stats.max_abs_err)))
|
|
}
|
|
|
|
/// The index kind, destination bytes and method of an F16 conversion: F32 stays F32 for the loader to narrow.
|
|
fn f16_layout(&self) -> (u32, u64, String) {
|
|
if self.src == 0 {
|
|
(3, self.written / 2, "f32->f16 by the loader (index kind 3, round-to-nearest-even)".to_owned())
|
|
} else {
|
|
(5, self.written, format!("{}->f16 round-to-nearest-even (--compat-bf16)", self.src_lower()))
|
|
}
|
|
}
|
|
|
|
fn convert_f32(&mut self, input: &mut File, dense: &mut File) -> Result<Converted> {
|
|
if !matches!(self.src, 0 | 1 | 30) {
|
|
self.need_compat(kind_name(self.src))?;
|
|
}
|
|
let (shard, tensor, src) = (self.shard, self.tensor, self.src);
|
|
stream_f32(input, shard, tensor, |raw, values| {
|
|
self.digest.update(raw);
|
|
if src != 1 {
|
|
return write_counted(dense, &mut self.written, values);
|
|
}
|
|
// F16 -> F32 as numpy/IEEE conversion does it: a signaling NaN comes out quiet.
|
|
self.out.clear();
|
|
for v in values_of(values) {
|
|
let bits = v.to_bits();
|
|
let quiet = if v.is_nan() { bits | 0x0040_0000 } else { bits };
|
|
self.out.extend_from_slice(&quiet.to_le_bytes());
|
|
}
|
|
write_counted(dense, &mut self.written, &self.out)
|
|
})?;
|
|
let written = self.written;
|
|
let record = (format!("{}->f32 widening", self.src_lower()), true, 0.0);
|
|
Ok(self.finish(2, written, record))
|
|
}
|
|
}
|
|
|
|
fn exact_bf16_value(name: &str, v: f32, out: &mut Vec<u8>) -> Step {
|
|
if !v.is_finite() {
|
|
return Err(format!("{name} is F32 with non-finite values; refused rather than converted"));
|
|
}
|
|
out.extend_from_slice(&((v.to_bits() >> 16) as u16).to_le_bytes());
|
|
Ok(())
|
|
}
|
|
|
|
fn rounded_bf16_value(name: &str, v: f32, stats: &mut Error64, out: &mut Vec<u8>) -> Step {
|
|
if !v.is_finite() {
|
|
return Err(format!("{name}: cannot convert non-finite weights to BF16"));
|
|
}
|
|
let bits = bf16_round_nearest_even(v);
|
|
let back = f32::from_bits(u32::from(bits) << 16);
|
|
if back.is_infinite() {
|
|
// iq_pack.py writes the infinity and records max_abs_err=inf; a pack must not carry it.
|
|
return Err(format!("{name}: a value rounds beyond BF16's range, which the engine reads it as"));
|
|
}
|
|
stats.note(back, v);
|
|
out.extend_from_slice(&bits.to_le_bytes());
|
|
Ok(())
|
|
}
|
|
|
|
fn f16_value(name: &str, v: f32, src: u32, stats: &mut Error64, out: &mut Vec<u8>) -> Step {
|
|
if !v.is_finite() {
|
|
return Err(format!("{name}: cannot convert non-finite weights to F16"));
|
|
}
|
|
let half = kar_codec::f32_to_f16_bits(v);
|
|
let back = kar_codec::f16_bits_to_f32(half);
|
|
if !back.is_finite() {
|
|
return Err(format!("{name}: a value is beyond F16's range, which the engine reads it as"));
|
|
}
|
|
stats.note(back, v);
|
|
if src == 0 {
|
|
// Index kind 3 stores F32; the existing loader narrows it.
|
|
out.extend_from_slice(&v.to_le_bytes());
|
|
} else {
|
|
out.extend_from_slice(&half.to_le_bytes());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// `iq_pack.py` `NATIVE_PLE_KEY`: the PLE key encodings left in the GGUF for the engine's native PLE key (Q8_0, Q2_0,
|
|
/// and since Strata 0.1.50 IQ3_XXS and IQ4_XS, #381). Another quantized key takes the BF16 path (`--compat-bf16`).
|
|
pub(super) fn native_ple_key(kind: u32) -> bool {
|
|
matches!(kind, 8 | 42 | 18 | 23)
|
|
}
|