Skip to main content

qualia_core_db/q42/p64_weight/
layout.rs

1//! P64 container **byte layout**: magic/version/flags, the cache-line (64 B) DOD structs
2//! (`P64WeightHeader`, `P64TensorEntry`, `P64HParams`, `P64LayerScheduleEntry`), the tensor-role
3//! and header-flag constants, and the little-endian (de)serialization for the header + hparams.
4//! Every constant and offset here is format-critical and must not change.
5
6pub const P64_MAGIC: [u8; 4] = *b"p64\0";
7/// Container format version written by the canonical compiler.
8/// Keep in lock-step with `docs/manuals/standards/p64-weight-container-standard.md`.
9pub const P64_VERSION: u16 = 4;
10
11/// Return `true` only for the canonical four-byte P64 container magic.
12///
13/// Keep format sniffing centralized here. Historical code used `.q42` names
14/// and, in one WASM path, compared against the non-canonical `b"P64"` literal.
15#[inline]
16pub fn has_p64_magic(data: &[u8]) -> bool {
17    data.starts_with(&P64_MAGIC)
18}
19/// 14 = 16 KB pages (default; minimizes page faults on large FFN blocks). 12 = 4 KB.
20pub const P64_DEFAULT_PAGE_LOG2: u16 = 14;
21pub const P64_WEIGHT_HEADER_BYTES: usize = 64;
22pub const P64_TENSOR_ENTRY_BYTES: usize = 64;
23/// Ten little-endian `f32` values plus 24 bytes of zero padding.
24///
25/// Keeping every coordinate in one cache line makes `manifold_idx` an exact
26/// 64-byte stride and prevents neighbouring coordinates from sharing a cache
27/// line or a WASM SIMD fetch.
28pub const P64_MANIFOLD_ENTRY_BYTES: usize = 64;
29
30// ── Header flags (bits of `P64WeightHeader::flags`) ─────────────────────────
31pub const P64_FLAG_LITTLE_ENDIAN: u16 = 1 << 0;
32// Bits 1–2: see `FORMAT_FLAG_RAW_TRANSCODE` / `FORMAT_FLAG_TERNARY` below (aliases kept
33// for historical call sites).
34/// At least one 2-D weight matrix was converted to `GGML_TYPE_Q4_K_SOA` (112).
35pub const P64_FLAG_Q4K_SOA: u16 = 1 << 3;
36/// Tensor blob region is **layer-major** (known roles ordered by layer, then role).
37/// Decode residency / CUDA slab fill SHOULD walk entries in table order.
38pub const P64_FLAG_LAYER_MAJOR: u16 = 1 << 4;
39/// Blobs use **layer-pack** alignment: page-align at layer boundaries only; 256 B within layer.
40pub const P64_FLAG_LAYER_PACK: u16 = 1 << 5;
41/// `role_table_offset` points at a layer schedule table (`P64LayerScheduleEntry` × n_layer).
42pub const P64_FLAG_LAYER_SCHEDULE: u16 = 1 << 6;
43
44/// One row of the optional layer schedule table (64 B, cache-line DOD).
45/// Written when [`P64_FLAG_LAYER_SCHEDULE`] is set; offset in `role_table_offset`.
46#[repr(C, align(64))]
47#[derive(Clone, Copy, Debug)]
48pub struct P64LayerScheduleEntry {
49    pub layer: u32,
50    /// Inclusive start of first blob in this layer (file offset).
51    pub blob_begin: u32,
52    /// Exclusive end of last blob in this layer.
53    pub blob_end: u32,
54    pub tensor_count: u16,
55    /// Bit i set if role_id `i` (0..14) appears in this layer.
56    pub roles_mask: u16,
57    pub reserved: [u8; 48],
58}
59impl Default for P64LayerScheduleEntry {
60    fn default() -> Self {
61        Self {
62            layer: 0,
63            blob_begin: 0,
64            blob_end: 0,
65            tensor_count: 0,
66            roles_mask: 0,
67            reserved: [0; 48],
68        }
69    }
70}
71const _: () = assert!(core::mem::size_of::<P64LayerScheduleEntry>() == 64);
72
73// Tensor roles.
74pub const P64_ROLE_ATTN_K: u16 = 0;
75pub const P64_ROLE_ATTN_V: u16 = 1;
76pub const P64_ROLE_ATTN_Q: u16 = 2;
77pub const P64_ROLE_ATTN_OUTPUT: u16 = 3;
78pub const P64_ROLE_FFN_GATE: u16 = 4;
79pub const P64_ROLE_FFN_UP: u16 = 5;
80pub const P64_ROLE_FFN_DOWN: u16 = 6;
81pub const P64_ROLE_ATTN_NORM: u16 = 7;
82pub const P64_ROLE_FFN_NORM: u16 = 8;
83pub const P64_ROLE_TOKEN_EMBD: u16 = 9;
84pub const P64_ROLE_OUTPUT: u16 = 10;
85pub const P64_ROLE_OUTPUT_NORM: u16 = 11;
86pub const P64_ROLE_ATTN_SUBLN: u16 = 12;
87pub const P64_ROLE_FFN_SUBLN: u16 = 13;
88/// A source GGUF tensor preserved byte-for-byte but not consumed by a known
89/// engine role. Its source offset and name hash remain in the entry so a
90/// validator can still prove complete model preservation.
91pub const P64_ROLE_UNKNOWN: u16 = 0xFFFE;
92/// `layer` sentinel for non-layer (global) tensors.
93pub const P64_LAYER_GLOBAL: u16 = 0xFFFF;
94
95// Metadata bitfields are handled by the q42 layer, no longer embedded in weights.
96
97/// Precision view flags for multi-precision `.p64` containers.
98pub const P64_VIEW_FLAG_F32: u16 = 1 << 0;
99pub const P64_VIEW_FLAG_F16: u16 = 1 << 1;
100pub const P64_VIEW_FLAG_BF16: u16 = 1 << 2;
101pub const P64_VIEW_FLAG_Q8_0: u16 = 1 << 3;
102pub const P64_VIEW_FLAG_Q4_K: u16 = 1 << 4;
103pub const P64_VIEW_FLAG_SOA: u16 = 1 << 5;
104pub const P64_VIEW_FLAG_TERNARY_158: u16 = 1 << 6;
105
106#[repr(C, align(64))]
107#[derive(Clone, Copy, Debug)]
108pub struct P64WeightHeader {
109    pub magic: [u8; 4], // b"p64\0"
110    pub version: u16,   // 3
111    pub flags: u16,     // Endianness & Feature Flags
112
113    // 32-bit Relative Offsets (WASM-native)
114    pub role_table_offset: u32,     // Maps tensors to semantic roles
115    pub tensor_table_offset: u32,   // Descriptor table (shape, dtype)
116    pub tokenizer_offset: u32,      // Embedded tokenizer vocabulary
117    pub hparams_offset: u32,        // Hyperparameters
118    pub string_table_offset: u32,   // Centralized string pool
119    pub checksum_offset: u32,       // Cryptographic hash for tamper-evidence
120    pub manifold_table_offset: u32, // Offset to 10D ManifoldCoordinate10D table
121
122    pub tensor_count: u32, // Number of tensors
123    pub page_size: u32,    // Hardware alignment (e.g., 4096)
124
125    pub reserved: [u8; 20], // Pad exactly to 64 bytes
126}
127
128#[repr(C, align(64))]
129#[derive(Clone, Copy, Debug)]
130pub struct P64TensorEntry {
131    pub name_offset: u32,          // Relative offset to string table
132    pub role_id: u16,              // Standardized enum (e.g., P64_ROLE_FFN_UP)
133    pub dtype: u16,                // Primary data type (FP32, FP16, etc.)
134    pub manifold_idx: u32,         // Index into the 10D Manifold table
135    pub rank: u32,                 // Number of dimensions
136    pub dimensions: [u32; 4],      // Shape of the tensor
137    pub blob_offset: u32,          // Relative offset to primary tensor data
138    pub blob_size: u32,            // Size in bytes of primary blob
139    pub source_offset: u64,        // Original offset inside source container
140    pub source_name_hash: u64,     // Original tensor-name hash
141    pub alt_dtype: u16,            // Secondary/quantized view dtype (e.g. Q4_K / Ternary)
142    pub precision_views_mask: u16, // Bitmask of available precision loading views
143    pub alt_blob_offset: u32,      // Relative offset to secondary quantized blob
144}
145
146#[repr(C, align(64))]
147#[derive(Clone, Copy, Debug)]
148pub struct P64HParams {
149    pub n_layer: u32,
150    pub n_embd: u32,
151    pub n_head: u32,
152    pub n_kv_head: u32,
153    pub vocab_size: u32,
154    pub rope_freq_base: f32,
155    pub rope_scale: f32,
156    /// Explicit head dim (`0` = derive n_embd/n_head). Occupies former reserved[0..4].
157    pub head_dim: u32,
158    pub head_dim_swa: u32,
159    pub sliding_window: u32,
160    pub shared_kv_layers: u32,
161    pub logit_softcap: f32,
162    pub architecture: u32,
163    pub arch_flags: u32,
164    pub reserved: [u8; 8], // Pad exactly to 64 bytes
165}
166
167// Layouts are exact multiples of 64 for Cache-Line DOD perfection.
168const _: () = assert!(core::mem::size_of::<P64WeightHeader>() == P64_WEIGHT_HEADER_BYTES);
169const _: () = assert!(core::mem::size_of::<P64TensorEntry>() == P64_TENSOR_ENTRY_BYTES);
170const _: () = assert!(core::mem::size_of::<P64HParams>() == 64);
171
172impl P64WeightHeader {
173    pub fn read_le(data: &[u8]) -> Result<Self, String> {
174        if data.len() < P64_WEIGHT_HEADER_BYTES {
175            return Err("p64: truncated header".to_string());
176        }
177        let u16a = |o: usize| u16::from_le_bytes(data[o..o + 2].try_into().unwrap());
178        let u32a = |o: usize| u32::from_le_bytes(data[o..o + 4].try_into().unwrap());
179        let mut magic = [0u8; 4];
180        magic.copy_from_slice(&data[0..4]);
181        Ok(Self {
182            magic,
183            version: u16a(4),
184            flags: u16a(6),
185            role_table_offset: u32a(8),
186            tensor_table_offset: u32a(12),
187            tokenizer_offset: u32a(16),
188            hparams_offset: u32a(20),
189            string_table_offset: u32a(24),
190            checksum_offset: u32a(28),
191            manifold_table_offset: u32a(32),
192            tensor_count: u32a(36),
193            page_size: u32a(40),
194            reserved: {
195                let mut r = [0u8; 20];
196                r.copy_from_slice(&data[44..64]);
197                r
198            },
199        })
200    }
201
202    pub fn write_le(&self, out: &mut [u8]) {
203        assert!(out.len() >= P64_WEIGHT_HEADER_BYTES);
204        out[..P64_WEIGHT_HEADER_BYTES].fill(0);
205        out[0..4].copy_from_slice(&self.magic);
206        out[4..6].copy_from_slice(&self.version.to_le_bytes());
207        out[6..8].copy_from_slice(&self.flags.to_le_bytes());
208        out[8..12].copy_from_slice(&self.role_table_offset.to_le_bytes());
209        out[12..16].copy_from_slice(&self.tensor_table_offset.to_le_bytes());
210        out[16..20].copy_from_slice(&self.tokenizer_offset.to_le_bytes());
211        out[20..24].copy_from_slice(&self.hparams_offset.to_le_bytes());
212        out[24..28].copy_from_slice(&self.string_table_offset.to_le_bytes());
213        out[28..32].copy_from_slice(&self.checksum_offset.to_le_bytes());
214        out[32..36].copy_from_slice(&self.manifold_table_offset.to_le_bytes());
215        out[36..40].copy_from_slice(&self.tensor_count.to_le_bytes());
216        out[40..44].copy_from_slice(&self.page_size.to_le_bytes());
217        out[44..64].copy_from_slice(&self.reserved);
218    }
219}
220
221impl P64HParams {
222    pub(super) fn read_le(data: &[u8]) -> Result<Self, String> {
223        if data.len() < 64 {
224            return Err("p64: truncated hyperparameters".to_string());
225        }
226        let u32a = |o: usize| u32::from_le_bytes(data[o..o + 4].try_into().unwrap());
227        let f32a = |o: usize| f32::from_le_bytes(data[o..o + 4].try_into().unwrap());
228        Ok(Self {
229            n_layer: u32a(0),
230            n_embd: u32a(4),
231            n_head: u32a(8),
232            n_kv_head: u32a(12),
233            vocab_size: u32a(16),
234            rope_freq_base: f32a(20),
235            rope_scale: f32a(24),
236            head_dim: u32a(28),
237            head_dim_swa: u32a(32),
238            sliding_window: u32a(36),
239            shared_kv_layers: u32a(40),
240            logit_softcap: f32a(44),
241            architecture: u32a(48),
242            arch_flags: u32a(52),
243            reserved: [0; 8],
244        })
245    }
246
247    pub(super) fn write_le(&self, out: &mut [u8]) {
248        assert!(out.len() >= 64);
249        out[..64].fill(0);
250        out[0..4].copy_from_slice(&self.n_layer.to_le_bytes());
251        out[4..8].copy_from_slice(&self.n_embd.to_le_bytes());
252        out[8..12].copy_from_slice(&self.n_head.to_le_bytes());
253        out[12..16].copy_from_slice(&self.n_kv_head.to_le_bytes());
254        out[16..20].copy_from_slice(&self.vocab_size.to_le_bytes());
255        out[20..24].copy_from_slice(&self.rope_freq_base.to_le_bytes());
256        out[24..28].copy_from_slice(&self.rope_scale.to_le_bytes());
257        out[28..32].copy_from_slice(&self.head_dim.to_le_bytes());
258        out[32..36].copy_from_slice(&self.head_dim_swa.to_le_bytes());
259        out[36..40].copy_from_slice(&self.sliding_window.to_le_bytes());
260        out[40..44].copy_from_slice(&self.shared_kv_layers.to_le_bytes());
261        out[44..48].copy_from_slice(&self.logit_softcap.to_le_bytes());
262        out[48..52].copy_from_slice(&self.architecture.to_le_bytes());
263        out[52..56].copy_from_slice(&self.arch_flags.to_le_bytes());
264    }
265}
266
267/// `format_flags` bit: container produced by the **raw streaming transcode** (safetensor/MLX →
268/// P64) — tensors are verbatim high-fidelity blobs not yet mapped to engine GEMM roles, and the
269/// GGUF hyperparameter block is absent. (Distinguishes it from a `compile_gguf_to_p64` container.)
270pub const FORMAT_FLAG_RAW_TRANSCODE: u16 = 1 << 1;
271/// Alias of [`FORMAT_FLAG_RAW_TRANSCODE`] (header-flag naming).
272pub const P64_FLAG_RAW_TRANSCODE: u16 = FORMAT_FLAG_RAW_TRANSCODE;
273/// `format_flags` bit: tensors were **ternary-quantized (BitNet 1.58b)** during transcode — each
274/// blob is `[scale: f32][packed trits]` (`ggml_type = ternary::GGML_TYPE_TERNARY_158`); decode via
275/// `ternary::dequantize_blob`.
276pub const FORMAT_FLAG_TERNARY: u16 = 1 << 2;
277/// Alias of [`FORMAT_FLAG_TERNARY`] (header-flag naming).
278pub const P64_FLAG_TERNARY: u16 = FORMAT_FLAG_TERNARY;