A SavedModel is a folder, not a single file. saved_model.pb describes
the computation; the trained weights and any extra files sit beside it. Only
saved_model.pb is this format; the other files have formats of their
own.
What the folder holds
/saved_model.pb the SavedModel message: meta graphs, signatures and functionsfile/variables/variables.indexandvariables.data-00000-of-00001(one or more data shards): the values of the variables, in the layout of a TensorFlow checkpointfolder/assets/ extra files the graph reads, such as vocabularies; each is named by an AssetFileDeffolder/assets.extra/ files that are not read by the graph but kept with the model, for the programs that serve itfolder, optional/fingerprint.pb hashes that identify the model, written by newer versions of TensorFlowfile/debug/saved_model_debug_info.pb a GraphDebugInfo: the source locations of the graph’s nodes, when saved with debug informationfile, optional/keras_metadata.pb written by TF-Keras: its objects, belowfile, optional
The names come from TensorFlow’s cc/saved_model/constants.h. The
SaverDef of each meta
graph names the ops that restore the variables from variables/; in the
checkpoint, the object graph is stored under the key
_CHECKPOINTABLE_OBJECT_GRAPH. The explorer reads
fingerprint.pb, saved_model_debug_info.pb and
keras_metadata.pb by their names.
saved_model.cpb
A SavedModel too large for one Protocol Buffers message (the
2 GiB limit) can be saved as
saved_model.cpb instead, when it is saved with
tf.saved_model.SaveOptions(experimental_image_format=True): TensorFlow’s
proto splitter cuts the message into chunks and writes them, with a description of
where each chunk goes, as a {prefix}.cpb file. If nothing needed
splitting, the splitter writes an ordinary {prefix}.pb instead. The layout
is documented in TensorFlow’s
tensorflow/tools/proto_splitter (its README,
g3doc/in-depth-guide.md and chunk.proto), and the container in
Riegeli’s riegeli_records_file_format.md.
The container: a Riegeli records file
- The file is cut into 64 KiB blocks, each starting with a 24-byte block header:
header_hash,previous_chunkandnext_chunk(8 bytes each, little-endian), giving the distances to the start and end of the chunk the header interrupts. - The data is a series of chunks, each with a 40-byte header:
header_hash(8),data_size(8),data_hash(8),chunk_type(1:ssignature,mfile metadata,ppadding,rsimple records,ttransposed records),num_records(7) anddecoded_data_size(8), then the data, then padding. Hashes are 64-bit HighwayHash with the key “Riegeli/records\n” twice. - The first 64 bytes are fixed: a block header and a file-signature chunk, beginning
83 AF 70 D1 0D 88 4A 3F. - A simple chunk’s data is a compression byte (0 none,
bBrotli,zZstd,sSnappy), a varint size, the compressed list of record sizes (varints), and the compressed record bodies. A compressed block starts with its decompressed size as a varint. A writer with no options uses Brotli at level 6, which is what the splitter does unless it is given Riegeli options.
The records: chunks and ChunkMetadata
Each record is one chunk of the SavedModel: a serialised message
(ChunkInfo.Type MESSAGE) or raw bytes (BYTES), such as a large tensor’s
content. The last record is a ChunkMetadata message
(chunk.proto, package tensorflow.proto_splitter, proto3):
| Message | Field | Name | Type | Meaning |
|---|---|---|---|---|
| ChunkMetadata | 1 | version | VersionDef | The splitter version that wrote it, and which merger versions can read it. |
| ChunkMetadata | 2 | chunks | repeated ChunkInfo | Where each chunk is. |
| ChunkMetadata | 3 | message | ChunkedMessage | The tree that says how the chunks join into the original message. |
| ChunkInfo | 1 | type | enum | 0 UNSET, 1 MESSAGE, 2 BYTES. |
| ChunkInfo | 2 | size | uint64 | The chunk’s size in bytes. |
| ChunkInfo | 3 | offset | uint64 | The chunk’s position in the Riegeli file (the record position the writer reported, last_pos.numeric). |
| ChunkedMessage | 1 | chunk_index | optional uint64 | The chunk holding this message’s own fields, by index in chunks. |
| ChunkedMessage | 2 | chunked_fields | repeated ChunkedField | Fields whose values are in other chunks; a field may appear several times, merged in list order (repeated fields append, bytes concatenate). |
| ChunkedField | 1 | field_tag | repeated FieldIndex | The path from the parent message to the field; empty when the chunk is of the parent’s own type and merges straight into it. |
| ChunkedField | 3 | message | ChunkedMessage | The chunks of that field, as a tree. Field 2 is not used. |
| FieldIndex | 1 | field | uint32 | One step of the path: a field number. |
| FieldIndex | 2 | map_key | MapKey | A map key: one of s 1 (string), boolean 2, ui32 3, ui64 4, i32 5, i64 6. |
| FieldIndex | 3 | index | uint64 | An index into a repeated field. |
To rebuild the SavedModel, a reader parses the chunk named by the root
ChunkedMessage.chunk_index, then merges each chunked field’s chunks into the
place its field_tag path names, parents before children, sorted by depth and
index.
Transposed chunks and the file metadata chunk
Riegeli’s file-format document says “TODO: Document this” for chunk type
t. What follows is read from Riegeli’s C++ source
(riegeli/chunk_encoding/transpose_decoder.cc, with the enums in
transpose_internal.h and constants.h). A transposed chunk
holds protocol buffer messages, but not as written: the encoder splits each message
into its fields and stores the values of each kind of field together (so that like
values compress well), with a small state machine whose walk visits the fields of the
records, last record first, field by field from the last. The decoder walks the machine
and writes each field in front of what it has written, so the output grows
backwards and every record comes out in order.
- Data. A compression byte (as in a simple chunk); the
header_size(varint64); the header,header_sizebytes, compressed (a varint of its decoded size, then the compressed bytes) unless the compression is none; the buckets, each its own compressed stream; and the transitions, the rest of the data, compressed. - Header (decompressed, all varints):
num_bucketsandnum_buffers(varint32); each bucket’s compressed length (varint64); each buffer’s length (varint64);state_machine_size; that many tags (varint32); that many next-node indices (varint32); one subtype byte for every tag that has one; for each node that has a data buffer, its buffer index (varint32); andfirst_node. The buffers are the decompressed buckets cut in order, so each buffer lies inside one bucket. - Tags. 0 no-op; 1 a non-proto record (its bytes are in a buffer, its
length in the last buffer); 2 the start of a submessage; 3 the start of a message
(the record’s end of work; it records a record boundary); 8 and above a protocol
buffer tag,
field << 3 | wire type. Wire type 6, which a message cannot hold, marks the end of a submessage: it is read as the length-delimited tag of that field. A tag with a wire type of 7, or 6 and 7 inside a field, is invalid. - Subtypes (only for varint tags): 0 to 9 a varint of 1 to 10 bytes kept in a buffer, without its continuation bits (the decoder sets them on all but the last byte); 10 to 137 an inline value, 0 to 127, with no buffer. Fixed32 and fixed64 fields keep 4 or 8 bytes in a buffer; a string or bytes field keeps its length varint and its bytes in a buffer; a group start or end has no data.
- Next node. An index at or above
state_machine_sizemarks the node implicit: the size is taken off, and its transition is not stored. A loop made only of implicit nodes is invalid. - Transitions. One byte each. After a node is handled, the walk moves to its next node; if no steps are pending it reads a byte, adds its high 6 bits to the node index (so alternatives lie side by side), and sets the pending count to the low 2 bits (plus one if the node it landed on is implicit); otherwise it decrements the count unless the node is implicit. The walk ends when the bytes run out.
- Writing. A field node writes its tag and value; the end-of-submessage
node remembers the size written so far, and the start-of-submessage node takes the
difference as the submessage length and writes the tag and length in front. A
start-of-message node (or a non-proto record) records the size so far as a limit; at
the end there must be exactly
num_recordslimits and the output must bedecoded_data_sizebytes. The limits count from the end, so record i ends at the size less limit n − 2 − i.
The file metadata chunk (m) is encoded like a transposed
chunk of one record, a RecordsMetadata message (file_comment 1,
record_type_name 2, file_descriptor 3 (repeated
FileDescriptorProto), record_writer_options 4, num_records 5,
extensions from 1000), except that its num_records is 0.
The explorer reads a .cpb file’s Riegeli container: it checks the
signature, walks every chunk across the block headers, and lists each chunk’s type,
records, size and compression. It decodes uncompressed, Snappy, Brotli (with the
static dictionary of RFC 7932, loaded when the viewer opens) and Zstd chunks (RFC
8878, with the content checksum checked), transposed chunks and the file metadata
chunk, and from the last record the ChunkMetadata: the splitter version,
the list of proto chunks (each matched to its record by position and checked against
its size) and the merge tree of chunked fields. A chunk that cannot be decoded (a
damaged stream, a state machine that names a missing buffer) is listed with the reason;
when the last record is not decoded, the ChunkMetadata is not shown. The
transposed decoder was written from Riegeli’s source and checked on chunks built to
that description; the explorer has no transposed chunk that Riegeli wrote. The hashes
(HighwayHash) are not checked, and the .cpb file is not reassembled into
the SavedModel message it was split from.
keras_metadata.pb
TF-Keras saves a SavedMetadata message beside
saved_model.pb (schema tf_keras/protobuf/saved_metadata.proto):
| Message | Field | Name | Type | Meaning |
|---|---|---|---|---|
| SavedMetadata | 1 | nodes | repeated SavedObject | One entry per TF-Keras object. |
| SavedObject | 2 | node_id | int32 | Its index in the SavedObjectGraph. |
| 3 | node_path | string | Its path from the root, such as root.child_layer. | |
| 4 | identifier | string | Which loader to use: _tf_keras_layer, _tf_keras_input_layer, _tf_keras_rnn_layer, _tf_keras_metric, _tf_keras_network, _tf_keras_model or _tf_keras_sequential. | |
| 5 | metadata | string | The object’s other attributes, as JSON. | |
| 6 | version | VersionDef | The version of the code that wrote it. Number 1 is reserved. |
saved_model.pbtxt
The same SavedModel message may be saved in Protocol Buffers
text format as
saved_model.pbtxt instead. It is printable text, so the explorer does not
read it as this format.
A Git LFS pointer in place of the file
Models kept in Git repositories often store large files with Git LFS. When such a
repository is cloned without fetching the LFS files, saved_model.pb is
not the model but a short text file that begins:
version https://git-lfs.github.com/spec/v1
oid sha256:…
size …
The explorer turns such a file down, because it is printable text. Fetch the LFS
files (git lfs pull) to get the real model.
History
TensorFlow was released as open source in November 2015, with GraphDef already in
place. The release notes of TensorFlow 1.0.0 say “saved_model is available as
tf.saved_model”; 1.1.0 let Java load SavedModels, and 1.2.0 added the
saved_model_cli tool. TensorFlow 2, released in 2019, made SavedModel the
standard way to save a whole model. saved_model_schema_version has been 1
throughout.