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

Method maybe_create

backends/mlx/patterns.py:463–510  ·  view source on GitHub ↗
(cls, ep: ExportedProgram, head: Node)

Source from the content-addressed store, hash-verified

461
462 @classmethod
463 def maybe_create(cls, ep: ExportedProgram, head: Node) -> Optional["SDPAHandler"]:
464 sdpa_node = head
465 if not match_target(
466 sdpa_node, torch.ops.aten.scaled_dot_product_attention.default
467 ):
468 return None
469
470 q, k, v, _, _, _, _, _ = cls._parse_sdpa_args_and_kwargs(sdpa_node)
471
472 # Detect grouped kv attention pattern with repeat_interleave before SDPA
473 is_grouped_kv = False
474 k_base = k
475 v_base = v
476 body: List[Node] = []
477 if (
478 match_target(k, torch.ops.aten.repeat_interleave.self_int)
479 and has_single_user(k)
480 and (len(k.args) == 3)
481 and (len(k.kwargs) == 0)
482 and match_target(v, torch.ops.aten.repeat_interleave.self_int)
483 and has_single_user(v)
484 and (len(v.args) == 3)
485 and (len(v.kwargs) == 0)
486 ):
487 k_unrepeated, k_reps, k_dim = k.args
488 v_unrepeated, v_reps, v_dim = v.args
489
490 if (k_dim == 1 and v_dim == 1) and (k_reps == v_reps):
491 is_grouped_kv = True
492 k_base = k_unrepeated
493 v_base = v_unrepeated
494 body = [k, v]
495
496 # Detect HuggingFace repeat_kv pattern:
497 # unsqueeze(dim=2) → expand → clone → view
498 if not is_grouped_kv:
499 k_unwrap = cls._try_unwrap_repeat_kv(k)
500 v_unwrap = cls._try_unwrap_repeat_kv(v)
501 if k_unwrap is not None and v_unwrap is not None:
502 k_base, k_body = k_unwrap
503 v_base, v_body = v_unwrap
504 is_grouped_kv = True
505 body = k_body + v_body
506
507 head = sdpa_node
508 if not is_grouped_kv:
509 body = []
510 return SDPAHandler(head, body, q_node=q, k_node=k_base, v_node=v_base)
511
512 def __call__(self, P: MLXProgramBuilder, n: Node) -> Slot:
513 assert n == self.head

Callers

nothing calls this directly

Calls 5

match_targetFunction · 0.90
has_single_userFunction · 0.90
SDPAHandlerClass · 0.85
_try_unwrap_repeat_kvMethod · 0.80

Tested by

no test coverage detected