MCPcopy Create free account
hub / github.com/pytorch/executorch / find_pattern

Function find_pattern

backends/qualcomm/_passes/utils.py:200–267  ·  view source on GitHub ↗

Implement wildcard pattern matching - node: fx.Node - pattern: predicate list, can contain followings Callable(fx.node): predicate '*': wildcard '?': any single node - from_args: if True find from node.args, otherwise from node.users

(
    node: torch.fx.Node,
    pattern: List[Callable[[torch.fx.Node], bool] | str],
    from_args: bool = True,
    max_wildcard_life: int = 3,
    verbose: bool = False,
)

Source from the content-addressed store, hash-verified

198
199
200def find_pattern(
201 node: torch.fx.Node,
202 pattern: List[Callable[[torch.fx.Node], bool] | str],
203 from_args: bool = True,
204 max_wildcard_life: int = 3,
205 verbose: bool = False,
206):
207 """
208 Implement wildcard pattern matching
209 - node: fx.Node
210 - pattern: predicate list, can contain followings
211 Callable(fx.node): predicate
212 '*': wildcard
213 '?': any single node
214 - from_args: if True find from node.args, otherwise from node.users
215 - max_wildcard_life: max number of skips for wildcard
216
217 If not matched, return None.
218 Otherwise, return list of matched node list, which is the same length as pattern
219 """
220
221 asterisk, question = "*", "?"
222
223 def _probe(
224 cur, hist, pat_idx, asterisk_life_count=max_wildcard_life, verbose=verbose
225 ):
226 if pat_idx == len(pattern):
227 # Expected len(hist) is equal to pat_idx
228 assert len(hist) == len(pattern)
229 if list(hist) not in matched:
230 matched.append(list(hist))
231 return
232 if verbose:
233 print(
234 f"cur:{cur}, idx:{pat_idx}, life={asterisk_life_count}, pattern:{pattern[pat_idx]} hist={hist}"
235 )
236 if pattern[pat_idx] == question or _pred(cur, pattern[pat_idx]):
237 hist.append(cur)
238 for child in _next(cur, from_args):
239 _probe(child, hist, pat_idx + 1)
240 hist.pop()
241 elif pattern[pat_idx] == asterisk and asterisk_life_count > 0:
242 # 3 cases: ignore/consume/keep asterisk
243 # 1, Ignore asterisk
244 hist.append(None)
245 _probe(cur, hist, pat_idx + 1)
246 hist.pop()
247
248 # 2. Consume asterisk
249 hist.append(None)
250 for child in _next(cur, from_args):
251 _probe(child, hist, pat_idx + 1)
252 hist.pop()
253
254 # 3. keep asterisk and skip to next node
255 for child in _next(cur, from_args):
256 _probe(child, hist, pat_idx, asterisk_life_count - 1)
257

Callers 4

_get_attention_outputMethod · 0.90
_visit_reshapeMethod · 0.90
_is_making_mhaMethod · 0.90
find_patternsFunction · 0.85

Calls 1

_probeFunction · 0.85

Tested by

no test coverage detected