1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Aprender Model Format (.apr)
//!
//! Binary format for ML model serialization with built-in quality (Jidoka):
//! - CRC32 checksum (integrity)
//! - Ed25519 signatures (provenance)
//! - AES-256-GCM encryption (confidentiality)
//! - Zstd compression (efficiency)
//! - Quantization (`Q8_0`, `Q4_0`, `Q4_1` - GGUF compatible)
//! - Streaming/mmap (JIT loading)
//!
//! # Format Structure
//!
//! ```text
//! ┌─────────────────────────────────────────┐
//! │ Header (32 bytes, fixed) │
//! ├─────────────────────────────────────────┤
//! │ Metadata (variable, MessagePack) │
//! ├─────────────────────────────────────────┤
//! │ Chunk Index (if STREAMING flag) │
//! ├─────────────────────────────────────────┤
//! │ Salt + Nonce (if ENCRYPTED flag) │
//! ├─────────────────────────────────────────┤
//! │ Payload (variable, compressed) │
//! ├─────────────────────────────────────────┤
//! │ Signature Block (if SIGNED flag) │
//! ├─────────────────────────────────────────┤
//! │ Checksum (4 bytes, CRC32) │
//! └─────────────────────────────────────────┘
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use aprender::format::{save, load, ModelType, SaveOptions};
//! use aprender::linear_model::LinearRegression;
//!
//! let model = LinearRegression::new();
//! // ... train model ...
//!
//! // Save with compression
//! save(&model, ModelType::LinearRegression, "model.apr", SaveOptions::default())?;
//!
//! // Load with verification
//! let loaded: LinearRegression = load("model.apr", ModelType::LinearRegression)?;
//! ```
// Imports needed by test modules via `use super::*`
// These were the original mod.rs imports before PMAT-198 extraction.
// The production code lives in submodules now, but tests use `use super::*`
// and need these types in scope.
use crate;
use ;
use HashMap;
use File;
use Cursor;
use ;
use Path;
// Quantization module (spec §6.2)
// Homomorphic encryption module (spec: homomorphic-encryption-spec.md)
// Weight comparison module (GH-121, HuggingFace/SafeTensors comparison)
// APR format module (GH-119, 64-byte alignment, JSON metadata, sharding)
// GGUF export module (spec §7.2)
// ONNX format reader (GH-238)
// Hex dump and data flow visualization (GH-122, Toyota Principle 12: Genchi Genbutsu)
// Model card module (spec §11)
// Validation module (spec §11 - 100-Point QA Checklist)
// Converter types module (PMAT-197 - File size reduction)
// Converter module (spec §13 - Import/Convert Pipeline)
// Lint module (spec §4.11 - Best Practices & Conventions)
// Sharded model import module (GH-127 - multi-tensor repos, streaming import)
// Golden trace verification (spec §7.6.3 - prove model authenticity)
// Rosetta Stone - Universal Model Format Converter (PMAT-ROSETTA-001)
// Bidirectional conversion: GGUF ↔ APR ↔ SafeTensors
// Rosetta ML Diagnostics (ROSETTA-ML-001)
// ML-powered format conversion diagnostics using aprender's own algorithms
// Type definitions (spec §2-§9, PMAT-198)
// F16 safety constants and helpers (GH-186 - prevent NaN propagation)
// Core I/O operations (save, load, inspect, PMAT-198)
// Tensor listing library (TOOL-APR-001 - reads actual tensor index)
// Model diff library (TOOL-APR-002 - format-agnostic comparison)
// Tensor Layout Contract - THE SOURCE OF TRUTH (LAYOUT-CONTRACT-001)
// ALL tooling that deals with tensor shapes/layouts MUST use this module.
// See: contracts/tensor-layout-v1.yaml and docs/specifications/qwen2.5-coder-showcase-demo.md §E.8
// Validated Tensor Types - Compile-Time Contract Enforcement (PMAT-235)
// Implements Poka-Yoke (mistake-proofing) via newtype pattern.
// Makes it IMPOSSIBLE to use unvalidated tensor data at compile time.
// See: contracts/tensor-layout-v1.yaml §type_enforcement
// Validated Classification Types - Classification Fine-Tuning Contract
// Poka-Yoke types for classifier logits, labels, and weights.
// See: contracts/classification-finetune-v1.yaml
// Model Family Contract Types (PMAT-241)
// Compiler-enforced model family contracts: trait, config types, registry.
// See: contracts/model-families/*.yaml and
// docs/specifications/compiler-enforced-model-types-model-oracle.md
// Model Family YAML Contract Loader (PMAT-242)
// Runtime YAML parser for model family contracts (no external deps).
// Fallback path; build.rs codegen (PMAT-250) is preferred.
// SHIP-TWO-001 AC-SHIP1-010 / FALSIFY-SHIP-010 algorithm-level PARTIAL
// discharge: pure decision rules for the published-artifact ship gate
// (SHA-256 byte-identity + manifest URL well-formedness).
// See: contracts/publish-manifest-v1.yaml v1.4.0 GATE-PM-010.
// Special tokens registry contract falsification (FALSIFY-ST-001..006)
// Model metadata bounds contract falsification (FALSIFY-MB-001..006)
// Tokenizer-vocabulary contract falsification (FALSIFY-TV-001..006)
// Embedding contract falsification (FALSIFY-EM-001..004, FALSIFY-EMB-001..007)
// Refs: embedding-lookup-v1.yaml, embedding-algebra-v1.yaml (PMAT-339, PMAT-340)
// Classification contract falsification (FALSIFY-CLASS-001..006)
// Refs: classification-finetune-v1.yaml
// Digital signatures (spec §4.2, PMAT-198)
// Encryption operations (spec §4.1, PMAT-198)
// Formal verification: Kani proofs for APR format invariants
// Formal verification: Verus-compatible specification contracts
// Test factory - Pygmy model builders (T-COV-95)
// Implements the "Active Pygmy" pattern for creating minimal valid models in memory
// Re-export golden trace types
pub use ;
// Re-export model card types
pub use ;
// Re-export validation types (spec §11 - 100-Point QA Checklist)
pub use ;
// Re-export Poka-yoke types (APR-POKA-001 - Toyota Way mistake-proofing)
pub use no_validation_result;
pub use ;
// Re-export converter types (spec §13 - Import/Convert Pipeline)
pub use ;
// Re-export lint types (spec §4.11 - Best Practices & Conventions)
pub use ;
// Re-export sharded import types (GH-127 - multi-tensor repos)
pub use ;
// Re-export Rosetta Stone types (PMAT-ROSETTA-001 - Universal Model Format Converter)
pub use ;
// Note: rosetta::TensorStats intentionally not re-exported to avoid conflict with validation::TensorStats
// Use aprender::format::rosetta::TensorStats directly if needed
// Re-export Rosetta ML Diagnostics types (ROSETTA-ML-001)
pub use ;
// Re-export tensor listing types (TOOL-APR-001 - reads actual tensor index)
// Note: TensorListInfo used instead of TensorInfo to avoid conflict with rosetta::TensorInfo
pub use ;
// Re-export diff types (TOOL-APR-002 - format-agnostic comparison)
pub use ;
// Re-export layout contract types (LAYOUT-CONTRACT-001 - Source of Truth)
pub use ;
// Re-export validated tensor types (PMAT-235 - Compile-Time Contract Enforcement)
// Implements Poka-Yoke: makes invalid tensor states unrepresentable
// RowMajor: PMAT-248 layout marker (PhantomData zero-cost enforcement)
pub use ;
// Re-export validated classification types (classification-finetune-v1 contract)
pub use ;
// Re-export quantization types when feature is enabled
pub use ;
// Re-export homomorphic encryption types when feature is enabled
pub use ;
// Re-export signing types when feature is enabled
pub use ;
/// Ed25519 signature size in bytes
pub const SIGNATURE_SIZE: usize = 64;
/// Ed25519 public key size in bytes
pub const PUBLIC_KEY_SIZE: usize = 32;
/// Argon2id salt size in bytes (spec §4.1.2)
pub const SALT_SIZE: usize = 16;
/// AES-GCM nonce size in bytes
pub const NONCE_SIZE: usize = 12;
/// AES-256 key size in bytes
pub const KEY_SIZE: usize = 32;
/// X25519 public key size in bytes (spec §4.1.3)
pub const X25519_PUBLIC_KEY_SIZE: usize = 32;
/// Recipient public key hash size for identification (spec §4.1.3)
pub const RECIPIENT_HASH_SIZE: usize = 8;
/// HKDF info string for X25519 key derivation (spec §4.1.3)
pub const HKDF_INFO: & = b"apr-v1-encrypt";
// Re-export X25519 types when feature is enabled
pub use ;
/// Magic number: "APRN" in ASCII (0x4150524E)
pub const MAGIC: = ;
/// Current format version (1.0)
pub const FORMAT_VERSION: = ;
/// Header size in bytes
pub const HEADER_SIZE: usize = 32;
/// Maximum uncompressed size (1GB safety limit)
pub const MAX_UNCOMPRESSED_SIZE: u32 = 1024 * 1024 * 1024;
// FALSIFY-SHIP-003 / AC-SHIP1-003 — per-layer cosine similarity threshold
// verdict fn for `apr convert --quantize q4_k_m` round-trip quality.
// See contracts/qwen2-e2e-verification-v1.yaml FALSIFY-QW2E-SHIP-003 and
// docs/specifications/aprender-train/ship-two-models-spec.md §4.2 AC-SHIP1-003.
// FALSIFY-SHIP-004 / AC-SHIP1-004 — GGUF export boundary verdict fns:
// llama-cli exit code + GGUF magic bytes + GGUF version.
// See contracts/qwen2-e2e-verification-v1.yaml FALSIFY-QW2E-SHIP-004 and
// docs/specifications/aprender-train/ship-two-models-spec.md §4.2 AC-SHIP1-004.
// FALSIFY-SHIP-001 / AC-SHIP1-001 — safetensors load boundary verdict fns:
// Result<Model, _> → bool, safetensors header size invariant, JSON-object
// open-brace byte. See contracts/qwen2-e2e-verification-v1.yaml
// FALSIFY-QW2E-SHIP-001 and docs/specifications/aprender-train/ship-two-
// models-spec.md §4.2 AC-SHIP1-001.
// FALSIFY-SHIP-023 / AC-SHIP1-023 — two-day HumanEval pass@1 drift verdict:
// pair-of-runs drift ≤ 1.2 pp with symmetric `.abs()` combinator + input
// well-formedness guards. See contracts/qwen2-e2e-verification-v1.yaml
// FALSIFY-QW2E-SHIP-023 and docs/specifications/aprender-train/ship-two-
// models-spec.md §7.1 FALSIFY-SHIP-023.
// FALSIFY-SHIP-024 / AC-SHIP1-024 — adversarial-suite runtime-invariant
// verdict: suite-size floor ≥ 50 AND panic_count == 0 AND nan_count == 0.
// See contracts/qwen2-e2e-verification-v1.yaml FALSIFY-QW2E-SHIP-024 and
// docs/specifications/aprender-train/ship-two-models-spec.md §7.1
// FALSIFY-SHIP-024.
// SHIP-TWO-001 §6 Compound Ship Gates — aggregate / cross-cutting PARTIAL
// algorithm-level discharges. Each module binds one §6 compound-gate row
// to one pure verdict fn + mutation survey. Authoritative contract:
// contracts/compound-ship-gates-v1.yaml v1.0.0.
// FALSIFY-APR-GGUF-PARITY — per-layer ffn_swigl ratio gate for SHIP-007.
// FALSIFY-APR-DISTILL-TRAIN-005 — precompute byte-determinism gate.
// INV-DATA-006 — dataset-thestack-python disjoint train/val splits.
// FALSIFY-APR-DISTILL-TRAIN-002 — KL loss decreases over epochs gate.
// FALSIFY-QA-002 + 006 — apr-cli error-exit honesty (exit != 0 on missing file / error output).
// FALSIFY-QA-004 — apr-cli no NaN/Inf in user output (zero-tolerance scan).
// FALSIFY-QA-001 — apr-cli all 58 commands respond to --help.
// FALSIFY-PUB-CLI-002 + 004 — cargo install/check exit codes (shared verdict).
// FALSIFY-PUB-CLI-001 — apr-cli default features contain no forbidden substrings.
// FALSIFY-PUB-CLI-003 — apr --help line count > 50 (all 58 commands listed).
// FALSIFY-APR-PULL-DATASET-001 — apr pull dataset --help shows both flags + exits 0.
// FALSIFY-APR-PULL-DATASET-005 — apr pull <model> --dry-run backward compat.
// FALSIFY-APR-PULL-DATASET-003 — apr pull dataset no-match glob fails fast.
// FALSIFY-APR-PULL-DATASET-004 — license allowlist drops disallowed rows.
// FALSIFY-APR-PULL-DATASET-002 — apr pull dataset --include glob exact match count.
// FALSIFY-APR-DISTILL-TRAIN-009 — distill student val_loss < from-scratch baseline.
// INV-BPE-001 — tokenizer-bpe vocab range + paired-model match.
// INV-BPE-006 — tokenizer-bpe encode determinism (cross-process bit-identical IDs).
// INV-BPE-003 — tokenizer-bpe round-trip byte-equality on 10K held-out docs.
// INV-BPE-002 — tokenizer-bpe four required special tokens distinct + in range.
// FALSIFY-PROF10-003 — apr profile graphed vs ungraphed sanity inequality.
// FALSIFY-SUB-FFN-005 — sub-FFN telemetry per-layer line count.
// FALSIFY-APR-TOK-PAR-002 — parallel BPE 80% efficiency floor.
// INV-DATA-004 — dataset-thestack-python train range + val floor.
// INV-DATA-007 — dataset-thestack-python UTF-8 + NFC round-trip.
// INV-DATA-001 — dataset-thestack-python license whitelist (zero-tolerance).
// INV-DATA-002 — dataset-thestack-python PII scrub zero-match invariant.
// INV-DATA-003 — dataset-thestack-python Jaccard dedup floor (< 0.85).
// INV-DATA-005 — dataset-thestack-python corpus_sha256 reproducibility.
// INV-PRETOK-003 — pretokenize-bin manifest sum=actual invariant.
// INV-PRETOK-002 — pretokenize-bin shard u32-alignment invariant.
// INV-PRETOK-001 — pretokenize-bin token id < vocab_size invariant.
// FALSIFY-APR-DISTILL-TRAIN-006 — stage train resumes from precompute cache.
// FALSIFY-APR-DISTILL-TRAIN-001 — real-training (not stub) tensor-diff gate.
// GATE-SHIP-001 — MODEL-1 aggregate-AND over 10 AC-SHIP1-* booleans.
// GATE-SHIP-002 — MODEL-2 aggregate-AND over 12 AC-SHIP2-* booleans.
// GATE-SHIP-003 — Golden Output byte-identity across quantize round-trip.
// GATE-SHIP-004 — HumanEval bitwise-identical determinism (two seed=0 runs).
// GATE-SHIP-005 — License metadata non-empty ASCII-printable byte-equal.
// GATE-SHIP-006 — GGUF round-trip first-token probability delta ≤ 1e-3.
// GATE-SHIP-007 — Zero-tolerance .unwrap() count threshold on new code.
// GATE-SHIP-008 — Contract-density ratio threshold on new public fns.
// GATE-SHIP-009 — CI aggregate-AND over 3 required checks (fmt / clippy / test).
// GATE-SHIP-010 — Zero-tolerance security-advisory count threshold.
// GATE-SHIP-011 — PMAT TDG score inclusive-floor threshold (≥ 90.0 / A-).
// GATE-SHIP-012 — Line-coverage percentage inclusive-floor threshold (≥ 95.0).
// Re-export types (PMAT-198 - backward compatibility)
pub use *;
// Re-export core I/O (PMAT-198 - backward compatibility)
pub use *;
// Re-export signing functions (PMAT-198 - backward compatibility)
pub use *;
// Re-export encryption functions (PMAT-198 - backward compatibility)
pub use *;