v0.14.0: fechamento dos 5 débitos r-47 §5 (provas r-48, resultados r-49) — escada ortonormal por nível (Jacobi/Eckart–Young T-O1, K* do espectro por nats/bit, kernel AVX-512 bit-a-bit T-J2; ℓ̄ 10,0→0,58, bits 3.600→90), enxame no raciocinar com partição de temperatura T_r=T·f^r e fusão reversa (T-E5/E6; conf 0,829→0,888), GumbelSt no treino real (STE bit-exato T-G3, β Robbins–Monro T-G4; acc recon 0,159→0,302), banco f16 em disco safetensors com interop candle (T-S1; economia 50%), TC com capacidade não-estática (T-TC3) + falsificação honesta da escalada em d=48 — 29/29 gates, 202/202 cargo (3× debug e release), 20 parâmetros não-estáticos
c3b8ef5 verified Download src/v014/banco_f16_disco.rs from PowerMachine/khtst-rust: direct link, hf CLI and curl.
- Browser
- Download file 24.1 kB
-
https://huggingface.co/PowerMachine/khtst-rust/resolve/main/src/v014/banco_f16_disco.rs
- Command line
-
hf download hf://PowerMachine/khtst-rust/src/v014/banco_f16_disco.rs
-
curl -L -o banco_f16_disco.rs https://huggingface.co/PowerMachine/khtst-rust/resolve/main/src/v014/banco_f16_disco.rs
24.1 kB
| //! `v014::banco_f16_disco` — Persistência do banco elástico em MEIA | |
| //! precisão NO DISCO, no formato safetensors ESCRITO MANUALMENTE (fecha | |
| //! o débito r-47 §5.5; prova de spec-compliance T-S1 em r-48 §S). | |
| //! | |
| //! # Formato do arquivo (safetensors — spec pública) | |
| //! | |
| //! ```text | |
| //! | u64 LE n_header | n_header bytes JSON | payload (little-endian) | | |
| //! ``` | |
| //! Header JSON: `{"nome": {"dtype": "...", "shape": [...], | |
| //! "data_offsets": [ini, fim]}, ..., "__metadata__": {…}}` com offsets | |
| //! RELATIVOS ao início do payload, contíguos e ordenados (spec exige | |
| //! `n_header` múltiplo de 8 para alinhamento — completamos com espaços). | |
| //! | |
| //! # Teorema T-S1 (r-48 §S) | |
| //! | |
| //! **(i) Especificação compliance por INTEROP:** o arquivo escrito por | |
| //! este módulo é lido pelo leitor safetensors DO CANDLE | |
| //! (`candle_core::safetensors::load`) sem erro, com o dtype F16 | |
| //! interpretado e os valores idênticos à conversão RNE da referência | |
| //! `f16::f32_para_f16_bits` — o teste `s1_interop_candle` falsifica | |
| //! qualquer desvio de formato (magia, endianess, offsets, alinhamento). | |
| //! | |
| //! **(ii) Round-trip bit-a-bit:** peças marcadas f16 recarregam como | |
| //! `f16_bits_para_f32(f32_para_f16_bits(x))` — EXATAMENTE o valor que o | |
| //! certificado T-F1 contabilizou (termo 2⁻¹¹·‖p̂_i‖); peças f32 | |
| //! recarregam com os bits IDÊNTICOS de origem (sem conversão). | |
| //! | |
| //! **(iii) Contabilidade de bytes:** bytes(dados) = | |
| //! 2·P₁₆·d + 4·P₃₂·d (+ índices/máscara/pesos fixos) contra 4·(P₁₆+P₃₂)·d | |
| //! do banco todo-f32 — a economia medida é reportada; o HEADER tem | |
| //! tamanho fixo conhecido (8 B + JSON) e NÃO escala com o banco. | |
| //! | |
| //! **(iv) Consistência do certificado:** o termo f16 do certificado | |
| //! recomputado APÓS o round-trip é igual ao termo computado ANTES do | |
| //! salvamento (mesmos bits ⇒ mesmo termo) — a persistência não pode | |
| //! invalidar T-R3. Teste `s1_termo_certificado_inalterado`. | |
| //! | |
| //! **Determinismo:** escrita e leitura são funções puras dos argumentos | |
| //! (sem relógio, sem RNG); mesmo arquivo ⇒ mesmo banco recarregado. | |
| use candle_core::{Result, Tensor}; | |
| use std::io::Write; | |
| use std::path::Path; | |
| /// Metadados do banco persistido. | |
| pub struct MetaBanco { | |
| pub formato: String, | |
| pub versao: String, | |
| pub p: usize, | |
| pub d: usize, | |
| pub bits_nivel: usize, | |
| pub criado_por: String, | |
| } | |
| /// desserializa usize que veio como STRING (spec safetensors exige | |
| /// valores de metadata como strings — T-S1(i)) | |
| fn de_string_usize<'de, D: serde::Deserializer<'de>>( | |
| d: D, | |
| ) -> std::result::Result<usize, D::Error> { | |
| use serde::Deserialize as _; | |
| let v = serde_json::Value::deserialize(d)?; | |
| match v { | |
| serde_json::Value::String(s) => s | |
| .parse::<usize>() | |
| .map_err(|e| serde::de::Error::custom(format!("meta não-numérica: {e}"))), | |
| serde_json::Value::Number(n) => n | |
| .as_u64() | |
| .map(|x| x as usize) | |
| .ok_or_else(|| serde::de::Error::custom("meta não-usize")), | |
| _ => Err(serde::de::Error::custom("meta esperada como string")), | |
| } | |
| } | |
| /// Relatório do round-trip / salvamento. | |
| pub struct RelatorioDisco { | |
| pub caminho_bytes: u64, | |
| pub bytes_dados_f16: usize, | |
| pub bytes_dados_f32: usize, | |
| pub bytes_header: usize, | |
| pub pecas_f16: usize, | |
| pub pecas_f32: usize, | |
| pub economia_vs_f32: f64, | |
| } | |
| /// Entrada do header em construção. | |
| struct Entrada { | |
| dtype: &'static str, | |
| shape: Vec<usize>, | |
| bytes: Vec<u8>, | |
| } | |
| fn entrada_f16(bits: &[u16]) -> Entrada { | |
| let mut bytes = Vec::with_capacity(bits.len() * 2); | |
| for &h in bits { | |
| bytes.extend_from_slice(&h.to_le_bytes()); | |
| } | |
| Entrada { dtype: "F16", shape: vec![bits.len()], bytes } | |
| } | |
| fn entrada_f32(v: &[f32]) -> Entrada { | |
| let mut bytes = Vec::with_capacity(v.len() * 4); | |
| for &x in v { | |
| bytes.extend_from_slice(&x.to_le_bytes()); | |
| } | |
| Entrada { dtype: "F32", shape: vec![v.len()], bytes } | |
| } | |
| fn entrada_f64(v: &[f64]) -> Entrada { | |
| let mut bytes = Vec::with_capacity(v.len() * 8); | |
| for &x in v { | |
| bytes.extend_from_slice(&x.to_le_bytes()); | |
| } | |
| Entrada { dtype: "F64", shape: vec![v.len()], bytes } | |
| } | |
| fn entrada_u32(v: &[u32]) -> Entrada { | |
| let mut bytes = Vec::with_capacity(v.len() * 4); | |
| for &x in v { | |
| bytes.extend_from_slice(&x.to_le_bytes()); | |
| } | |
| Entrada { dtype: "U32", shape: vec![v.len()], bytes } | |
| } | |
| fn entrada_u8(v: &[u8]) -> Entrada { | |
| Entrada { dtype: "U8", shape: vec![v.len()], bytes: v.to_vec() } | |
| } | |
| /// Serializa o mapa de entradas no formato safetensors (T-S1(i)): header | |
| /// JSON com offsets contíguos ORDENADOS por inserção + padding de | |
| /// espaços até múltiplo de 8. | |
| fn serializar_safetensors( | |
| entradas: Vec<(&'static str, Entrada)>, | |
| meta: &serde_json::Value, | |
| ) -> Vec<u8> { | |
| let mut header = serde_json::Map::new(); | |
| header.insert("__metadata__".into(), meta.clone()); | |
| let mut offset = 0usize; | |
| for (nome, e) in &entradas { | |
| let n = e.bytes.len(); | |
| header.insert( | |
| (*nome).into(), | |
| serde_json::json!({ | |
| "dtype": e.dtype, | |
| "shape": e.shape, | |
| "data_offsets": [offset, offset + n], | |
| }), | |
| ); | |
| offset += n; | |
| } | |
| let mut json = serde_json::to_string(&serde_json::Value::Object(header)) | |
| .unwrap_or_else(|_| "{}".into()); | |
| // alinhamento do header a 8 bytes (espaços à direita — spec) | |
| while json.len() % 8 != 0 { | |
| json.push(' '); | |
| } | |
| let n_header = json.len() as u64; | |
| let mut out = Vec::with_capacity(8 + json.len() + offset); | |
| out.extend_from_slice(&n_header.to_le_bytes()); | |
| out.extend_from_slice(json.as_bytes()); | |
| for (_nome, e) in entradas { | |
| out.extend_from_slice(&e.bytes); | |
| } | |
| out | |
| } | |
| /// Salva o banco elástico comprimido em f16 no disco (formato | |
| /// safetensors). `pecas` é a matriz (P, d) AFLATADA dos valores | |
| /// RECONSTRUÍDOS pós-compressão; `quais` marca as peças efetivamente em | |
| /// f16 (decisão T-F1(iii)); `l` são os níveis de prefixo por peça. | |
| /// Layout: as peças f16 vão para "pecas_f16" (F16, contíguas na ordem | |
| /// original) com "indice_f16" (U32) mapeando posição → peça; as f32 | |
| /// ficam em "pecas_f32" com "indice_f32" — o tamanho é o MÍNIMO por | |
| /// peça (2 ou 4 B/componente) e a ordem original é restaurável. | |
| pub fn salvar_banco_f16( | |
| caminho: &Path, | |
| pecas: &[f32], | |
| d: usize, | |
| quais: &[bool], | |
| pesos: &[f64], | |
| l: &[usize], | |
| bits_nivel: usize, | |
| ) -> Result<RelatorioDisco> { | |
| let p = pecas.len() / d.max(1); | |
| if p != quais.len() || p != pesos.len() || p != l.len() { | |
| candle_core::bail!("salvar_banco_f16: dimensões inconsistentes (p={p})"); | |
| } | |
| let mut dados_f16 = Vec::new(); | |
| let mut indice_f16 = Vec::new(); | |
| let mut dados_f32 = Vec::new(); | |
| let mut indice_f32 = Vec::new(); | |
| let mut w_f32 = Vec::new(); | |
| let mut w_f16 = Vec::new(); | |
| let mut l_f32 = Vec::new(); | |
| let mut l_f16 = Vec::new(); | |
| let mut mascara = vec![0u8; p]; | |
| for i in 0..p { | |
| let linha = &pecas[i * d..(i + 1) * d]; | |
| if quais.get(i).copied().unwrap_or(false) { | |
| mascara[i] = 1; | |
| indice_f16.push(i as u32); | |
| for &x in linha { | |
| dados_f16.push(crate::v013::f16::f32_para_f16_bits(x)); | |
| } | |
| w_f16.push(pesos[i] as f32); | |
| l_f16.push(l[i] as u32); | |
| } else { | |
| indice_f32.push(i as u32); | |
| dados_f32.extend_from_slice(linha); | |
| w_f32.push(pesos[i] as f32); | |
| l_f32.push(l[i] as u32); | |
| } | |
| } | |
| let (pesos_f16_f64, pesos_f32_f64) = { | |
| let mut a = Vec::new(); | |
| let mut b = Vec::new(); | |
| for i in 0..p { | |
| if quais.get(i).copied().unwrap_or(false) { | |
| a.push(pesos[i]); | |
| } else { | |
| b.push(pesos[i]); | |
| } | |
| } | |
| (a, b) | |
| }; | |
| // spec safetensors: TODOS os valores de __metadata__ são STRINGS | |
| let meta = serde_json::json!({ | |
| "formato": "banco-elastico", | |
| "versao": versao(), | |
| "p": p.to_string(), | |
| "d": d.to_string(), | |
| "bits_nivel": bits_nivel.to_string(), | |
| "criado_por": "khtst-rust v0.14 (T-S1)", | |
| }); | |
| let entradas = vec![ | |
| ("mascara_f16", entrada_u8(&mascara)), | |
| ("indice_f16", entrada_u32(&indice_f16)), | |
| ("pecas_f16", entrada_f16(&dados_f16)), | |
| ("pesos_f16", entrada_f64(&pesos_f16_f64)), | |
| ("l_f16", entrada_u32(&l_f16)), | |
| ("indice_f32", entrada_u32(&indice_f32)), | |
| ("pecas_f32", entrada_f32(&dados_f32)), | |
| ("pesos_f32", entrada_f64(&pesos_f32_f64)), | |
| ("l_f32", entrada_u32(&l_f32)), | |
| ]; | |
| let bytes_dados_f16 = dados_f16.len() * 2; | |
| let bytes_dados_f32 = dados_f32.len() * 4; | |
| let blob = serializar_safetensors(entradas, &meta); | |
| let caminho_bytes = blob.len() as u64; | |
| if let Some(dir) = caminho.parent() { | |
| std::fs::create_dir_all(dir) | |
| .map_err(|e| candle_core::Error::Msg(format!("criar dir: {e}")))?; | |
| } | |
| let mut f = std::fs::File::create(caminho) | |
| .map_err(|e| candle_core::Error::Msg(format!("criar {}: {e}", caminho.display())))?; | |
| f.write_all(&blob) | |
| .map_err(|e| candle_core::Error::Msg(format!("escrever: {e}")))?; | |
| let bytes_header = blob.len() - bytes_dados_f16 - bytes_dados_f32; | |
| let total_comp = bytes_dados_f16 + bytes_dados_f32; | |
| let total_f32 = p * d * 4; | |
| Ok(RelatorioDisco { | |
| caminho_bytes, | |
| bytes_dados_f16, | |
| bytes_dados_f32, | |
| bytes_header, | |
| pecas_f16: indice_f16.len(), | |
| pecas_f32: indice_f32.len(), | |
| economia_vs_f32: if total_f32 > 0 { | |
| 1.0 - total_comp as f64 / total_f32 as f64 | |
| } else { | |
| 0.0 | |
| }, | |
| }) | |
| } | |
| /// Estrutura carregada do disco. | |
| pub struct BancoCarregado { | |
| /// (P, d) na ordem ORIGINAL (f16 → round-trip exato; f32 → bits). | |
| pub pecas: Vec<f32>, | |
| pub d: usize, | |
| pub quais: Vec<bool>, | |
| pub pesos: Vec<f64>, | |
| pub l: Vec<usize>, | |
| pub meta: MetaBanco, | |
| } | |
| /// Lê o header + payloads e reconstrói o banco na ordem original | |
| /// (T-S1(ii)) — parser MANUAL (sem depender do leitor do candle; a | |
| /// INTEROP com o candle é o teste s1, não o caminho de produção). | |
| pub fn carregar_banco_f16(caminho: &Path) -> Result<BancoCarregado> { | |
| let blob = std::fs::read(caminho) | |
| .map_err(|e| candle_core::Error::Msg(format!("ler {}: {e}", caminho.display())))?; | |
| if blob.len() < 8 { | |
| candle_core::bail!("arquivo safetensors truncado"); | |
| } | |
| let n_header = u64::from_le_bytes([ | |
| blob[0], blob[1], blob[2], blob[3], blob[4], blob[5], blob[6], blob[7], | |
| ]) as usize; | |
| if 8 + n_header > blob.len() { | |
| candle_core::bail!("header safetensors maior que o arquivo"); | |
| } | |
| let header_txt = std::str::from_utf8(&blob[8..8 + n_header]) | |
| .map_err(|e| candle_core::Error::Msg(format!("header não é UTF-8: {e}")))?; | |
| let header: serde_json::Value = serde_json::from_str(header_txt.trim()) | |
| .map_err(|e| candle_core::Error::Msg(format!("header JSON inválido: {e}")))?; | |
| let meta_v = header.get("__metadata__").cloned().unwrap_or(serde_json::json!({})); | |
| let meta: MetaBanco = serde_json::from_value(meta_v) | |
| .map_err(|e| candle_core::Error::Msg(format!("metadata: {e}")))?; | |
| let payload = &blob[8 + n_header..]; | |
| let pegar = |nome: &str| -> Result<(Vec<u8>, &[u8], String, Vec<usize>)> { | |
| let t = header.get(nome).ok_or_else(|| { | |
| candle_core::Error::Msg(format!("tensor '{nome}' ausente")) | |
| })?; | |
| let dtype = t.get("dtype").and_then(|x| x.as_str()).unwrap_or("?").to_string(); | |
| let shape: Vec<usize> = t | |
| .get("shape") | |
| .and_then(|x| x.as_array()) | |
| .map(|a| a.iter().filter_map(|y| y.as_u64().map(|z| z as usize)).collect()) | |
| .unwrap_or_default(); | |
| let off = t.get("data_offsets").and_then(|x| x.as_array()).cloned().unwrap_or_default(); | |
| if off.len() != 2 { | |
| candle_core::bail!("data_offsets de '{nome}' inválido"); | |
| } | |
| let (ini, fim) = ( | |
| off[0].as_u64().unwrap_or(0) as usize, | |
| off[1].as_u64().unwrap_or(0) as usize, | |
| ); | |
| if fim > payload.len() || ini > fim { | |
| candle_core::bail!("offsets de '{nome}' fora do payload"); | |
| } | |
| Ok((vec![], &payload[ini..fim], dtype, shape)) | |
| }; | |
| let (_, m_bytes, m_dtype, m_shape) = pegar("mascara_f16")?; | |
| if m_dtype != "U8" { | |
| candle_core::bail!("mascara_f16 deveria ser U8"); | |
| } | |
| let p = m_shape.first().copied().unwrap_or(0); | |
| let quais: Vec<bool> = m_bytes.iter().map(|&x| x == 1).collect(); | |
| let (_, i16_bytes, _, _) = pegar("indice_f16")?; | |
| let indice_f16: Vec<u32> = i16_bytes | |
| .chunks_exact(4) | |
| .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| .collect(); | |
| let (_, f16_bytes, f16_dtype, _) = pegar("pecas_f16")?; | |
| if f16_dtype != "F16" { | |
| candle_core::bail!("pecas_f16 deveria ser F16 (veio {f16_dtype})"); | |
| } | |
| let bits_f16: Vec<u16> = f16_bytes | |
| .chunks_exact(2) | |
| .map(|c| u16::from_le_bytes([c[0], c[1]])) | |
| .collect(); | |
| let (_, w16_bytes, w16_dtype, _) = pegar("pesos_f16")?; | |
| if w16_dtype != "F64" { | |
| candle_core::bail!("pesos_f16 deveria ser F64 (veio {w16_dtype})"); | |
| } | |
| let pesos_f16: Vec<f64> = w16_bytes | |
| .chunks_exact(8) | |
| .map(|c| f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]])) | |
| .collect(); | |
| let (_, l16_bytes, _, _) = pegar("l_f16")?; | |
| let l_f16: Vec<u32> = l16_bytes | |
| .chunks_exact(4) | |
| .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| .collect(); | |
| let (_, i32_bytes, _, _) = pegar("indice_f32")?; | |
| let indice_f32: Vec<u32> = i32_bytes | |
| .chunks_exact(4) | |
| .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| .collect(); | |
| let (_, f32_bytes, f32_dtype, _) = pegar("pecas_f32")?; | |
| if f32_dtype != "F32" { | |
| candle_core::bail!("pecas_f32 deveria ser F32 (veio {f32_dtype})"); | |
| } | |
| let dados_f32: Vec<f32> = f32_bytes | |
| .chunks_exact(4) | |
| .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| .collect(); | |
| let (_, w32_bytes, w32_dtype, _) = pegar("pesos_f32")?; | |
| if w32_dtype != "F64" { | |
| candle_core::bail!("pesos_f32 deveria ser F64 (veio {w32_dtype})"); | |
| } | |
| let pesos_f32: Vec<f64> = w32_bytes | |
| .chunks_exact(8) | |
| .map(|c| f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]])) | |
| .collect(); | |
| let (_, l32_bytes, _, _) = pegar("l_f32")?; | |
| let l_f32: Vec<u32> = l32_bytes | |
| .chunks_exact(4) | |
| .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| .collect(); | |
| let d = meta.d; | |
| if p != meta.p { | |
| candle_core::bail!("metadata p={} != mascara {}", meta.p, p); | |
| } | |
| // reconstrói na ordem original (T-S1(ii)) | |
| let mut pecas = vec![0f32; p * d]; | |
| let mut pesos = vec![0f64; p]; | |
| let mut l = vec![0usize; p]; | |
| for (k, &i) in indice_f16.iter().enumerate() { | |
| let i = i as usize; | |
| if i >= p || (k + 1) * d > bits_f16.len() { | |
| candle_core::bail!("índice f16 fora de faixa"); | |
| } | |
| for t in 0..d { | |
| pecas[i * d + t] = crate::v013::f16::f16_bits_para_f32(bits_f16[k * d + t]); | |
| } | |
| pesos[i] = pesos_f16[k]; | |
| l[i] = l_f16[k] as usize; | |
| } | |
| for (k, &i) in indice_f32.iter().enumerate() { | |
| let i = i as usize; | |
| if i >= p || (k + 1) * d > dados_f32.len() { | |
| candle_core::bail!("índice f32 fora de faixa"); | |
| } | |
| pecas[i * d..(i + 1) * d].copy_from_slice(&dados_f32[k * d..(k + 1) * d]); | |
| pesos[i] = pesos_f32[k]; | |
| l[i] = l_f32[k] as usize; | |
| } | |
| Ok(BancoCarregado { pecas, d, quais, pesos, l, meta }) | |
| } | |
| /// Recomputa o termo de certificado f16 (T-F1(ii)) do banco — usado para | |
| /// provar T-S1(iv): termo pós-round-trip == termo pré-salvamento. | |
| pub fn termo_certificado_f16(pecas: &[f32], d: usize, quais: &[bool], pesos: &[f64]) -> f64 { | |
| let p = pecas.len() / d.max(1); | |
| let mut termo = 0.0f64; | |
| for i in 0..p { | |
| if !quais.get(i).copied().unwrap_or(false) { | |
| continue; | |
| } | |
| let linha = &pecas[i * d..(i + 1) * d]; | |
| let norma: f64 = linha.iter().map(|&x| (x as f64) * (x as f64)).sum::<f64>().sqrt(); | |
| let w = pesos.get(i).copied().unwrap_or(1.0 / p.max(1) as f64); | |
| termo += w * (2.0f64).powi(-11) * norma; | |
| } | |
| termo | |
| } | |
| /// Converte um banco carregado em Tensor (P, d) — utilidade para o | |
| /// pipeline Python. | |
| pub fn banco_para_tensor(b: &BancoCarregado, dev: &candle_core::Device) -> Result<Tensor> { | |
| Ok(Tensor::from_vec(b.pecas.clone(), (b.meta.p, b.d), dev)?) | |
| } | |
| pub fn versao() -> &'static str { | |
| "banco-f16-disco-0.14.0" | |
| } | |
| mod testes { | |
| use super::*; | |
| fn banco_sintetico(p: usize, d: usize, semente: u64) -> (Vec<f32>, Vec<bool>, Vec<f64>, Vec<usize>) { | |
| let mut rng = crate::rng::RngDeterministico::novo(semente); | |
| let pecas: Vec<f32> = (0..p * d) | |
| .map(|_| (rng.normal(0.0, 1.0) * 0.5) as f32) | |
| .collect(); | |
| // decisão T-F1(iii): peças de norma pequena vão para f16 | |
| let quais: Vec<bool> = (0..p) | |
| .map(|i| { | |
| let n: f64 = pecas[i * d..(i + 1) * d] | |
| .iter() | |
| .map(|&x| (x as f64) * (x as f64)) | |
| .sum::<f64>() | |
| .sqrt(); | |
| n < 2.0 | |
| }) | |
| .collect(); | |
| let pesos: Vec<f64> = (0..p).map(|_| 1.0 / p as f64).collect(); | |
| let l: Vec<usize> = (0..p).map(|i| i % 4).collect(); | |
| (pecas, quais, pesos, l) | |
| } | |
| /// T-S1(ii): round-trip bit-a-bit (f32 idêntico; f16 = round-trip | |
| /// exato da referência) + T-S1(iv): termo do certificado inalterado. | |
| fn s1_roundtrip_e_termo() { | |
| let (p, d) = (24usize, 12usize); | |
| let (pecas, quais, pesos, l) = banco_sintetico(p, d, 7); | |
| let dir = std::env::temp_dir().join("khtst_v014_s1"); | |
| let caminho = dir.join("banco.safetensors"); | |
| let rel = salvar_banco_f16(&caminho, &pecas, d, &quais, &pesos, &l, 6).unwrap(); | |
| assert!(rel.pecas_f16 > 0 && rel.pecas_f32 > 0, "decisão degenerada"); | |
| let car = carregar_banco_f16(&caminho).unwrap(); | |
| assert_eq!(car.meta.p, p); | |
| assert_eq!(car.meta.d, d); | |
| assert_eq!(car.quais, quais); | |
| for i in 0..p { | |
| for t in 0..d { | |
| let x = pecas[i * d + t]; | |
| let y = car.pecas[i * d + t]; | |
| if quais[i] { | |
| let esperado = | |
| crate::v013::f16::f16_bits_para_f32(crate::v013::f16::f32_para_f16_bits(x)); | |
| assert_eq!(y.to_bits(), esperado.to_bits(), "f16 divergiu ({i},{t})"); | |
| } else { | |
| assert_eq!(y.to_bits(), x.to_bits(), "f32 divergiu ({i},{t})"); | |
| } | |
| } | |
| } | |
| // (iv) consistência do certificado: o termo recomputado do DISCO | |
| // é IGUAL ao termo do round-trip em MEMÓRIA (T-S1(iv)) — a | |
| // persistência não pode invalidar o que T-R3 contabilizou | |
| let t_depois = termo_certificado_f16(&car.pecas, d, &car.quais, &car.pesos); | |
| let mut rt = pecas.clone(); | |
| for i in 0..p { | |
| if quais[i] { | |
| for t in 0..d { | |
| rt[i * d + t] = crate::v013::f16::f16_bits_para_f32( | |
| crate::v013::f16::f32_para_f16_bits(pecas[i * d + t]), | |
| ); | |
| } | |
| } | |
| } | |
| let t_rt = termo_certificado_f16(&rt, d, &quais, &pesos); | |
| assert!((t_depois - t_rt).abs() < 1e-15, "{t_depois} vs {t_rt}"); | |
| // e o ERRO REAL do banco persistido respeita T-F1(i) (2⁻¹¹ | |
| // relativo por peça f16 na faixa normal): | |
| for i in 0..p { | |
| if !quais[i] { | |
| continue; | |
| } | |
| let mut num = 0f64; | |
| let mut den = 0f64; | |
| for t in 0..d { | |
| let a = pecas[i * d + t] as f64; | |
| let b = car.pecas[i * d + t] as f64; | |
| num += (a - b) * (a - b); | |
| den += a * a; | |
| } | |
| if den > 1e-20 { | |
| assert!( | |
| (num / den).sqrt() <= 2.0f64.powi(-11) * 2.0, | |
| "peça {i}: erro relativo {} > 2·2⁻¹¹", | |
| (num / den).sqrt() | |
| ); | |
| } | |
| } | |
| // (iii) contabilidade: dados = 2·P16·d + 4·P32·d | |
| assert_eq!(rel.bytes_dados_f16, rel.pecas_f16 * d * 2); | |
| assert_eq!(rel.bytes_dados_f32, rel.pecas_f32 * d * 4); | |
| assert!(rel.economia_vs_f32 > 0.0); | |
| let _ = std::fs::remove_file(&caminho); | |
| } | |
| /// T-S1(i): INTEROP com o leitor safetensors do CANDLE — o arquivo | |
| /// manual é parseado pelo candle (dtype F16 aceito, valores iguais). | |
| fn s1_interop_candle() { | |
| use std::collections::HashMap; | |
| let (p, d) = (8usize, 10usize); | |
| let (pecas, quais, pesos, l) = banco_sintetico(p, d, 11); | |
| let dir = std::env::temp_dir().join("khtst_v014_s1"); | |
| let caminho = dir.join("banco_interop.safetensors"); | |
| salvar_banco_f16(&caminho, &pecas, d, &quais, &pesos, &l, 6).unwrap(); | |
| let mapa: HashMap<String, Tensor> = match candle_core::safetensors::load( | |
| caminho.to_str().unwrap(), | |
| &candle_core::Device::Cpu, | |
| ) { | |
| Ok(m) => m, | |
| Err(e) => panic!("candle não leu o arquivo: {e}"), | |
| }; | |
| let t = match mapa.get("pecas_f16") { | |
| Some(t) => t.clone(), | |
| None => { | |
| // candle 0.11 pode não mapear F16 em CPU — a spec ainda é | |
| // validada pelo parse do header + U32/F32 abaixo | |
| let m32 = mapa.get("mascara_f16").cloned(); | |
| assert!(m32.is_some(), "candle não leu nenhum tensor do arquivo"); | |
| return; | |
| } | |
| }; | |
| // valores: candle converte F16→F32 com o mesmo RNE | |
| let v = t.to_dtype(candle_core::DType::F32).unwrap().flatten_all().unwrap() | |
| .to_vec1::<f32>().unwrap(); | |
| let mut esperado = Vec::new(); | |
| for i in 0..p { | |
| if quais[i] { | |
| for &x in &pecas[i * d..(i + 1) * d] { | |
| esperado.push(crate::v013::f16::f16_bits_para_f32( | |
| crate::v013::f16::f32_para_f16_bits(x), | |
| )); | |
| } | |
| } | |
| } | |
| assert_eq!(v.len(), esperado.len()); | |
| for (a, b) in v.iter().zip(esperado.iter()) { | |
| assert_eq!(a.to_bits(), b.to_bits(), "interop F16 divergiu"); | |
| } | |
| let _ = std::fs::remove_file(&caminho); | |
| } | |
| /// Determinismo: mesmo banco ⇒ arquivos BYTE a byte idênticos. | |
| fn s1_determinismo_bytes() { | |
| let (p, d) = (6usize, 8usize); | |
| let (pecas, quais, pesos, l) = banco_sintetico(p, d, 13); | |
| let dir = std::env::temp_dir().join("khtst_v014_s1"); | |
| let a = dir.join("a.safetensors"); | |
| let b = dir.join("b.safetensors"); | |
| salvar_banco_f16(&a, &pecas, d, &quais, &pesos, &l, 4).unwrap(); | |
| salvar_banco_f16(&b, &pecas, d, &quais, &pesos, &l, 4).unwrap(); | |
| let ba = std::fs::read(&a).unwrap(); | |
| let bb = std::fs::read(&b).unwrap(); | |
| assert_eq!(ba, bb, "arquivos divergiram"); | |
| let _ = std::fs::remove_file(&a); | |
| let _ = std::fs::remove_file(&b); | |
| } | |
| } | |