Scaling prototypes into ML models · Topic 3 of 4

Hyperparameter Tuning and Fine-Tuning Foundation Models

Run hyperparameter tuning jobs with search algorithms and trial limits, and decide when and how to fine-tune Gemini and open models from Model Garden.

  • 5 min
In a nutshell
  • Tuning jobs need a metric and goal, parameter specs, a search algorithm and trial limits.
  • Training code reports the metric with the hypertune library.
  • Bayesian is the default; grid for small discrete sets; random for many cheap parallel trials.

What it is

Hyperparameters are settings chosen before training, such as learning rate, tree depth or batch size. A hyperparameter tuning job trains many versions (trials) with different values and keeps the best by a metric you choose.

Fine-tuning adapts a pretrained foundation model, such as Gemini or an open model from Model Garden, to your task with your own examples. The exam asks how to set up tuning jobs and, for foundation models, whether tuning is needed at all.

Search spaceTrialsparallel training runsReport metriceach trialSearch algorithmpicks next valuesBest trial

How it works

Hyperparameter tuning jobs

An Agent Platform hyperparameter tuning job wraps a custom training job. You define:

SettingMeaning
Metric and goalFor example auc to maximize or rmse to minimize
Parameter specsRanges or lists per hyperparameter, with linear or log scale
Search algorithmDefault Bayesian optimization (through the Vizier service), grid search, or random search
max_trial_countTotal trials, which caps cost
parallel_trial_countTrials at once; more is faster but gives the Bayesian search less feedback between trials
from google.cloud import aiplatform
from google.cloud.aiplatform import hyperparameter_tuning as hpt

PREBUILT_TRAINING_IMAGE = "..."   # a prebuilt training container URI

aiplatform.init(project="my-project", location="us-central1",
                staging_bucket="gs://my-staging")
custom_job = aiplatform.CustomJob.from_local_script(
    display_name="churn-train",
    script_path="train.py",
    container_uri=PREBUILT_TRAINING_IMAGE,
)
hp_job = aiplatform.HyperparameterTuningJob(
    display_name="churn-hpt",
    custom_job=custom_job,
    metric_spec={"auc": "maximize"},
    parameter_spec={
        "learning_rate": hpt.DoubleParameterSpec(min=0.001, max=0.1, scale="log"),
        "max_depth": hpt.IntegerParameterSpec(min=3, max=10, scale="linear"),
    },
    max_trial_count=30,
    parallel_trial_count=3,
)
hp_job.run()

The training script receives the trial's values as command-line arguments and reports the metric back:

import hypertune

hypertune.HyperTune().report_hyperparameter_tuning_metric(
    hyperparameter_metric_tag="auc", metric_value=auc, global_step=epoch)
ChoiceUse when
Bayesian optimizationDefault; expensive trials, continuous ranges
Grid searchFew discrete values that must all be tried
Random searchMany dimensions, cheap trials, many trials in parallel
Log scaleValues spanning orders of magnitude, such as learning rate

BigQuery ML also tunes hyperparameters with the num_trials option, and AutoML tunes them for you.

Exam tip

"Reduce tuning time" means raise parallel_trial_count; "reduce tuning cost" means fewer trials or early stopping. Raising parallelism trades some search quality for speed.

When to fine-tune a foundation model

Try firstThen considerTune when
Prompt engineering: clear instructions, system instructions, few-shot examplesGrounding or RAG for facts and citationsOutput style, format or domain behaviour stays inconsistent after good prompts
Smaller model with a good promptLarger modelA tuned small model can replace a large one with long prompts, cutting cost and latency

Tuning needs quality labeled examples (prompt and ideal response), an evaluation set, and budget for training and testing. It does not keep facts current: RAG does that.

How foundation models are tuned

ModelMethodNotes
GeminiSupervised fine-tuning on Agent PlatformUpload JSON Lines training and validation examples to Cloud Storage; uses parameter-efficient tuning; the tuned model is served from its own endpoint
Gemini from BigQueryRemote model with prompt and label columnsSQL-only teams; data already in BigQuery
Open models in Model Garden (for example Gemma)Parameter-efficient methods such as LoRA, or full fine-tuning, run as training jobs from Model Garden notebooks or your own codeYou choose GPUs or TPUs and pay for them; you serve the result yourself

Parameter-efficient tuning (for example LoRA adapters) trains a small number of extra weights instead of the whole model. It needs far less compute and memory than full fine-tuning and usually works well with hundreds to thousands of examples.

A worked example

A legal firm's Gemini prompt extracts clauses from contracts, but outputs vary in structure and miss firm-specific clause types, even with ten examples in the prompt. The engineer collects 1,500 reviewed prompt and response pairs, splits off 150 for validation, and runs supervised fine-tuning on a Flash model.

The tuned model is compared with the prompted base model on the held-out set and wins. It also needs a much shorter prompt, so each request costs less.

Prompting plateausCollect examplesprompt and responseSupervised tuningGemini FlashEvaluateheld out setDeploy tuned endpoint

How the exam asks about this

  • "Hyperparameter tuning takes too long; budget allows more parallel compute." Increase parallel_trial_count.
  • "A chatbot must answer about prices that change daily." Use RAG or grounding, not fine-tuning.
  • "An open model must learn a domain task on limited GPU memory." Use parameter-efficient tuning such as LoRA.

What to remember for the exam

  • Tuning jobs need a metric and goal, parameter specs, a search algorithm and trial limits.
  • Training code reports the metric with the hypertune library.
  • Bayesian is the default; grid for small discrete sets; random for many cheap parallel trials.
  • Tune foundation models only after prompting and grounding fall short.
  • Parameter-efficient tuning cuts compute; RAG, not tuning, supplies current facts.
Watch out

A tuning metric must be measured on validation data. Tuning against the test set leaks it into model selection and inflates the final score.

Common mistakes

Tuning many values on a linear scale. Learning rates spanning 0.0001 to 0.1 need a log scale, or most trials land at the top of the range.

Setting all trials to run in parallel. Bayesian search then learns nothing between trials and behaves like random search.

Fine-tuning to add knowledge. Facts change; retrieval supplies them without retraining.

Check yourself

  • How does a training script tell the tuning job how well a trial did?

    It reports the metric with the hypertune library using the metric tag defined in the tuning job.

  • What is the trade-off of raising parallel_trial_count?

    Tuning finishes sooner, but the Bayesian search has less feedback between trials, so it may need more trials to find the best values.

  • What should you try before fine-tuning Gemini?

    Prompt engineering with system instructions and few-shot examples, and grounding or RAG when the problem is missing or outdated facts.

Topic 3 of 4 in Scaling prototypes into ML models

Test yourself on Scaling prototypes into ML models

The full Google Cloud Professional Machine Learning Engineer question bank has 749 questions, with timed practice exams and an explanation for every answer.

This study guide is independent and is not affiliated with, endorsed by, or sponsored by Google Cloud. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.