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,
)
| 198 | |
| 199 | |
| 200 | def 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 |
no test coverage detected