|
| 1 | +--- |
| 2 | +title: 'Author scoring scripts for batch deployments' |
| 3 | +titleSuffix: Azure Machine Learning |
| 4 | +description: In this article, learn how to author scoring scripts to perform batch inference in batch deployments. |
| 5 | +services: machine-learning |
| 6 | +ms.service: machine-learning |
| 7 | +ms.subservice: mlops |
| 8 | +ms.topic: conceptual |
| 9 | +author: santiagxf |
| 10 | +ms.author: fasantia |
| 11 | +ms.reviewer: larryfr |
| 12 | +ms.date: 11/03/2022 |
| 13 | +ms.custom: how-to |
| 14 | +--- |
| 15 | + |
| 16 | +# Author scoring scripts for batch deployments |
| 17 | + |
| 18 | +[!INCLUDE [cli v2](../../../includes/machine-learning-dev-v2.md)] |
| 19 | + |
| 20 | +Batch endpoints allow you to deploy models to perform inference at scale. Because how inference should be executed varies from model's format, model's type and use case, batch endpoints require a scoring script (also known as batch driver script) to indicate the deployment how to use the model over the provided data. In this article you will learn how to use scoring scripts in different scenarios and their best practices. |
| 21 | + |
| 22 | +> [!TIP] |
| 23 | +> MLflow models don't require a scoring script as it is autogenerated for you. For more details about how batch endpoints work with MLflow models, see the dedicated tutorial [Using MLflow models in batch deployments](how-to-mlflow-batch.md). Notice that this feature doesn't prevent you from writing an specific scoring script for MLflow models as explained at [Using MLflow models with a scoring script](how-to-mlflow-batch.md#using-mlflow-models-with-a-scoring-script). |
| 24 | +
|
| 25 | +> [!WARNING] |
| 26 | +> If you are deploying an Automated ML model under a batch endpoint, notice that the scoring script that Automated ML provides only works for Online Endpoints and it is not designed for batch execution. Please follow this guideline to learn how to create one depending on what your model does. |
| 27 | +
|
| 28 | +## Understanding the scoring script |
| 29 | + |
| 30 | +The scoring script is a Python file (`.py`) that contains the logic about how to run the model and read the input data submitted by the batch deployment executor driver. Each model deployment has to provide a scoring script, however, an endpoint may host multiple deployments using different scoring script versions. |
| 31 | + |
| 32 | +The scoring script must contain two methods: |
| 33 | + |
| 34 | +#### The `init` method |
| 35 | + |
| 36 | +Use the `init()` method for any costly or common preparation. For example, use it to load the model into a global object. This function will be called once at the beginning of the process. You model's files will be available in an environment variable called `AZUREML_MODEL_DIR`. Use this variable to locate the files associated with the model. |
| 37 | + |
| 38 | +```python |
| 39 | +def init(): |
| 40 | + global model |
| 41 | + |
| 42 | + # AZUREML_MODEL_DIR is an environment variable created during deployment |
| 43 | + # The path "model" is the name of the registered model's folder |
| 44 | + model_path = os.path.join(os.environ["AZUREML_MODEL_DIR"], "model") |
| 45 | + |
| 46 | + # load the model |
| 47 | + model = load_model(model_path) |
| 48 | +``` |
| 49 | + |
| 50 | +Notice that in this example we are placing the model in a global variable `model`. Use global variables to make available any asset needed to perform inference to your scoring function. |
| 51 | + |
| 52 | +#### The `run` method |
| 53 | + |
| 54 | +Use the `run(mini_batch: List[str]) -> Union[List[Any], pandas.DataFrame]` method to perform the scoring of each mini-batch generated by the batch deployment. Such method will be called once per each `mini_batch` generated for your input data. Batch deployments read data in batches accordingly to how the deployment is configured. |
| 55 | + |
| 56 | +```python |
| 57 | +def run(mini_batch): |
| 58 | + results = [] |
| 59 | + |
| 60 | + for file in mini_batch: |
| 61 | + (...) |
| 62 | + |
| 63 | + return pd.DataFrame(results) |
| 64 | +``` |
| 65 | + |
| 66 | +The method receives a list of file paths as a parameter (`mini_batch`). You can use this list to either iterate over each file and process it one by one, or to read the entire batch and process it at once. The best option will depend on your compute memory and the throughput you need to achieve. For an example of how to read entire batches of data at once see [High throughput deployments](how-to-image-processing-batch.md#high-throughput-deployments). |
| 67 | + |
| 68 | +> [!NOTE] |
| 69 | +> __How is work distributed?__: |
| 70 | +> |
| 71 | +> Batch deployments distribute work at the file level, which means that a folder containing 100 files with mini-batches of 10 files will generate 10 batches of 10 files each. Notice that this will happen regardless of the size of the files involved. If your files are too big to be processed in large mini-batches we suggest to either split the files in smaller files to achieve a higher level of parallelism or to decrease the number of files per mini-batch. At this moment, batch deployment can't account for skews in the file's size distribution. |
| 72 | +
|
| 73 | +The `run()` method should return a pandas DataFrame or an array/list. Each returned output element indicates one successful run of an input element in the input `mini_batch`. For file datasets, each row/element will represent a single file processed. For a tabular dataset, each row/element will represent a row in a processed file. |
| 74 | + |
| 75 | +> [!IMPORTANT] |
| 76 | +> __How to write predictions?__: |
| 77 | +> |
| 78 | +> Use __arrays__ when you need to output a single prediction. Use __pandas DataFrames__ when you need to return multiple pieces of information. For instance, for tabular data, you may want to append your predictions to the original record. Use a pandas DataFrame for this case. For file datasets, __we still recommend to output a pandas DataFrame__ as they provide a more robust approach to read the results. |
| 79 | +> |
| 80 | +> Although pandas DataFrame may contain column names, they are not included in the output file. If needed, please see [Customize outputs in batch deployments](how-to-deploy-model-custom-output.md). |
| 81 | +
|
| 82 | +> [!WARNING] |
| 83 | +> Do not not output complex data types (or lists of complex data types) in the `run` function. Those outputs will be transformed to string and they will be hard to read. |
| 84 | +
|
| 85 | +The resulting DataFrame or array is appended to the output file indicated. There's no requirement on the cardinality of the results (1 file can generate 1 or many rows/elements in the output). All elements in the result DataFrame or array will be written to the output file as-is (considering the `output_action` isn't `summary_only`). |
| 86 | + |
| 87 | +## Writing predictions in a different way |
| 88 | + |
| 89 | +By default, the batch deployment will write the model's predictions in a single file as indicated in the deployment. However, there are some cases where you need to write the predictions in multiple files. For instance, if the input data is partitioned, you typically would want to generate your output partitioned too. On those cases you can [Customize outputs in batch deployments](how-to-deploy-model-custom-output.md) to indicate: |
| 90 | + |
| 91 | +> [!div class="checklist"] |
| 92 | +> * The file format used (CSV, parquet, json, etc). |
| 93 | +> * The way data is partitioned in the output. |
| 94 | +
|
| 95 | +Read the article [Customize outputs in batch deployments](how-to-deploy-model-custom-output.md) for an example about how to achieve it. |
| 96 | + |
| 97 | +## Source control of scoring scripts |
| 98 | + |
| 99 | +It is highly advisable to put scoring scripts under source control. |
| 100 | + |
| 101 | +## Best practices for writing scoring scripts |
| 102 | + |
| 103 | +When writing scoring scripts that work with big amounts of data, you need to take into account several factors, including: |
| 104 | + |
| 105 | +* The size of each file. |
| 106 | +* The amount of data on each file. |
| 107 | +* The amount of memory required to read each file. |
| 108 | +* The amount of memory required to read an entire batch of files. |
| 109 | +* The memory footprint of the model. |
| 110 | +* The memory footprint of the model when running over the input data. |
| 111 | +* The available memory in your compute. |
| 112 | + |
| 113 | +Batch deployments distribute work at the file level, which means that a folder containing 100 files with mini-batches of 10 files will generate 10 batches of 10 files each. Notice that this will happen regardless of the size of the files involved. If your files are too big to be processed in large mini-batches we suggest to either split the files in smaller files to achieve a higher level of parallelism or to decrease the number of files per mini-batch. At this moment, batch deployment can't account for skews in the file's size distribution. |
| 114 | + |
| 115 | +### Running inference at the mini-batch, file or the row level |
| 116 | + |
| 117 | +Batch endpoints will call the `run()` function in your scoring script once per mini-batch. However, you will have the power to decide if you want to run the inference over the entire batch, over one file at a time, or over one row at a time (if your data happens to be tabular). |
| 118 | + |
| 119 | +#### Mini-batch level |
| 120 | + |
| 121 | +You will typically want to run inference over the batch all at once when you want to achieve high throughput in your batch scoring process. This is the case for instance if you run inference over a GPU where you want to achieve saturation of the inference device. You may also be relying on a data loader that can handle the batching itself if data doesn't fit on memory, like `TensorFlow` or `PyTorch` data loaders. On those cases, you may want to consider running inference on the entire batch. |
| 122 | + |
| 123 | +> [!WARNING] |
| 124 | +> Running inference at the batch level may require having high control over the input data size to be able to correctly account for the memory requirements and avoid out of memory exceptions. Whether you are able or not of loading the entire mini-batch in memory will depend on the size of the mini-batch, the size of the instances in the cluster, the number of workers on each node, and the size of the mini-batch. |
| 125 | +
|
| 126 | +For an example about how to achieve it see [High throughput deployments](how-to-image-processing-batch.md#high-throughput-deployments). |
| 127 | + |
| 128 | +#### File level |
| 129 | + |
| 130 | +One of the easiest ways to perform inference is by iterating over all the files in the mini-batch and run your model over it. In some cases, like image processing, this may be a good idea. If your data is tabular, you may need to make a good estimation about the number of rows on each file to estimate if your model is able to handle the memory requirements to not just load the entire data into memory but also to perform inference over it. Remember that some models (specially those based on recurrent neural networks) will unfold and present a memory footprint that may not be linear with the number of rows. If your model is expensive in terms of memory, please consider running inference at the row level. |
| 131 | + |
| 132 | +> [!TIP] |
| 133 | +> If file sizes are too big to be readed even at once, please consider breaking down files into multiple smaller files to account for better parallelization. |
| 134 | +
|
| 135 | +For an example about how to achieve it see [Image processing with batch deployments](how-to-image-processing-batch.md). |
| 136 | + |
| 137 | +#### Row level (tabular) |
| 138 | + |
| 139 | +For models that present challenges in the size of their inputs, you may want to consider running inference at the row level. Your batch deployment will still provide your scoring script with a mini-batch of files, however, you will read one file, one row at a time. This may look inefficient but for some deep learning models may be the only way to perform inference without scaling up your hardware requirements. |
| 140 | + |
| 141 | +For an example about how to achieve it see [Text processing with batch deployments](how-to-nlp-processing-batch.md). |
| 142 | + |
| 143 | +### Relationship between the degree of parallelism and the scoring script |
| 144 | + |
| 145 | +Your deployment configuration controls the size of each mini-batch and the number of workers on each node. Take into account them when deciding if you want to read the entire mini-batch to perform inference. When running multiple workers on the same instance, take into account that memory will be shared across all the workers. Usually, increasing the number of workers per node should be accompanied by a decrease in the mini-batch size or by a change in the scoring strategy (if data size remains the same). |
| 146 | + |
| 147 | +## Next steps |
| 148 | + |
| 149 | +* [Troubleshooting batch endpoints](how-to-troubleshoot-batch-endpoints.md). |
| 150 | +* [Use MLflow models in batch deployments](how-to-mlflow-batch.md). |
| 151 | +* [Image processing with batch deployments](how-to-image-processing-batch.md). |
0 commit comments