Skip to content

Commit efcfe4c

Browse files
committed
Decline QKV fusion for graph inputs
1 parent ba0d0dd commit efcfe4c

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

‎onnxoptimizer/passes/fuse_qkv.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ struct FuseQKV final : public PredicateBasedPass {
3131
bool runTransform(Node* n, Graph& graph,
3232
NodeDestroyType& destroy_current) override {
3333
destroy_current = NodeDestroyType::DestroyZero;
34+
if (n->input(0)->node()->kind() == kParam) {
35+
return false;
36+
}
3437
const auto uses = n->input(0)->uses();
3538
for (const auto& use : uses) {
3639
if (use.offset != 0 || !CheckKind(use.user, kMatMul) ||

‎onnxoptimizer/test/optimizer_test.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5096,6 +5096,47 @@ def test_fuse_qkv(self): # type: () -> None
50965096
self._test_fuse_qkv_with_opset(opset_version)
50975097
self._test_fuse_qkv_with_opset(LATEST_STABLE_OPSET_VERSION)
50985098

5099+
def test_fuse_qkv_declines_graph_input(self): # type: () -> None
5100+
for weight_shape in ([3], [3, 1]):
5101+
with self.subTest(weight_shape=weight_shape):
5102+
X = helper.make_tensor_value_info("X", TensorProto.FLOAT, [2, 3])
5103+
output_shape = [2] if len(weight_shape) == 1 else [2, 1]
5104+
outputs = [
5105+
helper.make_tensor_value_info(name, TensorProto.FLOAT, output_shape)
5106+
for name in ("Y1", "Y2", "Y3")
5107+
]
5108+
weights = [
5109+
helper.make_tensor(
5110+
f"W{i}",
5111+
TensorProto.FLOAT,
5112+
weight_shape,
5113+
np.ones(weight_shape, dtype=np.float32).flatten(),
5114+
)
5115+
for i in range(3)
5116+
]
5117+
matmuls = [
5118+
helper.make_node("MatMul", ["X", f"W{i}"], [f"M{i}"])
5119+
for i in range(3)
5120+
]
5121+
identities = [
5122+
helper.make_node("Identity", [f"M{i}"], [f"Y{i + 1}"])
5123+
for i in range(3)
5124+
]
5125+
graph = helper.make_graph(
5126+
matmuls + identities, "test", [X], outputs, weights
5127+
)
5128+
5129+
optimized_model = self._optimized(graph, ["fuse_qkv"], False)
5130+
5131+
assert [node.op_type for node in optimized_model.graph.node] == [
5132+
"MatMul",
5133+
"MatMul",
5134+
"MatMul",
5135+
"Identity",
5136+
"Identity",
5137+
"Identity",
5138+
]
5139+
50995140
def test_fuse_consecutive_unsqueezes_opset13(self): # type: () -> None
51005141
graph = parser.parse_graph("""
51015142
agraph (float[4, 64, 160, 160] X) => (float[1, 1, 1, 4, 64, 1, 160, 160, 1, 1, 1] Z)

0 commit comments

Comments
 (0)