Map: Parallel computation

An example of how to run several CPU intensive nodes in parallel and aggregate the results. There is also an example notebook available here

Example worker

We use an encryption function as a placeholder for a CPU intensive worker function. For demonstration purposes we ensure that the plaintexts are short enough (and the work factor small enough) that the graph runs in under 10s.

The following worker is in the Tierkreis GitHub repo at docs/source/examples/example_workers/auth_worker:

import logging
import secrets
from time import time
from typing import TYPE_CHECKING, NamedTuple, cast

import pyscrypt  # type: ignore
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.hashes import SHA256
from tierkreis.data.models import portmapping
from tierkreis.worker import Worker

if TYPE_CHECKING:
    from cryptography.hazmat.primitives.asymmetric.rsa import (
        RSAPrivateKey,
        RSAPublicKey,
    )

worker = Worker("auth_worker")
logger = logging.getLogger(__name__)


@portmapping
class EncryptionResult(NamedTuple):
    ciphertext: str
    time_taken: float


@portmapping
class SigningResult(NamedTuple):
    hex_signature: str
    time_taken: float


@worker.task()
def encrypt(plaintext: str, work_factor: int) -> EncryptionResult:
    start_time = time()
    salt = secrets.token_bytes(32)
    ciphertext = pyscrypt.hash(  # type:ignore
        password=plaintext.encode(),
        salt=salt,
        N=work_factor,
        r=1,
        p=1,
        dkLen=32,
    )
    time_taken = time() - start_time

    return EncryptionResult(ciphertext=str(ciphertext), time_taken=time_taken)


@worker.task()
def sign(private_key: bytes, passphrase: bytes, message: str) -> SigningResult:
    start_time = time()
    key = cast(
        "RSAPrivateKey",
        serialization.load_pem_private_key(private_key, password=passphrase),
    )
    signature = key.sign(
        message.encode(),
        padding=padding.PSS(
            mgf=padding.MGF1(SHA256()),
            salt_length=padding.PSS.MAX_LENGTH,
        ),
        algorithm=SHA256(),
    ).hex()
    time_taken = time() - start_time

    return SigningResult(signature, time_taken)


@worker.task()
def verify(public_key: bytes, signature: str, message: str) -> bool:
    key = cast("RSAPublicKey", serialization.load_pem_public_key(public_key))
    try:
        key.verify(
            bytes.fromhex(signature),
            message.encode(),
            padding=padding.PSS(
                mgf=padding.MGF1(SHA256()),
                salt_length=padding.PSS.MAX_LENGTH,
            ),
            algorithm=SHA256(),
        )
        return True
    except InvalidSignature:
        return False

Generating stubs

Since this worker uses the Tierkreis Python library, we can automatically generate stub files using the following command. The stub files will provide us with type hints in the graph building process later on.

!cd ../examples/example_workers/auth_worker && uv run tkr_auth_worker_impl/main.py --stubs-path ./api/api.py > /dev/null 2>&1

Writing a graph

We can import this stub file to help create our graph.

The graph builder manipulates references to values, not the values themselves. (The one exception to this rule is when we add a constant value to a graph using Graph.const. Then the actual value is added to the graph definition and Graph.const returns a reference to this value.) The references are type checked using the TKR type. I.e. a reference to an int has the type TKR[int].

from typing import NamedTuple
from tierkreis.models import EmptyModel, TKR
from tierkreis.builder import Graph
from tierkreis.builtins import mean

from auth_worker import encrypt, EncryptionResult


def map_body():
    g = Graph(TKR[str], EncryptionResult)
    result = g.task(encrypt(plaintext=g.inputs, work_factor=g.const(2**14)))
    return g.finish_with_outputs(result)


class GraphOutputs(NamedTuple):
    average_time_taken: TKR[float]
    ciphertexts: TKR[list[str]]


def graph():
    g = Graph(EmptyModel, GraphOutputs)
    plaintexts = g.const([f"plaintext+{n}" for n in range(20)])
    results = g.map(map_body(), plaintexts)

    ciphertexts = g.map(lambda x: x.ciphertext, results)
    times = g.map(lambda x: x.time_taken, results)

    av = g.task(mean(values=times))
    out = GraphOutputs(ciphertexts=ciphertexts, average_time_taken=av)

    return g.finish_with_outputs(out)

Running the graph

The default runtime discovers the installed authentication worker and runs the Map body concurrently. Fold/unfold compatibility nodes from legacy graphs are removed during conversion because Map handles collection inputs directly.

import json
import time
from tierkreis.runtime import new_default

workflow = graph()
runtime = await new_default()
start = time.time()
with runtime:
    workflow_id = await runtime.save_workflow("auth_graph", workflow)
    run_id = await runtime.start_new_run(workflow_id, {})
    await runtime.wait_for(run_id)
    outputs = await runtime.get_outputs(run_id)
    total_time = time.time() - start

av = outputs["average_time_taken"]
ciphertexts = outputs["ciphertexts"]
print(f"Encrypted 20 plaintexts in {total_time:1g}s with mean encryption time {av:1g}")
Encrypted 20 plaintexts in 18.3491s with mean encryption time 3.31788

We should see that the mean time to encrypt a single plaintext is quite close to the time taken for the whole workflow, which indicates that the encryptions were run in parallel.