Insert calls to free for dynamic unbound tensors that goes out of lifetime. Only handle the module itself. Submodule is handles in separate calls of this function. NOTE: this method will invalidate lifetime recorded in TensorSpec because of extra free node added to the graph.
(
graph_module: fx.GraphModule, allspecs: Set[TensorSpec]
)
| 1211 | |
| 1212 | |
| 1213 | def insert_calls_to_free( |
| 1214 | graph_module: fx.GraphModule, allspecs: Set[TensorSpec] |
| 1215 | ) -> None: |
| 1216 | """ |
| 1217 | Insert calls to free for dynamic unbound tensors that goes out of lifetime. |
| 1218 | |
| 1219 | Only handle the module itself. Submodule is handles in separate calls of |
| 1220 | this function. |
| 1221 | |
| 1222 | NOTE: this method will invalidate lifetime recorded in TensorSpec because |
| 1223 | of extra free node added to the graph. |
| 1224 | """ |
| 1225 | # Note: we should never free a output tensor |
| 1226 | return_specs = get_return_specs(graph_module) |
| 1227 | # Note: we should never free a input tensor since buffer for input tensor |
| 1228 | # may be passed in from user. |
| 1229 | input_specs = get_input_specs(graph_module) |
| 1230 | idx_to_dead_specs = defaultdict(list) |
| 1231 | for spec in allspecs: |
| 1232 | if ( |
| 1233 | spec.shape_dynamism == TensorShapeDynamism.DYNAMIC_UNBOUND |
| 1234 | and spec not in return_specs |
| 1235 | and spec not in input_specs |
| 1236 | ): |
| 1237 | idx_to_dead_specs[spec.lifetime[1]].append(spec) |
| 1238 | |
| 1239 | num_nodes = len(graph_module.graph.nodes) |
| 1240 | # iterate in reverse order so inserted node does not disturbe node |
| 1241 | # numbering. |
| 1242 | for node, node_idx in zip( |
| 1243 | reversed(graph_module.graph.nodes), range(num_nodes - 1, -1, -1) |
| 1244 | ): |
| 1245 | dead_specs = idx_to_dead_specs.get(node_idx, []) |
| 1246 | if not dead_specs: |
| 1247 | continue |
| 1248 | with graph_module.graph.inserting_after(node): |
| 1249 | for spec in dead_specs: |
| 1250 | graph_module.graph.call_function(memory.free, (spec,)) |
| 1251 | graph_module.recompile() |
| 1252 | |
| 1253 | |
| 1254 | def _merge_bufsizes(bufsizes: list[int], new_bufsizes: list[int]) -> list[int]: |
no test coverage detected