# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Shared no-pickle serialization helpers."""
from __future__ import annotations
import importlib
import inspect
from collections.abc import Callable, Mapping
from functools import lru_cache
from types import ModuleType, NoneType, UnionType
from typing import Annotated, Any, Self, Union, get_args, get_origin
import torch
from pydantic import (
BaseModel,
BeforeValidator,
ConfigDict,
PlainSerializer,
ValidationError,
)
_TYPE_SERIALIZERS: dict[type, tuple[Callable[[Any], Any], Callable[[Any], Any]]] = {}
"""Registry mapping a type to its ``(serialize, deserialize)`` callable pair."""
[docs]
def register_type_serializer(
type_: type,
serialize: Callable[[Any], Any],
deserialize: Callable[[Any], Any],
) -> None:
"""Register JSON (de)serializers for a custom type.
Parameters
----------
type_
The Python type to register, for example :class:`torch.dtype`.
serialize
Callable converting a ``type_`` instance to a JSON-safe value.
deserialize
Callable converting the JSON-safe value back into a ``type_`` instance.
"""
_TYPE_SERIALIZERS[type_] = (serialize, deserialize)
def _wrap_custom_type(t: type) -> Any:
"""Wrap a registered type in an ``Annotated[...]`` with Pydantic hooks."""
ser, deser = _TYPE_SERIALIZERS[t]
def _before(v: Any) -> Any:
return v if isinstance(v, t) else deser(v)
return Annotated[t, BeforeValidator(_before), PlainSerializer(ser)]
def _dtype_deserialize(s: Any) -> torch.dtype:
"""Rehydrate a :class:`torch.dtype` from its string form with a type guard."""
if isinstance(s, torch.dtype):
return s
if not isinstance(s, str):
raise TypeError(
f"torch.dtype deserializer expected str, got {type(s).__name__}"
)
result = getattr(torch, s.removeprefix("torch."), None)
if not isinstance(result, torch.dtype):
raise ValueError(
f"{s!r} does not resolve to a torch.dtype "
"(defense-in-depth against attacker-controlled JSON smuggling "
"non-dtype torch.* attributes)."
)
return result
def _tensor_serialize(t: torch.Tensor) -> dict[str, Any]:
"""Serialize a :class:`torch.Tensor` as ``{data, dtype, shape}``."""
return {
"data": t.detach().cpu().tolist(),
"dtype": str(t.dtype),
"shape": list(t.shape),
}
def _tensor_deserialize(v: Any) -> torch.Tensor:
"""Rehydrate a :class:`torch.Tensor` from its ``{data, dtype, shape}`` dict."""
if isinstance(v, torch.Tensor):
return v
if not isinstance(v, dict):
raise TypeError(f"Cannot deserialize torch.Tensor from {type(v).__name__}")
dtype = _dtype_deserialize(v["dtype"])
out = torch.tensor(v["data"], dtype=dtype)
expected_shape = tuple(v["shape"])
if tuple(out.shape) != expected_shape:
out = out.reshape(expected_shape)
return out
register_type_serializer(
torch.dtype,
serialize=str,
deserialize=_dtype_deserialize,
)
register_type_serializer(
torch.device,
serialize=str,
deserialize=lambda s: s if isinstance(s, torch.device) else torch.device(s),
)
register_type_serializer(torch.Tensor, _tensor_serialize, _tensor_deserialize)
@lru_cache(maxsize=None)
def _import_object(path: str) -> Any:
"""Import an object identified by a dotted module/attribute path."""
parts = path.split(".")
module: Any = None
module_depth = 0
for i in range(1, len(parts)):
try:
module = importlib.import_module(".".join(parts[:i]))
except ModuleNotFoundError:
break
module_depth = i
if module is None:
raise ModuleNotFoundError(
f"Could not import any module prefix of {path!r}. "
"Expected a dotted path like 'pkg.mod.Object' or "
"'pkg.mod.Outer.method'."
)
obj: Any = module
for part in parts[module_depth:]:
obj = getattr(obj, part)
return obj
@lru_cache(maxsize=None)
def _import_cls(cls_path: str) -> type:
"""Import the class identified by a dotted path."""
obj = _import_object(cls_path)
if not isinstance(obj, type):
raise TypeError(f"{cls_path!r} resolved to non-class {obj!r}")
return obj
@lru_cache(maxsize=None)
def _import_callable(target_path: str) -> Callable[..., Any]:
"""Import the callable identified by a dotted path."""
obj = _import_object(target_path)
if not callable(obj):
raise TypeError(f"{target_path!r} resolved to non-callable {obj!r}")
return obj
def capture_callable_spec(fn: Callable[..., Any], *, field_name: str) -> "BaseSpec":
"""Capture a callable field as a :class:`~nvalchemi.training.BaseSpec`.
Uses the object's own ``to_spec()`` when it provides one (model-owning
procedures carry their construction), else a dotted-path capture through
:func:`_import_callable` as the recorded builder. Lambdas, closures, and
``functools.partial`` objects carry no import path and are rejected by
:func:`_callable_path_of`.
Parameters
----------
fn
The live callable to capture.
field_name
The model field being serialized; labels capture errors.
Returns
-------
BaseSpec
The captured construction spec.
Raises
------
TypeError
If ``fn.to_spec()`` does not return a
:class:`~nvalchemi.training.BaseSpec`.
"""
from nvalchemi.training import BaseSpec, create_model_spec
to_spec = getattr(fn, "to_spec", None)
if callable(to_spec):
spec = to_spec()
if not isinstance(spec, BaseSpec):
raise TypeError(
f"{field_name}.to_spec() must return a BaseSpec, "
f"got {type(spec).__name__}."
)
return spec
return create_model_spec(_import_callable, target_path=_callable_path_of(fn))
def _callable_path_of(target: Callable[..., Any]) -> str:
"""Return the canonical dotted path (``module.QualName``) for ``target``."""
owner = getattr(target, "__self__", None)
if owner is not None and not isinstance(owner, (type, ModuleType)):
raise TypeError(
f"{target!r} is an instance-bound method and cannot be captured by "
"import path alone. Wrap it in a callable object with a to_spec() "
"method that returns a BaseSpec."
)
function = getattr(target, "__func__", None)
if isinstance(owner, type) and function is not None:
try:
owner_path = _cls_path_of(owner)
if _import_cls(owner_path) is not owner:
raise TypeError("the imported owner is a different class")
except (AttributeError, ImportError, TypeError) as error:
raise TypeError(
f"{target!r} has a class-bound owner that is not importable by "
"dotted path. Wrap it in a callable object with a to_spec() "
"method that returns a BaseSpec."
) from error
candidate_names = [getattr(target, "__name__", None)]
candidate_names.extend(
name
for base in owner.__mro__
for name, descriptor in vars(base).items()
if isinstance(descriptor, classmethod) and descriptor.__func__ is function
)
seen: set[str] = set()
for name in candidate_names:
if not isinstance(name, str) or name in seen:
continue
seen.add(name)
if getattr(owner, name, None) is None:
continue
try:
imported = _import_callable(f"{owner_path}.{name}")
except (AttributeError, ImportError, TypeError):
continue
if (
getattr(imported, "__self__", None) is owner
and getattr(imported, "__func__", None) is function
):
return f"{owner_path}.{name}"
raise TypeError(
f"{target!r} has no importable class attribute on {owner_path!r} "
"that preserves its classmethod binding. Wrap it in a callable "
"object with a to_spec() method that returns a BaseSpec."
)
module = getattr(target, "__module__", None)
qualname = getattr(target, "__qualname__", None)
if not module or not qualname or "<locals>" in qualname or "<lambda>" in qualname:
raise TypeError(
f"{target!r} is not an importable callable. Specs require a "
"module-level class, function, staticmethod, or classmethod."
)
return f"{module}.{qualname}"
def _cls_path_of(cls_: type) -> str:
"""Return the canonical dotted path (``module.QualName``) for ``cls_``."""
return _callable_path_of(cls_)
@lru_cache(maxsize=None)
def _callable_signature(target: Callable[..., Any]) -> inspect.Signature:
"""Return the string-annotation-resolved signature for ``target``."""
return inspect.signature(target, eval_str=True)
@lru_cache(maxsize=None)
def _constructor_signature(cls_: type) -> inspect.Signature:
"""Return the string-annotation-resolved constructor signature for ``cls_``."""
return _callable_signature(cls_)
def _extract_init_kwargs_from_attrs(instance: Any) -> dict[str, Any]:
"""Extract constructor kwargs from matching attributes on ``instance``."""
sig = _constructor_signature(type(instance))
kwargs: dict[str, Any] = {}
for name, param in sig.parameters.items():
if name == "self" or param.kind in {
inspect.Parameter.VAR_POSITIONAL,
inspect.Parameter.VAR_KEYWORD,
}:
continue
try:
value = getattr(instance, name)
except AttributeError:
continue
# A constructor argument may share its name with an inherited method
# (``nn.Module.train``), which ``getattr`` returns instead of the stored
# value; fall back to the private attribute that holds it.
if inspect.ismethod(value) and value.__self__ is instance:
try:
value = getattr(instance, f"_{name}")
except AttributeError:
continue
kwargs[name] = value
return kwargs
def _serialize_type(value: type | None) -> str | None:
"""Serialize a class to its dotted path; pass ``None`` through."""
if value is None:
return None
return _cls_path_of(value)
def _validate_type(value: Any) -> Any:
"""Accept a ``type`` or dotted-path string; convert strings to classes."""
if value is None or isinstance(value, type):
return value
if _is_tagged_type(value):
return _deserialize_tagged_type(value)
if isinstance(value, str):
try:
return _import_cls(value)
except (ImportError, AttributeError, TypeError) as exc:
raise ValueError(f"{value!r} must resolve to an importable class.") from exc
return value
def _is_class_type_annotation(annotation: Any) -> bool:
"""Return whether ``annotation`` accepts a class object."""
if annotation is type:
return True
return get_origin(annotation) is type
def _is_optional_class_type_annotation(annotation: Any) -> bool:
"""Return whether ``annotation`` accepts a class object or ``None``."""
origin = get_origin(annotation)
if origin not in {Union, UnionType}:
return False
args = get_args(annotation)
non_none_args = [arg for arg in args if arg is not NoneType]
return len(non_none_args) == 1 and _is_class_type_annotation(non_none_args[0])
def _wrap_class_type_annotation(annotation: Any) -> Any:
"""Wrap class-object annotations with dotted-path Pydantic hooks."""
return Annotated[
annotation,
BeforeValidator(_validate_type),
PlainSerializer(_serialize_type),
]
def _serialize_tagged_type(value: type) -> dict[str, str]:
"""Serialize an inferred class value with an explicit type tag."""
return {"__type__": _cls_path_of(value)}
def _is_tagged_type(value: Any) -> bool:
"""Return whether ``value`` is a tagged class serialization payload."""
return isinstance(value, dict) and set(value) == {"__type__"}
def _deserialize_tagged_type(value: Any) -> type:
"""Deserialize a tagged class serialization payload."""
if isinstance(value, type):
return value
if not _is_tagged_type(value):
raise TypeError(
f"tagged type deserializer expected {{'__type__': str}}, "
f"got {type(value).__name__}"
)
cls_path = value["__type__"]
if not isinstance(cls_path, str):
raise TypeError(f"tagged type path must be str, got {type(cls_path).__name__}")
return _deserialize_type(cls_path)
SerializableTaggedClass = Annotated[
type,
BeforeValidator(_deserialize_tagged_type),
PlainSerializer(_serialize_tagged_type),
]
"""``type`` annotation for inferred class fields using tagged JSON."""
def _is_serializable_class_annotation(annotation: Any) -> bool:
"""Return whether ``annotation`` should use class dotted-path hooks."""
return _is_class_type_annotation(annotation) or _is_optional_class_type_annotation(
annotation
)
def _deserialize_type(value: Any) -> type:
"""Deserialize a class object from a dotted path for the type registry."""
if isinstance(value, type):
return value
if not isinstance(value, str):
raise TypeError(
f"type deserializer expected str or type, got {type(value).__name__}"
)
try:
return _import_cls(value)
except (ImportError, AttributeError, TypeError) as exc:
raise ValueError(
f"{value!r} is not a dotted path resolving to a class."
) from exc
register_type_serializer(
type,
serialize=_serialize_type,
deserialize=_deserialize_type,
)
SerializableClass = Annotated[
type,
BeforeValidator(_validate_type),
PlainSerializer(_serialize_type),
]
"""``type`` field annotation that round-trips via dotted-path strings."""
SerializableOptionalClass = Annotated[
type | None,
BeforeValidator(_validate_type),
PlainSerializer(_serialize_type),
]
"""``type | None`` field annotation that round-trips via dotted-path strings."""
[docs]
class MeasurementRecord(BaseModel):
"""Frozen measurement that exports as a plain dictionary and rebuilds from one.
A *measurement record* holds the results of one measurement. Subclasses
declare their fields as annotations. ``to_dict`` returns the field dump and
keeps tuples and ``None`` values as they are. ``from_dict`` validates a
mapping back into the record. A list read out of JSON therefore returns as
the tuple its field declares, and a non-finite float that a strict writer
spelled as a string returns as the number. The rebuild refuses a key the
record does not declare and a required field the export lacks.
Examples
--------
>>> from nvalchemi._serialization import MeasurementRecord
>>> class Timing(MeasurementRecord):
... steps: int
... seconds: float | None = None
>>> Timing.from_dict(Timing(steps=3).to_dict())
Timing(steps=3, seconds=None)
"""
model_config = ConfigDict(frozen=True, extra="forbid")
def to_dict(self) -> dict[str, Any]:
"""Return every field as a plain dictionary."""
return self.model_dump()
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> Self:
"""Rebuild the record from a :meth:`to_dict` export.
Raises
------
ValueError
If *data* carries a key the record does not declare, omits one of
its fields that has no default, or holds a value that fails a
field's validation.
"""
try:
return cls.model_validate(dict(data))
except ValidationError as exc:
raise ValueError(_rebuild_failure(cls, exc)) from exc
def _rebuild_failure(cls: type[MeasurementRecord], exc: ValidationError) -> str:
"""Return the rebuild error for *exc*, naming the keys or the fields at fault."""
unknown = sorted(
str(error["loc"][0])
for error in exc.errors()
if error["type"] == "extra_forbidden"
)
if unknown:
return (
f"{cls.__name__} cannot be rebuilt from a mapping carrying "
f"{unknown!r}; expected keys from {sorted(cls.model_fields)!r}."
)
missing = sorted(
str(error["loc"][0]) for error in exc.errors() if error["type"] == "missing"
)
if missing:
return (
f"{cls.__name__} cannot be rebuilt from a mapping missing the "
f"required {missing!r}."
)
faults = "; ".join(
f"{cls.__name__}.{'.'.join(str(part) for part in error['loc'])}: {error['msg']}"
for error in exc.errors()
)
return f"{cls.__name__} cannot be rebuilt from a mapping: {faults}."