sdk/python/foundation-models/system/inference/image-object-detection/image-object-detection-batch-endpoint.ipynb (534 lines of code) (raw):
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Image Object Detection Inference using Batch Endpoints\n",
"\n",
"This sample shows how deploy `image-object-detection` type models to an batch endpoint for inference.\n",
"\n",
"### Task\n",
"`image-object-detection` tasks assign box(es) with their scaled top-left and bottom-right coordinates along with box label and confidence score to an image.\n",
" \n",
"### Model\n",
"Models that can perform the `image-object-detection` task are tagged with `image-object-detection`. We will use the `yolof_r50_c5_8x8_1x_coco` model in this notebook. If you opened this notebook from a specific model card, remember to replace the specific model name.\n",
"\n",
"### Inference data\n",
"We will use the [fridgeObjects](https://automlsamplenotebookdata-adcuc7f7bqhhh8a4.b02.azurefd.net/image-object-detection/odFridgeObjects.zip) dataset for image object detection.\n",
"\n",
"\n",
"### Outline\n",
"1. Setup pre-requisites\n",
"2. Pick a model to deploy\n",
"3. Prepare data for inference - using a folder of images; using a csv file with base64 images\n",
"4. Deploy the model to a batch endpoint\n",
"5. Test the endpoint - using a folder of images; Using a csv file with base64 images\n",
"6. Clean up resources - delete the endpoint"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1. Setup pre-requisites\n",
"* Install dependencies\n",
"* Connect to AzureML Workspace. Learn more at [set up SDK authentication](https://learn.microsoft.com/en-us/azure/machine-learning/how-to-setup-authentication?tabs=sdk). Replace `<WORKSPACE_NAME>`, `<RESOURCE_GROUP>` and `<SUBSCRIPTION_ID>` below.\n",
"* Connect to `azureml` system registry"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azure.ai.ml import MLClient, Input\n",
"from azure.ai.ml.entities import AmlCompute\n",
"from azure.ai.ml.constants import AssetTypes\n",
"from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential\n",
"import time\n",
"\n",
"try:\n",
" credential = DefaultAzureCredential()\n",
" credential.get_token(\"https://management.azure.com/.default\")\n",
"except Exception as ex:\n",
" credential = InteractiveBrowserCredential()\n",
"\n",
"try:\n",
" workspace_ml_client = MLClient.from_config(credential)\n",
" subscription_id = workspace_ml_client.subscription_id\n",
" resource_group = workspace_ml_client.resource_group_name\n",
" workspace_name = workspace_ml_client.workspace_name\n",
"except Exception as ex:\n",
" print(ex)\n",
" # Enter details of your AML workspace\n",
" subscription_id = \"<SUBSCRIPTION_ID>\"\n",
" resource_group = \"<RESOURCE_GROUP>\"\n",
" workspace_name = \"<AML_WORKSPACE_NAME>\"\n",
"\n",
"workspace_ml_client = MLClient(\n",
" credential, subscription_id, resource_group, workspace_name\n",
")\n",
"\n",
"# The models, fine tuning pipelines and environments are available in the AzureML system registry, \"azureml\"\n",
"registry_ml_client = MLClient(\n",
" credential,\n",
" subscription_id,\n",
" resource_group,\n",
" registry_name=\"azureml\",\n",
")\n",
"# Generating a unique timestamp that can be used for names and versions that need to be unique\n",
"timestamp = str(int(time.time()))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a compute cluster\n",
"Use the model card from the AzureML system registry to check the minimum required inferencing SKU, referenced as size below. If you already have a sufficient compute cluster, you can simply define the name in compute_name in the following code block."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azure.ai.ml.entities import AmlCompute\n",
"from azure.core.exceptions import ResourceNotFoundError\n",
"\n",
"compute_name = \"cpu-cluster\"\n",
"\n",
"try:\n",
" _ = workspace_ml_client.compute.get(compute_name)\n",
" print(\"Found existing compute target.\")\n",
"except ResourceNotFoundError:\n",
" print(\"Creating a new compute target...\")\n",
" compute_config = AmlCompute(\n",
" name=compute_name,\n",
" description=\"An AML compute cluster\",\n",
" size=\"Standard_DS3_V2\",\n",
" min_instances=0,\n",
" max_instances=3,\n",
" idle_time_before_scale_down=120,\n",
" )\n",
" workspace_ml_client.begin_create_or_update(compute_config).result()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2. Pick a model to deploy\n",
"\n",
"Browse models in the Model Catalog in the AzureML Studio, filtering by the `image-object-detection` task. In this example, we use the `yolof_r50_c5_8x8_1x_coco ` model. If you have opened this notebook for a different model, replace the model name accordingly. This is a pre-trained model and may not give correct prediction for your dataset. We strongly recommend to finetune this model on a down-stream task to be able to use it for predictions and inference. Please refer to the [image object detection finetuning notebook](../../finetune/image-object-detection/mmdetection-fridgeobjects-object-detection.ipynb)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_name = \"mmd-3x-yolof_r50_c5_8x8_1x_coco\"\n",
"foundation_models = registry_ml_client.models.list(name=model_name)\n",
"foundation_model = max(foundation_models, key=lambda x: int(x.version))\n",
"print(\n",
" f\"\\n\\nUsing model name: {foundation_model.name}, version: {foundation_model.version}, id: {foundation_model.id} for inferencing\"\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3. Prepare data for inference - using a folder of images; using a csv file with base64 images\n",
"\n",
"We will use the [odFridgeObjects](https://automlsamplenotebookdata-adcuc7f7bqhhh8a4.b02.azurefd.net/image-object-detection/odFridgeObjects.zip) dataset for image object detection.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import urllib\n",
"import shutil\n",
"from zipfile import ZipFile\n",
"\n",
"# Change to a different location if you prefer\n",
"dataset_parent_dir = \"./data\"\n",
"\n",
"# create data folder if it doesnt exist.\n",
"os.makedirs(dataset_parent_dir, exist_ok=True)\n",
"\n",
"# Download data\n",
"download_url = \"https://automlsamplenotebookdata-adcuc7f7bqhhh8a4.b02.azurefd.net/image-object-detection/odFridgeObjects.zip\"\n",
"\n",
"# Extract current dataset name from dataset url\n",
"dataset_name = os.path.split(download_url)[-1].split(\".\")[0]\n",
"# Get dataset path for later use\n",
"dataset_dir = os.path.join(dataset_parent_dir, dataset_name)\n",
"\n",
"if os.path.exists(dataset_dir):\n",
" shutil.rmtree(dataset_dir)\n",
"\n",
"# Get the data zip file path\n",
"data_file = os.path.join(dataset_parent_dir, f\"{dataset_name}.zip\")\n",
"\n",
"# Download the dataset\n",
"urllib.request.urlretrieve(download_url, filename=data_file)\n",
"\n",
"# Extract files\n",
"with ZipFile(data_file, \"r\") as zip:\n",
" print(\"extracting files...\")\n",
" zip.extractall(path=dataset_parent_dir)\n",
" print(\"done\")\n",
"\n",
"# Delete zip file\n",
"os.remove(data_file)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.1 Arrange images in common folder for batch inference input"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"image_directory = os.path.join(dataset_dir, \"images\")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.2 Prepare CSV file with base64 images for batch inference input\n",
"\n",
"We can provide input images to batch inference either in a folder containing images or in a csv file containing \"image\" named column having images in base64 format.\n",
"\n",
"The deployment in the \"Create batch deployment\" section below takes the argument `mini_batch_size`, which is the number of CSV files processed by the model in a single mini_batch."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import base64\n",
"import pandas as pd\n",
"\n",
"image_list = []\n",
"csv_file_path = os.path.join(dataset_parent_dir, \"image_list.csv\")\n",
"\n",
"for image in os.listdir(image_directory):\n",
" with open(os.path.join(image_directory, image), \"rb\") as f:\n",
" data = f.read()\n",
" data = base64.encodebytes(data).decode(\"utf-8\")\n",
" image_list.append(data)\n",
"\n",
"df = pd.DataFrame(image_list, columns=[\"image\"]).sample(10)\n",
"df.to_csv(csv_file_path, index=False, header=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from IPython.display import Image\n",
"\n",
"sample_image = os.path.join(image_directory, \"99.jpg\")\n",
"Image(filename=sample_image)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4. Deploy the model to an batch endpoint\n",
"Batch endpoints are endpoints that are used to do batch inferencing on large volumes of data over a period of time. The endpoints receive pointers to data and run jobs asynchronously to process the data in parallel on compute clusters. Batch endpoints store outputs to a data store for further analysis. For more information on batch endpoints and deployments see [What are batch endpoints?](https://learn.microsoft.com/en-us/azure/machine-learning/concept-endpoints?view=azureml-api-2#what-are-batch-endpoints) In this sub-section, we will cover the following items:\n",
"\n",
"* Create a batch endpoint.\n",
"* Create a batch deployment.\n",
"* Set the deployment as default. Doing so allows invoking the endpoint without specifying the deployment's name."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a batch endpoint"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time, sys\n",
"from azure.ai.ml.entities import (\n",
" BatchEndpoint,\n",
" BatchDeployment,\n",
" BatchRetrySettings,\n",
" AmlCompute,\n",
")\n",
"\n",
"# Endpoint names need to be unique in a region, hence using timestamp to create unique endpoint name\n",
"endpoint_name = \"mmd-image-od-\" + str(timestamp)\n",
"# Create a batch endpoint\n",
"endpoint = BatchEndpoint(\n",
" name=endpoint_name,\n",
" description=\"Batch endpoint for \"\n",
" + foundation_model.name\n",
" + \", for image-object-detection task\",\n",
")\n",
"workspace_ml_client.begin_create_or_update(endpoint).result()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a batch deployment\n",
"\n",
"__Note__: `mini_batch_size` is the number of CSV files processed by the model in a single mini_batch."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"deployment_name = \"demo\"\n",
"\n",
"deployment = BatchDeployment(\n",
" name=deployment_name,\n",
" endpoint_name=endpoint_name,\n",
" model=foundation_model.id,\n",
" compute=compute_name,\n",
" error_threshold=0,\n",
" instance_count=1,\n",
" logging_level=\"info\",\n",
" max_concurrency_per_instance=1,\n",
" mini_batch_size=2,\n",
" output_file_name=\"predictions.csv\",\n",
" retry_settings=BatchRetrySettings(max_retries=3, timeout=600),\n",
")\n",
"workspace_ml_client.begin_create_or_update(deployment).result()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Set the deployment as default"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"endpoint = workspace_ml_client.batch_endpoints.get(endpoint_name)\n",
"endpoint.defaults.deployment_name = deployment_name\n",
"workspace_ml_client.begin_create_or_update(endpoint).result()\n",
"\n",
"endpoint = workspace_ml_client.batch_endpoints.get(endpoint_name)\n",
"print(f\"The default deployment is {endpoint.defaults.deployment_name}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 5. Test the endpoint - using a folder of images; using a csv file with base64 images\n",
"\n",
"We will fetch some sample data from the test dataset and invoke batch endpoint for inference."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 5.1 Test the endpoint - using folder of images from 3.1\n",
"\n",
"Invoke the batch endpoint with the input parameter pointing to the folder containing the batch inference input. This creates a pipeline job using the default deployment in the endpoint. Wait for the job to complete."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"input = Input(path=image_directory, type=AssetTypes.URI_FOLDER)\n",
"\n",
"job = workspace_ml_client.batch_endpoints.invoke(\n",
" endpoint_name=endpoint.name, input=input\n",
")\n",
"\n",
"workspace_ml_client.jobs.stream(job.name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"scoring_job = list(workspace_ml_client.jobs.list(parent_job_name=job.name))[0]\n",
"\n",
"workspace_ml_client.jobs.download(\n",
" name=scoring_job.name,\n",
" download_path=os.path.join(dataset_parent_dir, \"image-folder-output\"),\n",
" output_name=\"score\",\n",
")\n",
"\n",
"predictions_file = os.path.join(\n",
" dataset_parent_dir,\n",
" \"image-folder-output\",\n",
" \"named-outputs\",\n",
" \"score\",\n",
" \"predictions.csv\",\n",
")\n",
"\n",
"# Load the batch predictions file with no headers into a dataframe and set your column names\n",
"score_df = pd.read_csv(\n",
" predictions_file,\n",
" header=None,\n",
" names=[\"row_number_per_file\", \"preds\", \"file_name\"],\n",
")\n",
"score_df.head()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 5.2 Test the endpoint - using CSV input with base64 images from 3.2\n",
"\n",
"Invoke the batch endpoint with the input parameter pointing to the csv file containing the batch inference input. This creates a pipeline job using the default deployment in the endpoint. Wait for the job to complete."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"job = None\n",
"input = Input(path=csv_file_path, type=AssetTypes.URI_FILE)\n",
"num_retries = 3\n",
"for i in range(num_retries):\n",
" try:\n",
" job = workspace_ml_client.batch_endpoints.invoke(\n",
" endpoint_name=endpoint.name, input=input\n",
" )\n",
" break\n",
" except Exception as e:\n",
" if i == num_retries - 1:\n",
" raise e\n",
" else:\n",
" print(\"Endpoint invocation failed. Retrying after 5 seconds...\")\n",
" time.sleep(5)\n",
"if job is not None:\n",
" workspace_ml_client.jobs.stream(job.name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: If job failed with error Assertion Error (`The actual length exceeded max length 100 MB`) then please try with less number of input images or use ImageFolder Input mode."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"scoring_job = list(workspace_ml_client.jobs.list(parent_job_name=job.name))[0]\n",
"\n",
"workspace_ml_client.jobs.download(\n",
" name=scoring_job.name,\n",
" download_path=os.path.join(dataset_parent_dir, \"csv-output\"),\n",
" output_name=\"score\",\n",
")\n",
"\n",
"predictions_file = os.path.join(\n",
" dataset_parent_dir, \"csv-output\", \"named-outputs\", \"score\", \"predictions.csv\"\n",
")\n",
"\n",
"# Load the batch predictions file with no headers into a dataframe and set your column names\n",
"score_df = pd.read_csv(\n",
" predictions_file,\n",
" header=None,\n",
" names=[\"row_number_per_file\", \"preds\", \"file_name\"],\n",
")\n",
"score_df.head()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### 6. Clean up resources - delete the endpoint\n",
"Batch endpoints use compute resources only when jobs are submitted. You can keep the batch endpoint for your reference without worrying about compute bills, or choose to delete the endpoint. If you created your compute cluster to have zero minimum instances and scale down soon after being idle, you won't be charged for an unused compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"workspace_ml_client.batch_endpoints.begin_delete(name=endpoint_name).result()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
}