All Products
Search
Document Center

Realtime Compute for Apache Flink:Custom model

Last Updated:Sep 21, 2026

This topic describes how to develop a Python custom model, register the model, and invoke it for inference in an SQL job.

Prerequisites

Before you begin, make sure that the following preparations are complete:

  • A Realtime Compute for Apache Flink workspace is activated. For more information, see Activate Realtime Compute for Apache Flink.

  • Realtime Compute engine VVR 11.9 and later have Python 3.9, 3.10, and 3.11 pre-installed. Select one of them as the Python version of your local development environment.

Set up a local environment

  1. Create a working directory.

    mkdir custom-model-quickstart
    cd custom-model-quickstart
  2. (Optional) Configure the local development environment. The Flink Python API is provided only in VVR 11.9 and later, and is not available in open source Flink. Run the following command to install the PyFlink dependencies of VVR:

    pip install "pyarrow>=5.0.0" "ververica-flink==11.9.0"
    Note
    • ververica-flink is an API-only package that provides only type definitions and interface declarations for local development. You must still submit jobs on the Realtime Compute for Apache Flink platform.

    • Custom models depend on pyarrow. We recommend that you also install pyarrow of the corresponding version.

Develop a custom model

This example implements a linear prediction model. The formula is as follows:

Create a model resource file

Create linear-weight.txt in the current directory and add the following content.

5

Create a model implementation file

Create custom_model.py in the current directory and add the following content.

import os

from pyflink.table import DataTypes
from pyflink.table.udf import PredictFunction, udpf

class LinearPredictFunction(PredictFunction):
    def load_model(self, model_options, weight_path, device):
        """Load the model resources and initialize the inference parameters.

        The framework calls this method during model initialization. Store the
        loaded model or parameters in self so that predict() can reuse them,
        instead of loading them again for each batch.

        Args:
            model_options (dict): The WITH parameters of CREATE MODEL.
                This example reads factor. The default value is 10.
            weight_path (str | None): The local path of the model resource
                that is resolved by the framework. The path can point to a
                file or a directory. The value is None if no model resource is
                bound.
            device: The computing device that is selected by the framework.
        """
        self.factor = int(model_options.get("factor", "10"))

        if weight_path is None:
            raise ValueError("Configure the model resource by using model-path")

        if os.path.isdir(weight_path):
            weight_path = os.path.join(weight_path, "linear-weight.txt")

        with open(weight_path, "r", encoding="utf-8") as weight_file:
            self.bias = int(weight_file.read().strip())

    def predict(self, batch):
        """Perform linear prediction on an Arrow input batch.

        Each record is calculated as value * factor + bias. A null input
        returns a null output.

        Args:
            batch (pa.RecordBatch): The input data batch of this invocation.
                The column order is the same as the order specified by
                DESCRIPTOR(...) in SQL, and the column types match the INPUT
                declaration of the model. This example reads the first column,
                which is of the BIGINT type.

        Returns:
            pa.RecordBatch: The data batch that contains only the prediction
                column score. The column type is pa.int64(), which maps to
                SQL BIGINT. The number of output rows is the same as the
                number of input rows, and the row-by-row correspondence is
                kept.
        """
        import pyarrow as pa
        values = batch.column(0).to_pylist()

        scores = [
            value * self.factor + self.bias
            for value in values
        ]

        return pa.RecordBatch.from_arrays(
            [pa.array(scores, type=pa.int64())],
            names=["score"],
        )

linear_predict = udpf(
    LinearPredictFunction(),
    input_types=[DataTypes.BIGINT()],
    result_type=DataTypes.ROW([
        DataTypes.FIELD("score", DataTypes.BIGINT()),
    ]).not_null(),
    name="linear_predict",
)   

Upload deployment files

After the custom model is developed, register the model files on the platform:

  1. Log on to the Realtime Compute for Apache Flink console and go to the target workspace.

  2. In the left-side navigation pane, choose Artifacts, and upload custom_model.py.

  3. In the left-side navigation pane, choose Artifacts, and upload linear-weight.txt.

After the files are uploaded, view the OSS paths. For more information, see Artifacts.

Write an SQL job

  1. Log on to the Realtime Compute for Apache Flink console and go to the target workspace.

  2. Create an SQL job draft and select VVR 11.9 or later.

  3. In the SQL editor, add the following content. Replace model-path with the actual path of the model resource, which is the OSS path of the uploaded deployment file.

    SET 'python.files' = '<resource URL of custom_model.py>';
    
    CREATE TEMPORARY MODEL linear_model
    INPUT (`value` BIGINT)
    OUTPUT (score BIGINT)
    WITH (
        'model-path' = '<resource URL of linear-weight.txt>',
        'factor' = '10'
    )
    AS 'custom_model.linear_predict'
    LANGUAGE PYTHON;
    
    CREATE TEMPORARY VIEW source_t AS
    SELECT *
    FROM (
        VALUES
            (CAST(1 AS BIGINT)),
            (CAST(2 AS BIGINT)),
            (CAST(3 AS BIGINT))
    ) AS T(id);
    
    CREATE TEMPORARY TABLE result_t (
        id BIGINT,
        score BIGINT
    ) WITH (
        'connector' = 'print',
        'logger' = 'true'
    );
    
    INSERT INTO result_t
    SELECT id, score
    FROM ML_PREDICT(
        TABLE source_t,
        MODEL linear_model,
        DESCRIPTOR(id),
        MAP[
            'bundle-size', '2',
            'bundle-allow-latency', '1s'
        ]
    );
    Note
    • AS 'custom_model.linear_predict' refers to the object that is exported by udpf in the Python module.

    • INPUT and OUTPUT must be consistent with the input and output types that are declared in Python.

    • DESCRIPTOR(id) specifies the input columns that are passed to the model.

    • bundle-size specifies the maximum number of records in an inference batch. bundle-allow-latency specifies the maximum wait time for batch buffering.

Start the job

  1. On the O&M > Deployments page, select STREAM or BATCH from the drop-down list.

  2. On the right side of the target job name, click Start in the Actions column.

  3. In the panel that appears, click Start.

Verify the result

The job uses the Print connector to print the result to the TaskManager logs. After the job is finished, check the logs to verify the result:

  1. On the O&M > Deployments page, select STREAM or BATCH from the drop-down list.

  2. Click the name of the target job.

  3. Click Logs.

  4. Click the Task Managers tab, and select a task manager from the Current TaskManager drop-down list.

The job runs successfully if the following data appears in the logs:

+I[1, 15]
+I[2, 25]
+I[3, 35]

Advanced usage

Batch execution

Multiple input records can be grouped into a batch and then passed to predict() for inference. This reduces the invocation overhead and increases the throughput of the model. Configure the batch size and the maximum wait time in the parameters of ML_PREDICT:

SELECT *
FROM ML_PREDICT(
    TABLE source_t,
    MODEL linear_model,
    DESCRIPTOR(id),
    MAP[
        'bundle-size', '32',
        'bundle-allow-latency', '1s'
    ]
);
  • bundle-size: the maximum number of records that can be buffered in each batch.

  • bundle-allow-latency: the maximum wait time for batch accumulation.

The framework triggers inference after the batch size or the wait time limit is reached. Therefore, an actual batch may be smaller than the configured value. Adjust the parameters based on the throughput, memory usage, and latency requirements of the model.

Arrow-based data transfer

Apache Arrow is used for batch data transfer between Flink and the Python model. The columnar format of Arrow reduces the overhead of per-record transfer and conversion, which suits batch inference scenarios.

predict() accepts a pyarrow.RecordBatch. You can read the input columns directly and perform batch calculations:

def predict(self, batch):
    import pyarrow as pa
    import pyarrow.compute as pc
    values = batch.column(0)
    # Perform batch inference and return the predictions in the Arrow format.
    scores = pc.add(values, pa.scalar(1, type=pa.int64()))

    return pa.RecordBatch.from_arrays(
        [scores],
        names=["score"],
    )

The output can be a pyarrow.RecordBatch or a sequence of columns that consist of Arrow arrays. The number of output rows must be the same as the number of input rows, and the row-by-row correspondence must be kept.

Weight management

In the CREATE MODEL statement, use the model-path parameter to specify model resources. The framework prepares a local resource path and passes it to load_model().

The following resource formats are supported:

  • Local files or directories: the corresponding path is used directly.

  • Remote files or directories: the resources are copied to a local path before use. The file system must support the path, and you must have the required access permissions.

  • Archives: zip, tar, tar.gz, and tgz are supported. The archive is decompressed and the local path is provided.

GPU invocation

In the CREATE MODEL statement, you can specify the GPU device type and the number of GPUs in the WITH parameters:

WITH (
    'model-path' = '<path of the model resource>',
    'gpu-type' = 'A10',
    'gpu-number' = '1'
)
  • gpu-type: the requested GPU type, which must be a resource type provided by the cluster.

  • gpu-number: the number of requested GPUs. You must configure gpu-type at the same time.

In the model implementation, you can use device to specify the inference device, and move the model and the input data to the device for inference. For example, if you use PyTorch, call model.to(device) and input_tensor.to(device). The device parameter is passed only in the load_model operation. Store the value as an instance property.

Note

To use GPU resources, contact technical support to enable the feature.