r"""Gets oprs in some topological order for a dumped model. Args: outputs: model outputs. prune_reshape: whether to prune the useless operators used by Reshape opr during inference. prune_immtensor: whether to prune the ImmutableTensor opr. Returns: opr list
(
outputs: List[_VarNode], prune_reshape=False, prune_immtensor=True
)
| 172 | |
| 173 | |
| 174 | def get_oprs_seq( |
| 175 | outputs: List[_VarNode], prune_reshape=False, prune_immtensor=True |
| 176 | ) -> List[_OpNode]: |
| 177 | r"""Gets oprs in some topological order for a dumped model. |
| 178 | |
| 179 | Args: |
| 180 | outputs: model outputs. |
| 181 | prune_reshape: whether to prune the useless operators used by Reshape opr during inference. |
| 182 | prune_immtensor: whether to prune the ImmutableTensor opr. |
| 183 | |
| 184 | Returns: |
| 185 | opr list with some correct execution order. |
| 186 | """ |
| 187 | |
| 188 | def topological_sort(map_oprs, opr2receivers, indegree2opr, opr2indegree): |
| 189 | # generate an execution order with topological sort algorithm |
| 190 | oprs_seq = [] |
| 191 | nr_remain = len(map_oprs) |
| 192 | while indegree2opr[0]: |
| 193 | opr = indegree2opr[0].pop_min() |
| 194 | opr_id = opr.id |
| 195 | nr_remain -= 1 |
| 196 | if opr.type != "ImmutableTensor" or not prune_immtensor: |
| 197 | oprs_seq.append(opr) |
| 198 | |
| 199 | for post_id in opr2receivers[opr_id]: |
| 200 | indegree = opr2indegree[post_id] |
| 201 | indegree2opr[indegree].remove(post_id) |
| 202 | |
| 203 | indegree -= 1 |
| 204 | if indegree == 0: |
| 205 | indegree2opr[indegree].add(map_oprs[post_id]) |
| 206 | else: |
| 207 | indegree2opr[indegree].add(post_id) |
| 208 | opr2indegree[post_id] = indegree |
| 209 | |
| 210 | assert nr_remain == 0, "there are {} remaining nodes; cyclic graph?".format( |
| 211 | nr_remain |
| 212 | ) |
| 213 | return oprs_seq |
| 214 | |
| 215 | # reshape op definition: reshape(input_tensor, dest_shape) -> output_tensor |
| 216 | # when inferencing, shape of output_tensor is already known, so one can prune some operators related to dest_shape in the loaded graph |
| 217 | def prune_reshape_oprs(outputs, oprs_seq, var2oprs): |
| 218 | def iterative_pruning(cur_opr, post_opr, marked_opr_ids, visited): |
| 219 | useless = True |
| 220 | for oup in cur_opr.outputs: |
| 221 | if "workspace" not in oup.name: |
| 222 | var_idx = post_opr.inputs.index(oup) |
| 223 | var2oprs[oup.id].remove((post_opr.id, var_idx)) |
| 224 | useless = useless and (len(var2oprs[oup.id]) == 0) |
| 225 | |
| 226 | if useless: |
| 227 | marked_opr_ids.append(cur_opr.id) |
| 228 | |
| 229 | for opr in set([var.owner for var in cur_opr.inputs]): |
| 230 | if (opr.id, cur_opr.id) not in visited: |
| 231 | visited.add((opr.id, cur_opr.id)) |
no test coverage detected