Skip to content

[0-size Tensor No.98] Add 0-size Tensor support for kron #72997

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

Closed
wants to merge 1 commit into from
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
13 changes: 12 additions & 1 deletion paddle/phi/kernels/impl/kron_grad_kernel_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@

#pragma once

#include "paddle/phi/kernels/full_kernel.h"
#include "paddle/phi/kernels/impl/kron_kernel_impl.h"
#include "paddle/phi/kernels/reduce_sum_kernel.h"

namespace phi {

template <typename T>
Expand Down Expand Up @@ -266,6 +266,17 @@ void KronGradKernel(const Context &ctx,
const DenseTensor &out_grad,
DenseTensor *x_grad,
DenseTensor *y_grad) {
if (out_grad.numel() == 0) {
if (x_grad) {
phi::Full<T, Context>(
ctx, phi::IntArray(common::vectorize(x_grad->dims())), 0, x_grad);
}
if (y_grad) {
phi::Full<T, Context>(
ctx, phi::IntArray(common::vectorize(y_grad->dims())), 0, y_grad);
}
return;
}
if (x_grad) {
ctx.template Alloc<T>(x_grad);
}
Expand Down
3 changes: 3 additions & 0 deletions paddle/phi/kernels/impl/kron_kernel_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@ void KronKernel(const Context &ctx,
const DenseTensor &y,
DenseTensor *out) {
ctx.template Alloc<T>(out);
if (out && out->numel() == 0) {
return;
}

int ndims = out->dims().size();
DenseTensor xx = UnsqueezeTo(x, ndims);
Expand Down
27 changes: 27 additions & 0 deletions test/legacy_test/test_kron_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,33 @@ def _init_dtype(self):
return "float16"


class TestKronOp_ZeroSize(OpTest):
def setUp(self):
self.op_type = "kron"
self.prim_op_type = "prim"
self.python_api = paddle.kron
self.public_python_api = paddle.kron
self.dtype = self._init_dtype()
x = np.random.uniform(size=(10, 0, 2)).astype(self.dtype)
y = np.random.uniform(size=(2, 3, 4, 3, 2)).astype(self.dtype)
out_ref = np.kron(x, y)
self.inputs = {'X': x, 'Y': y}
self.outputs = {'Out': out_ref}

def _init_dtype(self):
return "float64"

def test_check_output(self):
self.check_output(check_pir=True)

def test_check_grad(self):
self.check_grad(
['X', 'Y'],
'Out',
check_pir=True,
)


@unittest.skipIf(
not core.is_compiled_with_cuda()
or not core.is_bfloat16_supported(core.CUDAPlace(0)),
Expand Down
Loading