AI-300 Cheatsheet
Operationalizing Machine Learning and Generative AI Solutions
Download free PDFGovern and secure AI platforms
Workspaces, projects and registries
- An **Azure Machine Learning workspace** organizes jobs, experiments, compute and versioned assets. Separate development and production boundaries when access, billing or release controls differ.
- An **Azure ML registry** shares versioned models, environments and components across workspaces. A workspace organizes a team's work; a registry distributes reusable assets.
- Workspace dependencies include **Storage** for files, **Key Vault** for secrets and **Application Insights** for telemetry. **Container Registry** stores environment images when required.
- In **Microsoft Foundry**, use projects to organize team assets and access. Centralize shared connections and governance at the parent resource; hub-based deployments use a shared hub with separate projects.
- Record **owner, purpose, data lineage, code revision, environment and evaluation results** with release artifacts. Registration supplies versioned identity; approval controls determine what can enter production.
Identity and private networking
- Prefer **managed identities** and Microsoft Entra authentication for supported service-to-service access. Grant each identity the required **data-plane role** on Storage, Search or another dependency.
- Use **Azure RBAC** at the narrowest useful scope. Separate platform administration from project development; resource access does not automatically authorize access to connected data.
- Use **private endpoints** for private inbound access and explicitly disable public access where required. Configure private DNS and network reachability for clients and dependent services.
- A **managed virtual network** controls supported outbound paths. Allow required Storage, registry, Key Vault and model-service connections; private inbound access alone does not isolate outbound traffic.
- Keep secrets in **Key Vault** when keyless access is unavailable. A **SAS** grants time-limited, permission-scoped storage access; an account key is broader and needs secure storage and rotation.
Infrastructure and source control
- Define infrastructure in **Bicep or ARM templates** and keep it in Git. Use environment parameters to deploy consistent development, test and production resources.
- A **GitHub Actions** or Azure DevOps workflow can validate changes, preview infrastructure changes and deploy approved revisions. Configure branch protection and production environment approvals.
- Use **federated workload identity** for supported CI authentication instead of long-lived deployment secrets. Repository authentication is a separate integration; choose a credential mechanism supported by the Git host.
- Clone code into the intended filesystem: shared workspace files support collaboration, while compute-local storage can improve local I/O. Protect private-repository credentials and commit reproducible job definitions.
Develop repeatable training workflows
Notebooks and compute
- A **compute instance** supports interactive notebooks and development. An **Azure ML compute cluster** scales submitted training jobs; configure minimum and maximum nodes for the workload.
- Use **minimum nodes = 0** to release idle cluster capacity. Keep the required maximum unchanged when reducing idle cost, and allow for cold-start time and subscription quota.
- **Low-priority or Spot capacity** lowers cost but can be interrupted. Use checkpointing and retries for tolerant training jobs; dedicated capacity better suits strict completion requirements.
- A notebook's **kernel** holds variables in memory. Restarting or replacing the kernel clears that state; changing the visible notebook page need not stop its kernel. Persist important results to durable storage.
- Create an isolated Python environment, install dependencies and **ipykernel**, then register its Jupyter kernel. **%pip** installs into the running notebook kernel's environment; restart when a package change requires it.
Data assets and access
- A **datastore** describes a storage connection; a **data asset** gives data a named, versioned reference. **uri_file**, **uri_folder** and **mltable** represent one file, a collection and a tabular blueprint respectively.
- An **MLTable** definition specifies paths and transformations. Use **mltable.load()** for a folder containing that definition, then **to_pandas_dataframe()** to materialize the table.
- For CSV files without an MLTable definition, **mltable.from_delimited_files()** builds a table; use the corresponding Parquet reader for Parquet data. Merely registering a folder does not create a tabular blueprint.
- An **AzureBlobDatastore** identifies the storage account and container. Use identity-based authorization where possible; credential-based connections can use **SasTokenConfiguration** or **AccountKeyConfiguration**.
- Pin **data asset versions** for reproducible runs and preserve their underlying files. Registering a new version does not freeze a mutable external path or recreate overwritten data.
- For tabular exploration, **pandas.read_csv()** loads CSV data and **DataFrame.describe()** summarizes numeric count, mean, standard deviation, extrema and quartiles. Count excludes missing values.
Environments and command jobs
- A versioned **Environment** captures runtime dependencies. Use **image** for an existing Docker image, **build** for a Docker build context and **conda_file** for Python or Conda dependencies.
- Publish a **new environment version** when dependencies change. Pin package versions and image digests where practical; a mutable image tag can undermine repeatability.
- An SDK v2 **command job** specifies code, command, inputs, outputs, environment and compute. Bind a declared input with **${{inputs.training_data}}** and pass it using the argument name expected by the script.
- Keep reusable job environments separate from interactive notebook kernels. A package installed in a notebook is not automatically present on remote job compute.
- Use **.amlignore** to exclude files from the uploaded code snapshot. When both **.amlignore** and **.gitignore** exist, Azure ML uses .amlignore for this purpose.
Pipelines and experiment tracking
- A **component** packages a reusable step with typed inputs, outputs, code and environment. Load a YAML definition with **load_component()**, then register it through **ml_client.components.create_or_update()**.
- A **pipeline** connects preparation, training and evaluation through explicit data dependencies. Submit or schedule it as a job; version its components and promote the same validated assets across environments.
- **MLflow Tracking** groups runs in experiments. Point external training clients at the workspace tracking URI; managed Azure ML jobs integrate run tracking with the workspace.
- Use **log_param()** for configuration, **log_metric()** for numeric values and **log_artifact()** for saved files. **log_figure()**, **log_image()** and **log_table()** record richer artifacts.
- Use **log_metrics()** for a dictionary of metric names and values; use steps to record a time series. The lower-level **MlflowClient.log_batch()** batches metric, parameter and tag entities.
- Log the model in a supported **MLflow flavor**, retain run artifacts and register the selected model version. Compare metrics alongside data, code and dependency versions rather than the score alone.
AutoML and hyperparameter search
- **AutoML** explores supported algorithms and settings for a task. Supply training data, target column, primary metric, validation strategy, compute and limits; keep test data separate from selection.
- SDK v2 tabular AutoML uses **MLTable** inputs. Automated image training uses task-specific **JSONL annotations** exposed through MLTable; labels and schema must match classification, detection or segmentation.
- A **sweep job** runs a parameterized trial over a search space. Declare the primary metric and maximize/minimize goal, and log that exact metric name from each trial.
- **Grid** exhausts discrete combinations; **random** samples the space; **Bayesian** sampling uses earlier results to choose promising trials. Choice, Uniform and LogUniform are useful Bayesian search-space forms.
- Set **total trials, concurrency and timeout** separately. Higher concurrency uses more compute, but fewer completed observations are available to guide each new Bayesian choice.
- **Bandit** compares a trial with the best using slack; **median stopping** compares with median running performance; **truncation selection** removes a chosen fraction of low performers. Interval and delay control when supported policies evaluate trials.
Deploy and operate machine learning
Inference and safe releases
- Use a **managed online endpoint** for synchronous, low-latency requests. Use a **batch endpoint** for asynchronous scoring of large file collections, with parallelism, retries and output storage.
- An **endpoint** supplies a stable invocation address; a **deployment** supplies a model and serving configuration. Multiple online deployments allow controlled traffic allocation.
- A custom scoring script uses **init()** to load the model once and **run()** to validate and score requests. Supported MLflow models can use **no-code deployment** instead of a custom script.
- Create a new deployment beside the current one, test it directly, then shift a small traffic share and monitor. Expand only after quality and operational gates pass; **roll back traffic** to the retained deployment when problems occur.
- A separate **staging endpoint** tests without serving production users. **Traffic mirroring** tests supported requests against a shadow deployment while the production deployment supplies the user response.
- For isolated serving, prepare the **model package and inference environment** before release and ensure required artifacts are reachable privately. Blocked outbound dependency downloads can prevent startup.
Features, lifecycle and responsible AI
- A **feature store entity** defines identifying keys; a **feature set** groups versioned feature definitions. **Feature retrieval specifications** capture the features a model uses and support consistent training and inference retrieval.
- Avoid **training-serving skew** by sharing feature transformations and validating freshness. Point-in-time training retrieval prevents future information from leaking into historical examples; online serving needs an appropriately populated online store.
- Retain model versions and lineage for audit and rollback. **Archiving** hides assets from normal active listings; enforce production eligibility through permissions and release policy rather than treating archive status as a deployment ban.
- The **Responsible AI dashboard** combines error analysis, explanations, fairness and supported what-if tools. Compare performance across demographic or business **cohorts**; global averages can hide large disparities.
- **Feature explanations** describe model influence. **Counterfactuals** find input changes that alter a prediction. **Causal analysis** estimates treatment effects under assumptions; feature importance alone does not establish causation.
- **Fairlearn ThresholdOptimizer** applies postprocessing to an existing classifier. **ExponentiatedGradient** and **GridSearch** are reduction-based training approaches; choose **demographic parity** or **equalized odds** according to the fairness objective.
Production health and drift
- Monitor **request rate, latency percentiles, active connections, errors and resource utilization** for serving health. Configure autoscale rules and capacity limits; endpoint availability alone says little about prediction quality.
- Use **deployment logs** for startup, dependency and scoring failures. Check request schema and authentication for caller errors; inspect saturation, timeouts and downstream dependencies for latency or intermittent failures.
- **Data drift** changes input distributions; **prediction drift** changes output distributions; **concept drift** changes the relationship between inputs and outcomes. Drift is a warning signal, not proof of accuracy loss.
- Compare production with a representative **reference dataset**. Monitor missing values, ranges, schema and category frequencies; use trustworthy outcome labels to measure actual model performance.
- For regression, **MAE** measures average absolute error, **RMSE** emphasizes large errors and **R-squared** compares against a mean baseline. For classification, inspect precision, recall, F1 and a confusion matrix across relevant cohorts.
- Connect threshold breaches to **alerts and action groups** for notifications or automation. Diagnose data failures before retraining; send validated degradation signals to a retraining pipeline and evaluate candidates before promotion.
Build and optimize generative AI
Models and serving capacity
- Select models using **task quality, modalities, context window, latency, cost and governance**. Benchmark on representative inputs; the largest or smallest model is not automatically the best fit.
- A context budget includes **instructions, history, retrieved passages and output**. Long-context support does not guarantee low latency; test representative input lengths and reserve enough output capacity.
- **Standard** deployment uses consumption-based shared capacity; **provisioned throughput** allocates capacity for predictable sustained demand. Size against token workload and latency objectives, then load-test.
- **Global**, **data-zone** and **regional** processing scopes serve different residency needs. Select the permitted processing boundary as well as the capacity model; global routing does not promise processing in the resource's region.
- Use **batch inference** for delay-tolerant bulk work and keep it separate from interactive chat capacity. Plan quota, throttling, retries with backoff and an explicitly governed overflow route for excess demand.
Prompts and flow development
- Use **system instructions** for role, tone, constraints and output format. Separate trusted instructions from user text and retrieved data, and use parameterized templates with representative examples.
- Treat **prompts as code**: version templates in Git, experiment in feature branches, review pull requests and tag approved releases. Keep a known-good revision available for rollback.
- For prompt updates without application redeployment, load an **external versioned prompt artifact** through controlled configuration. Pin production to an approved version; validate and promote changes explicitly.
- **Prompt flow** connects inputs, LLM calls and tools. Use an **LLM tool** for prompt variants and a **Python tool** for custom processing or API calls; manage service connections separately from prompt content.
- Compare variants with the **same inputs, model settings and evaluators**. Lower temperature can reduce sampling variation, but does not ensure factual accuracy. Track quality alongside token usage and latency.
RAG ingestion and retrieval
- **Retrieval-Augmented Generation** retrieves authorized passages and supplies them as context to generation. Ingest documents, extract text, chunk it, create embeddings, index content and retrieve relevant evidence at query time.
- Store source identity, headings and access metadata with chunks. Tune **chunk size and overlap** to document structure: oversized chunks mix topics, while excessive overlap creates duplicate evidence.
- **Keyword search** preserves exact terms and policy identifiers. **Vector search** retrieves semantic similarity; **hybrid search** combines lexical and vector signals for mixed query types.
- Use **semantic ranking** to rerank an initial candidate set. Configure prioritized title, content and keyword fields in a semantic configuration; fields must satisfy the search index's required capabilities.
- Generate query and document vectors with a **compatible embedding model and dimensions**. Changing the embedding model normally requires re-embedding indexed content; vector dimension alone is not a retrieval quality score.
- Inspect retrieved passages before changing the generator. Tune chunking, filters, candidate count, hybrid retrieval and reranking; deduplicate or diversify results so repeated chunks do not consume the evidence budget.
- Use supported **Blob Storage data connections and URIs** for grounding files. Apply document authorization during retrieval and govern index copies, logs and model access as carefully as the original data.
Fine-tuning and training data
- Start with a measured **baseline**, then improve instructions and retrieval. Use **fine-tuning** for persistent task behavior, format or style gaps; use RAG for changing external knowledge.
- Prepare **UTF-8 JSONL** with one valid training example per line. Chat fine-tuning uses **messages** with **role** and **content**; use the schema supported by the selected model and tuning method.
- **Supervised fine-tuning** learns from input and desired-response examples. **Direct preference optimization** learns from preferred and rejected responses to the same input; preference data differs from ordinary labeled chat examples.
- **Reinforcement learning from human feedback** uses preference feedback to guide behavior. Model and method support must be checked before planning a job; a base model's inference capabilities do not imply every tuning method is available.
- Use high-quality, representative examples and separate training, validation and test sets. Remove sensitive data and leakage; more examples do not compensate for inconsistent labels or poor coverage.
- Use a **simulator** to generate task-shaped synthetic interactions when real conversations cannot be used. Review realism, diversity, safety and labels before training; telemetry logs are not automatically valid training examples.
- Evaluate the tuned variant against the baseline on the **same held-out dataset**, including safety and regressions. Deploy it as a separate release artifact, validate integration and promote through controlled production gates.
Evaluate and observe AI applications
Evaluation data and quality
- Build a **versioned evaluation dataset** with representative queries, expected behavior and edge cases. Store reference responses or relevance judgments when a metric requires them, and map dataset columns to evaluator inputs explicitly.
- **Groundedness** checks whether response claims are supported by supplied context. **Relevance** checks alignment with the query. A relevant, fluent answer can still contain unsupported claims.
- **Fluency** assesses grammar and natural language; **coherence** assesses logical consistency and organization. **Similarity** compares a response with reference text; it is not a substitute for grounding checks.
- Evaluate **retrieval** separately from generation: precision measures how much retrieved evidence is relevant, recall measures how much relevant evidence is found, and ranking metrics reward useful ordering.
- Use task-appropriate **embedding benchmarks** for retrieval, clustering or classification. Evaluate a generator with response quality and task outcomes; token throughput measures speed rather than semantic accuracy.
- Inspect both **answer completeness** and **use of retrieved evidence**. Missing evidence points toward retrieval; ignored relevant evidence points toward prompting or context use. Inspect examples before selecting an improvement.
Safety and release gates
- Use **content safety evaluators** to score harms such as hate, violence, sexual content and self-harm. Test both normal scenarios and adversarial cases before exposing a release to users.
- **Indirect attack** testing targets hostile instructions embedded in retrieved content or tool output. **Protected material** checks address reproduction risks; these measure different risks from ordinary harmful language.
- Runtime **content filters, blocklists and guardrails** enforce policies on live interactions. They complement offline evaluations; passing one safety check does not establish overall safety.
- Run built-in and **custom evaluators** in CI on a fixed dataset. Fail the build when defined quality or safety thresholds are missed, and retain per-example results, aggregate scores and artifact versions.
- Combine **human review** with automated scoring for ambiguous or high-impact cases. Save evaluation runs for comparison; production feedback helps discover test cases but does not replace repeatable release validation.
Tracing, performance and cost
- **Tracing** follows a request through retrieval, tools and model calls. Record spans, inputs, outputs, errors, token counts and timing through supported Foundry observability and **Application Insights** integration.
- Use **time to first token** for initial streaming responsiveness, **time per output token** for generation pace and **end-to-end latency** for the complete user request. Monitor percentiles rather than relying only on averages.
- Track **requests and tokens per minute**, concurrency, throttling, failures and capacity utilization. Compare service-level objectives under representative chat and batch load.
- For incomplete responses, inspect the **trace, finish reason, output-token limit, content filtering and orchestration**. A successful model HTTP call does not prove the final application response is complete.
- Compare **input and output token usage** with the applicable pricing and capacity model. Longer prompts, history, retrieved context and answers can raise cost and latency; optimize while preserving measured quality.
- Use **continuous monitoring** for runtime health and behavior, and **offline evaluation** for controlled release comparison. Protect sensitive trace content, define retention and route meaningful alerts to operational responders.