Datachain

Python Operations

Python functions run batch processing on a chain to generate new chain values. A function takes fields from one or more rows of the data and outputs new fields. Functions run at scale on multiple workers and processes.

Any Python function works as an operation. The classes below are useful to implement a "stateful" operation where a plain function is insufficient, such as when additional setup() or teardown() steps need to happen before or after the processing function runs.

UDFBase

UDFBase()

Bases: AbstractUDF

Base class for stateful user-defined functions.

Any class that inherits from it must have a process() method that takes input params from one or more rows in the chain and produces the expected output.

Optionally, the class may include these methods: - setup() to run code on each worker before process() is called. - teardown() to run code on each worker after process() completes.

Example
import datachain as dc
import open_clip

class ImageEncoder(dc.Mapper):
    def __init__(self, model_name: str, pretrained: str):
        self.model_name = model_name
        self.pretrained = pretrained

    def setup(self):
        self.model, _, self.preprocess = (
            open_clip.create_model_and_transforms(
                self.model_name, self.pretrained
            )
        )

    def process(self, file) -> list[float]:
        img = file.get_value()
        img = self.preprocess(img).unsqueeze(0)
        emb = self.model.encode_image(img)
        return emb[0].tolist()

(
    dc.read_storage(
        "gs://datachain-demo/fashion-product-images/images", type="image"
    )
    .limit(5)
    .map(
        ImageEncoder("ViT-B-32", "laion2b_s34b_b79k"),
        params=["file"],
        output={"emb": list[float]},
    )
    .show()
)
Source code in datachain/lib/udf.py
397
398
399
400
def __init__(self):
    self.params: SignalSchema | None = None
    self.output = None
    self._func = None

hash

hash(include_body: bool = True) -> str

The hash that checkpoints compare to reuse an earlier result: of the function (or the process method), its parameters and its output.

Attributes set in __init__ aren't part of it, so a class whose constructor options change the output should add them, as a hex digest:

import hashlib

import datachain as dc

class Scale(dc.Mapper):
    def __init__(self, factor: int):
        super().__init__()
        self.factor = factor

    def process(self, x: int) -> int:
        return x * self.factor

    def hash(self, include_body: bool = True) -> str:
        key = f"{super().hash(include_body)}:{self.factor}"
        return hashlib.sha256(key.encode()).hexdigest()

With include_body=False, the function body is left out: only its module, name and defaults count. Lambdas always include their bytecode, since they all share the name <lambda>.

Source code in datachain/lib/udf.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def hash(self, include_body: bool = True) -> str:
    """The hash that checkpoints compare to reuse an earlier result: of the
    function (or the `process` method), its parameters and its output.

    Attributes set in `__init__` aren't part of it, so a class whose
    constructor options change the output should add them, as a hex digest:

    ```py
    import hashlib

    import datachain as dc

    class Scale(dc.Mapper):
        def __init__(self, factor: int):
            super().__init__()
            self.factor = factor

        def process(self, x: int) -> int:
            return x * self.factor

        def hash(self, include_body: bool = True) -> str:
            key = f"{super().hash(include_body)}:{self.factor}"
            return hashlib.sha256(key.encode()).hexdigest()
    ```

    With `include_body=False`, the function body is left out: only its
    module, name and defaults count. Lambdas always include their bytecode,
    since they all share the name `<lambda>`.
    """
    # Hash user code: either _func (function-based) or process method (class-based)
    func_to_hash = self._func or self.process

    parts = [
        hash_callable(func_to_hash, include_body=include_body),
        self.params.hash() if self.params else "",
        self.output.hash(),
    ]

    return hashlib.sha256(
        b"".join([bytes.fromhex(part) for part in parts])
    ).hexdigest()

process

process(*args, **kwargs)

Processing function that needs to be defined by user

Source code in datachain/lib/udf.py
444
445
446
447
448
def process(self, *args, **kwargs):
    """Processing function that needs to be defined by user"""
    if not self._func:
        raise NotImplementedError("UDF processing is not implemented")
    return self._func(*args, **kwargs)

setup

setup()

Initialization process executed on each worker before processing begins. This is needed for tasks like pre-loading ML models prior to scoring.

Source code in datachain/lib/udf.py
450
451
452
453
def setup(self):
    """Initialization process executed on each worker before processing begins.
    This is needed for tasks like pre-loading ML models prior to scoring.
    """

teardown

teardown()

Teardown process executed on each process/worker after processing ends. This is needed for tasks like closing connections to end-points.

Source code in datachain/lib/udf.py
455
456
457
458
def teardown(self):
    """Teardown process executed on each process/worker after processing ends.
    This is needed for tasks like closing connections to end-points.
    """

Aggregator

Aggregator()

Bases: UDFBase

Inherit from this class to pass to DataChain.agg().

process() gets, for each parameter, the list of values from all rows in a partition_by group, and yields any number of results.

Source code in datachain/lib/udf.py
397
398
399
400
def __init__(self):
    self.params: SignalSchema | None = None
    self.output = None
    self._func = None

Generator

Generator()

Bases: UDFBase

Inherit from this class to pass to DataChain.gen().

process() gets one row's values and yields any number of results. Each becomes a new row.

Source code in datachain/lib/udf.py
397
398
399
400
def __init__(self):
    self.params: SignalSchema | None = None
    self.output = None
    self._func = None

Mapper

Mapper()

Bases: UDFBase

Inherit from this class to pass to DataChain.map().

process() gets one row's values and returns one result, or a tuple for several output columns.

For lists of rows per call, use BatchMapper with DataChain.batch_map().

Source code in datachain/lib/udf.py
397
398
399
400
def __init__(self):
    self.params: SignalSchema | None = None
    self.output = None
    self._func = None

BatchMapper

BatchMapper()

Bases: Mapper

Inherit from this class to pass to DataChain.batch_map().

process() receives a list of up to batch values for each column parameter, even with batch=1; resources from chain.setup() are passed unchanged. It returns list[T] or Iterator[T] with one result per input row, in input order, and the output column has type T. Any other number of results raises UdfError. setup() and teardown() run once per worker process.

Source code in datachain/lib/udf.py
397
398
399
400
def __init__(self):
    self.params: SignalSchema | None = None
    self.output = None
    self._func = None