Commit 62c9532
committed
Fix gh-18459: pre-build Sequential sublayers not reached through call()
Root cause: when a Sequential sublayer is only used inside a custom
`train_step` (not in `call()`), it is not built during `_symbolic_build`,
which only traces `call()`. For the TF backend without a distribute
strategy, `_maybe_symbolic_build()` previously returned early without
calling `_symbolic_build` at all. This caused the Sequential sublayer to
be built lazily during the first `tf.function` trace of `train_step`.
`Sequential.build()` creates KerasTensors and calls `compute_output_spec`,
which for TF creates a nested `FuncGraph` inside the already-active
`tf.function` context. When TF then tries to use a KerasTensor as a real
tensor, it hits `KerasTensor.__tf_tensor__` which raises:
"A KerasTensor cannot be used as input to a TensorFlow function."
Fix (two parts):
1. `_symbolic_build` (trainer.py): after tracing `call()`, iterate over
all sublayers and pre-build any that are still unbuilt by running
`compute_output_spec` on the symbolic input `x`.
2. TF `_maybe_symbolic_build` (tensorflow/trainer.py): instead of always
deferring when no distribute strategy is set, only defer when all
layers are already built. If unbuilt sublayers exist, call
`_symbolic_build` so they are built before `tf.function` traces
`train_step`.
Also updates the regression test docstrings to accurately describe the
root cause (gh-18459).1 parent 316d355 commit 62c9532
3 files changed
Lines changed: 35 additions & 7 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
715 | 715 | | |
716 | 716 | | |
717 | 717 | | |
| 718 | + | |
| 719 | + | |
| 720 | + | |
| 721 | + | |
| 722 | + | |
| 723 | + | |
| 724 | + | |
| 725 | + | |
| 726 | + | |
718 | 727 | | |
719 | 728 | | |
720 | 729 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1130 | 1130 | | |
1131 | 1131 | | |
1132 | 1132 | | |
| 1133 | + | |
| 1134 | + | |
| 1135 | + | |
| 1136 | + | |
| 1137 | + | |
| 1138 | + | |
| 1139 | + | |
| 1140 | + | |
| 1141 | + | |
| 1142 | + | |
| 1143 | + | |
| 1144 | + | |
| 1145 | + | |
1133 | 1146 | | |
1134 | 1147 | | |
1135 | 1148 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
82 | 82 | | |
83 | 83 | | |
84 | 84 | | |
85 | | - | |
86 | | - | |
87 | | - | |
88 | | - | |
89 | | - | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
90 | 94 | | |
91 | 95 | | |
92 | 96 | | |
| |||
791 | 795 | | |
792 | 796 | | |
793 | 797 | | |
794 | | - | |
795 | | - | |
| 798 | + | |
| 799 | + | |
| 800 | + | |
| 801 | + | |
796 | 802 | | |
797 | 803 | | |
798 | 804 | | |
| |||
0 commit comments