OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[JAX FE] Support JAX 0.6.0 (#30283)
Roman Kazantsevbcfb7b705737
diff --git a/src/bindings/python/src/openvino/frontend/jax/jaxpr_decoder.py b/src/bindings/python/src/openvino/frontend/jax/jaxpr_decoder.pyindex d66f15fa318..3e69207e2f0 100644--- a/src/bindings/python/src/openvino/frontend/jax/jaxpr_decoder.py+++ b/src/bindings/python/src/openvino/frontend/jax/jaxpr_decoder.py@@ -4,21 +4,31 @@# flake8: noqa# mypy: ignore-errors-import jax.core++import jax+from packaging import version++if version.parse(jax.__version__) < version.parse("0.6.0"):+ import jax as jex+ import jax.core+else:+ import jax.extend as jex+from openvino.frontend.jax.py_jax_frontend import _FrontEndJaxDecoder as Decoderfrom openvino import PartialShape, Type as OVType, OVAnyfrom openvino.frontend.jax.utils import jax_array_to_ov_const, get_ov_type_for_value, \ivalue_to_constant, param_to_constants-import jaximport numpy as npfrom typing import Listimport logging+logger = logging.getLogger(__name__)logger.setLevel(logging.WARNING)-class JaxprPythonDecoder (Decoder):++class JaxprPythonDecoder(Decoder):'''The jaxpr decoder uses Jaxpr to get graph information from a jax module.It takes use of the following parts.@@ -40,7 +50,7 @@ class JaxprPythonDecoder (Decoder):- `aval`: the abstract value.- `Literal`: the literal object that contains the value of the constants.'''-+def __init__(self, jaxpr, name=None, literals=None):'''Inputs:@@ -49,10 +59,10 @@ class JaxprPythonDecoder (Decoder):- literals: the literals (constants) that are used in the model.'''Decoder.__init__(self)-- if isinstance(jaxpr, (jax.core.JaxprEqn, jax.core.Jaxpr)):++ if isinstance(jaxpr, (jex.core.JaxprEqn, jex.core.Jaxpr)):self.jaxpr = jaxpr- elif isinstance(jaxpr, jax.core.ClosedJaxpr):+ elif isinstance(jaxpr, jex.core.ClosedJaxpr):# Take the `Jaxpr` from `ClosedJaxpr`, see https://github.com/google/jax/blob/jaxlib-v0.4.29/jax/_src/core.py#L85self.jaxpr = jaxpr.jaxpr# Literal should be a `Jax.core.Var`, see https://github.com/google/jax/blob/jaxlib-v0.4.29/jax/_src/core.py#L85@@ -64,23 +74,23 @@ class JaxprPythonDecoder (Decoder):self.name = "jax_module"if literals is not None:self.literals = literals-+self.params = {}if hasattr(self.jaxpr, 'params') and isinstance(self.jaxpr.params, dict):for k in self.jaxpr.params.keys():converted = self.convert_param_to_constant_node(self.jaxpr, k)if converted is not None:self.params.update(converted)-+# TODO: this implementation may lead to memory increasing. Any better solution?self.m_decoders = []-+def inputs(self) -> List[int]:- if isinstance(self.jaxpr, jax.core.JaxprEqn):+ if isinstance(self.jaxpr, jex.core.JaxprEqn):idx = 0res = []for inp in self.jaxpr.invars:- if isinstance(inp, jax.core.Literal):+ if isinstance(inp, jex.core.Literal):res.append(self.literals[idx].output(0))idx += 1else:@@ -88,25 +98,25 @@ class JaxprPythonDecoder (Decoder):return reselse:return [id(v) for v in self.jaxpr.invars]-+def input(self, idx: int) -> int:return id(self.jaxpr.invars[idx])-+def get_input_shape(self, index):return PartialShape(self.jaxpr.invars[index].aval.shape)-+def get_input_signature_name(self, index) -> str:return "jaxpr_invar_" + str(index)-+def get_input_type(self, index) -> OVType:return get_ov_type_for_value(self.jaxpr.invars[index])-+def get_named_param(self, name):'''Get the object id of the named parameter by the name.'''return self.params[name].output(0)-+def get_named_param_as_constant(self, name):'''The named parameter in JAX is a python object but we want to use its value in cpp.@@ -114,7 +124,7 @@ class JaxprPythonDecoder (Decoder):to extract the value of it in cpp-level.'''return self.params[name].as_constant()-+def get_param_names(self):'''In JAX, the named parameters may exist in `params` attribute of `JaxEqn`.@@ -124,26 +134,26 @@ class JaxprPythonDecoder (Decoder):Here we return the names of all the named params that appear in the model for the current `JaxEqn`.'''return list(self.params.keys())-+def get_output_type(self, index) -> OVType:return get_ov_type_for_value(self.jaxpr.outvars[index])-+def get_output_name(self, index) -> str:return "jaxpr_outvar_" + str(index)-+def get_output_shape(self, index):return PartialShape(self.jaxpr.outvars[index].aval.shape)-+def visit_subgraph(self, node_visitor) -> None:- if isinstance(self.jaxpr, jax.core.JaxprEqn):+ if isinstance(self.jaxpr, jex.core.JaxprEqn):returnfor _, decoder in self.params.items():self.m_decoders.append(decoder)node_visitor(decoder)for idx, node in enumerate(self.jaxpr.constvars):decoder = self.convert_literal_to_constant_node(- literal=self.literals[idx],- name=self.name + "/" + f"const({id(node)})",+ literal=self.literals[idx],+ name=self.name + "/" + f"const({id(node)})",output_id=id(node))self.m_decoders.append(decoder)@@ -152,32 +162,32 @@ class JaxprPythonDecoder (Decoder):for node in self.jaxpr.eqns:literal_decoders = []for inp in node.invars:- if isinstance(inp, jax.core.Literal):+ if isinstance(inp, jex.core.Literal):literal_decoder = self.convert_literal_to_constant_node(inp)literal_decoders.append(literal_decoder)node_visitor(literal_decoder)decoder = JaxprPythonDecoder(node, name=self.name + "/" + node.primitive.name, literals=literal_decoders)self.m_decoders.append(decoder)node_visitor(decoder)-+def get_op_type(self) -> str:- if isinstance(self.jaxpr, jax.core.JaxprEqn):+ if isinstance(self.jaxpr, jex.core.JaxprEqn):return self.jaxpr.primitive.nameelse:return "root"-+def outputs(self) -> List[int]:return [id(v) for v in self.jaxpr.outvars]-+def output(self, idx: int) -> int:return id(self.jaxpr.outvars[idx])-+def num_inputs(self) -> int:return len(self.jaxpr.invars)-+def num_outputs(self) -> int:return len(self.jaxpr.outvars)-+def as_constant(self):if self.get_op_type() == 'constant':value = self.literals@@ -187,7 +197,7 @@ class JaxprPythonDecoder (Decoder):return ov_const.outputs()else:raise ValueError("This is not a constant node so it cannot be converted to a constant.")-+@staticmethoddef convert_param_to_constant_node(jaxpr, param) -> dict:assert hasattr(jaxpr, 'params'), "The jaxpr does not have params."@@ -201,18 +211,19 @@ class JaxprPythonDecoder (Decoder):constant = ivalue_to_constant(jaxpr.params[param], shared_memory=False)res = {param: _JaxprPythonConstantDecoder(constant=constant)} if constant is not None else {}return res-+@staticmethoddef convert_literal_to_constant_node(literal, name=None, output_id=None):- if isinstance(literal, jax.core.Literal):+ if isinstance(literal, jex.core.Literal):constant = ivalue_to_constant(literal.val, shared_memory=False)elif isinstance(literal, (jax.Array, np.ndarray)):constant = ivalue_to_constant(literal, shared_memory=False)else:- raise TypeError( f"The input should be a literal or jax array, but got {type(literal)}.")+ raise TypeError(f"The input should be a literal or jax array, but got {type(literal)}.")return _JaxprPythonConstantDecoder(constant=constant, name=name, output_id=output_id)--class _JaxprPythonConstantDecoder (Decoder):+++class _JaxprPythonConstantDecoder(Decoder):def __init__(self, name=None, constant=None, output_id=None):'''A decoder specially for constants and named parameters.@@ -223,32 +234,32 @@ class _JaxprPythonConstantDecoder (Decoder):- output_id: the id specified for this decoder's output. If none, use `id(self.constant)`.'''Decoder.__init__(self)-+self.name = nameself.constant = constantself.output_id = id(self.constant) if output_id is None else output_id-+def inputs(self) -> List[int]:return []-+def input(self, idx: int) -> int:raise ValueError("This is a constant node so it does not have input.")-+def get_input_shape(self, index):raise ValueError("This is a constant node so it does not have input shape.")-+def get_input_signature_name(self, index) -> str:raise ValueError("This is a constant node so it does not have input signature name.")-+def get_input_type(self, index) -> OVType:raise ValueError("This is a constant node so it does not have input type.")-+def get_named_param(self, name):raise ValueError("This is a constant node so it does not have named param.")-+def get_named_param_as_constant(self, name):raise ValueError("This is a constant node so it does not have named param.")-+def get_param_names(self):'''In JAX, the named parameters may exist in `params` attribute of `JaxEqn`.@@ -259,35 +270,35 @@ class _JaxprPythonConstantDecoder (Decoder):So it will never have a named param.'''return []-+def get_output_type(self, index) -> OVType:assert len(self.constant) == 1return OVAny(self.constant[0].element_type)-+def get_output_name(self, index) -> str:return "jaxpr_outvar_" + str(index)-+def get_output_shape(self, index):assert len(self.constant) == 1return PartialShape(self.constant[0].shape)-+def visit_subgraph(self, node_visitor) -> None:return-+def get_op_type(self) -> str:return "constant"-+def outputs(self) -> List[int]:return [self.output_id]-+def output(self, idx: int) -> int:return self.output_id-+def num_inputs(self) -> int:return 0-+def num_outputs(self) -> int:return 1-+def as_constant(self):- return self.constant\ No newline at end of file+ return self.constantdiff --git a/src/bindings/python/src/openvino/frontend/jax/utils.py b/src/bindings/python/src/openvino/frontend/jax/utils.pyindex 135200faa24..30948536e54 100644--- a/src/bindings/python/src/openvino/frontend/jax/utils.py+++ b/src/bindings/python/src/openvino/frontend/jax/utils.py@@ -5,6 +5,14 @@# mypy: ignore-errorsimport jax+from packaging import version++if version.parse(jax.__version__) < version.parse("0.6.0"):+ import jax as jex+ import jax.core+else:+ import jax.extend as jex+import jax.numpy as jnpimport numpy as npfrom openvino.frontend.jax.passes import filter_element, filter_ivalue, filter_param@@ -95,7 +103,7 @@ def _get_ov_type_from_value(value):def get_ov_type_for_value(value):- if isinstance(value, (jax.core.Var, jax.core.Literal)):+ if isinstance(value, (jex.core.Var, jex.core.Literal)):if value.aval.dtype in jax_to_ov_type_map:return OVAny(jax_to_ov_type_map[value.aval.dtype])for k, v in numpy_to_ov_type_map.items():@@ -151,7 +159,8 @@ def ivalue_to_constant(ivalue, shared_memory=True):second_len = len(ivalue[0])flattened_ivalue = []for value in ivalue:- assert isinstance(value, (list, tuple)), "Can't deduce type for a list with both list and basic types."+ assert isinstance(value,+ (list, tuple)), "Can't deduce type for a list with both list and basic types."assert len(value) == second_len or len(value) == 0, "Can't deduce type for nested list with different lengths."flattened_ivalue.extend([filter_element(item) for item in value])diff --git a/tests/requirements_jax b/tests/requirements_jaxindex 607713e7f7e..4249352aa5d 100644--- a/tests/requirements_jax+++ b/tests/requirements_jax@@ -3,7 +3,7 @@ numpy==2.2.1; python_version >= "3.12" and (platform_system != "Darwin" or platfpytest==7.0.1pytest-xdist[psutil]==3.6.1pytest-html==4.1.1-jax==0.5.2; (platform_system != "Darwin" or platform_machine != "x86_64") and python_version > "3.9"+jax==0.6.0; (platform_system != "Darwin" or platform_machine != "x86_64") and python_version > "3.9"# tensorflow 2.16.2 depends on ml-dtypes~=0.3.1 and jax 0.4.35 depends on ml-dtypes>=0.4.0jax==0.4.33; (platform_system == "Darwin" and platform_machine == "x86_64") and python_version > "3.9"jax==0.4.30; python_version <= "3.9"diff --git a/tools/ovc/openvino/tools/ovc/convert_impl.py b/tools/ovc/openvino/tools/ovc/convert_impl.pyindex bb4c8ae0b4d..d699276d19a 100644--- a/tools/ovc/openvino/tools/ovc/convert_impl.py+++ b/tools/ovc/openvino/tools/ovc/convert_impl.py@@ -208,7 +208,8 @@ def check_model_object(argv):return "tf"if 'torch' in sys.modules:import torch- if isinstance(model, (torch.nn.Module, torch.jit.ScriptFunction)) or (hasattr(torch, "export") and isinstance(model, (torch.export.ExportedProgram))):+ if isinstance(model, (torch.nn.Module, torch.jit.ScriptFunction)) or (+ hasattr(torch, "export") and isinstance(model, (torch.export.ExportedProgram))):return "pytorch"try:from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder@@ -236,7 +237,13 @@ def check_model_object(argv):if 'jax' in sys.modules:import jax- if isinstance(model, (jax.core.Jaxpr, jax.core.ClosedJaxpr)):+ from packaging import version+ if version.parse(jax.__version__) < version.parse("0.6.0"):+ import jax as jex+ import jax.core+ else:+ import jax.extend as jex+ if isinstance(model, (jex.core.Jaxpr, jex.core.ClosedJaxpr)):return "jax"raise Error('Unknown model type: {}'.format(type(model)))