JSON debug format: reading a fitted model with your eyes
1. The problem we were solving
Production model persistence wants binary files: contiguous IEEE-754 buffers, random access by tensor offset and zero text parsing. That is the job of the binary Safetensors adapter. Binary efficiency, however, comes with an immediate tax whenever a human needs to answer a simple question:
- Did my
SKStandardScaleractually center column 2, or didwith_meandefault tofalse? - Why did two training runs on different machines diverge in the third decimal place?
- Can I check a tiny golden model fixture into Git and review parameter changes with
git diff?
With a binary file, every one of those questions requires a bespoke inspection tool. In
sciencekit, fitted estimators already speak a single format-agnostic vocabulary in
sciencekit_common: SKExportable produces an SKModelState<F>, and SKImportable
reconstructs a fitted estimator from it. Adding a human-readable JSON debug adapter in
crates/sciencekit_interop/src/json/ gives every exportable model a diffable,
hand-inspectable text representation without touching a single estimator crate.
2. The idea in one picture
flowchart LR
accTitle: JSON debug export, inspection and validated import pipeline
accDescr: An SKExportable model produces an SKModelState, which SKJsonDebugWriter validates for finite scalars and renders as deterministic pretty or compact JSON. SKJsonDebugReader parses the JSON, validates format_version, dtypes, unique names and tensor shapes before reconstructing SKModelState and importing back into SKImportable.
M1["Fitted model<br/>SKExportable"]:::violet --> S1["SKModelState<br/>metadata + BTreeMap"]:::blue
S1 --> W["SKJsonDebugWriter<br/>Pretty | Compact"]:::green
W --> J["Deterministic JSON<br/>sorted keys, flat arrays"]:::amber
J --> R["SKJsonDebugReader<br/>validate before work"]:::orange
R -->|"valid v1"| S2["SKModelState<br/>exact round-trip"]:::blue
R -->|"corrupt / mismatch"| E["Structured SKError<br/>no partial model"]:::rose
S2 --> M2["Reconstructed model<br/>SKImportable"]:::violet
classDef blue fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
classDef green fill:#f0fdf4,stroke:#16a34a,color:#14532d
classDef orange fill:#fff7ed,stroke:#ea580c,color:#7c2d12
classDef violet fill:#ede9fe,stroke:#7c3aed,color:#3b0764
classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
classDef rose fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d
The central state SKModelState<F> sits on both sides of the wire. Fitted models implementing SKExportable and SKImportable (such as SKLinearRegressionModel<F>, and other estimator families as their export contracts land) never know JSON exists; they export and import SKModelState<F>, while sciencekit_interop::json owns the text grammar and every byte of serde_json dependency.
3. The decisions — and the roads not taken
| Decision | Why we chose it | Alternatives we discarded |
|---|---|---|
Keep sciencekit_common free of serde and own the wire schema in sciencekit_interop::json | Format policy (field names, version envelope, untagged hyperparameters, forward-compatible unknown fields) belongs to the format adapter, not the core trait crate. | Deriving Serialize/Deserialize directly on SKModelState — couples internal Rust enum layout to the wire format and leaks serde into sciencekit_common. |
Deterministic BTreeMap key order + shortest exact float formatting | Two runs that learn the same parameters emit byte-for-byte identical JSON regardless of insertion order, so git diff only highlights genuine numerical changes. Native f32 slices serialize directly as f32 (0.1 instead of 0.10000000149011612). | HashMap maps or casting f32 through f64 on write — scrambles key order across runs and pollutes single-precision fixtures with binary64 conversion noise. |
| Custom duplicate-preserving map visitor on read | Standard serde BTreeMap deserialization silently overwrites duplicate object keys ("w": ..., "w": ...). Reading entries into a sequence first lets validation deterministically reject duplicate tensor or hyperparameter names. | Deserializing straight into BTreeMap or serde_json::Value — silently drops the earlier duplicate tensor and hides file corruption. |
Check format_version before requiring version-1 fields, ignore unknown fields within version 1 | If major version 2 renames top-level sections, a version-1 reader still reports UnsupportedRepresentation on the version header rather than a confusing missing-field parse error, while minor additive hints inside version 1 stay forward-compatible. | #[serde(deny_unknown_fields)] — breaks older readers whenever an optional diagnostic annotation is added within major version 1. |
| Document memory expansion for large tensors instead of pretending JSON is a checkpoint format | Flat UTF-8 decimal arrays expand past raw 8-byte binary buffers and materialize in memory. Stating that boundary clearly points production checkpoints at Safetensors while keeping JSON simple and self-contained. | Base64-encoding tensor buffers inside JSON — destroys the entire point of reading tensor values with human eyes. |
4. The JSON debug schema, taught from zero
When SKJsonDebugWriter serializes a fitted four-feature SKStandardScaler in the default SKJsonFormatMode::Pretty mode, it produces:
{
"format_version": 1,
"estimator": "SKStandardScaler",
"dtype": "f64",
"feature_count": 4,
"class_labels": null,
"hyperparameters": {
"with_mean": true,
"with_std": true
},
"tensors": {
"standard_scaler.mean": {
"dtype": "F64",
"shape": [
4
],
"values": [
1.0,
2.0,
3.0,
4.0
]
}
}
}
Every field has one job:
format_version(SK_JSON_DEBUG_FORMAT_VERSION = 1): the major version of the JSON debug envelope itself. Any other value is rejected immediately withSKError::UnsupportedRepresentation. When an estimator’s ownSKModelMetadata::format_version()differs from1, an optionalestimator_format_versionfield is emitted so arbitrary metadata versions round-trip losslessly without cluttering version-1 fixtures.estimator,dtype,feature_count,class_labels: the model identity contract fromSKModelMetadata. The top-level"dtype"names the Rust model scalar ("f32"or"f64"), while classifiers populate"class_labels"in canonical index order soSKLabelTablemappings remain reversible.hyperparameters: a sorted map of untagged JSON booleans, 64-bit signed integers, finite 64-bit floats, strings and nested lists mirroringSKParameterValue. Becauseserde_jsonalways emits a decimal point on floating-point numbers (1.0) and omits it on integers (1),SKParameterValue::Float(1.0)andSKParameterValue::Integer(1)round-trip without variant wrapper tags.tensors: a sorted map keyed by stable dotted tensor names ("standard_scaler.mean","linear.coefficients","tree.is_leaf"). Each entry carries its element"dtype"("F32","F64","I64"or"Bool"), its dimension vector"shape"($[s_1, s_2, \dots, s_r]$, with $[]$ for a scalar tensor because the empty product equals $1$), and its flat"values"array whose length $N$ must satisfy:
$$\prod_{d=1}^{r} s_d = N$$
Checked multiplication (usize::checked_mul) guards that product on read so an adversarial shape such as [18446744073709551615, 2] returns SKError::ShapeMismatch rather than overflowing.
5. Each public object, explained
All public types and functions live in sciencekit_interop::json and follow the workspace naming and builder conventions (SK on types, sk_ on free functions, no abbreviations):
SK_JSON_DEBUG_FORMAT_VERSION:u32constant equal to1.SKJsonFormatMode:Pretty(default, two-space indented multi-line JSON) andCompact(single-line JSON with no insignificant whitespace).SKJsonDebugWriter&SKJsonDebugWriterBuilder: builder-configured writer implementingSKBuilder<SKJsonDebugWriter>, exposing.format_mode(...),.backend(SKBackendKind)(defaultFaer) and.execution_mode(...)(defaultAutomatic). Its methodswrite_state_to_string,write_state_to_writer,write_state_to_path,export_to_stringandexport_to_pathvalidate scalar finiteness up front, borrow tensor slices without copying, and emit asciencekit.interop.json.writetracingspan.SKJsonDebugReader&SKJsonDebugReaderBuilder: builder-configured reader implementingSKBuilder<SKJsonDebugReader>, exposing.backend(SKBackendKind)and.execution_mode(...). Its methodsread_state_from_string,read_state_from_reader,read_state_from_path,import_from_stringandimport_from_pathvalidate headers before materializing tensors and emit asciencekit.interop.json.readtracingspan.- Convenience entry points:
sk_write_model_state_json,sk_write_model_state_json_pretty,sk_write_model_state_json_compact,sk_write_model_state_json_file,sk_read_model_state_json,sk_read_model_state_json_file,sk_export_model_jsonandsk_import_model_json.
use sciencekit_interop::json::{
SKJsonFormatMode, sk_export_model_json, sk_import_model_json,
};
let json = sk_export_model_json(&fitted_model, SKJsonFormatMode::Pretty)?;
let restored: SKLinearRegressionModel<f64> = sk_import_model_json(&json)?;
6. Validation table: every rejection is structured
Validation runs before SKTensor and SKModelState construction so a malformed or mismatched document never leaves a half-built model behind:
| Failure condition | Returned SKError |
|---|---|
| Invalid JSON syntax, wrong root type, trailing bytes, missing required v1 field | SKError::Conversion |
| Missing or unreadable file path / stream I/O failure | SKError::Io |
format_version != 1 (including 0, 2, or evolved schemas) | SKError::UnsupportedRepresentation |
NaN or ±Infinity in floating tensor or hyperparameter (or f32 overflow on read) | SKError::NonFiniteValue { position } |
| Tensor value count $\neq \prod s_d$, or dimension product overflow | SKError::ShapeMismatch |
Unknown/mismatched scalar dtype ("f16", or "f32" read into SKModelState<f64>) | SKError::InvalidHyperparameter { name: "dtype", .. } |
Duplicate tensor names in "tensors": { ... } | SKError::InvalidHyperparameter { name: "tensor_names", .. } |
| Empty tensor name | SKError::InvalidHyperparameter { name: "tensor_name", .. } |
Unknown tensor dtype ("U8") or element type disagreeing with tensor dtype | SKError::InvalidHyperparameter { name: "tensor_data_type", .. } |
Duplicate hyperparameter keys or unsupported JSON null/object hyperparameter | SKError::InvalidHyperparameter { name: "hyperparameters", .. } |
7. Walking through the companion tests
The implementation in crates/sciencekit_interop/src/json/ is split into small single-responsibility files (mod.rs pure dispatcher, format_mode.rs, schema.rs, writer_builder.rs, writer.rs, parameter_deserialization.rs, schema_deserialization.rs, tensor_decoding.rs, state_decoding.rs, reader_builder.rs, reader.rs), paired with six companion test suites:
- Schema & hand-written fixture (
json_schema_tests.rs):json_schema_matches_hand_written_standard_scaler_fixtureasserts byte-for-byte equality against the documentedSKStandardScalerJSON fixture.json_schema_renders_readable_metadata_and_typed_hyperparameterschecksf32single-precision formatting (0.1rather than0.10000000149011612), class labels and everySKParameterValuekind including nested lists.json_schema_renders_all_tensor_data_types_and_shapes_as_flat_arraysverifiesF64, scalar[]shapes,I64andBooltensors.json_schema_rejects_non_finite_values_before_serializationconfirmsf64::NANat index1fails up front withSKError::NonFiniteValue { position: 1 }.
- Deterministic writer (
json_writer_tests.rs):json_writer_defaults_to_pretty_format_and_deterministic_key_orderingandjson_writer_produces_byte_identical_output_across_insertion_ordersinsert parameters and tensors in forward and reverse order and verify identical output bytes.json_writer_compact_mode_emits_single_line_jsonandjson_writer_writes_to_io_sink_file_and_exportable_modelverify single-line compact mode,io::Writesinks, file output andSKExportable.
- Round-trip fidelity (
json_round_trip_tests.rs):json_round_trip_reconstructs_identical_model_stateandjson_round_trip_preserves_single_precision_state_and_nested_listsverify exactSKModelStateequality acrossf64andf32.json_round_trip_reconstructs_model_through_export_and_import_traitsround-trips a fitted model throughSKExportableandSKImportable.json_round_trip_supports_files_streams_and_ignores_unknown_fieldsverifies stream/file reads and forward compatibility when extra unknown fields appear inside version1.
- Validation (
json_validation_tests.rs):json_validation_rejects_malformed_json_with_conversion_error,json_validation_rejects_unknown_major_versions,json_validation_rejects_duplicate_tensor_and_hyperparameter_names,json_validation_rejects_invalid_and_mismatched_dtypesandjson_validation_rejects_tensor_shape_mismatchespin every row of the error table above.
- Equivalence, large tensors & concurrency (
json_concurrency_tests.rs):json_concurrency_pretty_and_compact_modes_parse_to_identical_stateconfirms pretty and compact outputs reconstruct identical states.json_concurrency_large_tensor_round_trips_and_validates_shaperound-trips a $256 \times 256$ (65,536-element) matrix, checks its text expansion and verifies shape-mismatch rejection.json_concurrency_concurrent_reads_from_same_file_agreespawns eight OS threads reading the same JSON file and re-encoding concurrently, confirming thread-safe determinism.
- End-to-end acceptance (
acceptance_tests/):json_acceptance_tiny_states_round_trip_for_both_scalars,json_acceptance_large_state_preserves_all_dtypes_class_table_and_spansandjson_acceptance_imported_regressor_reproduces_predictions_and_zero_errorvalidate tiny/large states,sk_canonicalize_labelsclass tables,tracingspan recording and zero-drift predictions.json_acceptance_truncated_prefixes_return_conversion_without_panickingtruncates a valid JSON state at every UTF-8 character offset and proves the reader never panics, paired withjson_acceptance_corrupt_metadata_and_missing_files_return_structured_errors.