Sub topic 11
Adding pre- and post-processing with a transformer
This chapter assumes you can write and apply an InferenceService manifest, you know what a predictor is, and you have called a V1 endpoint with curl. It also assumes you are comfortable reading a short Python class and a Dockerfile.
Why a model server should not do everything
A trained model accepts numbers in a fixed layout. Clients rarely have data in that layout. A client may send named fields, raw text, or a base64 image. It may want a label back instead of a class index.
You can handle this in three places:
- Make every client convert its own data. This duplicates logic across callers, and the copies drift apart.
- Bake the conversion into the model artifact or a custom predictor. This ties feature logic to the model's release cycle and its hardware.
- Put the conversion in a separate component in front of the predictor. This is the transformer.
A KServe transformer is an optional second component of an InferenceService. It receives the client's request, runs preprocess, forwards the result to the predictor, then runs postprocess on the predictor's response. The client only talks to the transformer.
The request path
The transformer and the predictor are separate pods with separate containers. They are also separate scaling units. Each has its own minReplicas, maxReplicas, resource requests, and logs. This lets you run feature logic on cheap CPU nodes and keep the model on GPU nodes.
What a transformer is made of
The transformer is a container that serves the same protocol as the predictor. The easiest way to build one is the KServe Python SDK. You subclass Model and override two methods:
preprocess(payload, headers)receives the client's request body and returns the body to send to the predictor.postprocess(response, headers)receives the predictor's response and returns the body for the client.
You do not write the call to the predictor. The base class predict method forwards the request to the predictor host. KServe injects that host as the --predictor_host argument when it starts your container.
A transformer for the iris service
The predictor from the first chapters expects {"instances": [[...4 numbers...]]} and returns {"predictions": [1, 1]}. This transformer lets clients send named measurements and get species names back.
import argparse
from kserve import Model, ModelServer, model_server
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABELS = ["setosa", "versicolor", "virginica"]
class IrisTransformer(Model):
def __init__(self, name: str, predictor_host: str, protocol: str):
super().__init__(name)
self.predictor_host = predictor_host
self.protocol = protocol
self.ready = True
def preprocess(self, payload, headers=None):
# Client sends {"samples": [{"sepal_length": 6.8, ...}, ...]}
rows = [[float(sample[f]) for f in FEATURES] for sample in payload["samples"]]
return {"instances": rows}
def postprocess(self, response, headers=None):
# Predictor returns {"predictions": [1, 1]}
results = [
{"class_index": int(p), "label": LABELS[int(p)]}
for p in response["predictions"]
]
return {"results": results}
if __name__ == "__main__":
parser = argparse.ArgumentParser(parents=[model_server.parser])
args, _ = parser.parse_known_args()
transformer = IrisTransformer(
args.model_name,
predictor_host=args.predictor_host,
protocol=args.protocol,
)
ModelServer().start([transformer])model_server.parser already defines --model_name, --predictor_host, --protocol, and the port options, so you do not declare them yourself. parse_known_args ignores any flags the SDK adds that you did not list.
Package it like any Python service:
FROM python:3.11-slim
WORKDIR /app
RUN pip install --no-cache-dir kserve
COPY transformer.py .
ENTRYPOINT ["python", "transformer.py"]Build the image, push it to a registry your cluster can pull from, and use that image name in the manifest below.
Attaching the transformer to an InferenceService
Add a transformer section beside predictor. It takes a containers list, like a pod spec:
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
name: sklearn-iris
spec:
transformer:
minReplicas: 1
maxReplicas: 3
containers:
- name: kserve-container
image: registry.example.com/ml/iris-transformer:0.1
args:
- --model_name=sklearn-iris
resources:
requests:
cpu: 200m
memory: 256Mi
predictor:
minReplicas: 1
model:
modelFormat:
name: sklearn
storageUri: gs://kfserving-examples/models/sklearn/1.0/modelApply it and check the service:
kubectl apply -f sklearn-iris-transformer.yaml
kubectl get inferenceservice sklearn-iris
kubectl get pods -l serving.kserve.io/inferenceservice=sklearn-irisYou should see one pod for the transformer and one for the predictor. Their names contain transformer and predictor. KServe creates the same ingress route as before, but it now points at the transformer.
Call it with the client's own format. The path is unchanged:
cat <<'EOF' > samples.json
{"samples": [
{"sepal_length": 6.8, "sepal_width": 2.8, "petal_length": 4.8, "petal_width": 1.4},
{"sepal_length": 6.0, "sepal_width": 3.4, "petal_length": 4.5, "petal_width": 1.6}
]}
EOF
curl -H "Host: ${SERVICE_HOSTNAME}" -H "Content-Type: application/json" \
http://${INGRESS_HOST}:${INGRESS_PORT}/v1/models/sklearn-iris:predict \
-d @./samples.jsonThe response is {"results": [{"class_index": 1, "label": "versicolor"}, ...]}. The exact indices depend on the model.
How preprocess and postprocess are called
The model server handles each request in a fixed order:
- Parse the body (JSON for V1) and call
preprocess. - Call
predict, which sends the preprocessed body to the predictor host. - Call
postprocesson the predictor's reply. - Serialize the return value as the HTTP response.
Both hooks can be async def. Use that form when the hook calls another service, such as a feature store, so the event loop is not blocked. The headers argument carries the incoming request headers, which is useful for tracing IDs or tenant information.
If you leave postprocess unimplemented, the predictor's response passes through unchanged. If you implement only postprocess, preprocess passes the request through. You can override just the half you need.
Edge cases and common errors
The payload shape depends on the protocol
With the V1 protocol, preprocess receives a plain dict, as above. With the V2 (Open Inference) protocol, newer SDK versions pass an InferRequest object, and the predictor returns an InferResponse. Code that indexes payload["instances"] will fail there. Check the SDK version you pin, and set --protocol to match the predictor. The transformer and predictor must use the same protocol, because the transformer forwards the request to the predictor in that protocol.
Latency and payload cost
The transformer adds a network hop and two serialization steps. For small tabular requests this is a few milliseconds. For large tensors or images, JSON encoding can cost more than the model call. Measure before assuming the transformer is free. If the preprocessing is trivial and tied to one model, a custom predictor may be simpler.
Training and serving skew
The most valuable use of a transformer is applying the same feature code that training used. Put that code in a shared Python package and import it in both the training job and the transformer image. If you copy the logic, the two copies will diverge and accuracy will drop with no error message.
Scaling and readiness
- The transformer scales on its own metrics. If it is the bottleneck, raise its
maxReplicasand set its CPU requests, not the predictor's. - Setting
ready = Truein the constructor is acceptable when there is nothing to load. If the transformer loads a vocabulary or tokenizer, setreadyonly after loading completes. Otherwise traffic arrives before the container can handle it. - With scale to zero in Serverless mode, a cold request waits for both components to start. Keep
minReplicas: 1on the transformer if your latency target cannot absorb that.
Rollouts
The canary settings you used earlier act on a component's new revision. Confirm in your KServe version whether canaryTrafficPercent applies to the transformer as well as the predictor. When you change the transformer's output format and the predictor together, deploy them as a single change and test the pair.
Troubleshooting
Start with the pod that failed:
kubectl logs -l serving.kserve.io/inferenceservice=sklearn-iris \
-c kserve-container --tail=50The same container name appears in both components, so filter by pod name to separate them. A KeyError in the transformer log usually means the client sent a field your preprocess did not expect. A 500 from the predictor shows up first in the transformer log as an HTTP error from predict.
Summary of when to use a transformer
| Situation | Transformer fits? |
|---|---|
| Clients send named fields, the model needs a vector | Yes |
| Predictions need human-readable labels or thresholds | Yes |
| Feature lookup from a store before inference | Yes, with async hooks |
| Preprocessing needs a GPU | Usually no, put it in the predictor |
| Very large payloads, tiny preprocessing | Probably no, the extra hop dominates |
Exercise
A client sends {"samples": [{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}]} to your service and gets a 500 error. The transformer log shows KeyError: 'instances' raised inside postprocess. The predictor pod log shows no request. What is the most likely cause, and where would you look first?
Show answer
The error is raised in the transformer, and the predictor never saw a request, so the failure is not in the model. A KeyError: 'instances' in postprocess means the code is reading the wrong dictionary, for example indexing the request shape instead of the predictor's predictions response. The other likely cause is that preprocess or predict returned something unexpected. Check the postprocess code first, and check that --protocol matches the predictor so the response has the shape postprocess expects. Then read the transformer pod's kserve-container logs with kubectl logs.