Home

Awesome

Integration Test Lint and Test

GitHub Action for deploying Machine Learning Models to Azure

Deprecation notice

This Action is deprecated. Instead, consider using the CLI (v2) to manage and interact with Azure Machine Learning endpoints and deployments in GitHub Actions.

Important: The CLI (v2) is not recommended for production use while in preview.

Usage

The Deploy Machine Learning Models to Azure action will deploy your model on Azure Machine Learning using GitHub Actions.

Get started today with a free Azure account!

This repository contains GitHub Action for deploying Machine Learning Models to Azure Machine Learning and creates a real-time endpoint on the model to integrate models in other systems. The endpoint can be hosted either on an Azure Container Instance or on an Azure Kubernetes Service.

This GitHub Action also allows you to provide a python script that executes tests against the Webservice endpoint after the model deployment has completed successfully. You can enable tests by setting the parameter test_enabled to true. In addition to that, you have to provide a python script (default code/test/test.py) which includes a function (default def main(webservice):) that describes your tests that you want to execute against the service object. The python script gets the webservice object injected. The action fails, if the test script fails.

Dependencies on other GitHub Actions

Create Azure Machine Learning and deploy an machine learning model using GitHub Actions

This action is one in a series of actions that can be used to setup an ML Ops process. We suggest getting started with one of our template repositories, which will allow you to create an ML Ops process in less than 5 minutes.

  1. Simple template repository: ml-template-azure

    Go to this template and follow the getting started guide to setup an ML Ops process within minutes and learn how to use the Azure Machine Learning GitHub Actions in combination. This template demonstrates a very simple process for training and deploying machine learning models.

  2. Advanced template repository: mlops-enterprise-template

    This template demonstrates how approval processes can be included in the process and how training and deployment workflows can be splitted. It also shows how workflows (e.g. deployment) can be triggered from pull requests. More enhancements will be added to this template in the future to make it more enterprise ready.

Example workflow

name: My Workflow
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
    - name: Check Out Repository
      id: checkout_repository
      uses: actions/checkout@v2

    # AML Workspace Action
    - uses: Azure/aml-workspace@v1
      id: aml_workspace
      with:
        azure_credentials: ${{ secrets.AZURE_CREDENTIALS }}
    
    # AML Register Model Action
    - uses: Azure/aml-registermodel@v1
      id: aml_registermodel
      with:
        azure_credentials: ${{ secrets.AZURE_CREDENTIALS }}
        run_id:  "<your-run-id>"
        experiment_name: "<your-experiment-name>"
    
    # Deploy model in Azure Machine Learning to ACI
    - name: Deploy model
      id: aml_deploy
      uses: Azure/aml-deploy@v1
      with:
        # required inputs
        azure_credentials: ${{ secrets.AZURE_CREDENTIALS }}
        model_name:  ${{ steps.aml_registermodel.outputs.model_name }}
        model_version: ${{ steps.aml_registermodel.outputs.model_version }}
        # optional inputs
        parameters_file: "deploy.json"

Inputs

InputRequiredDefaultDescription
azure_credentialsx-Output of az ad sp create-for-rbac --name <your-sp-name> --role contributor --scopes /subscriptions/<your-subscriptionId>/resourceGroups/<your-rg> --sdk-auth. This should be stored in your secrets
model_namex-Name of the model that will be deployed. You will get it as an output of register model action as in above example workflow.
model_versionx-Version of the model that will be deployed. You will get it as an output of register model action as in above example workflow.
parameters_file"deploy.json"We expect a JSON file in the .cloud/.azure folder in root of your repository specifying your model deployment details. If you have want to provide these details in a file other than "deploy.json" you need to provide this input in the action.

azure_credentials ( Azure Credentials )

Azure credentials are required to connect to your Azure Machine Learning Workspace. These may have been created for an action you are already using in your repository, if so, you can skip the steps below.

Install the Azure CLI on your computer or use the Cloud CLI and execute the following command to generate the required credentials:

# Replace {service-principal-name}, {subscription-id} and {resource-group} with your Azure subscription id and resource group name and any name for your service principle
az ad sp create-for-rbac --name {service-principal-name} \
                         --role contributor \
                         --scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group} \
                         --sdk-auth

This will generate the following JSON output:

{
  "clientId": "<GUID>",
  "clientSecret": "<GUID>",
  "subscriptionId": "<GUID>",
  "tenantId": "<GUID>",
  (...)
}

Add this JSON output as a secret with the name AZURE_CREDENTIALS in your GitHub repository.

parameters_file (Parameters File)

The action tries to load a JSON file in the .cloud/.azure folder in your repository, which specifies details for the model deployment to your Azure Machine Learning Workspace. By default, the action expects a file with the name deploy.json. If your JSON file has a different name, you can specify it with this parameter. Note that none of these values are required and, in the absence, defaults will be created with a combination of the repo name and branch name.

A sample file can be found in this repository in the folder .cloud/.azure. There are separate parameters that are used for the ACI deployment, the AKS deployment and some that are common for both deployment options.

Common parameters
ParameterRequiredAllowed ValuesDefaultDescription
namestr<REPOSITORY_NAME>-<BRANCH_NAME>The name to give the deployed service. Must be unique to the workspace, only consist of lowercase letters, numbers, or dashes, start with a letter, and be between 3 and 32 characters long.
deployment_compute_target(for AKS deployment)strnullName of the compute target to deploy the webservice to. As Azure Container Instances has no associated ComputeTarget, leave this parameter as null to deploy to Azure Container Instances.
inference_source_directorystr"code/deploy/"The path to the folder that contains all files to create the image.
inference_entry_scriptstr"score.py"The path to a local file in your repository that contains the code to run for the image and score the data. This path is relative to the specified source directory. The python script has to define an init and a run function. A sample can be found in the template repositories.
conda_filestr"environment.yml"The path to a local file in your repository containing a conda environment definition to use for the image. This path is relative to the specified source directory.
extra_docker_file_stepsstrnullThe path to a local file in your repository containing additional Docker steps to run when setting up image. This path is relative to the specified source directory.
enable_gpuboolfalseIndicates whether to enable GPU support in the image. The GPU image must be used on Microsoft Azure Services such as Azure Container Instances, Azure Machine Learning Compute, Azure Virtual Machines, and Azure Kubernetes Service.
cuda_versionstr"9.1" if enable_gpu is set to trueThe Version of CUDA to install for images that need GPU support. The GPU image must be used on Microsoft Azure Services such as Azure Container Instances, Azure Machine Learning Compute, Azure Virtual Machines, and Azure Kubernetes Service. Supported versions are 9.0, 9.1, and 10.0.
runtimestr: "python" or "spark-py""python"The runtime to use for the image.
custom_base_imagestrnullA custom Docker image to be used as base image. If no base image is given then the base image will be used based off of given runtime parameter.
model_data_collection_enabledboolfalseWhether or not to enable model data collection for this Webservice.
authentication_enabledboolfalse for ACI, true for AKSWhether or not to enable key auth for this Webservice.
app_insights_enabledboolfalseWhether or not to enable Application Insights logging for this Webservice.
cpu_coresfloat: ]0.0, inf[0.1The number of CPU cores to allocate for this Webservice. Can be a decimal.
memory_gbfloat: ]0.0, inf[0.5The amount of memory (in GB) to allocate for this Webservice. Can be a decimal.
delete_service_after_deploymentboolfalseIndicates whether the service gets deleted after the deployment completed successfully.
tagsdict: {"<your-run-tag-key>": "<your-run-tag-value>", ...}nullDictionary of key value tags to give this Webservice.
propertiesdict: {"<your-run-tag-key>": "<your-run-tag-value>", ...}Dictionary of key value properties to give this Webservice. These properties cannot be changed after deployment, however new key value pairs can be added.
descriptionstrnullA description to give this Webservice and image.
test_enabledboolfalseWhether to run tests for this model deployment and the created real-time endpoint.
test_file_pathstr"code/test/test.py"Path to the python script in your repository in which you define your own tests that you want to run against the webservice endpoint. The GitHub Action fails, if your script fails.
test_file_function_namestr"main"Name of the function in your python script in your repository in which you define your own tests that you want to run against the webservice endpoint. The function gets the webservice object injected and allows you to run tests against the scoring uri. The GitHub Action fails, if your script fails.
profiling_enabledboolfalseWhether or not to profile this model for an optimal combination of cpu and memory. To use this functionality, you also have to provide a model profile dataset (profiling_dataset). If the parameter is not specified, the Action will try to use the sample input dataset that the model was registered with. Please, note that profiling is a long running operation and can take up to 25 minutes depending on the size of the dataset. More details can be found here.
profiling_datasetstrnullName of the dataset that should be used for model profiling.
skip_deploymentboolfalseIndicates whether the deployment to ACI or AKS should be skipped. This can be used in combination with create_image to only create a Docker image that can be used for further deployment.
create_imagestr: "docker", "function_blob", "function_http" or "function_service_bus_queue"nullIndicates whether a Docker image should be created which can be used for further deployment.

Please visit this website and this website for more details.

ACI specific parameters

ACI is the default deployment resource. A sample file for an aci deployment can be found in the .cloud/.azure folder.

ParameterRequiredAllowed ValuesDefaultDescription
locationstr: supported regionworkspace locationThe Azure region to deploy this Webservice to.
ssl_enabledboolfalseWhether or not to enable SSL for this Webservice.
ssl_cert_pem_filestrnullA file path to a file containing cert information for SSL validation. Must provide all three CName, cert file, and key file to enable SSL validation.
ssl_key_pem_filestrnullA file path to a file containing key information for SSL validation. Must provide all three CName, cert file, and key file to enable SSL validation.
ssl_cnamestrnullA CName to use if enabling SSL validation on the cluster. Must provide all three CName, cert file, and key file to enable SSL validation.
dns_name_labelstrnullThe DNS name label for the scoring endpoint. If not specified a unique DNS name label will be generated for the scoring endpoint.

Please visit this website for more details.

AKS Deployment

For the deployment of the model to AKS, you must configure an AKS resource and specify the name of the AKS cluster with the deployment_compute_target parameter. Additional parameters allow you to finetune your deployment on AKS with options like autoscaling and the liveness probe requirements. These will be set to default parameters if not provided.

ParameterRequiredAllowed ValuesDefaultDescription
gpu_coresint: [0, inf[1The number of GPU cores to allocate for this Webservice.
autoscale_enabledbooltrue if num_replicas is nullWhether to enable autoscale for this Webservice.
autoscale_min_replicasint: [1, inf[1The minimum number of containers to use when autoscaling this Webservice.
autoscale_max_replicasint: [1, inf[10The maximum number of containers to use when autoscaling this Webservice.
autoscale_refresh_secondsint: [1, inf[1How often the autoscaler should attempt to scale this Webservice (in seconds).
autoscale_target_utilizationint: [1, 100]70The target utilization (in percent out of 100) the autoscaler should attempt to maintain for this Webservice.
scoring_timeout_msint: [1, inf[60000A timeout in ms to enforce for scoring calls to this Webservice.
replica_max_concurrent_requestsint: [1, inf[1The number of maximum concurrent requests per replica to allow for this Webservice. Do not change this setting from the default value of 1 unless instructed by Microsoft Technical Support or a member of Azure Machine Learning team.
max_request_wait_timeint: [0, inf[500The maximum amount of time a request will stay in the queue (in milliseconds) before returning a 503 error.
num_replicasintnullThe number of containers to allocate for this Webservice. No default, if this parameter is not set then the autoscaler is enabled by default.
period_secondsint: [1, inf[10How often (in seconds) to perform the liveness probe.
initial_delay_secondsint: [1, inf[310The number of seconds after the container has started before liveness probes are initiated.
timeout_secondsint: [1, inf[1The number of seconds after which the liveness probe times out.
success_thresholdint: [1, inf[1The minimum consecutive successes for the liveness probe to be considered successful after having failed.
failure_thresholdint: [1, inf[3When a Pod starts and the liveness probe fails, Kubernetes will try failureThreshold times before giving up.
namespacestrnullThe Kubernetes namespace in which to deploy this Webservice: up to 63 lowercase alphanumeric ('a'-'z', '0'-'9') and hyphen ('-') characters. The first and last characters cannot be hyphens.
token_auth_enabledboolfalseWhether to enable Token authentication for this Webservice. If this is enabled, users can access this Webservice by fetching an access token using their Azure Active Directory credentials.

Please visit this website for more details. More Information on autoscaling parameters can be found here and for liveness probe here.

Outputs

OutputDescription
service_scoring_uriScoring URI of the webservice that was created (only provided if delete_service_after_deployment is set to False).
service_swagger_uriSwagger Uri of the webservice that was created (only provided if delete_service_after_deployment is set to False).
acr_addressThe DNS name or IP address (e.g. myacr.azurecr.io) of the Azure Container Registry (ACR) (only provided if create_image is not None).
acr_usernameThe username for ACR (only provided if create_image is not None).
acr_passwordThe password for ACR (only provided if create_image is not None).
package_locationFull URI of the docker image (e.g. myacr.azurecr.io/azureml/azureml_*) (only provided if create_image is not None).
profiling_detailsDictionary of details of the model profiling result. This will only be provided, if the model profiling method is used and successfully executed.

Environment variables

Certain parameters are considered secrets and should therefore be passed as environment variables from your secrets, if you want to use custom values.

Environment variableRequiredAllowed ValuesDefaultDescription
CONTAINER_REGISTRY_ADRESSstrnullThe DNS name or IP address of the Azure Container Registry (ACR). Required, if you specified a custom_base_image that is only available in your ACR.
CONTAINER_REGISTRY_USERNAMEstrnullThe username for ACR. Required, if you specified a custom_base_image that is only available in your ACR.
CONTAINER_REGISTRY_PASSWORDstrnullThe password for ACR. Required, if you specified a custom_base_image that is only available in your ACR.
PRIMARY_KEYstrnullA primary auth key to use for this Webservice. If not specified, Azure will automatically assign a key.
SECONDARY_KEYstrnullA secondary auth key to use for this Webservice. If not specified, Azure will automatically assign a key.
CMK_VAULT_BASE_URLstrnullCustomer managed Key Vault base url. This value is ACI specific.
CMK_KEY_NAMEstrnullCustomer managed key name. This value is ACI specific.
CMK_KEY_VERSIONstrnullCustomer managed key version. This value is ACI specific.

Other Azure Machine Learning Actions

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.