Skip to content

[Grappler/Kernels] Support multi-dimensional bias with leading ones in fused MatMul and Conv2D - #126737

Closed
PranshulSoni wants to merge 1 commit into
tensorflow:masterfrom
PranshulSoni:fix/fused-matmul-bias-dims-126661
Closed

PranshulSoni wants to merge 1 commit into
tensorflow:masterfrom
PranshulSoni:fix/fused-matmul-bias-dims-126661

Conversation

@PranshulSoni

Copy link
Copy Markdown

Fixes #126661

Description

Adding a [1, N] tensor to the result of a MatMul (specifically when transpose_a=True) or Conv2D succeeds in eager execution via broadcasting. However, when wrapped in tf.function, graph execution crashes with:

W0000 00:00:1788378737.932106 29856 op_kernel.cc:1858] OP_REQUIRES failed at matmul_op_fused.cc:136 : INVALID_ARGUMENT: bias must be 1-dimensional[1,7]
InvalidArgumentError: Graph execution error:
Detected at node Add: bias must be 1-dimensional[1,7] [[{{node Add}}]]

Root Cause

  1. In Grappler Remapper (remapper.cc:705-725), IsBiasSemanticAdd matches an Add node with an addend having shape [1, N] (since all leading dimensions before the channel dimension are 1). Remapper replaces the node with _FusedMatMul (or _FusedConv2D), passing the [1, N] tensor as the bias operand.
  2. In mkl_layout_pass.cc, FusedMatMulRewrite skips rewriting _FusedMatMul to _MklNativeFusedMatMul when transpose_a=True to avoid reorder overhead. On GPU or non-oneDNN builds, the op also remains _FusedMatMul.
  3. In fused_eigen_output_kernels.h, InitBiasAddArgs strictly checked if (bias.dims() != 1) and failed with InvalidArgumentError. Similarly, the GPU fused MatMul and Conv2D kernels strictly asserted bias.dims() == 1. However, the memory layout of any [1, ..., 1, N] tensor is contiguous and identical to a 1D vector of length N. In oneDNN's mkl_matmul_op_fused.cc and mkl_conv_ops.h, this relaxed check had already been implemented.

Solution

  1. Eigen CPU Kernel: In fused_eigen_output_kernels.h, updated InitBiasAddArgs to allow bias.dims() >= 1 as long as all leading dimensions before the last (channel) dimension are 1.
  2. GPU Kernels: In matmul_op_fused.cc and conv_ops_fused_impl.h, updated GPU LaunchFusedMatMulOp and FusedConv2D bias validation to accept bias.dims() >= 1 with leading ones.
  3. Grappler Remapper Guard: In remapper.cc:711, added if (bcast_shape.dim_size() > shape.dim_size()) return false; to prevent fusing when the broadcast shape would expand the output tensor's rank.
  4. Tests:
    • Added FuseMatmulTransposeAWithAdd and DoNotFuseMatmulWithAddHigherRank in remapper_test.cc.
    • Added VerifyMatMulWith2DBias and MatMul2DBias in matmul_op_test.cc testing all 4 transpose combinations (FF, TF, FT, TT) with [1, N] bias.
    • Added test_matmul_transpose_a_broadcast_bias_add in remapper_test.py.

…Conv2D

Fixes tensorflow#126661

When Grappler Remapper fuses an Add node into _FusedMatMul or _FusedConv2D
with a broadcastable bias shape (e.g. [1, N] where leading dimensions are 1),
the non-oneDNN CPU kernel (InitBiasAddArgs) and GPU kernels strictly checked
bias.dims() == 1, raising:
'InvalidArgumentError: bias must be 1-dimensional'.

This commit:
1. Updates InitBiasAddArgs in fused_eigen_output_kernels.h to accept bias
   tensors with rank >= 1 as long as all leading dimensions are 1, matching
   oneDNN's MklFusedMatMulOp behavior.
2. Updates GPU fused MatMul and Conv2D kernels to similarly accept bias
   tensors with leading 1 dimensions.
3. Guards IsBiasSemanticAdd in remapper.cc from fusing when the broadcast shape
   has higher rank than the contraction output tensor.
4. Adds C++ unit tests in remapper_test.cc and matmul_op_test.cc, and a Python
   regression test in remapper_test.py.
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Sep 3, 2026
@google-cla

google-cla Bot commented Sep 3, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@nithyak0204
nithyak0204 requested a review from a team September 3, 2026 14:57
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 3, 2026
@nithyak0204 nithyak0204 added the prtype:bugfix PR to fix a bug label Sep 3, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Sep 3, 2026
@nithyak0204

Copy link
Copy Markdown

Hi @PranshulSoni, Can you please sign the CLA. Thank you!

@dmiltr3
dmiltr3 self-requested a review September 3, 2026 16:44
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 3, 2026
@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Approved by Reviewer in PR Queue Sep 3, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 4, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your contribution and for addressing multi-dimensional bias support for fused MatMul and Conv2D operations (#126661)!

We've reviewed your pull request and identified a few necessary updates and improvements:

1. Rebase Against master

A related PR (#126688) was recently merged into master, applying kernel relaxations in fused_eigen_output_kernels.h, conv_ops_fused_impl.h, and matmul_op_fused.cc. However, that change did not include your crucial Grappler Remapper rank guard in remapper.cc:711 (if (bcast_shape.dim_size() > shape.dim_size()) return false;), nor did it have your 4-way transpose tests.
Please rebase your branch on latest master and resolve the overlapping kernel edits, while preserving your Remapper fix and enhanced tests.

2. Missing Channel Dimension Validation in GPU Kernel

In tensorflow/core/kernels/matmul_op_fused.cc inside LaunchFusedMatMulOp, the GPU launch path should verify that the inner bias dimension matches matrix column size n:

OP_REQUIRES(context, bias.dim_size(bias.dims() - 1) == n,
            absl::InvalidArgumentError(absl::StrCat(
                "bias depth must equal matrix column size: ",
                bias.shape().DebugString(), " vs. ", n)));

This protects against out-of-bounds GPU reads if _FusedMatMul is invoked with mismatched inner bias dimension. Also prefer idiomatic OP_REQUIRES over if (cond) OP_REQUIRES_OK(context, ...).

3. Test Coverage

  • In tensorflow/core/kernels/matmul_op_test.cc, please ensure your VerifyMatMulWith2DBias test (covering all 4 transpose combinations FF, TF, FT, TT against un-fused MatMul) is retained during the rebase. Please also include negative test cases verifying that invalid bias shapes (e.g., [2, N], [0, N]) return INVALID_ARGUMENT.
  • In tensorflow/core/kernels/conv_ops_test.cc, please add a unit test exercising _FusedConv2D with multi-dimensional bias (e.g., [1, 1, 1, C] or [1, C]).

Could you please rebase on latest master and update the PR with these adjustments? Thanks again!

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed ready to pull PR ready for merge process labels Sep 28, 2026
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 14 days with no activity. It will be closed if no further activity occurs. Thank you.

@github-actions github-actions Bot added the stale This label marks the issue/pr stale - to be closed automatically if no activity label Oct 13, 2026
@github-actions

Copy link
Copy Markdown

This PR was closed because it has been inactive for 14 days since being marked as stale. Please reopen if you'd like to work on this further.

@github-actions github-actions Bot closed this Oct 28, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Closed/Rejected in PR Queue Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

prtype:bugfix PR to fix a bug size:M CL Change Size: Medium stale This label marks the issue/pr stale - to be closed automatically if no activity stat:awaiting response Status - Awaiting response from author

Projects

Status: Closed/Rejected

Development

Successfully merging this pull request may close these issues.

Add(MatMul(...), [1, N]) fails in tf.function with "bias must be 1-dimensional" while eager works

4 participants