Sub topic 10
Writing a Custom Predictor
This chapter assumes you understand pods, deployments, services, namespaces, and YAML manifests. You should also know how to save a machine learning model and send JSON with HTTP. The earlier chapters introduced InferenceService, serving runtimes, and inference protocols.
KServe includes ready-made runtimes for common formats such as scikit-learn and TensorFlow. A custom predictor is useful when your model needs code that those runtimes do not provide. You can load unusual artifacts, apply custom logic, or expose a model with a nonstandard implementation.
What a custom predictor does
A predictor is the server-side program that receives an inference request and returns a prediction. With the KServe Python SDK, you create a class that extends Model.
The class normally does four things:
- Gives the model a name.
- Loads weights or other artifacts.
- Reports whether it is ready.
- Implements
predict.
The SDK's ModelServer handles the HTTP server and protocol details. Your class focuses on model-specific behavior.
Build a minimal predictor
The following predictor accepts V1-style input. The instances field contains a list of rows. Each row contains numbers, and the predictor returns the sum of each row.
from kserve import Model, ModelServer
class SumModel(Model):
def __init__(self, name: str):
super().__init__(name)
self.load()
def load(self):
# Load weights or other artifacts here.
self.ready = True
def predict(self, payload, headers=None):
instances = payload["instances"]
return {"predictions": [sum(row) for row in instances]}
if __name__ == "__main__":
ModelServer().start([SumModel("sum-model")])load runs when the server creates the model. In a real predictor, it might download a file already placed in the container, open a tokenizer, or initialize a framework model. Set self.ready only after all required initialization succeeds. KServe uses readiness to decide whether the model can receive traffic.
The predict method receives the decoded request payload. It should validate required fields and return a JSON-serializable object. Production code should also handle malformed input and model errors deliberately. Do not let a missing field produce an unclear server error.
Package and deploy the predictor
Place the Python file and its dependencies in a container image. The image's command must start the Python process. Push the image to a registry that the Kubernetes cluster can read.
A custom predictor is then selected by referencing that image in the InferenceService predictor container. The exact image name and registry credentials depend on your cluster. The important boundary is:
| Component | Responsibility |
|---|---|
| Container image | Includes the predictor code, dependencies, and startup command |
| `InferenceService` | Gives KServe the service name, resources, and image |
| `Model` subclass | Loads the model and implements prediction logic |
Use the same protocol at both ends. If the predictor reads V1 instances, clients must send V1 requests. A predictor written for the V2/Open Inference protocol needs to parse its V2 request shape instead.
Common errors
A custom predictor can be healthy as a process but still fail as a service. Check these boundaries:
- The image is available from every cluster node.
- The startup command imports the required package.
- The model becomes ready only after loading completes.
- The request field names match the selected protocol.
- The response is valid JSON and follows the expected response schema.
- CPU and memory requests are large enough for model initialization.
Test the predictor with a small, known input before adding autoscaling, transformers, or an inference graph. Once the basic request works, KServe features such as traffic splitting and monitoring can be added around the same service.
Exercise
Why should a predictor set self.ready = True only after loading finishes?
Show answer
KServe uses readiness to decide whether the model can receive traffic. Setting it too early can send requests to an uninitialized model.