Skip to content
Open
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
50 changes: 45 additions & 5 deletions keras/src/backend/openvino/numpy.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import numpy as np
Copy link
Contributor

Choose a reason for hiding this comment

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

switch on the corresponding tests

import openvino.runtime.opset14 as ov_opset
import openvino.opset14 as ov_opset
from openvino import Type

from keras.src.backend import config
Expand Down Expand Up @@ -561,10 +561,50 @@ def diag(x, k=0):
raise NotImplementedError("`diag` is not supported with openvino backend")


def diagonal(x, offset=0, axis1=0, axis2=1):
raise NotImplementedError(
"`diagonal` is not supported with openvino backend"
)
def diagonal(x, offset=0, axis1=-2, axis2=-1):
x = get_ov_output(x)
x_shape = x.get_partial_shape()
rank = x_shape.rank.get_length()

if rank < 2:
raise ValueError("diagonal requires at least a 2D input.")

axis1 = axis1 % rank
axis2 = axis2 % rank

if axis1 == axis2:
raise ValueError("axis1 and axis2 must be different.")

dim1 = x_shape[axis1]
dim2 = x_shape[axis2]

if not dim1.is_static or not dim2.is_static:
raise ValueError("diagonal requires static input shapes.")

D1 = dim1.get_length()
D2 = dim2.get_length()

if offset >= 0:
L = np.minimum(D1, D2 - offset) if (D2 - offset) > 0 else 0
indices = [[i, i + offset] for i in range(L)]
else:
L = np.minimum(D1 + offset, D2) if (D1 + offset) > 0 else 0
indices = [[i - offset, i] for i in range(L)]

if L <= 0:
keras_dtype = ov_to_keras_type(x.get_element_type())
np_dtype = np.dtype(keras_dtype)
empty_np = np.empty((0,), dtype=np_dtype)
empty_const = ov_opset.constant(empty_np, x.get_element_type()).output(
0
)
return OpenVINOKerasTensor(empty_const)

indices = np.array(indices, dtype=np.int32)
indices_const = ov_opset.constant(indices, dtype=Type.i32).output(0)
diag_vec = ov_opset.gather_nd(x, indices_const)

return OpenVINOKerasTensor(diag_vec.output(0))


def diff(a, n=1, axis=-1):
Expand Down