[vLLM IR] 2/N fused_add_rms_norm and maybe_inplace overload (#36823)
Signed-off-by: Luka Govedič <lgovedic@redhat.com> Signed-off-by: Luka Govedič <ProExpertProg@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import torch
|
||||
from torch import fx
|
||||
from torch._higher_order_ops.auto_functionalize import auto_functionalized
|
||||
from torch._higher_order_ops.triton_kernel_wrap import TritonKernelWrapperFunctional
|
||||
from torch._ops import HigherOrderOperator, OpOverload
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from ..fx_utils import is_func
|
||||
from ..inductor_pass import get_pass_context
|
||||
from ..vllm_inductor_pass import VllmInductorPass
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def user_writes_to_node(user: fx.Node, node: fx.Node) -> bool:
|
||||
if user.op == "output":
|
||||
return False
|
||||
|
||||
if is_func(user, auto_functionalized):
|
||||
# While autofunc writes to the node,
|
||||
# this is a follow-up use we're not interested in.
|
||||
# It is also guaranteed to be the final use,
|
||||
# as auto_functionalized returns the tensor back for follow-up use.
|
||||
return False
|
||||
elif user.op == "call_function" and isinstance(user.target, HigherOrderOperator):
|
||||
# By default, be conservative, assume this could be a write
|
||||
# (except functional HOPs)
|
||||
return not isinstance(user.target, TritonKernelWrapperFunctional)
|
||||
|
||||
assert isinstance(user.target, OpOverload), (
|
||||
f"{node=} {user=} {user.op=} {user.target=}"
|
||||
)
|
||||
schema = user.target._schema
|
||||
assert len(user.args) <= len(schema.arguments)
|
||||
for i, arg in enumerate(user.args):
|
||||
# Only interested in writes to node
|
||||
if arg is not node:
|
||||
continue
|
||||
|
||||
# If not a write, next arg could be
|
||||
if schema.arguments[i].is_write:
|
||||
return True
|
||||
|
||||
# No writes found
|
||||
return False
|
||||
|
||||
|
||||
class UnsafeCloneEliminationPass(VllmInductorPass):
|
||||
"""
|
||||
This pass removes clone nodes that are no longer needed after vLLM IR lowering.
|
||||
It uses donated_input_ids to eliminate clones of donated graph inputs, preserving
|
||||
contents of non-donated graph inputs.
|
||||
|
||||
It is "unsafe" because it does not (yet) take aliasing into account. Solving
|
||||
aliasing is an open problem, so this pass intends to support known vLLM cases
|
||||
and not guarantee soundness on general graphs. In the future, this pass will likely
|
||||
support basic forms of aliasing to handle simple views (e.g. qkv -> q,k,v).
|
||||
"""
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig) -> None:
|
||||
super().__init__(vllm_config)
|
||||
|
||||
@VllmInductorPass.time_and_log
|
||||
def __call__(self, graph: fx.Graph) -> None:
|
||||
count = 0
|
||||
node_to_idx = {node: i for i, node in enumerate(graph.nodes)}
|
||||
pass_context = get_pass_context()
|
||||
donated_input_ids = pass_context.donated_input_ids
|
||||
logger.debug("Donated input ids: %s", donated_input_ids)
|
||||
|
||||
for node in graph.nodes:
|
||||
if not is_func(node, torch.ops.aten.clone.default):
|
||||
continue
|
||||
|
||||
original_node = node.args[0]
|
||||
assert isinstance(original_node, fx.Node)
|
||||
|
||||
# Clone needs to be preserved if node is getting written to and
|
||||
# the old value is used again.
|
||||
# This could only happen if an inplace implementation was lowered.
|
||||
# Then node (the clone) will have one write.
|
||||
# TODO(luka) hopefully this can be removed once we lower functional graphs.
|
||||
write_idxs = [
|
||||
node_to_idx[u] for u in node.users if user_writes_to_node(u, node)
|
||||
]
|
||||
assert len(write_idxs) in (0, 1)
|
||||
if write_idxs:
|
||||
# Check if a user of original_node occurs after a write
|
||||
write_idx = write_idxs[0]
|
||||
if any(
|
||||
node_to_idx[orig_user] > write_idx
|
||||
for orig_user in original_node.users
|
||||
):
|
||||
logger.debug(
|
||||
"Clone removal not possible, "
|
||||
"original_node=%s used after mutation on node=%s",
|
||||
original_node,
|
||||
node,
|
||||
)
|
||||
continue
|
||||
|
||||
# Check if a node is a (non-donated) graph input
|
||||
if (
|
||||
original_node.op == "placeholder"
|
||||
and node_to_idx[original_node] not in donated_input_ids
|
||||
):
|
||||
logger.debug(
|
||||
"Graph input %s not donated, cannot eliminate its clone",
|
||||
original_node,
|
||||
)
|
||||
continue
|
||||
|
||||
logger.debug(
|
||||
"Node %s is a redundant clone node of %s, removing it",
|
||||
node,
|
||||
original_node,
|
||||
)
|
||||
node.replace_all_uses_with(original_node)
|
||||
graph.erase_node(node)
|
||||
count += 1
|
||||
|
||||
logger.debug("CloneCleanupPass removed %d clone nodes", count)
|
||||
@@ -0,0 +1,101 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections import defaultdict
|
||||
|
||||
from torch import fx
|
||||
from torch._inductor.pattern_matcher import (
|
||||
PatternMatcherPass,
|
||||
)
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from ..inductor_pass import get_pass_context
|
||||
from ..vllm_inductor_pass import VllmInductorPass
|
||||
from .lowering_pass import get_ir_op
|
||||
from .utils import overload_or_default
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class VllmIRInplaceFunctionalizationPass(VllmInductorPass):
|
||||
"""
|
||||
This pass functionalizes maybe_inplace vLLM IR ops to the default overload.
|
||||
The maybe_inplace overloads have the same signature as the default overload
|
||||
so the pass simply replaces the called overload.
|
||||
That makes the graph properly functional.
|
||||
The pass also validates that activations passed to maybe_inplace have no later
|
||||
uses in the graph: they are donated to the maybe_inplace op call,
|
||||
and their contents are not defined afterward.
|
||||
|
||||
This pass operates pre-AOTAutograd,
|
||||
so it must handle non-normalized and non-functional IR.
|
||||
"""
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig) -> None:
|
||||
super().__init__(vllm_config)
|
||||
self.patterns = PatternMatcherPass(self.pass_name)
|
||||
self.functionalized_ops: dict[str, int] = defaultdict(lambda: 0)
|
||||
|
||||
@VllmInductorPass.time_and_log
|
||||
def __call__(self, graph: fx.Graph) -> None:
|
||||
# clear at the beginning instead of end, so that tests can inspect
|
||||
self.functionalized_ops.clear()
|
||||
assert graph.owning_module is not None
|
||||
node_to_idx = {node: i for i, node in enumerate(graph.nodes)}
|
||||
|
||||
# Pass donated input via vLLM's pass context
|
||||
pass_context = get_pass_context()
|
||||
pass_context.donated_input_ids = set[int]()
|
||||
|
||||
for node in graph.nodes:
|
||||
if (ir_op := get_ir_op(node)) is None:
|
||||
continue
|
||||
|
||||
op_overload = overload_or_default(node.target)
|
||||
overload_name = op_overload._overloadname
|
||||
if overload_name != "maybe_inplace":
|
||||
assert overload_name == "default", (
|
||||
f"Found overload {overload_name} for op {ir_op.name}, "
|
||||
f"expected maybe_inplace or default"
|
||||
)
|
||||
continue
|
||||
|
||||
# must have maybe_inplace overload and allow_inplace
|
||||
assert ir_op.allow_inplace and hasattr(ir_op, "maybe_inplace")
|
||||
|
||||
# Check that activation inputs are not used after this op
|
||||
for arg_idx in ir_op.activation_indices:
|
||||
arg = node.args[arg_idx]
|
||||
assert isinstance(arg, fx.Node), "Activation inputs must be fx.Node"
|
||||
for user in arg.users:
|
||||
if node_to_idx[user] > node_to_idx[node]:
|
||||
raise ValueError(
|
||||
f"Input {arg} to maybe_inplace node {node} "
|
||||
f"is used again after the node. "
|
||||
f"This is not allowed; activation inputs to maybe_inplace "
|
||||
f"ops are donated to the op, meaning their memory may be "
|
||||
f"recycled for outputs.\n\n"
|
||||
f"To preserve the inputs, use the default overload or "
|
||||
f"clone them manually beforehand."
|
||||
)
|
||||
|
||||
if arg.op == "placeholder":
|
||||
# Graph input that maybe_inplace might modify.
|
||||
# Mark it so downstream passes know it's donated.
|
||||
# TODO(luka) store in placeholder node meta once supported
|
||||
pass_context.donated_input_ids.add(node_to_idx[arg])
|
||||
|
||||
# Same signature, just replace the overload that's called.
|
||||
node.target = ir_op.torch_op
|
||||
self.functionalized_ops[ir_op.name] += 1
|
||||
|
||||
count = sum(self.functionalized_ops.values())
|
||||
ops = ",".join(self.functionalized_ops.keys())
|
||||
logger.debug("Donated input IDs: %s", pass_context.donated_input_ids)
|
||||
logger.debug(
|
||||
"%s functionalized %d vLLM IR nodes for op(s) %s",
|
||||
self.pass_name,
|
||||
count,
|
||||
ops,
|
||||
)
|
||||
@@ -10,7 +10,6 @@ from torch._inductor.pattern_matcher import (
|
||||
PatternMatcherPass,
|
||||
register_graph_pattern,
|
||||
)
|
||||
from torch._ops import OpOverload, OpOverloadPacket
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.ir.op import IrOp
|
||||
@@ -18,41 +17,11 @@ from vllm.logger import init_logger
|
||||
from vllm.logging_utils import lazy
|
||||
|
||||
from ..vllm_inductor_pass import VllmInductorPass
|
||||
from .utils import get_ir_op
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def get_default_overload(op: OpOverload | OpOverloadPacket) -> OpOverload:
|
||||
if isinstance(op, OpOverloadPacket):
|
||||
return op.default
|
||||
assert isinstance(op, OpOverload), "Expected an OpOverload or OpOverloadPacket"
|
||||
return op
|
||||
|
||||
|
||||
def get_ir_op(node: fx.Node) -> IrOp | None:
|
||||
if node.op != "call_function":
|
||||
return None
|
||||
|
||||
if not isinstance(node.target, (OpOverload, OpOverloadPacket)):
|
||||
return None
|
||||
|
||||
op_overload = get_default_overload(node.target)
|
||||
if op_overload.namespace != "vllm_ir":
|
||||
return None
|
||||
|
||||
op_name = op_overload._opname
|
||||
if op_name not in IrOp.registry:
|
||||
logger.warning(
|
||||
"Unknown vLLM IR op %s, there's likely an issue with torch registration, "
|
||||
"or a torch custom op was registered in the vllm_ir namespace by mistake.",
|
||||
op_name,
|
||||
)
|
||||
return None
|
||||
|
||||
ir_op = IrOp.registry[op_name]
|
||||
return ir_op
|
||||
|
||||
|
||||
class VllmIRLoweringPass(VllmInductorPass):
|
||||
"""
|
||||
This pass lowers vLLM IR ops to their implementations the priority list.
|
||||
@@ -76,7 +45,7 @@ class VllmIRLoweringPass(VllmInductorPass):
|
||||
|
||||
assert len(match.nodes) == 1, "Expected single node match"
|
||||
node = match.nodes[0]
|
||||
ir_op = get_ir_op(node)
|
||||
ir_op = get_ir_op(node) # TODO is node.target always an overload?
|
||||
assert ir_op is not None, "Expected vLLM IR op"
|
||||
assert not node.kwargs # I think there should never be kwargs here
|
||||
|
||||
@@ -86,13 +55,18 @@ class VllmIRLoweringPass(VllmInductorPass):
|
||||
self.selected_impls[ir_op.name][node.name] = ir_op_impl.provider
|
||||
|
||||
# replace_by_example wants node args, not the fake tensors
|
||||
# use func_impl_fn to properly handle in-place implementations
|
||||
# TODO(luka): Use aot_export_module to get functionalized graph
|
||||
# TODO(luka): Cache the fx_replacement to avoid re-tracing the same impl
|
||||
|
||||
# Defaults not present on node.args but required for replacement tracing
|
||||
bound_args = ir_op._py_signature.bind(*node.args)
|
||||
bound_args.apply_defaults()
|
||||
match.replace_by_example(ir_op_impl.impl_fn, bound_args.args)
|
||||
# It is not safe to run functional passes (like DCE) on the replacements
|
||||
# as they might not be functional.
|
||||
match.replace_by_example(
|
||||
ir_op_impl.func_impl_fn, bound_args.args, run_functional_passes=False
|
||||
)
|
||||
|
||||
@VllmInductorPass.time_and_log
|
||||
def __call__(self, graph: fx.Graph) -> None:
|
||||
@@ -136,7 +110,7 @@ class VllmIRLoweringPass(VllmInductorPass):
|
||||
|
||||
if failed_nodes or failed_ops:
|
||||
logger.warning("Failed to lower vLLM IR ops: %s", ",".join(failed_ops))
|
||||
logger.warning("Full node list: %s", failed_nodes)
|
||||
logger.warning("Full node list: %s", ",".join(str(n) for n in failed_nodes))
|
||||
|
||||
def uuid(self) -> str:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from torch import fx
|
||||
from torch._ops import OpOverload, OpOverloadPacket
|
||||
|
||||
from vllm.ir.op import IrOp
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def overload_or_default(op: OpOverload | OpOverloadPacket) -> OpOverload:
|
||||
if isinstance(op, OpOverloadPacket):
|
||||
return op.default
|
||||
assert isinstance(op, OpOverload), "Expected an OpOverload or OpOverloadPacket"
|
||||
return op
|
||||
|
||||
|
||||
def get_ir_op(node: fx.Node) -> IrOp | None:
|
||||
if node.op != "call_function":
|
||||
return None
|
||||
|
||||
if not isinstance(node.target, (OpOverload, OpOverloadPacket)):
|
||||
return None
|
||||
|
||||
op_overload = overload_or_default(node.target)
|
||||
if op_overload.namespace != "vllm_ir":
|
||||
return None
|
||||
|
||||
op_name = op_overload._opname
|
||||
if op_name not in IrOp.registry:
|
||||
logger.warning(
|
||||
"Unknown vLLM IR op %s, there's likely an issue with torch registration, "
|
||||
"or a torch custom op was registered in the vllm_ir namespace by mistake.",
|
||||
op_name,
|
||||
)
|
||||
return None
|
||||
|
||||
ir_op = IrOp.registry[op_name]
|
||||
return ir_op
|
||||
Reference in New Issue
Block a user