I have a batch transform job which which i am trying to run in jupyternotebook in studio. below is the code.Problem is the entrypoint is not getting triggered.
import sagemaker
from sagemaker.model import Model # Use generic Model class for Triton
# Define S3 paths for input images, output predictions, and the model tarball
input_s3_path = 's3://sagemaker-aviro/json_input/'
output_s3_path = 's3://sagemaker-aviro/batch_transform/'
model_s3_path = 's3://sagemaker-aviro/model/sightio_prim_det.tar.gz'
# Step 2: Now, run the batch transform job using the uploaded JSON as input
triton_container = '007439368137.dkr.ecr.us-east-2.amazonaws.com/sagemaker-tritonserver:23.12-py3'
# Create the SageMaker Model object for Triton inference
model = Model(
model_data=model_s3_path,
role=sagemaker.get_execution_role(),
image_uri=triton_container,
entry_point='inference.py'
)
# Set up the transformer object for batch transform
transformer = model.transformer(
instance_count=1,
instance_type='ml.g4dn.2xlarge',
output_path=output_s3_path,
strategy='SingleRecord',
accept='application/jsonlines',
max_payload=100 # Output format should be JSONLines
)
# Step 3: Run the batch transform job using the JSON file as input
transformer.transform(
data=input_s3_path, # Use the S3 path to the uploaded JSON file as input
content_type='application/json', # Set content type to JSON
split_type='Line'
)
transformer.wait()
here is the inference.py code
import numpy as np
import os
import json
import onnxruntime as ort # Assuming you're using ONNX Runtime for inference
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("Starting model loading...")
def predict_fn(input_data, model):
"""
Perform the actual prediction. SageMaker calls this function to get predictions from the model.
"""
logging.info(f"Received input data: {input_data}")
input_name = model.get_inputs()[0].name # Assuming single input
raw_preds = model.run(None, {input_name: input_data}) # Perform inference
return raw_preds
# Post-processing function (called by SageMaker to process the raw model predictions)
def postprocess(raw_preds, output_dims=(1920, 1024)):
"""
Takes raw predictions from the model and refines them into a usable format.
"""
box = np.asarray(raw_preds[0]) # Adjust based on your model's output
batch_size = int(box.shape[0] / (4 * 20160))
box = box.reshape((batch_size, 20160, 1, 4))
cls = np.asarray(raw_preds[1]).reshape((batch_size, 20160, 4, 1))
predictions = (box, cls)
return parse_preds(predictions, output_dims=output_dims)
# Function to format the output (called by SageMaker to return the final output)
def output_fn(prediction, content_type):
"""
Format the output. SageMaker calls this function to return the prediction in the response.
"""
if content_type == "application/json":
# Format the post-processed output
return json.dumps({"predictions": prediction})
else:
raise ValueError("Unsupported content type: {}".format(content_type))
# Additional helper functions for post-processing
def box_iou_batch(boxes_a, boxes_b):
"""Calculates IOU between 2 boxes."""
def box_area(box):
return (box[2] - box[0]) * (box[3] - box[1])
area_a = box_area(boxes_a.T)
area_b = box_area(boxes_b.T)
top_left = np.maximum(boxes_a[:, None, :2], boxes_b[:, :2])
bottom_right = np.minimum(boxes_a[:, None, 2:], boxes_b[:, 2:])
area_inter = np.prod(np.clip(bottom_right - top_left, a_min=0, a_max=None), 2)
return area_inter / (area_a[:, None] + area_b - area_inter)
def non_max_suppression(predictions, iou_threshold=0.5):
"""Performs NMS"""
rows, columns = predictions.shape
sort_index = np.flip(predictions[:, 4].argsort())
predictions = predictions[sort_index]
boxes = predictions[:, :4]
categories = predictions[:, 5]
ious = box_iou_batch(boxes, boxes)
ious = ious - np.eye(rows)
keep = np.ones(rows, dtype=bool)
for index, (iou, category) in enumerate(zip(ious, categories)):
if not keep[index]:
continue
condition = (iou > iou_threshold) & (categories == category)
keep = keep & ~condition
return keep[sort_index.argsort()]
def find_keepers(vect_preds):
"""Finds boxes to keep based on NMS."""
ordered = np.flip(vect_preds[vect_preds[:, 4].argsort()], 0)
keep = non_max_suppression(ordered)
return list(ordered[keep].tolist())
def get_class_and_score(label):
"""Gets the predicted class and its score from raw model preds."""
pred_class = np.argmax(label)
score = label[pred_class].item()
return pred_class, score
def parse_preds(predictions, output_dims, conf_thresh=0.6):
"""
Parses the model predictions into a usable format.
"""
batch_size = len(predictions[0])
boxes, labels = predictions
all_preds = []
for b in range(batch_size):
label = labels[b]
box = boxes[b]
check = np.where(np.any(label > conf_thresh, 1))[0]
filtered_labels = label[check]
filtered_boxes = box[check]
pred_label = np.argmax(filtered_labels, 1).astype(np.float32)
conf_score = np.max(filtered_labels, 1)
converted_boxes = filtered_boxes * np.array([output_dims[0], output_dims[1], output_dims[0], output_dims[1]])
vect_preds = np.concatenate((converted_boxes.squeeze(), conf_score, pred_label), axis=1)
if vect_preds.size != 0:
kept_boxes = find_keepers(vect_preds)
else:
kept_boxes = []
all_preds.append(kept_boxes)
return all_preds
# No need for a main function since SageMaker calls the lifecycle functions