Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backends/xnnpack/_passes/BUCK
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ fbcode_target(_kind = runtime.python_library,
"//executorch/exir:pass_base",
"//executorch/exir/dialects:lib",
"//executorch/exir/passes:const_prop_pass",
"//executorch/exir/passes:constant_prop_pass",
"//executorch/exir/passes:memory_format_ops_pass",
"//executorch/exir/program:program",
"//executorch/backends/transforms:utils",
Expand Down
83 changes: 83 additions & 0 deletions backends/xnnpack/_passes/constant_folding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Copyright 2026 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

from collections.abc import Mapping, Set
from typing import Any

import torch
from executorch.backends.transforms.utils import create_constant_placeholder
from torch.export import ExportedProgram
from torch.export.graph_signature import InputKind


def _evaluate_constants(
graph: torch.fx.Graph,
selected: Set[torch.fx.Node],
known_values: Mapping[torch.fx.Node, Any],
) -> tuple[dict[torch.fx.Node, Any], list[torch.fx.Node]]:
values = dict(known_values)
evaluated = []
with torch.no_grad():
for node in graph.nodes:
if node not in selected or not all(
arg in values for arg in node.all_input_nodes
):
continue
args, kwargs = torch.fx.node.map_arg(
(node.args, node.kwargs), values.__getitem__
)
value = node.target(*args, **kwargs)
if isinstance(value, torch.Tensor):
value = value.detach()
if 0 in value.stride():
value = value.clone(memory_format=torch.contiguous_format)
values[node] = value
evaluated.append(node)
return values, evaluated


def fold_constants(
exported_program: ExportedProgram,
selected: Set[torch.fx.Node],
known_values: Mapping[torch.fx.Node, Any],
kind: InputKind,
) -> bool:
"""Evaluate selected computations and lift tensors at surviving boundaries."""
graph = exported_program.graph
values, evaluated = _evaluate_constants(graph, selected, known_values)

removable = set(evaluated)
for node in reversed(evaluated):
if not isinstance(values[node], torch.Tensor) and any(
user not in removable for user in node.users
):
removable.remove(node)

taken = (
{node.name for node in graph.nodes}
| exported_program.state_dict.keys()
| exported_program.constants.keys()
)
for node in evaluated:
if node not in removable or all(user in removable for user in node.users):
continue
name = f"{node.name}_folded"
while name in taken:
name += "_"
taken.add(name)
with graph.inserting_before(next(iter(graph.nodes))):
constant = create_constant_placeholder(
exported_program, graph, name, kind, values[node]
)
# Keep fresh tensor metadata, including normalized strides.
constant.meta = {**node.meta, **constant.meta}
node.replace_all_uses_with(constant)

for node in reversed(evaluated):
if node in removable:
graph.erase_node(node)
if removable:
exported_program.graph_module.recompile()
return bool(removable)
60 changes: 26 additions & 34 deletions backends/xnnpack/_passes/conv1d_unsqueeze_pass.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# Copyright 2026 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
Expand All @@ -8,6 +9,7 @@

import torch
from executorch.backends.transforms import get_shape
from executorch.backends.transforms.utils import create_constant_placeholder
from executorch.backends.xnnpack._passes.xnnpack_pass import XNNPACKPass
from executorch.backends.xnnpack.utils.quant_utils import (
is_dequant,
Expand All @@ -18,6 +20,7 @@
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.pass_base import PassResult
from torch._ops import OpOverload
from torch.export.graph_signature import InputKind


class Conv1dUnsqueezePass(XNNPACKPass):
Expand Down Expand Up @@ -77,7 +80,7 @@ def insert_q_dq_pair(
# node's first use
q.args = (anchor,) + q_params

def unsqueeze_kernel_weights(self, kernel_node):
def unsqueeze_kernel_weights(self, kernel_node, consumer):
"""
Unsqueezes the weights of a conv1d to make it 4 dimensional.

Expand All @@ -88,39 +91,18 @@ def unsqueeze_kernel_weights(self, kernel_node):
if kernel_param_3d is None:
raise AssertionError("Expected param tensor for the kernel node")

kernel_param_4d = torch.nn.Parameter(
data=kernel_param_3d.data.contiguous().unsqueeze(dim=-1),
requires_grad=False,
)

if torch._export.utils.is_param(self.exported_program, kernel_node):
parameter_name = self.exported_program.graph_signature.inputs_to_parameters[
kernel_node.name
]
self.exported_program.state_dict[parameter_name] = kernel_param_4d
kernel_node.meta["val"] = kernel_param_4d.data.contiguous()
elif torch._export.utils.is_buffer(self.exported_program, kernel_node):
buffer_name = self.exported_program.graph_signature.inputs_to_buffers[
kernel_node.name
]
self.exported_program.state_dict[buffer_name] = kernel_param_4d
kernel_node.meta["val"] = kernel_param_4d.data.contiguous()
elif torch._export.utils.is_lifted_tensor_constant(
self.exported_program, kernel_node
):
buffer_name = (
self.exported_program.graph_signature.inputs_to_lifted_tensor_constants[
kernel_node.name
]
)
self.exported_program.constants[buffer_name] = kernel_param_4d
kernel_node.meta["val"] = kernel_param_4d.data.contiguous()
else:
setattr(
kernel_node.graph.owning_module,
kernel_node.target,
kernel_param_4d,
graph = kernel_node.graph
with graph.inserting_before(next(iter(graph.nodes))):
weight = create_constant_placeholder(
self.exported_program,
graph,
name=f"{kernel_node.name}_{consumer.name}_4d",
kind=InputKind.CONSTANT_TENSOR,
data=kernel_param_3d.detach().contiguous().unsqueeze(-1),
)
if "custom" in kernel_node.meta:
weight.meta["custom"] = kernel_node.meta["custom"].copy()
return weight

def call(self, graph_module: torch.fx.GraphModule):
graph = graph_module.graph
Expand All @@ -145,7 +127,17 @@ def call(self, graph_module: torch.fx.GraphModule):
)

# Modify graph such that the conv changes from 1d to 2d
self.unsqueeze_kernel_weights(kernel_node)
weight = self.unsqueeze_kernel_weights(kernel_node, node)
if is_dequant(node.args[1]):
dequant = node.args[1]
with graph.inserting_before(node):
weight = graph.call_function(
dequant.target,
(weight,) + dequant.args[1:],
dequant.kwargs,
)
weight.meta = dequant.meta.copy()
node.update_arg(1, weight)

# (b) Extend stride, padding, and dilation for extra dim
node.args = (
Expand Down
58 changes: 13 additions & 45 deletions backends/xnnpack/_passes/fold_computed_params.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# Copyright 2026 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

import torch
from executorch.backends.transforms.utils import create_constant_placeholder
from executorch.backends.xnnpack._passes.constant_folding import fold_constants
from executorch.backends.xnnpack._passes.xnnpack_pass import XNNPACKPass
from executorch.backends.xnnpack.utils.utils import (
COMPUTED_PARAM_TAG,
Expand All @@ -25,58 +26,25 @@ class FoldComputedParamsPass(XNNPACKPass):
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
graph = graph_module.graph
names = {node.name for node in graph.nodes}
values = {}
values = {
node: get_param_tensor(self.exported_program, node)
for node in graph.nodes
if is_param_node(self.exported_program, node)
}
selected = set()
for node in graph.nodes:
# A GEMM rejected after its check, possibly by an earlier partitioner,
# leaves tags behind, which delegate outputs and inputs inherit. So
# fold a tagged node only next to its GEMM, and only from params.
if (
node.op != "call_function"
or not names & node.meta.get(COMPUTED_PARAM_TAG, set())
or not all(
n in values or is_param_node(self.exported_program, n)
for n in node.all_input_nodes
)
or not all(n in values or n in selected for n in node.all_input_nodes)
):
continue
args, kwargs = torch.fx.node.map_arg(
(node.args, node.kwargs),
lambda n: (
values[n]
if n in values
else get_param_tensor(self.exported_program, n)
),
)
with torch.no_grad():
values[node] = node.target(*args, **kwargs)
selected.add(node)

if not values:
return PassResult(graph_module, False)

taken = (
names
| self.exported_program.state_dict.keys()
| self.exported_program.constants.keys()
changed = fold_constants(
self.exported_program, selected, values, InputKind.PARAMETER
)
for node, value in values.items():
if all(user in values for user in node.users):
continue
name = f"{node.name}_folded"
while name in taken:
name += "_"
taken.add(name)
with graph.inserting_before(next(iter(graph.nodes))):
param = create_constant_placeholder(
exp_program=self.exported_program,
graph=graph,
kind=InputKind.PARAMETER,
name=name,
data=value,
)
node.replace_all_uses_with(param)

for node in reversed(values):
graph.erase_node(node)

graph_module.recompile()
return PassResult(graph_module, True)
return PassResult(graph_module, changed)
Loading