Table of Contents

    Deploying ML Model on Cloud

    Model Deployment

    Deploying ML Model on Cloud

    Learn how to deploy an approved Machine Learning model to a cloud environment using versioned artifacts, reproducible environments, scoring code, managed endpoints, secure access, gradual traffic rollout, automated testing, monitoring, scaling, cost controls, fallback, rollback, and responsible operational practices.

    Introduction

    Cloud deployment makes a trained Machine Learning model available through infrastructure hosted and managed in a cloud environment. Applications, scheduled jobs, business workflows, and authorized services can submit new data and receive model predictions.

    A cloud deployment is not only an uploaded model file. A complete deployment includes the approved model artifact, preprocessing, runtime environment, scoring logic, compute resources, endpoint, authentication, network controls, logs, metrics, scaling rules, release strategy, and rollback procedure.

    This lesson uses Azure Machine Learning managed online endpoints as the primary implementation example. The architectural principles also apply to managed Machine Learning services, container platforms, serverless services, and Kubernetes-based deployments on other cloud platforms.

    Lesson goal: Deploy a versioned Machine Learning model as a controlled cloud prediction service and operate it safely throughout its lifecycle.

    Learning Objectives

    By the End of This Lesson

    • Explain cloud-based Machine Learning deployment
    • Identify the components of a cloud inference system
    • Compare managed endpoints, containers, serverless services, and Kubernetes
    • Distinguish online and batch cloud endpoints
    • Prepare a model artifact and inference environment
    • Create model initialization and scoring logic
    • Register a model in Azure Machine Learning
    • Create a managed online endpoint
    • Create and validate an endpoint deployment
    • Send authenticated inference requests
    • Create multiple deployment versions
    • Allocate traffic between deployments
    • Use shadow or mirrored traffic where supported
    • Configure health checks and deployment probes
    • Understand identity, authorization, and network controls
    • Monitor availability, latency, errors, inputs, and predictions
    • Apply scaling and cost-management controls
    • Plan fallback and rollback
    • Apply responsible-AI requirements
    • Create a cloud deployment-readiness checklist

    Prerequisites

    Recommended Knowledge

    • Python programming
    • Machine Learning model evaluation
    • Saving and loading models
    • scikit-learn pipelines
    • Flask or FastAPI fundamentals
    • REST APIs and JSON
    • Command-line usage
    • Git and source control
    • Docker fundamentals
    • Basic cloud-computing concepts
    • Identity and access-control fundamentals

    Example Packages

    • azure-ai-ml
    • azure-identity
    • pandas
    • NumPy
    • scikit-learn
    • Joblib
    python -m pip install azure-ai-ml azure-identity pandas numpy scikit-learn joblib
    Cloud requirement: Use an approved cloud subscription, resource group, workspace, identity, region, quota, and access policy. Do not place cloud credentials directly in source code.

    What Is Cloud Model Deployment?

    Cloud model deployment places an approved model and its inference dependencies in a cloud-hosted environment capable of receiving input and producing predictions.

    Cloud Inference Flow
    Authorized Client → Cloud Endpoint → Input Validation → Model Runtime → Prediction → Response and Monitoring
    Component Responsibility
    Model Artifact Contains the approved fitted inference behavior
    Environment Defines runtime libraries and system dependencies
    Scoring Code Loads the artifact, validates input, and generates output
    Compute Provides CPU, memory, accelerator, and network resources
    Endpoint Provides the stable interface used by clients
    Deployment Connects a model version, environment, code, and compute configuration
    Identity Controls which clients and services may access resources
    Monitoring Tracks service, data, prediction, and outcome behavior

    Online vs Batch Endpoints

    Area Online Endpoint Batch Endpoint
    Purpose Provides near-real-time predictions Processes collections of records as jobs
    Invocation Application or service request Schedule, pipeline, or job request
    Latency Usually optimized for shorter response time Completion may take longer
    Input One or a small group of records Files, tables, folders, or large record collections
    Output Immediate response Stored output or job result
    Scaling Responds to request traffic Allocates compute for submitted jobs
    Example Churn probability requested by an application Nightly scoring of all eligible customers
    Selection rule: Do not create a continuously available online endpoint when a scheduled batch workflow satisfies the business requirement more simply and economically.

    Cloud Deployment Options

    Deployment Option General Characteristics
    Managed ML Endpoint Cloud platform manages significant serving infrastructure
    Managed Container Service Runs a custom inference container with managed orchestration
    Serverless Service Executes request-driven inference with managed infrastructure
    Kubernetes Provides greater control over orchestration, networking, and scaling
    Virtual Machine Provides direct control with greater operational responsibility
    Edge Deployment Runs inference close to the device or data source
    Architecture decision: Evaluate latency, traffic, availability, model size, hardware, networking, data location, governance, team capability, and total cost before choosing the deployment target.

    Cloud Deployment Lifecycle

    Deployment Lifecycle
    Evaluate → Register → Package → Deploy → Test → Release → Monitor → Improve or Roll Back

    Recommended Project Structure

    cloud-ml-deployment/
    ├── README.md
    ├── requirements.txt
    ├── .gitignore
    ├── artifacts/
    │   ├── customer_churn_pipeline.joblib
    │   └── model_metadata.json
    ├── cloud/
    │   ├── endpoint.yml
    │   ├── deployment-blue.yml
    │   ├── deployment-green.yml
    │   └── environment.yml
    ├── src/
    │   ├── register_model.py
    │   ├── deploy_endpoint.py
    │   ├── test_endpoint.py
    │   └── score.py
    ├── sample-data/
    │   └── request.json
    └── tests/
        ├── test_scoring.py
        ├── test_contract.py
        └── test_deployment.py

    Prepare the Model Artifact

    Artifact Requirements

    • The final model passed independent evaluation
    • Fitted preprocessing is included
    • Feature order is preserved
    • Class mappings are documented
    • The decision threshold is approved
    • The input and output contracts are documented
    • Dependency versions are recorded
    • The model version is immutable
    • An artifact checksum is recorded
    • Intended and prohibited uses are documented
    Incomplete Package Upload only the estimator while preprocessing and threshold logic remain in a notebook.
    Complete Package Register the complete fitted inference pipeline and preserve the metadata required to interpret its output.

    Connect to Azure Machine Learning

    from azure.ai.ml import MLClient
    from azure.identity import DefaultAzureCredential
    
    
    subscription_id = (
        "replace-with-subscription-id"
    )
    
    
    resource_group_name = (
        "replace-with-resource-group"
    )
    
    
    workspace_name = (
        "replace-with-workspace-name"
    )
    
    
    credential = DefaultAzureCredential()
    
    
    ml_client = MLClient(
        credential=credential,
        subscription_id=subscription_id,
        resource_group_name=(
            resource_group_name
        ),
        workspace_name=workspace_name
    )
    
    
    workspace = ml_client.workspaces.get(
        workspace_name
    )
    
    
    print(
        workspace.name
    )
    Credential rule: Use approved identity mechanisms and role assignments. Do not store client secrets, access keys, or service credentials in notebooks or source files.

    Register the Model

    from azure.ai.ml.entities import Model
    from azure.ai.ml.constants import AssetTypes
    
    
    model_asset = Model(
        path=(
            "artifacts/"
            "customer_churn_pipeline.joblib"
        ),
        type=AssetTypes.CUSTOM_MODEL,
        name="customer-churn-pipeline",
        description=(
            "Approved customer-churn "
            "classification pipeline"
        ),
        tags={
            "project": "customer-churn",
            "framework": "scikit-learn",
            "intended_use": (
                "retention-review-prioritization"
            )
        }
    )
    
    
    registered_model = (
        ml_client.models.create_or_update(
            model_asset
        )
    )
    
    
    print(
        registered_model.name
    )
    
    
    print(
        registered_model.version
    )
    Registration principle: Model registration creates a versioned cloud asset. It does not by itself make the model available for prediction.

    Define the Inference Environment

    name: customer-churn-inference
    
    channels:
      - conda-forge
    
    dependencies:
      - python=3.12
      - pip
      - pip:
          - azureml-inference-server-http
          - pandas
          - numpy
          - scikit-learn
          - joblib

    Environment Review

    • Use tested package versions
    • Include only required inference dependencies
    • Review dependency vulnerabilities
    • Use an approved base image
    • Test artifact loading in the same environment
    • Record environment and image versions
    • Rebuild when security or compatibility requires it

    Create the Scoring Script

    Azure Machine Learning scoring code commonly provides an initialization function and a request-processing function. The model should load once during initialization rather than during each request.

    import json
    import os
    from pathlib import Path
    
    import joblib
    import pandas as pd
    
    
    model = None
    
    
    required_features = [
        "tenure_months",
        "monthly_charges",
        "total_charges",
        "contract_type",
        "payment_method",
        "tech_support"
    ]
    
    
    decision_threshold = 0.60
    
    
    def init():
        global model
    
        model_directory = Path(
            os.getenv(
                "AZUREML_MODEL_DIR"
            )
        )
    
        model_files = list(
            model_directory.rglob(
                "*.joblib"
            )
        )
    
        if len(model_files) != 1:
    
            raise RuntimeError(
                "Exactly one Joblib model "
                "artifact is required."
            )
    
        model = joblib.load(
            model_files[0]
        )
    
    
    def run(
        raw_data
    ):
        if model is None:
    
            raise RuntimeError(
                "The model is not initialized."
            )
    
        payload = json.loads(
            raw_data
        )
    
        records = payload.get(
            "records"
        )
    
        if not isinstance(
            records,
            list
        ) or not records:
    
            raise ValueError(
                "records must be a non-empty array."
            )
    
        validated_records = [
            validate_record(
                record
            )
            for record in records
        ]
    
        input_frame = pd.DataFrame(
            validated_records
        )[
            required_features
        ]
    
        probabilities = model.predict_proba(
            input_frame
        )[:, 1]
    
        predictions = []
    
        for probability in probabilities:
    
            probability = float(
                probability
            )
    
            predictions.append(
                {
                    "predicted_class": (
                        "churned"
                        if probability
                        >=
                        decision_threshold
                        else "retained"
                    ),
                    "positive_class_probability": (
                        probability
                    ),
                    "retention_review_recommended": (
                        probability
                        >=
                        decision_threshold
                    )
                }
            )
    
        return {
            "predictions": predictions,
            "prediction_count": len(
                predictions
            ),
            "decision_threshold": (
                decision_threshold
            )
        }

    Validate Inference Records

    import math
    
    
    allowed_categories = {
        "contract_type": {
            "Monthly",
            "One year",
            "Two year"
        },
        "payment_method": {
            "Electronic",
            "Bank transfer",
            "Credit card",
            "Mailed check"
        },
        "tech_support": {
            "Yes",
            "No"
        }
    }
    
    
    def validate_record(
        record
    ):
        if not isinstance(
            record,
            dict
        ):
    
            raise ValueError(
                "Each record must be an object."
            )
    
        missing_features = (
            set(required_features)
            - set(record)
        )
    
        unexpected_features = (
            set(record)
            - set(required_features)
        )
    
        if missing_features:
    
            raise ValueError(
                "Missing features: "
                f"{sorted(missing_features)}"
            )
    
        if unexpected_features:
    
            raise ValueError(
                "Unexpected features: "
                f"{sorted(unexpected_features)}"
            )
    
        validated_record = {}
    
        for feature_name in [
            "tenure_months",
            "monthly_charges",
            "total_charges"
        ]:
            value = record[
                feature_name
            ]
    
            if isinstance(
                value,
                bool
            ) or not isinstance(
                value,
                (
                    int,
                    float
                )
            ):
                raise ValueError(
                    f"{feature_name} must be numeric."
                )
    
            value = float(
                value
            )
    
            if not math.isfinite(
                value
            ):
    
                raise ValueError(
                    f"{feature_name} must be finite."
                )
    
            if value < 0:
    
                raise ValueError(
                    f"{feature_name} cannot be negative."
                )
    
            validated_record[
                feature_name
            ] = value
    
        for feature_name, allowed_values in (
            allowed_categories.items()
        ):
            value = record[
                feature_name
            ]
    
            if value not in allowed_values:
    
                raise ValueError(
                    f"{feature_name} contains "
                    "an unsupported value."
                )
    
            validated_record[
                feature_name
            ] = value
    
        return validated_record
    Validation principle: Reject invalid cloud inference requests rather than silently changing values or generating potentially misleading predictions.

    Create the Managed Online Endpoint

    import uuid
    
    from azure.ai.ml.entities import (
        ManagedOnlineEndpoint
    )
    
    
    endpoint_name = (
        "churn-endpoint-"
        + uuid.uuid4().hex[:8]
    )
    
    
    endpoint = ManagedOnlineEndpoint(
        name=endpoint_name,
        description=(
            "Managed endpoint for approved "
            "customer-churn inference"
        ),
        auth_mode="key",
        tags={
            "project": "customer-churn",
            "environment": "development"
        }
    )
    
    
    endpoint_operation = (
        ml_client.online_endpoints
        .begin_create_or_update(
            endpoint
        )
    )
    
    
    created_endpoint = (
        endpoint_operation.result()
    )
    
    
    print(
        created_endpoint.name
    )
    Endpoint-name note: The generated suffix reduces name collisions in this learning example. Apply your organization's naming, tagging, region, and resource-governance standards.

    Create the First Deployment

    from azure.ai.ml.entities import (
        CodeConfiguration
    )
    from azure.ai.ml.entities import Environment
    from azure.ai.ml.entities import (
        ManagedOnlineDeployment
    )
    
    
    inference_environment = Environment(
        name=(
            "customer-churn-inference"
        ),
        description=(
            "Environment for customer-churn "
            "online inference"
        ),
        conda_file=(
            "cloud/environment.yml"
        ),
        image=(
            "mcr.microsoft.com/"
            "azureml/openmpi4.1.0-ubuntu22.04"
        )
    )
    
    
    blue_deployment = (
        ManagedOnlineDeployment(
            name="blue",
            endpoint_name=endpoint_name,
            model=registered_model,
            environment=(
                inference_environment
            ),
            code_configuration=(
                CodeConfiguration(
                    code="src",
                    scoring_script="score.py"
                )
            ),
            instance_type=(
                "Standard_DS3_v2"
            ),
            instance_count=1
        )
    )
    
    
    deployment_operation = (
        ml_client.online_deployments
        .begin_create_or_update(
            blue_deployment
        )
    )
    
    
    created_deployment = (
        deployment_operation.result()
    )
    
    
    print(
        created_deployment.name
    )
    Compute placeholder: The instance type is an example configuration. Select compute according to approved regional availability, quota, measured memory, latency, throughput, accelerator, and cost requirements.

    Configure Deployment Probes

    from azure.ai.ml.entities import (
        ProbeSettings
    )
    
    
    blue_deployment.liveness_probe = (
        ProbeSettings(
            initial_delay=10,
            period=10,
            timeout=2,
            failure_threshold=30
        )
    )
    
    
    blue_deployment.readiness_probe = (
        ProbeSettings(
            initial_delay=10,
            period=10,
            timeout=2,
            failure_threshold=30
        )
    )
    Probe Purpose
    Liveness Determines whether the serving process should be restarted
    Readiness Determines whether the instance should receive inference traffic
    Startup Delay Allows time for dependencies and large artifacts to initialize
    Probe configuration: Select timings from measured startup and inference behavior. Values that are too strict can cause unnecessary restarts, while values that are too permissive can delay failure detection.

    Allocate Endpoint Traffic

    endpoint.traffic = {
        "blue": 100
    }
    
    
    traffic_operation = (
        ml_client.online_endpoints
        .begin_create_or_update(
            endpoint
        )
    )
    
    
    traffic_operation.result()
    Release caution: Do not allocate production traffic until deployment logs, readiness, contract tests, smoke tests, security controls, and approval gates have passed.

    Create a Sample Request

    {
        "records": [
            {
                "tenure_months": 18,
                "monthly_charges": 64.5,
                "total_charges": 1161.0,
                "contract_type": "Monthly",
                "payment_method": "Electronic",
                "tech_support": "No"
            }
        ]
    }
    Synthetic-input notice: The request values are invented for endpoint testing and do not identify or describe a real customer.

    Invoke the Deployment

    response = (
        ml_client.online_endpoints.invoke(
            endpoint_name=endpoint_name,
            deployment_name="blue",
            request_file=(
                "sample-data/request.json"
            )
        )
    )
    
    
    print(
        response
    )
    Direct deployment testing: Test a specific deployment before sending endpoint traffic to it. This helps separate deployment validation from traffic-routing behavior.

    Review Deployment Logs

    deployment_logs = (
        ml_client.online_deployments
        .get_logs(
            name="blue",
            endpoint_name=endpoint_name,
            lines=100
        )
    )
    
    
    print(
        deployment_logs
    )

    Review Logs For

    • Model artifact discovery failures
    • Dependency import failures
    • Scoring-script syntax errors
    • Model deserialization errors
    • Input-schema failures
    • Memory exhaustion
    • Probe failures
    • Unexpected inference exceptions
    Privacy rule: Do not write complete customer records, credentials, access tokens, or sensitive feature values to deployment logs.

    Invoke the Endpoint Through HTTPS

    import requests
    
    
    endpoint_details = (
        ml_client.online_endpoints.get(
            endpoint_name
        )
    )
    
    
    endpoint_credentials = (
        ml_client.online_endpoints
        .get_keys(
            endpoint_name
        )
    )
    
    
    with open(
        "sample-data/request.json",
        "r",
        encoding="utf-8"
    ) as request_file:
    
        request_payload = request_file.read()
    
    
    response = requests.post(
        endpoint_details.scoring_uri,
        headers={
            "Authorization": (
                "Bearer "
                + endpoint_credentials.primary_key
            ),
            "Content-Type": "application/json"
        },
        data=request_payload,
        timeout=30
    )
    
    
    response.raise_for_status()
    
    
    print(
        response.json()
    )
    Key-handling rule: The example demonstrates the request structure. Never print, commit, or persist endpoint keys in source files or notebooks. Prefer approved identity-based authentication where required.

    Cloud Identity and Authorization

    Control Purpose
    User Identity Identifies administrators, developers, and reviewers
    Workload Identity Identifies calling applications and cloud services
    Role-Based Access Limits management and invocation permissions
    Managed Identity Allows supported services to obtain credentials without embedded secrets
    Secret Store Protects credentials that cannot be eliminated
    Audit Records Tracks management and access activity
    Credential Rotation Limits the lifetime of exposed credentials
    Unsafe Practice Store endpoint keys in Python files, notebooks, Docker images, or repository variables visible to unauthorized users.
    Required Practice Use managed identities, approved secret storage, minimum permissions, credential rotation, and auditable access.

    Network Security

    Network Review Questions

    • Should the endpoint be public or private?
    • Which networks and applications require access?
    • Is private connectivity required?
    • Are inbound and outbound paths restricted?
    • Are domain-name and certificate requirements defined?
    • Are dependencies available through approved routes?
    • Are data-transfer locations permitted?
    • Are network logs and alerts enabled?
    • Is denial-of-service protection required?
    Network principle: Expose only the connectivity required by approved clients and dependencies. Private data should not be made public merely to simplify deployment.

    Create a Candidate Deployment

    green_deployment = (
        ManagedOnlineDeployment(
            name="green",
            endpoint_name=endpoint_name,
            model=(
                candidate_registered_model
            ),
            environment=(
                inference_environment
            ),
            code_configuration=(
                CodeConfiguration(
                    code="src",
                    scoring_script="score.py"
                )
            ),
            instance_type=(
                "Standard_DS3_v2"
            ),
            instance_count=1
        )
    )
    
    
    green_operation = (
        ml_client.online_deployments
        .begin_create_or_update(
            green_deployment
        )
    )
    
    
    green_operation.result()
    Candidate requirement: A new deployment should reference an explicitly evaluated and registered model version. Do not overwrite the currently approved artifact.

    Canary Traffic Allocation

    endpoint.traffic = {
        "blue": 90,
        "green": 10
    }
    
    
    canary_operation = (
        ml_client.online_endpoints
        .begin_create_or_update(
            endpoint
        )
    )
    
    
    canary_operation.result()
    Synthetic allocation: The percentages demonstrate configuration syntax. Select production allocation using an approved rollout plan, risk assessment, monitoring capability, and rollback criteria.

    Cloud Rollout Strategies

    Strategy Approach Main Consideration
    Direct Replacement Move all traffic to the new deployment Simple but creates broader immediate exposure
    Blue-Green Maintain old and new deployments and switch traffic Requires additional temporary capacity
    Canary Send a controlled share of traffic to the candidate Requires version-specific monitoring
    Shadow Send production-like input to the candidate without using its output Requires careful privacy, cost, and comparison controls
    A/B Experiment Assign eligible traffic through an experimental design Requires valid outcome measurement and governance

    Roll Back Traffic

    endpoint.traffic = {
        "blue": 100,
        "green": 0
    }
    
    
    rollback_operation = (
        ml_client.online_endpoints
        .begin_create_or_update(
            endpoint
        )
    )
    
    
    rollback_operation.result()

    Possible Rollback Triggers

    • Security incident
    • Elevated request failures
    • Unacceptable latency
    • Schema incompatibility
    • Memory or compute instability
    • Material prediction-quality degradation
    • Harmful or unequal outcomes
    • Incorrect downstream integration

    Scaling the Deployment

    Scaling Area Question
    Instance Size How much CPU, memory, or accelerator capacity does one replica require?
    Minimum Instances What baseline availability and latency are required?
    Maximum Instances What cost and quota boundaries apply?
    Scale Metric Which load or resource signal should trigger scaling?
    Scale Delay How quickly can a new instance load the model and become ready?
    Concurrency How many requests can one instance process reliably?
    Peak Traffic Which realistic burst patterns must be handled?
    Capacity principle: Determine cloud compute and scaling settings through representative load tests. A larger instance or additional replicas do not automatically improve every workload.

    Cloud Deployment Testing

    Test Type Purpose
    Local Scoring Test Validates artifact loading and scoring code before cloud deployment
    Schema Test Validates accepted and rejected request structures
    Smoke Test Confirms basic endpoint operation after deployment
    Prediction-Consistency Test Compares cloud and approved offline model results
    Authentication Test Confirms unauthorized clients are rejected
    Load Test Measures latency, throughput, resources, and failures
    Failure Test Validates behavior during dependency and instance failures
    Rollback Test Confirms restoration of the previous approved deployment
    Security Test Reviews identities, permissions, network, images, and secrets

    Test Prediction Consistency

    import json
    import joblib
    import numpy as np
    import pandas as pd
    
    
    local_model = joblib.load(
        "artifacts/customer_churn_pipeline.joblib"
    )
    
    
    with open(
        "sample-data/request.json",
        "r",
        encoding="utf-8"
    ) as request_file:
    
        request_payload = json.load(
            request_file
        )
    
    
    records = request_payload[
        "records"
    ]
    
    
    local_probabilities = (
        local_model.predict_proba(
            pd.DataFrame(
                records
            )[
                required_features
            ]
        )[:, 1]
    )
    
    
    cloud_response = json.loads(
        response
    )
    
    
    cloud_probabilities = np.array(
        [
            item[
                "positive_class_probability"
            ]
            for item in cloud_response[
                "predictions"
            ]
        ]
    )
    
    
    np.testing.assert_allclose(
        local_probabilities,
        cloud_probabilities,
        rtol=1e-8,
        atol=1e-10
    )
    
    
    print(
        "Cloud predictions match "
        "the approved local pipeline."
    )
    Equivalence testing: Use representative approved inputs and documented numerical tolerances. Do not assume that successful endpoint invocation proves equivalent prediction behavior.

    Cloud Monitoring

    Monitoring Area Example Measure
    Availability Successful endpoint and probe responses
    Latency Request, queue, preprocessing, and inference duration
    Errors Authentication, validation, timeout, scoring, and server failures
    Traffic Request and record volume by deployment version
    Resource Use CPU, memory, accelerator, and replica utilization
    Input Quality Missing, malformed, stale, or unsupported values
    Data Drift Changes in production feature distributions
    Prediction Drift Changes in scores, classes, and threshold selections
    Delayed Quality Model performance after verified outcomes mature
    Group Performance Quality and selection metrics across appropriate operating groups
    Business Outcome Workflow impact, cost, value, complaints, and overrides

    Alerts and Operational Ownership

    Every Alert Should Define

    • The monitored signal
    • The alert threshold
    • The evaluation window
    • The severity
    • The responsible owner
    • The notification channel
    • The immediate mitigation
    • The escalation path
    • The fallback or rollback condition
    • The required incident evidence
    Operational principle: A dashboard without ownership and response procedures provides visibility but not an operational control.

    Cloud Cost Management

    Cost Driver Possible Control
    Always-On Instances Choose batch or scale-to-zero-capable designs when appropriate
    Oversized Compute Right-size using measured CPU, memory, and latency
    Excess Replicas Set justified minimum and maximum capacity
    Unused Deployments Remove obsolete test and candidate resources after approval
    Verbose Logging Define retention, sampling, and approved log fields
    Network Transfer Place related services and data according to approved architecture
    Accelerator Use Use specialized hardware only when performance evidence justifies it
    Duplicate Environments Version and reuse approved environments where suitable
    Cost rule: Evaluate total cost together with availability, latency, reliability, security, monitoring, and operational effort.

    Delete Learning Resources

    Remove temporary learning endpoints and deployments when they are no longer required. Cloud resources can continue consuming quota or generating charges until they are deleted.

    delete_operation = (
        ml_client.online_endpoints
        .begin_delete(
            name=endpoint_name
        )
    )
    
    
    delete_operation.result()
    
    
    print(
        "Endpoint deletion completed."
    )
    Deletion caution: Confirm that the endpoint is a temporary learning resource and that deletion is authorized. Do not delete shared or production resources through demonstration code.

    CI/CD Deployment Pipeline

    Automated Release Flow
    Code Change → Tests → Security Scan → Register Model → Deploy Candidate → Smoke Test → Approval → Traffic Shift → Monitor
    Pipeline Gate Required Evidence
    Code Quality Formatting, linting, static analysis, and review
    Unit Tests Validation, scoring, and transformation tests
    Model Quality Approved metrics and threshold checks
    Artifact Integrity Version and checksum validation
    Environment Security Dependency and image scanning
    Deployment Test Logs, readiness, schema, and smoke predictions
    Approval Authorized release decision
    Post-release Validation Availability, latency, errors, and prediction checks
    Rollback Verified previous deployment and traffic-restoration procedure

    Responsible Cloud Deployment

    Responsible-Use Requirements

    • Document intended and prohibited uses
    • Use only authorized input data
    • Minimize collection and retention
    • Encrypt data in transit and at rest
    • Restrict endpoint access
    • Return the model version with predictions
    • Communicate uncertainty and limitations
    • Evaluate relevant operating groups
    • Provide human review for consequential actions
    • Support correction of inaccurate source data
    • Monitor harmful or unequal outcomes
    • Maintain fallback, incident response, and rollback
    Unsafe Cloud Use Connect a newly deployed prediction directly to a consequential action without controlled testing, policy validation, or human oversight.
    Responsible Cloud Use Introduce the model gradually and use its output only within the documented workflow, eligibility rules, access controls, and review requirements.

    Common Cloud Deployment Mistakes

    Mistake Deploy before the final model and threshold are approved.
    Correction Freeze and register the evaluated artifact and configuration before deployment.
    Mistake Use mutable or unversioned model files.
    Correction Register immutable model versions with traceable lineage.
    Mistake Store endpoint credentials in code.
    Correction Use approved identities, secret stores, minimum permissions, and credential rotation.
    Mistake Send all traffic to a candidate immediately.
    Correction Use a rollout strategy aligned with user impact and rollback capability.
    Mistake Monitor service uptime but ignore model behavior.
    Correction Monitor service, input, prediction, delayed quality, group, and business metrics.
    Mistake Keep unused test endpoints running.
    Correction Apply ownership, expiration, tagging, budget alerts, and approved cleanup procedures.
    Mistake Assume cloud management removes all operational responsibility.
    Correction Define ownership for model quality, data, identity, cost, alerts, incidents, retraining, and retirement.

    Recommended Cloud Deployment Workflow

    1

    Define Cloud Requirements

    Document users, latency, volume, availability, data location, security, cost, and operational ownership.

    2

    Prepare the Approved Artifact

    Preserve preprocessing, model, threshold, metadata, schema, versions, and integrity evidence.

    3

    Select the Deployment Pattern

    Choose online, batch, serverless, container, Kubernetes, or edge inference according to the requirements.

    4

    Create the Runtime Environment

    Define tested dependencies, base image, scoring code, and resource requirements.

    5

    Register and Deploy

    Register the immutable model and create a versioned candidate deployment behind a stable endpoint.

    6

    Secure the Service

    Configure identity, permissions, secrets, encryption, network controls, and audit logging.

    7

    Test the Deployment

    Validate logs, probes, schemas, predictions, failures, load, security, and version traceability.

    8

    Release Gradually

    Use shadow, blue-green, canary, or another approved rollout strategy.

    9

    Monitor and Respond

    Track service, resources, inputs, predictions, delayed performance, user impact, and cost.

    10

    Improve or Retire

    Evaluate new candidates, roll back when required, and remove obsolete deployments safely.

    Hands-On Practice

    1

    Register a Model

    Register a trusted, tested, and versioned Machine Learning artifact in an approved workspace.

    2

    Create the Environment

    Define only the runtime dependencies required by inference.

    3

    Write the Scoring Script

    Load the model once, validate records, preserve feature order, and return controlled output.

    4

    Create an Endpoint and Deployment

    Deploy the registered model to development compute without assigning production traffic.

    5

    Test the Deployment Directly

    Send synthetic requests to the deployment and review logs, errors, latency, and prediction consistency.

    6

    Create a Candidate Version

    Deploy a second registered model version and compare it with the existing deployment.

    7

    Practice Traffic Rollout

    Apply a controlled traffic split, inspect version-specific metrics, and restore traffic to the previous deployment.

    8

    Clean Up Resources

    Delete authorized temporary resources and verify that no unnecessary cloud components remain active.

    Knowledge Check

    1

    What is cloud model deployment?

    Explain how it publishes an approved model through cloud-hosted inference infrastructure.

    2

    What is the difference between an endpoint and deployment?

    Explain the stable client-facing interface and the versioned model-serving configuration behind it.

    3

    Why should a model be registered?

    Explain versioning, lineage, approval, deployment reference, and traceability.

    4

    Why should scoring code load the model only once?

    Explain initialization, request latency, resource reuse, and controlled readiness.

    5

    Why test a deployment before assigning traffic?

    Explain artifact loading, environment, schema, scoring, probes, and prediction-equivalence validation.

    6

    What is a canary deployment?

    Explain how a limited share of traffic is assigned to a candidate before broader release.

    7

    Why is identity preferable to embedded credentials?

    Explain secret reduction, access control, rotation, and traceability.

    8

    Why monitor both the service and the model?

    Explain that a healthy endpoint can still produce degraded or inappropriate predictions.

    9

    Why must cloud cost be monitored?

    Explain always-on compute, scaling, logging, transfer, accelerators, and unused resources.

    10

    Why should rollback be tested?

    Explain that retained artifacts and deployments do not guarantee successful traffic restoration and service recovery.

    Cloud Deployment Readiness Checklist

    Confirm Before Release

    • The cloud architecture is approved
    • The deployment pattern matches the business requirement
    • The model passed independent evaluation
    • The complete fitted pipeline is registered
    • The model version is immutable
    • The input and output contracts are documented
    • The decision threshold is preserved
    • The environment uses tested dependencies
    • The scoring script validates input
    • The model loads during initialization
    • The endpoint and deployment are versioned
    • Deployment logs have been reviewed
    • Liveness and readiness checks pass
    • Cloud and offline predictions are consistent
    • Authentication and authorization are configured
    • Secrets are stored through approved mechanisms
    • Network access is restricted appropriately
    • Request and batch limits are defined
    • Production-like load tests pass
    • Scaling boundaries are configured
    • Cost ownership and alerts are defined
    • Monitoring metrics and alert owners are configured
    • Responsible-use requirements are approved
    • The release strategy is documented
    • Fallback and rollback procedures are tested
    • Temporary resources have an expiration or cleanup plan

    Lesson Summary

    Cloud Deployment Area Main Outcome
    Model Registration Creates a versioned and traceable cloud model asset
    Environment Defines the reproducible inference runtime
    Scoring Script Loads the model and processes validated requests
    Endpoint Provides the stable client-facing inference interface
    Deployment Connects a model, code, environment, and compute configuration
    Traffic Allocation Controls which deployment processes endpoint requests
    Identity Controls management and invocation access
    Network Security Restricts communication to approved paths
    Testing Validates schema, scoring, security, load, and prediction consistency
    Scaling Aligns resources with measured demand
    Monitoring Tracks service, data, model, business, and cost behavior
    Rollout Introduces model changes according to risk
    Rollback Restores the previous approved deployment
    Responsible AI Protects users through appropriate use, oversight, and accountability

    Key Takeaway

    Deploying a Machine Learning model on the cloud requires an approved and versioned artifact, reproducible inference environment, validated scoring code, correctly sized compute, secure endpoint, controlled traffic, automated tests, monitoring, cost governance, and operational ownership. Managed cloud services can reduce infrastructure work, but they do not remove responsibility for model quality, data protection, access control, responsible use, incident response, or rollback. A reliable release registers immutable model versions, tests candidate deployments before traffic assignment, introduces changes gradually, monitors service and model behavior separately, and preserves a tested path back to the previous approved version.

    Get Machine Learning updates by email

    Short, practical lessons and course updates from Rumman Ansari. No spam.