C.W.K.
Stream
Lesson 03 of 07 · published

Saving/Loading Weights Only

~8 min · serialize

Level 0Keras Apprentice
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

Weights without the architecture

Sometimes you don't want the whole model — you want just the trained numbers. save_weights writes only the tensors, leaving the architecture out entirely. That makes the file smaller and the save faster, which is exactly what you want when you're checkpointing every few epochs during a long training run.

The catch: you rebuild the architecture yourself

Because the architecture isn't in the file, loading is a two-step dance: construct the model in code first, then pour the weights in with load_weights. The model you build must match the saved one layer-for-layer — same shapes, same order. If it doesn't, the load can fail loudly or, worse, silently misalign tensors. That's the tradeoff against .keras: you trade self-describing safety for size and speed, and you take on the responsibility of keeping the build code in sync.

Sharding the giants

For very large models, a single weights file becomes unwieldy. Keras 3.10+ lets you cap the shard size with max_shard_size — pass "2GB" and the weights are split across multiple files automatically, which keeps each piece under filesystem and upload limits. Loading reassembles them transparently.

Code

Save, rebuild, load weights — and shard large ones·python
# Save weights
model.save_weights("weights.weights.h5")

# Load weights into an identical architecture
new_model = build_model()  # Must match original architecture
new_model.load_weights("weights.weights.h5")

# Weight sharding for large models (Keras 3.10+)
model.save_weights("large_model.weights.h5", max_shard_size="2GB")

External links

Exercise

Train a model for 10 epochs. Use ModelCheckpoint to save weights every 2 epochs. After training, load the epoch-6 weights into a fresh model instance with the same architecture. Verify accuracy matches what was logged at epoch 6.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.