Skip to content

AWs sagemaker Model entrypoint not getting triggered

0

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

asked 2 years ago269 views

1 Answer
0

it could be an issue with your code in that the entry_point parameter in the Model class is not being used correctly. The entry_point parameter is supposed to specify the Python script that contains the necessary functions (such as predict_fn, postprocess, and output_fn) for the SageMaker inference pipeline.

In your case, you have defined these functions in the inference.py file, but you're not specifying that file as the entry_point. Instead, you're passing 'inference.py' as the entry_point, which is not the correct way to use it.

To fix this, you should update your code as follows:

Ensure that the inference.py file is present in the same directory as your Jupyter Notebook or in a directory that is accessible to the SageMaker environment.

Update the Model object creation to use the correct entry_point:

model = Model( model_data=model_s3_path, role=sagemaker.get_execution_role(), image_uri=triton_container, entry_point='inference.py' )

Make sure that the functions in the inference.py file (predict_fn, postprocess, and output_fn) are defined correctly and match the signatures expected by SageMaker.

After making these changes, your batch transform job should be able to find and execute the entry_point script correctly, and the predict_fn should be triggered as expected.

Additionally, you might want to check the logs of your batch transform job to see if there are any errors or issues that might be preventing the entry_point script from running properly.

answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.