TensorFlow Import
Importing TensorFlow frozen graphs and SavedModels into SameDiff
TensorFlow Import
The nd4j-samediff-import-tensorflow module imports TensorFlow frozen graphs (.pb protobuf files) and TensorFlow SavedModels into SameDiff. After import, the model lives as a native SameDiff graph.
Maven Dependency
<dependency>
<groupId>org.nd4j</groupId>
<artifactId>nd4j-samediff-import-tensorflow</artifactId>
<version>${dl4j.version}</version>
</dependency>Preparing Your TensorFlow Model
Exporting a Frozen Graph from TF 1.x
import tensorflow as tf
from tensorflow.python.framework.graph_util import convert_variables_to_constants
# Assuming you have a trained session
with tf.Session() as sess:
# ... restore or train your model ...
# Freeze: convert variables to constants
frozen_graph_def = convert_variables_to_constants(
sess,
sess.graph_def,
output_node_names=['output/Softmax'] # your output node name(s)
)
# Write to disk
with tf.io.gfile.GFile('frozen_model.pb', 'wb') as f:
f.write(frozen_graph_def.SerializeToString())Exporting a Frozen Graph from TF 2.x
Getting Node Names
To identify placeholder (input) and output node names in a frozen graph:
Importing a Frozen Graph
Use TFGraphMapper to import a TF frozen protobuf file:
You can also import from an InputStream:
Placeholder Mapping
TF frozen graphs have placeholder nodes for inputs. After import, you must provide values for each placeholder at inference time. Use sd.output() with a map from placeholder name to INDArray:
Multiple Inputs and Outputs
For models with multiple inputs:
Inspecting the Imported Graph
After import, you can inspect the graph structure:
Supported TF Ops
The following categories of TensorFlow ops are mapped:
Arithmetic and math:
Add, AddV2, Sub, Mul, Div, FloorDiv, FloorMod, Pow, Exp, Log, Sqrt, Square, Abs, Neg, Sign, Ceil, Floor, Round
MatMul, BatchMatMul, BatchMatMulV2
Minimum, Maximum, BiasAdd
Neural network:
Conv2D, Conv2DBackpropInput, DepthwiseConv2dNative, Conv3D
Relu, Relu6, Elu, Selu, LeakyRelu, Sigmoid, Tanh, Softmax, LogSoftmax
MaxPool, AvgPool, MaxPool3D, AvgPool3D, MaxPoolV2
FusedBatchNorm, FusedBatchNormV2, FusedBatchNormV3
Shape and indexing:
Reshape, Transpose, Concat, ConcatV2, Stack, Unstack, Pack, Unpack
Split, SplitV, Slice, StridedSlice, GatherV2, GatherNd, ScatterNd
Squeeze, ExpandDims, Tile, Pad, PadV2, MirrorPad
Reduction:
Sum (ReduceSum), Mean (ReduceMean), Max (ReduceMax), Min (ReduceMin)
ReduceAll, ReduceAny, ReduceProd
Type and cast:
Cast, Identity, Snapshot
Control flow (TF 1.x):
Switch, Merge, Enter, Exit, NextIteration
Recurrent:
LSTMBlockCell, BlockLSTM, GRUBlockCell
Image:
ResizeBilinear, ResizeNearestNeighbor, CropAndResize, DecodeJpeg (decode only)
Lookup and embedding:
ResourceGather, GatherV2
Complete Example: MobileNet Inference
Troubleshooting
Op not found: a TF op in the frozen graph has no registered SameDiff mapper. Check the op name in the error message, verify the op list above, and open a GitHub issue if it should be supported.
Placeholder name unknown: run the Python snippet above to print all node names before import. Use the exact string that appears after the Placeholder op type.
Shape mismatch at inference: TF models trained with NHWC data format (TensorFlow default) expect inputs as [batch, height, width, channels]. Construct your INDArray accordingly.
Variables not frozen: if the frozen graph still contains Variable ops, the freeze step was incomplete. Ensure convert_variables_to_constants ran successfully and all variable names were captured.
Last updated
Was this helpful?