Sub topic 10
Writing a custom predictor
This chapter shows how to package your own model code as a KServe predictor. It assumes you can write an InferenceService manifest, know how a storageUri is used, and have seen the V1 request format ({"instances": [...]}) from earlier chapters. You also need Docker or another tool that builds container images, and a registry your cluster can pull from.
When a custom predictor is the right choice
KServe's built-in runtimes cover common model formats such as scikit-learn, XGBoost, TensorFlow, PyTorch and ONNX. If your model fits one of them, use the runtime. A custom predictor makes sense when:
- The model format has no matching runtime.
- Inference needs logic that does not belong in a model file, such as calling a rules engine or combining several libraries.
- You need a specific Python version or system library that the stock runtime images do not provide.
- You want full control over request validation and the shape of responses.
A custom predictor costs more to maintain. You own the image, its dependencies and its security patches. Check first whether a transformer (covered in a later chapter) or a runtime configuration change solves the problem.
The programming model
The KServe Python SDK gives you two pieces:
Modelis a base class. You subclass it and override methods that KServe calls during the request lifecycle.ModelServeris an HTTP server (with optional gRPC) that hosts one or moreModelinstances. It exposes the V1 and V2 endpoints, health checks and metrics for you.
The methods you will use most often are:
| Method | Called | Purpose |
|---|---|---|
| `load()` | Once at startup, by your code | Read weights and other artifacts into memory |
| `preprocess()` | Before `predict` | Convert the request into model input |
| `predict()` | For each request | Run the model and return outputs |
| `postprocess()` | After `predict` | Convert model output into the response |
The server calls preprocess, predict and postprocess in that order. The default preprocess and postprocess pass data through unchanged, so a minimal predictor overrides only predict.
The ready attribute controls readiness. The server reports the model as not ready until ready is True. Kubernetes uses this signal to decide whether to send traffic to the pod, so set it only after loading has finished.
A minimal predictor
This example sums each input row. It has no real model, but it has the same structure as a real predictor.
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")])Points to notice:
- The name passed to
SumModel("sum-model")becomes the model name in the URL:/v1/models/sum-model:predict. __init__callsload()andload()setsready. For a large model, loading can take minutes, which is why readiness exists.predictreceives the parsed JSON body as a dictionary and returns a dictionary. Theheadersargument carries the request headers.ModelServer().start([...])blocks and serves requests. You can pass several models in the list, but one model per container is the more common and simpler pattern.
Test it locally first
You can run the file without Kubernetes. Install the SDK, start the server, and call it with curl. The default HTTP port is 8080.
pip install kserve
python model.py &
curl -s -H "Content-Type: application/json" \
http://localhost:8080/v1/models/sum-model:predict \
-d '{"instances": [[1, 2, 3], [4, 5, 6]]}'The response should be {"predictions":[6,15]}. Testing locally shortens the feedback loop a great deal, because building and pushing an image for each change is slow.
Loading a model from storage
A real predictor loads files. KServe's storage initializer, which earlier chapters described, can download the storageUri contents into the pod and mount them at /mnt/models. Your load() then reads from that directory. Whether the initializer runs for a custom container depends on your manifest: set storageUri on the predictor and it is downloaded in the same way as for built-in runtimes.
A sketch of load() for a pickled scikit-learn model:
import os
import joblib
from kserve import Model, ModelServer
MODEL_DIR = os.environ.get("MODEL_DIR", "/mnt/models")
class PickleModel(Model):
def __init__(self, name: str):
super().__init__(name)
self.model = None
self.load()
def load(self):
self.model = joblib.load(os.path.join(MODEL_DIR, "model.joblib"))
self.ready = True
def predict(self, payload, headers=None):
rows = payload["instances"]
return {"predictions": self.model.predict(rows).tolist()}
if __name__ == "__main__":
ModelServer().start([PickleModel("pickle-model")])Two details prevent common bugs. First, call .tolist() on NumPy arrays, because the server must serialize the response to JSON and NumPy types are not JSON serializable. Second, read the directory from an environment variable with a default, so you can point it at a local folder during testing.
Packaging the image
The container must start the server process and listen on the port KServe expects. A small Dockerfile is enough:
FROM python:3.11-slim
WORKDIR /app
RUN pip install --no-cache-dir kserve==0.13.1 joblib scikit-learn
COPY model.py .
USER 1000
ENTRYPOINT ["python", "model.py"]Pin the kserve version. The SDK's method signatures have changed between releases, and an unpinned build can break without any change in your code. Match the pinned version to the KServe version installed in your cluster where you can. Running as a non-root user is a sensible default and many clusters enforce it.
Build and push the image:
docker build -t registry.example.com/team/sum-model:1.0.0 .
docker push registry.example.com/team/sum-model:1.0.0Use a specific tag, never latest. A mutable tag makes rollbacks and canary comparisons unreliable, because two revisions can silently run different code.
Referencing the image from an InferenceService
For a custom container, you use containers instead of model under predictor:
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
name: sum-model
spec:
predictor:
containers:
- name: kserve-container
image: registry.example.com/team/sum-model:1.0.0
args:
- --model_name=sum-model
resources:
requests:
cpu: "500m"
memory: 512Mi
limits:
memory: 1GiThe container is named kserve-container. KServe looks for that name to apply its settings, so keep it. The --model_name argument is read by the SDK's argument parser, and the value should match the name you registered in code. If the two disagree, requests to the URL you expect return a 404.
Apply it and wait for readiness:
kubectl apply -f sum-model.yaml
kubectl get inferenceservice sum-modelThen call it through the ingress with the same pattern as earlier chapters, using /v1/models/sum-model:predict.
Supporting the V2 protocol
ModelServer serves both protocols from the same Model class. The V1 path passes a dictionary with instances. A V2 request carries inputs, each with a name, shape, datatype and flat data list. The SDK can hand you a V2 request as an InferRequest object, and you may return an InferResponse. If you only handle plain dictionaries, V2 callers may get errors or unexpected shapes.
Decide which protocol your clients use and test it explicitly. If you support only V1, say so in the service documentation. If you need both, write a small conversion layer in preprocess and postprocess so that predict works on one internal format.
Common errors
- Pod stays not ready.
readywas never set toTrue, orload()raised an exception. Checkkubectl logs <pod> -c kserve-container. - 404 on the predict URL. The model name in the URL, the
--model_nameargument and the name in code do not all match. - 500 with a serialization error. The response contains NumPy arrays,
Decimalvalues or other non-JSON types. Convert to plain lists and numbers. OOMKilledpod status. The memory limit is below what the model needs. Raise the limit, and remember that loading can use more memory than steady-state serving.ImagePullBackOff. The image tag is wrong, or the cluster has no credentials for your registry. Add an image pull secret to the service account.- Slow requests under load. A blocking, CPU-heavy
predictties up the event loop. For heavy computation, use more replicas, as the autoscaling chapter describes, and avoid long synchronous work inside async methods.
Design decisions
| Decision | Option A | Option B | Guidance |
|---|---|---|---|
| Built-in runtime or custom | Built-in runtime | Custom container | Prefer the runtime unless you need logic or dependencies it lacks |
| Bake model into image | Faster start, larger image | Load from `storageUri` | Prefer `storageUri` so you can change models without rebuilding |
| Models per container | One | Several | One keeps scaling and failures independent |
| Base image | Slim | Full | Slim reduces size and attack surface, but check native libraries |
Exercises
Exercise
Your custom predictor pod starts but never becomes ready, and the logs show no errors. Which line in your Python class is the most likely cause, and why does it matter to Kubernetes?
Show answer
The code never sets self.ready = True after loading. The model server reports the model as not ready until that attribute is true, and Kubernetes uses that readiness signal to decide whether to route traffic to the pod, so the pod stays out of service.
Exercise
A predictor works locally, but after deployment curl to /v1/models/my-model:predict returns 404, even though the pod is ready. Name two things to compare.
Show answer
Compare the URL's model name with the name passed to the Model constructor in code, and with the --model_name argument in the InferenceService manifest. Any mismatch among them produces a 404.
Exercise
Write the predict return statement for a scikit-learn model stored in self.model so that the response serializes to JSON.
Show answer
return {"predictions": self.model.predict(payload["instances"]).tolist()}. The .tolist() call converts the NumPy array to plain Python lists and numbers, which JSON can encode.