serialization.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import ray
  2. import ray.cloudpickle as pickle
  3. from ray.util.annotations import DeveloperAPI, PublicAPI
  4. @PublicAPI
  5. def register_serializer(cls: type, *, serializer: callable, deserializer: callable):
  6. """Use the given serializer to serialize instances of type ``cls``,
  7. and use the deserializer to deserialize the serialized object.
  8. Args:
  9. cls: A Python class/type.
  10. serializer: A function that converts an instances of
  11. type ``cls`` into a serializable object (e.g. python dict
  12. of basic objects).
  13. deserializer: A function that constructs the
  14. instance of type ``cls`` from the serialized object.
  15. This function itself must be serializable.
  16. """
  17. context = ray._private.worker.global_worker.get_serialization_context()
  18. context._register_cloudpickle_serializer(cls, serializer, deserializer)
  19. @PublicAPI
  20. def deregister_serializer(cls: type):
  21. """Deregister the serializer associated with the type ``cls``.
  22. There is no effect if the serializer is unavailable.
  23. Args:
  24. cls: A Python class/type.
  25. """
  26. context = ray._private.worker.global_worker.get_serialization_context()
  27. context._unregister_cloudpickle_reducer(cls)
  28. @DeveloperAPI
  29. class StandaloneSerializationContext:
  30. # NOTE(simon): Used for registering custom serializers. We cannot directly
  31. # use the SerializationContext because it requires Ray workers. Please
  32. # make sure to keep the API consistent.
  33. def _register_cloudpickle_reducer(self, cls, reducer):
  34. pickle.CloudPickler.dispatch[cls] = reducer
  35. def _unregister_cloudpickle_reducer(self, cls):
  36. pickle.CloudPickler.dispatch.pop(cls, None)
  37. def _register_cloudpickle_serializer(
  38. self, cls, custom_serializer, custom_deserializer
  39. ):
  40. def _CloudPicklerReducer(obj):
  41. return custom_deserializer, (custom_serializer(obj),)
  42. # construct a reducer
  43. pickle.CloudPickler.dispatch[cls] = _CloudPicklerReducer