Custom Serializers¶
Runtime compatibility: this example uses the Rust runtime’s
get_raw_outputsAPI to compare binary and JSON NumPy serializers without forcing the result through JSON decoding.
By default Tierkreis serializes values to bytes when possible. In some cases it might be preferable to use a specific format.
Tierkreis supports this through Python Annotated types that specify custom serializers and deserializers.
A common example is the numpy.ndarray.
In this example we will serialize arrays in multiple ways.
We demonstrate this with a simple graph.
from typing import NamedTuple
from tierkreis.data.models import TKR, OpaqueType
NDArray = OpaqueType["numpy.ndarray"]
class ScipyOutputs(NamedTuple):
a: TKR[NDArray]
p: TKR[float]
We use a worker to expose some elementary tasks:
from scipy_worker import (
add_point,
eval_point,
linspace,
reshape,
transpose,
)
from tierkreis.builder import Graph
from tierkreis.data.core import EmptyModel
sample_graph = Graph(EmptyModel, ScipyOutputs)
onedim = sample_graph.task(linspace(sample_graph.const(0), sample_graph.const(10)))
pointed = sample_graph.task(add_point(onedim, sample_graph.const(0)))
scalar = sample_graph.task(eval_point(pointed))
twodim = sample_graph.task(reshape(onedim, sample_graph.const([5, 10])))
a = sample_graph.task(transpose(twodim))
workflow = sample_graph.finish_with_outputs(ScipyOutputs(a, scalar))
The worker contains the following code to use different serialization methods.
import io
import os
import pickle
from typing import Annotated
import numpy as np
from tierkreis.data.core import Deserializer, Serializer
def save(a: np.ndarray) -> bytes:
with io.BytesIO() as bs:
np.save(bs, a)
return bs.getvalue()
def load(bs: bytes) -> np.ndarray:
with io.BytesIO() as bi:
bi.write(bs)
bi.seek(0)
return np.load(bi, encoding="bytes")
SER_METHOD = os.environ.get("SER_METHOD")
if SER_METHOD == "dumps":
ser = Serializer(np.ndarray.dumps)
deser = Deserializer(pickle.loads)
elif SER_METHOD == "tolist":
ser = Serializer(np.ndarray.tolist, "json")
deser = Deserializer(np.array, "json")
elif SER_METHOD == "save":
ser = Serializer(save)
deser = Deserializer(load)
else:
ser = None
deser = None
NDArray = Annotated[np.ndarray, ser, deser]
It is crucial that the operations are the inverse of each other.
For the first run we use the Tierkreis defaults (dumps, pickle.loads).
import json
from tierkreis.runtime import new_default
os.environ.pop("SER_METHOD", None)
runtime = await new_default()
with runtime:
workflow_id = await runtime.save_workflow("scipy-default-serializer", workflow)
run_id = await runtime.start_new_run(workflow_id, {})
await runtime.wait_for(run_id)
default_raw_outputs = await runtime.get_raw_outputs(run_id)
default_array = pickle.loads(default_raw_outputs["a"])
default_scalar = json.loads(default_raw_outputs["p"])
get_raw_outputs returns the exact serialized bytes for each workflow output. The default NumPy payload begins with the pickle protocol header, and pickle.loads reconstructs the array.
print(default_raw_outputs["a"][:20])
print(default_array.shape, default_scalar)
b'\x80\x02cnumpy._core.multi'
(10, 5) 0.0
To change the serialization format, declare the $SER_METHOD environment variable and run the workflow with a fresh runtime. Worker subprocesses inherit the variable. The tolist serializer produces JSON bytes, which we decode explicitly before confirming that both serializers returned the same array.
os.environ["SER_METHOD"] = "tolist"
runtime = await new_default()
with runtime:
workflow_id = await runtime.save_workflow("scipy-tolist-serializer", workflow)
run_id = await runtime.start_new_run(workflow_id, {})
await runtime.wait_for(run_id)
tolist_raw_outputs = await runtime.get_raw_outputs(run_id)
tolist_array = np.array(json.loads(tolist_raw_outputs["a"]))
tolist_scalar = json.loads(tolist_raw_outputs["p"])
os.environ.pop("SER_METHOD")
assert np.array_equal(default_array, tolist_array)
assert default_scalar == tolist_scalar
print(tolist_raw_outputs["a"][:80])
b'[\n [\n 0.0,\n 2.0408163265306123,\n 4.081632653061225,\n 6.122448979591'