MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / get_oprs_seq

Function get_oprs_seq

imperative/python/megengine/utils/comp_graph_tools.py:174–277  ·  view source on GitHub ↗

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
)

Source from the content-addressed store, hash-verified

172
173
174def 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))

Callers 4

get_dep_oprsMethod · 0.85
all_oprsMethod · 0.85
__init__Method · 0.85
make_all_depsMethod · 0.85

Calls 5

graph_traversalFunction · 0.85
topological_sortFunction · 0.85
reorder_oprs_seqFunction · 0.85
prune_reshape_oprsFunction · 0.85
copyMethod · 0.45

Tested by

no test coverage detected