Serialization
Saving and loading SameDiff graphs in FlatBuffers format
SameDiff graphs — including their structure, variables, constants, and trained parameters — can be saved to and loaded from files using the FlatBuffers binary format. This enables model deployment, checkpointing during training, and sharing trained models.
Saving a SameDiff Graph
save()
Save the complete graph including all variables, constants, and parameter values:
import org.nd4j.autodiff.samediff.SameDiff;
import java.io.File;
// Save with updater state (for resuming training)
sd.save(new File("model.fb"), true);
// Save without updater state (smaller file, for inference only)
sd.save(new File("model.fb"), false);The second argument controls whether to include the updater state (momentum buffers, adaptive learning rate accumulators, etc.). Include it if you plan to resume training; omit it for inference-only deployment.
asFlatGraph()
Convert the graph to a FlatBuffers byte buffer in memory (useful for embedding in other formats or sending over the network):
import java.nio.ByteBuffer;
ByteBuffer buffer = sd.asFlatGraph(true); // true = include updater stateasFlatPrint()
Get a human-readable string representation of the graph (for debugging):
This prints the graph structure, variable names, shapes, and operation types.
Loading a SameDiff Graph
load()
Load a previously saved graph:
fromFlatGraph()
Load from a FlatBuffers byte buffer:
What Gets Saved
Graph structure (ops, connections)
Always
The computation graph topology
VARIABLE values (weights, biases)
Always
Trainable parameters
CONSTANT values
Always
Non-trainable stored values
PLACEHOLDER definitions
Always
Shape and type info (not values)
ARRAY definitions
Always
Shape and type info (not values — computed at runtime)
Updater state
Optional
Momentum/adaptive rate buffers. Only if saveUpdater=true
TrainingConfig
With updater
Optimizer settings
Training Checkpoints
Save periodic checkpoints during training for recovery:
Resume training from a checkpoint:
Interop with Model Import
SameDiff is also the target format for model import from other frameworks. When you import a TensorFlow or ONNX model, the result is a SameDiff graph:
This workflow (import once, save as FlatBuffers, load FlatBuffers for serving) avoids repeated parsing of the original model format.
File Format Details
SameDiff uses FlatBuffers as its serialization format:
Binary format: Compact, fast to serialize/deserialize
No schema evolution issues: Forward and backward compatible
Zero-copy reads: FlatBuffers can be read directly from the buffer without unpacking
Cross-platform: Same file works on any OS/architecture
Typical file sizes depend on model complexity:
Simple MLP (784→256→10): ~1-2 MB
ResNet-18: ~45 MB
Large transformer: 100+ MB
Best Practices
Save without updater state for deployment — reduces file size significantly (updater state can be 2-3x the model parameters for Adam)
Save with updater state for checkpoints — allows seamless training resumption
Convert imported models to FlatBuffers — much faster to load than parsing TF/ONNX format each time
Version your saved models — include epoch/date in filenames for traceability
Verify after loading — run a sample inference to confirm the loaded model produces expected results
SDNB and SDZ Formats (ADR 0035)
The original .fb FlatBuffers format has a hard 2 GB ceiling imposed by the FlatBuffers 32-bit size field. Two new container formats overcome this limit while also improving deployment ergonomics.
Format Overview
SDNB
.sdnb
Single-file binary with section header, manifest, graph, and appended arrays
Training checkpoints, highest performance I/O
SDZ
.sdz
Standard ZIP archive containing one or more .sdnb shards
Deployment, single-file distribution, compressed storage
Sharded SDNB
.shard0-of-N.sdnb …
Multiple .sdnb files, one per shard
Very large models (multi-hundred GB weights)
SameDiff.load() automatically detects all three formats by inspecting the file magic bytes and directory entries, so existing code that calls SameDiff.load() does not need to change.
SDNB Format
SDNB (SameDiff Native Binary) is a section-based binary container. Its file structure is:
Arrays are appended after the FlatBuffers graph region, bypassing the 2 GB limit. A manifest records the byte offset and length of every array so the loader can seek directly to each one without scanning the file.
SDZ Format
SDZ packages one or more .sdnb shards into a standard ZIP archive. This gives you a single file you can inspect with any ZIP tool (unzip -l model.sdz) and distribute without managing shard files separately. Compression typically reduces file size by 30–50%.
Internally SDZSerializer.save() calls SameDiffSerializer.saveAutoShard() to create the SDNB shards, then compresses them into the ZIP. SDZSerializer.load() extracts all shards to a temp directory, loads them in order, and deletes the temp directory on completion.
Sharding for Large Models (>2 GB)
When the total model weight exceeds what a single SDNB file can hold efficiently, sharding distributes variables across multiple files. Shard 0 always contains the graph structure; subsequent shards hold variable data.
For models intended for single-file distribution, prefer saving as SDZ: it shards internally and then bundles everything into one .sdz file.
Format Auto-Detection
SameDiff.load() probes the file and automatically selects the right loader:
Metadata
Both SDNB and SDZ support an extensible key-value metadata map (similar to GGUF). Metadata can be added after the model is saved without reserializing the weight tensors. Standardized keys include:
model.name
Human-readable model name
model.version
Semantic version string
training.epochs
Number of training epochs completed
training.dataset
Dataset used for training
nd4j.format.version
Format version (set automatically)
When to Use Each Format
Training checkpoints (fast save/load)
SDNB
Resuming training
SDNB with saveUpdaterState=true
Deployment / single-file distribution
SDZ
Models larger than 2 GB
SDZ (auto-shards internally) or sharded SDNB
Inspecting contents with standard tools
SDZ (unzip -l model.sdz)
Migrating an existing .fb model
Load .fb, save as .sdz
Backward Compatibility
Existing .fb files continue to load without any changes — the auto-detection path checks for the legacy format first. No migration is required for models already in production.
Last updated
Was this helpful?