sdk/python/foundation-models/system/inference/mask-generation/mask-generation-batch-endpoint.ipynb (514 lines of code) (raw):
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mask Generation Inference using Batch Endpoints\n",
"\n",
"This sample shows how to deploy `mask-generation` type models to a batch endpoint for inference.\n",
"\n",
"### Task\n",
"`mask-generation` takes in images and prompts (input points, input_boxes, input_labels) and for each image, generates segmentation masks based on the prompts given.\n",
"\n",
"### Model\n",
"Models that can perform the `mask-generation` task are tagged with `mask-generation`. We will use the `facebook/sam-vit-huge` 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 [odFridgeObjects](https://automlsamplenotebookdata-adcuc7f7bqhhh8a4.b02.azurefd.net/image-object-detection/odFridgeObjects.zip) dataset.\n",
"\n",
"\n",
"### Outline\n",
"1. Setup pre-requisites\n",
"2. Pick a model to deploy\n",
"3. Prepare data for inference\n",
"4. Deploy the model to a batch endpoint\n",
"5. Test the endpoint - using a folder of CSV files with base64 images\n",
"6. Clean up resources - delete the endpoint"
]
},
{
"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.constants import AssetTypes\n",
"from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential\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 = \"<WORKSPACE_NAME>\"\n",
"\n",
"workspace_ml_client = MLClient(\n",
" credential, subscription_id, resource_group, workspace_name\n",
")\n",
"\n",
"# The models 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",
")"
]
},
{
"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_DS5_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()"
]
},
{
"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 `mask-generation` task. In this example, we use the `facebook-sam-vit-huge` model. If you have opened this notebook for a different model, replace the model name accordingly."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_name = \"facebook-sam-vit-huge\"\n",
"\n",
"foundation_model = registry_ml_client.models.get(name=model_name, label=\"latest\")\n",
"print(\n",
" f\"\\n\\nUsing model name: {foundation_model.name}, version: {foundation_model.version}, id: {foundation_model.id} for inferencing\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3. Prepare data for inference\n",
"\n",
"We will use the [odFridgeObjects](https://automlsamplenotebookdata-adcuc7f7bqhhh8a4.b02.azurefd.net/image-object-detection/odFridgeObjects.zip) dataset for this mask-generation task.\n",
"\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 = \"./batchdata\"\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)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from IPython.display import Image\n",
"\n",
"sample_image = os.path.join(dataset_dir, \"images\", \"99.jpg\")\n",
"Image(filename=sample_image)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Prepare sample csv for batch endpoint inference."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import base64\n",
"import pandas as pd\n",
"import os\n",
"\n",
"sample_image = os.path.join(dataset_dir, \"images\", \"99.jpg\")\n",
"\n",
"\n",
"def read_image(image_path):\n",
" with open(image_path, \"rb\") as f:\n",
" return f.read()\n",
"\n",
"\n",
"# Convert the image to base64 and prepare the data for DataFrame\n",
"image_base64 = base64.encodebytes(read_image(sample_image)).decode(\"utf-8\")\n",
"data = [\n",
" [image_base64, \"[[[280,320]], [[300,350]]]\", \"\", \"\", False],\n",
" [image_base64, \"[[[280,320], [300,350]]]\", \"\", \"\", False],\n",
" [image_base64, \"\", \"[[125,240,375,425]]\", \"\", False],\n",
" [image_base64, \"[[[280,320]]]\", \"[[125,240,375,425]]\", \"\", False],\n",
" [image_base64, \"[[[280,320]]]\", \"[[125,240,375,425]]\", \"[[0]]\", False],\n",
"]\n",
"\n",
"# Create DataFrame\n",
"df = pd.DataFrame(\n",
" data,\n",
" columns=[\n",
" \"image\",\n",
" \"input_points\",\n",
" \"input_boxes\",\n",
" \"input_labels\",\n",
" \"multimask_output\",\n",
" ],\n",
")\n",
"\n",
"# Save DataFrame to CSV\n",
"batch_input_csv_file_path = \"sample_request_data.csv\"\n",
"df.to_csv(batch_input_csv_file_path, index=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4. Deploy the model to a 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)\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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a batch endpoint"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"from azure.ai.ml.entities import (\n",
" BatchEndpoint,\n",
" BatchDeployment,\n",
" BatchRetrySettings,\n",
")\n",
"\n",
"# Endpoint names need to be unique in a region, hence using timestamp to create unique endpoint name\n",
"timestamp = int(time.time())\n",
"endpoint_name = \"mask-gen-\" + 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 mask-generation task\",\n",
")\n",
"workspace_ml_client.begin_create_or_update(endpoint).result()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a batch deployment"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"deployment_name = \"mask-gen-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()"
]
},
{
"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 CSV input with base64 images from 3\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=batch_input_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": "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\", \"labels\", \"file_name\"],\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Visualize the results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import io\n",
"import base64\n",
"import json\n",
"from PIL import Image\n",
"\n",
"response = score_df[\"preds\"][0]\n",
"json_str = response.replace(\"'\", '\"')\n",
"data = json.loads(json_str)\n",
"encoded_mask = data[\"predictions\"][0][\"masks_per_prediction\"][0][\"encoded_binary_mask\"]\n",
"mask_iou = data[\"predictions\"][0][\"masks_per_prediction\"][0][\"iou_score\"]\n",
"\n",
"\n",
"# utility function to display the masks\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"\n",
"def show_mask(mask, ax, random_color=False):\n",
" if not isinstance(mask, np.ndarray):\n",
" mask = np.array(mask)\n",
" mask = mask > 0\n",
" if random_color:\n",
" color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n",
" else:\n",
" color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])\n",
" h, w = mask.shape[-2:]\n",
" mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n",
" ax.imshow(mask_image)\n",
"\n",
"\n",
"img = Image.open(io.BytesIO(base64.b64decode(encoded_mask)))\n",
"raw_image = Image.open(sample_image).convert(\"RGB\")\n",
"print(f\"mask_iou: {mask_iou}\")\n",
"fig, axes = plt.subplots(1, 1, figsize=(15, 15))\n",
"axes.imshow(np.array(raw_image))\n",
"show_mask(img, axes)\n",
"axes.title.set_text(f\"Score: {mask_iou:.3f}\")\n",
"axes.axis(\"off\")\n",
"plt.show()"
]
},
{
"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": {
"kernelspec": {
"display_name": "dri",
"language": "python",
"name": "dri"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}