Skip to content

Fix numpy vector_norm(keepdims=True) #96

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 3 commits into from
Feb 27, 2024
Merged
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
11 changes: 7 additions & 4 deletions array_api_compat/common/_linalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from typing import Literal, Optional, Tuple, Union
from ._typing import ndarray

import math

import numpy as np
if np.__version__[0] == "2":
from numpy.lib.array_utils import normalize_axis_tuple
Expand Down Expand Up @@ -110,21 +112,22 @@ def vector_norm(x: ndarray, /, xp, *, axis: Optional[Union[int, Tuple[int, ...]]
# on a single dimension.
if axis is None:
# Note: xp.linalg.norm() doesn't handle 0-D arrays
x = x.ravel()
_x = x.ravel()
_axis = 0
elif isinstance(axis, tuple):
# Note: The axis argument supports any number of axes, whereas
# xp.linalg.norm() only supports a single axis for vector norm.
normalized_axis = normalize_axis_tuple(axis, x.ndim)
rest = tuple(i for i in range(x.ndim) if i not in normalized_axis)
newshape = axis + rest
x = xp.transpose(x, newshape).reshape(
(xp.prod([x.shape[i] for i in axis], dtype=int), *[x.shape[i] for i in rest]))
_x = xp.transpose(x, newshape).reshape(
(math.prod([x.shape[i] for i in axis]), *[x.shape[i] for i in rest]))
_axis = 0
else:
_x = x
_axis = axis

res = xp.linalg.norm(x, axis=_axis, ord=ord)
res = xp.linalg.norm(_x, axis=_axis, ord=ord)

if keepdims:
# We can't reuse xp.linalg.norm(keepdims) because of the reshape hacks
Expand Down
2 changes: 1 addition & 1 deletion test_cupy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ mkdir -p $SCRIPT_DIR/.hypothesis
ln -s $SCRIPT_DIR/.hypothesis .hypothesis

export ARRAY_API_TESTS_MODULE=array_api_compat.cupy
pytest ${PYTEST_ARGS} --xfails-file $SCRIPT_DIR/cupy-xfails.txt --skips-file $SCRIPT_DIR/cupy-skips.txt "$@"
pytest ${PYTEST_ARGS} --xfails-file $SCRIPT_DIR/cupy-xfails.txt "$@"