Skip to content

[torchlib] Update linear implementation to support 1d weights #2340

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 26, 2025
Merged
Changes from 3 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
9 changes: 7 additions & 2 deletions onnxscript/function_libs/torch_lib/ops/nn.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,10 +825,15 @@
def aten_linear(input: TFloat, weight: TFloat, bias: Optional[TFloat] = None) -> TFloat:
"""linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor"""

if len(input.shape) == 2:
if len(input.shape) == 2 and len(weight.shape) == 2:
# Use Gemm for the rank 2 input
return op.Gemm(input, weight, bias, transB=True)
weight_transposed = op.Transpose(weight, perm=[1, 0])
if len(weight.shape) == 1:
# In rare cases the weight can be 1d
weight_transposed = op.Unsqueeze(weight, [1])
else:
assert len(weight.shape) == 2:
weight_transposed = op.Transpose(weight, perm=[1, 0])
mul = op.MatMul(input, weight_transposed)
if bias is None:
return mul
Expand Down
Loading