Agent Platform Model Tuning

Agent Platform Model Tuning

Guides an agent through fine-tuning open and Gemini models on Agent Platform: environment setup, dataset preparation, cost estimates, launching, monitoring and cancelling tuning jobs.

Skill files13 files

references/

scripts/

SKILL.md882 lines
1
---
2
name: agent-platform-tuning
3
metadata:
4
version: "1.0.2"
5
category: AiAndMachineLearning
6
description: >-
7
Agent Platform Model Tuning. Use when you need to fine-tune open models
8
or Gemini models using Agent Platform infrastructure. Don't use for model
9
training outside Agent Platform, model deployment to endpoints (use
10
`agent-platform-deploy`), or managing serving endpoints (use
11
`agent-platform-endpoint-management`).
12
---
13
14
# Agent Platform Model Tuning
15
16
## Attribution
17
18
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you MUST
19
read [Usage Attribution](references/attribution.md). For commands executed
20
directly in the terminal (never in generated scripts, Terraform, or user code),
21
prefix `gcloud` with `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` and append the
22
attribution suffix to `User-Agent` headers:
23
24
```text
25
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-tuning)"
26
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-tuning)
27
```
28
29
## Overview
30
31
This skill provides procedural knowledge for fine-tuning Large Language Models
32
(both Open Models and Gemini Models) using Agent Platform's tuning service. It
33
covers the entire lifecycle from environment setup and data preparation to job
34
configuration, monitoring, and deployment.
35
36
## Workflow Decision Tree
37
38
1. **Project & Region Verification Check**: Has the user provided the Google
39
Cloud project and region?
40
41
- **No** → **STOP tool execution immediately**. Do NOT run verification
42
commands (`gcloud services list`, `gcloud projects get-iam-policy`), do
43
NOT create resources, and do NOT begin dataset preparation. Prompt the
44
user to specify or confirm the project and region (e.g. "Could you
45
please specify which Google Cloud project and region you would like to
46
use?").
47
- If the user's inquiry is solely to check or verify environment
48
readiness (APIs, IAM, service agents), ask ONLY for the project and
49
region. Do NOT ask for the model category.
50
- If the user is requesting a tuning workflow and also omitted whether
51
they want to tune an Open Model or a Gemini Model, you may ask both
52
questions together.
53
- **Yes** → Proceed.
54
55
2. **Model Category Identification**: Has the user explicitly stated whether
56
they want to tune an **Open Model** or a **Gemini Model**?
57
58
- **No** →
59
- **EXCEPTION for Environment Verification Inquiries:** If the user is
60
only asking to check or verify that the environment, APIs, IAM
61
permissions, or service agents are ready for tuning, do NOT ask for
62
the model category. Verify the environment once the project and
63
region are known and confirm readiness.
64
- Otherwise, **STOP tool execution**. Ask the user if they want to
65
tune an Open Model or a Gemini Model. **General Setup and
66
Prerequisite Inquiries (e.g., "What environment setup is
67
needed?"):** If the user asks what environment setup, prerequisites,
68
APIs, or permissions are needed to start fine-tuning, and has not
69
yet chosen a model category:
70
* Describe the setup requirements (APIs, IAM permissions/service
71
agents, and Python SDKs).
72
* Regarding Cloud Storage: state that an existing Cloud Storage bucket
73
is needed for datasets and artifacts (e.g.,
74
`gs://<existing-bucket>`). **CRITICAL:** Do NOT instruct the user to
75
create a bucket, do NOT output a `gcloud storage buckets create`
76
command in setup instructions, and do NOT assume a non-existent
77
bucket exists (users may not have bucket creation permissions and
78
will provide their own existing bucket).
79
* You MUST explicitly conclude your prose response with the direct
80
question: **"Would you like to tune an Open Model or a Gemini
81
Model?"** (do NOT bury this choice inside a bulleted "Suggested Next
82
Steps" list). Never provide setup instructions without explicitly
83
asking this question in prose. (Note: if they ask to actively check
84
or verify a project whose ID or region is missing, ask for the
85
project and region first without running tool calls).
86
- If the user provides a specific tuning purpose, you should recommend
87
three models: one Open Model, one Gemini Model, and a third generally
88
recommended choice. Briefly list the pros and cons of each (e.g., Gemini
89
models might be more expensive, etc.). **CRITICAL:** You must read
90
`references/models.md` during this step and only recommend models
91
explicitly listed in that catalog. Never recommend uncataloged or
92
unsupported models like `google/gemma-2-9b-it`, `gemma-2`, or `Mistral`
93
— only recommend supported models such as Gemma 3
94
(`google/gemma3@gemma-3-12b-it`), Qwen 3 (`qwen/qwen3@qwen3-8b`), or
95
Llama 3.1 (`meta/llama3_1@llama-3.1-8b`). For Gemini models, ONLY
96
recommend `gemini-2.5-flash` (recommended for general/coding/chat) or
97
`gemini-2.5-pro`. Never recommend `gemini-1.5-flash-002`,
98
`gemini-1.5-pro-002`, or `gemini-1.5-flash`, which are deprecated and
99
unsupported by the tuning service. If the user names a model that is not
100
in the catalog, follow the fallback rule in that catalog. Do not proceed
101
with model configuration until the category is confirmed.
102
- **Distillation requests**: If the user asks to distill a model, names a
103
teacher model, or wants a smaller model to learn from a larger one, this
104
is an Open Model workflow using distillation. Read "Distillation" in
105
`references/models.md` and use only the teacher and student models
106
listed there.
107
- **Yes** → Proceed.
108
109
3. **Environment Check**: Has the environment (Auth, APIs, IAM, Venv) been
110
initialized?
111
112
- **No** → Go to [Phase 0: Environment & IAM Setup](#phase-0).
113
- **Yes** → Proceed.
114
115
4. **Dataset Status**: Is the dataset ready in JSONL format, **is its structure
116
valid for tuning**, and is it uploaded to Google Cloud Storage?
117
118
```
119
- **No** → Go to [Phase 1: Dataset Preparation & Upload](#phase-1).
120
- **Yes** → Proceed.
121
```
122
123
5. **Column Selection Confirmation**: Have you presented the columns to the
124
user and confirmed the mapping?
125
126
- **No** → **STOP**. You must show samples and get user confirmation on
127
column mapping as described in Phase 1.0 before proceeding.
128
- **Yes** → Proceed.
129
130
6. **Configuration**: Has the user provided the target model and
131
hyperparameters, or explicitly agreed to your recommendations?
132
133
- **No** → Go to
134
[Phase 2: Model Configuration & Recommendation](#phase-2).
135
- **Yes** → Proceed.
136
137
7. **Job Status**: Has the tuning job been submitted?
138
139
```
140
- **No** → Go to
141
[Phase 3: Tuning Job Execution](#phase-3-tuning-job-execution).
142
- **Yes** → Proceed.
143
```
144
145
8. **Job Completion**: Is the tuning job complete?
146
147
```
148
- **No** → Go to [Phase 4: Monitoring](#phase-4-monitoring).
149
- **Yes** → Proceed.
150
```
151
152
9. **Deployment**: Has the tuned model been deployed (if required)?
153
154
```
155
- **No** → Go to [Phase 5: Model Deployment](#phase-5-model-deployment).
156
- **Yes** → Task Complete.
157
```
158
159
## Phase 0: Environment & IAM Setup {#phase-0}
160
161
Ensure the foundational environment is ready before proceeding.
162
163
### 0.1 Authentication & Project Context
164
165
- Check if `gcloud` CLI is installed. If it is not installed, prompt the user
166
for permission to install it before proceeding. If it is installed, update
167
it:
168
169
```bash
170
gcloud components update --quiet > /dev/null 2>&1
171
```
172
173
- Verify `gcloud auth list`. If not authenticated, run `gcloud auth login`.
174
- **Project & Region Grounding**: Check if the user specified their GCP
175
project and region in their prompt. If the user's prompt omits either the
176
project or the region (e.g., in an environment verification or setup
177
request), you **MUST STOP tool execution immediately without running any
178
bash or gcloud commands** (do NOT call `gcloud config get project` or
179
`gcloud services list`). Ask the user to provide their project ID/number and
180
region.
181
- Once the project and region are provided or confirmed by the user, verify
182
that `gcloud` is authenticated and execute read-only checks to verify the
183
environment. When reporting environment readiness, your summary MUST
184
explicitly detail the status of all three categories:
185
1. **Required APIs**: explicitly report that both
186
`aiplatform.googleapis.com` (Agent Platform) and
187
`storage.googleapis.com` (Cloud Storage) are enabled.
188
2. **User / Caller IAM Permissions**: explicitly confirm that the user
189
identity or default compute service account has `roles/aiplatform.user`
190
and `roles/storage.admin` (or `roles/storage.objectAdmin`).
191
3. **Service Agents & Roles**: explicitly report that the Agent Platform
192
Service Agent
193
(`service-PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com`) has
194
`roles/aiplatform.serviceAgent`, and the Tuning Service Agent
195
(`service-PROJECT_NUMBER@gcp-sa-vertex-moss-ft.iam.gserviceaccount.com`
196
or `gcp-sa-vertex-tune`) has `roles/aiplatform.tuningServiceAgent`.
197
Always explicitly state the verified project and region (e.g., `project:
198
<PROJECT_NUMBER>, region: us-central1`) and explicitly confirm that the
199
environment is fully configured and ready for tuning.
200
201
### 0.2 Location
202
203
Location handling **depends on the model category** you established in the
204
workflow decision tree. The two categories have different supported locations —
205
never apply one category's locations to the other.
206
207
- **Open models** share one fixed location set, and `global` is the
208
recommended choice.
209
- **Gemini models** differ per model and must be looked up. `global` is not
210
accepted for them today.
211
212
If the user names a location that is not valid for their model and category,
213
STOP. Respond with an error naming the requested location as unsupported, list
214
the locations that are valid, and do NOT ask for a dataset, do NOT proceed with
215
any other setup step, and do NOT silently retry elsewhere.
216
217
#### Open Models (RECOMMEND: `global`)
218
219
**Recommend `global` and confirm it with the user.** Propose it as a single
220
recommended choice rather than making the user pick a region first, and do not
221
steer them toward a specific region instead.
222
223
These are the only locations available for open model tuning:
224
225
- `global` (the recommended choice)
226
- `us-central1`
227
- `europe-west4`
228
- `us-west1`
229
- `us-east5`
230
- `asia-southeast1`
231
232
The `global` endpoint automatically selects a supported region that has
233
available capacity, so it is the most likely to be scheduled successfully.
234
Pinning a region up front restricts the job to that one region's capacity, which
235
is why `global` is the recommended location for open model tuning.
236
237
- **The user named a location** → use it verbatim, provided it is `global` or
238
one of the regions listed above. Do not talk them out of it.
239
- **The user asked which locations are supported** → answer the question.
240
Share the list above and say that `global` is recommended and why. Never
241
withhold it.
242
- **The user did not name a location** → propose `global` and ask them to
243
confirm it before you proceed. Say that `global` lets the service pick a
244
region with available capacity. Do NOT silently assume `global`.
245
246
The point of proposing a single choice is to avoid making region selection a
247
decision the user must resolve before anything else can happen — that ordering
248
is what previously blocked people. It is not a reason to hide the list: quote it
249
whenever the user asks, and quote it when rejecting an unsupported location.
250
251
Fall back to an explicit region **only** in the cases below, and tell the user
252
why you are doing so:
253
254
- **CMEK.** Customer-managed encryption keys are rejected on `global` with a
255
`FAILED_PRECONDITION` error. A CMEK-protected job must name the region that
256
holds the key.
257
258
- **Data residency.** If the user requires the job to stay in a specific
259
jurisdiction, honor their region. `global` currently runs the job in either
260
`us-central1` or `europe-west4`.
261
262
If a `global` job is accepted but then fails with a `FAILED_PRECONDITION` error
263
saying the model does not support global endpoint tuning, that model is not
264
onboarded to the global endpoint yet. The model itself is still tunable:
265
resubmit once in an explicit region from the list above (`us-central1` is the
266
safest choice) and tell the user why you switched.
267
268
##### Working with a `global` job
269
270
- The API host stays `aiplatform.googleapis.com`. There is no
271
`global-aiplatform.googleapis.com` host.
272
- The service resolves `global` to a real region at run time. Sub-resources
273
(the tuned model, checkpoints, TensorBoard) come back with that **real**
274
region in their resource names, not `global`. Read the location out of the
275
returned resource name before using it for monitoring or deployment; never
276
assume it is still `global`.
277
- Quota is shared across regions, so pinning a region does not grant extra
278
quota.
279
280
#### Gemini Models (per-model, look it up)
281
282
`global` is **not accepted for Gemini tuning today** — the service rejects it at
283
job creation with a `FAILED_PRECONDITION` error, so do not propose it here.
284
285
**There is no single region allowlist for Gemini.** Supported tuning regions
286
vary by model and by model version: some Gemini models are restricted to two
287
regions while others support many more. Do NOT reuse the open model list above,
288
and do NOT assume a region carries over from another Gemini model.
289
290
Before submitting, look up the chosen model in the supervised fine-tuning
291
documentation and read its **"Supported endpoint for model tuning"**
292
row:
293
[supervised tuning](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/tuning/supervised-tuning)
294
295
296
- **The user asked which regions are supported** → look up that specific model
297
and tell them what the docs say. Do not answer from memory or from the open
298
model list, and do not answer for a different Gemini model.
299
- **The model's row names specific regions** → the user's region must be one
300
of them. If it is not, STOP and report the supported regions for that model.
301
- **The model's row is absent or the docs are unclear** → ask the user for the
302
region rather than guessing one.
303
304
Confirm the region with the user before proceeding. Note that some Gemini models
305
also restrict CMEK and serve tuned models only on the `us` and `eu` multi-region
306
endpoints, so check the same table for those limits before promising them.
307
308
### 0.3 Enable APIs
309
310
Ensure `aiplatform.googleapis.com` and `storage.googleapis.com` are enabled.
311
312
```bash
313
gcloud services enable aiplatform.googleapis.com storage.googleapis.com \
314
--project=YOUR_PROJECT
315
```
316
317
### 0.4 IAM Permissions
318
319
Verify the following identities have the required roles.
320
321
- **Agent Platform Service Agent**:
322
`service-PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com`
323
- **Managed OSS Fine Tuning Service Agent**:
324
`service-PROJECT_NUMBER@gcp-sa-vertex-moss-ft.iam.gserviceaccount.com`
325
- **User Identity**: The account running the commands.
326
327
### 0.5 Python Dependencies
328
329
The scripts in this skill import `vertexai` (from `google-cloud-aiplatform`),
330
`google-genai`, `google-cloud-storage`, and `datasets`.
331
332
**CRITICAL AGENT INSTRUCTION:** Do **not** create a virtual environment, and do
333
not install anything before checking. A venv starts empty and hides packages the
334
environment already provides, forcing a redundant several-minute install.
335
336
Probe first and install only if the probe fails:
337
338
```bash
339
python3 -c "import vertexai, google.genai, google.cloud.storage, datasets" \
340
|| pip install -r references/requirements.txt
341
```
342
343
Then run every script with a plain `python3 scripts/...` — no activation prefix.
344
345
The `references/requirements.txt` pins are a fallback for an environment that
346
does not already provide these SDKs. Do not apply them on top of a working
347
environment: they would downgrade packages other tools may share.
348
349
## Phase 1: Dataset Preparation & Upload {#phase-1}
350
351
### 1.0 Dataset Discovery & Confirmation
352
353
- **User-Provided Dataset Verification:** If the user specifies a dataset
354
filename or path in their prompt, verify its existence in the workspace
355
(e.g. via script execution or checking for typos).
356
* **If the file cannot be found anywhere**, you **MUST** inform the user
357
that the dataset file does not exist or cannot be accessed. You **MUST**
358
prompt the user to provide a valid dataset path. Alternatively, if
359
candidate dataset files are found in the workspace during your search,
360
you **MUST** present the candidates to the user and ask them to select
361
one. You **MUST** stop tool execution immediately after reporting the
362
missing file or presenting candidates, and wait for the user's response.
363
Do **NOT** ask for 90/10 validation split permission, and do **NOT**
364
attempt to upload the dataset before receiving a valid dataset file
365
selection from the user.
366
* **If the file is found and verified**, proceed to Step 1.1 Formatting &
367
Validation below.
368
- **Auto-Discovery: From User Bucket:** If the user does not have a dataset
369
and no suitable alternative is found in the Hugging Face reference, offer to
370
search the user's GCS buckets for potential training data. Prioritize
371
searching for files with extensions like `.jsonl`, `.json`, `.csv`, and
372
`.parquet`. If such files are found, read the first few lines/records of
373
each to determine if they contain text-based data suitable for tuning (e.g.,
374
prompt/completion pairs) that can be modified to follow
375
[Data Preparation Guide](references/data_prep.md) and is related to the
376
tuning task requested. **DO NOT** search without prompting first.
377
- **Auto-Discovery: From Task to Huggingface:** If the user has a specific
378
task (e.g. math reasoning, coding, instruction following) or wants to use a
379
Hugging Face dataset without naming a specific one, refer to
380
[Huggingface Datasets Reference](references/hf_datasets.md) and recommend
381
matching datasets (e.g., `open-r1/OpenR1-Math-220k` or
382
`AI-MO/NuminaMath-TIR` for mathematical reasoning; `openai/gsm8k` is also
383
widely used). For each dataset recommended, provide some information about
384
the dataset and provide some reasonable splits, and ask the user to select
385
one. Do NOT output generic instructions telling the user to prepare and
386
upload their own data — proactively guide the interactive dataset discovery,
387
preview, and preparation flow.
388
389
> [!IMPORTANT] **CRITICAL: Ask for Confirmation and Column Selection.** Once
390
> the dataset is selected, execute Python via `run_command` to inspect the
391
> dataset using `load_dataset(..., streaming=True)`. Do not proceed with
392
> dataset preparation or upload until you perform the following steps and
393
> get user confirmation: 1. **Dataset and Split Confirmation:** Present the
394
> dataset and available splits to the user and have them confirm which to
395
> use. 2. **Column Selection (Hugging Face or Custom Datasets):** You
396
> must: - Provide a list of all available columns in the selected dataset
397
> split. - **Show a few samples from the dataset** to help the user
398
> understand the content and make the choice of columns. - Recommend which
399
> columns should be mapped to `prompt` (or user message) and `completion`
400
> (or assistant response), offering a few reasonable options if
401
> applicable. - Ask the user to confirm the column mapping or specify which
402
> columns to use.
403
404
For distillation, map only the prompt column. The teacher model writes the
405
responses, so no completion column is needed.
406
407
### 1.1 Formatting & Validation
408
409
- **Conversion**: If data is in CSV, JSON, or Parquet, use
410
`scripts/prepare_dataset.py` to convert.
411
- **Validation Split Confirmation**: Except for prompt-only distillation data
412
(next bullet), whenever generating or preparing a single dataset without an
413
explicit validation set (including when generating sample chat/instruction
414
datasets or preparing training datasets), you MUST generate or process the
415
data using Python via `run_command` and **you MUST prompt the user** to seek
416
permission to split the training dataset 90/10 to form a validation dataset
417
(using `--validation_split 0.1` or Python script). If they agree, proceed
418
with the split. If they decline, just use the training dataset without a
419
validation dataset. Do **NOT** offer an 80/20 split; the tuning service
420
rejects it, for the reason given in
421
the
422
[Data Preparation Guide](references/data_prep.md#sizing-the-validation-split).
423
Do NOT proceed to upload the dataset or
424
submit the tuning job before asking the user about the 90/10 validation
425
split!
426
- **Distillation training data**: Convert with `--prompt_only` and no
427
`--completion_col`; see the
428
[Data Preparation Guide](references/data_prep.md#distillation-datasets). Do
429
**NOT** offer the 90/10 split for a prompt-only file: the split would have
430
no responses, and a validation dataset must include them. Validation is
431
optional for distillation; use one only if the user has separate data with
432
responses, and convert it the normal way.
433
- **Validation**: If data is already in JSONL, validate it before uploading.
434
Simply having a `.jsonl` extension is not enough. You must verify that the
435
content schema is valid for tuning (e.g. correct system/user/model roles).
436
437
```bash
438
python3 scripts/prepare_dataset.py \
439
--input my_data.jsonl \
440
--format <messages|messages_gemini> \
441
--validate_only
442
```
443
444
*(Use `--format messages` for open models and `--format messages_gemini` for
445
Gemini models.)* - Refer to [Data Preparation Guide](references/data_prep.md)
446
for required schemas.
447
448
### 1.2 Upload
449
450
Upload formatted `.jsonl` files (both training and validation splits, if
451
applicable) to GCS using a unique directory (e.g., with a datetime timestamp) to
452
avoid overwriting outputs from different runs. If the user named a bucket (e.g.,
453
`gs://mybucket`), use that bucket name EXACTLY as provided (verbatim) and NEVER
454
prepend the project ID or modify the bucket name. Upload local `.jsonl` splits
455
to an existing bucket via `google.cloud.storage.Client` in Python (do NOT create
456
a missing bucket unprompted here; see Phase 3 if a bucket needs to be proposed
457
and confirmed):
458
459
```python
460
from google.cloud import storage
461
462
storage_client = storage.Client(project=PROJECT)
463
bucket = storage_client.bucket(BUCKET_NAME)
464
bucket.blob(f"tuning_agent_job_{TIMESTAMP}/train.jsonl").upload_from_filename(
465
"/tmp/train.jsonl"
466
)
467
if VAL_DATASET_PATH:
468
bucket.blob(f"tuning_agent_job_{TIMESTAMP}/val.jsonl").upload_from_filename(
469
VAL_DATASET_PATH
470
)
471
```
472
473
## Phase 2: Model Configuration & Recommendation {#phase-2}
474
475
Help the user choose the best model and parameters. **Always seek user
476
confirmation before submitting the job.**
477
478
- If the user does not specify a specific model in their prompt, calculate
479
recommendations based on the **Models Catalog**.
480
- **Prompt for Confirmation:** Present the recommended model to the user and
481
ask for their confirmation before configuring hyperparameters.
482
483
### 2.1 Configuration
484
485
#### For Open Models
486
487
- Recommend `tuning_mode`, `epochs`, `learning_rate`, and `adapter_size` based
488
on the [Tuning Guide](references/tuning_guide.md) and model-specific
489
baselines in the [Models Catalog](references/models.md).
490
491
#### Verify the Live Model ID
492
493
Before submitting the job, run `scripts/list_models.py` and pick `--base_model`
494
only from its `models` output. Do not invent IDs or version numbers.
495
496
```bash
497
python3 scripts/list_models.py --project YOUR_PROJECT --filter gemini
498
```
499
500
Output: `{"models": [...], "total_count": N, "truncated": bool}`.
501
502
- For Gemini, strip `google/` and `@default` (e.g.
503
`google/gemini-2.5-flash@default` → `gemini-2.5-flash`); for open models,
504
pass `publisher/family@version` as-is.
505
- Skip Gemini variants ending in `-embedding`, `-tts`, `-image`,
506
`-computer-use`, or `-native-audio`; they are not tunable.
507
- If `truncated` is `true`, re-run with a tighter `--filter` (e.g.
508
`gemini-2.5`) before deciding the target version is unavailable.
509
- If `models` is empty, stop and ask the user.
510
511
### 2.2 Calculating Cost (Open Models Only)
512
513
> [!WARNING] **CRITICAL: Always Use `run_command` with
514
> `scripts/calculate_cost.py`** Do **NOT** call the `estimate_cost` ADK tool for
515
> model tuning. The `estimate_cost` tool only supports specific endpoint serving
516
> pricing and will fail with `Unsupported request type` on tuning requests. You
517
> **MUST** call the `run_command` tool to execute Python code or
518
> `scripts/calculate_cost.py` (or
519
> `/workspace/skills/agent-platform-tuning/scripts/calculate_cost.py`) to
520
> calculate the cost. Whenever a model is chosen or the user switches models
521
> (e.g. from Llama to Gemma), you **MUST** call `run_command` to calculate or
522
> recalculate the cost before presenting the dry-run confirmation prompt. Always
523
> report the calculated dollar figure (e.g., `Estimated tuning cost: $X.XX`) in
524
> the dry-run confirmation prompt.
525
526
- We calculate the estimated cost of tuning based on the dataset and the
527
selected model in the [Models Catalog](references/models.md):
528
529
```bash
530
python3 scripts/calculate_cost.py \
531
--input my_data.jsonl \
532
--model MODEL_NAME \
533
--tuning_mode TUNING_MODE \
534
--epochs epochs
535
```
536
537
`--model` takes either the display name (`Qwen 3 8B`) or the same resource
538
name you pass to `--base_model` (`qwen/qwen3@qwen3-8b`), so the value chosen
539
in Step 2.1 can be reused as-is.
540
541
> [!NOTE] **Distillation cost:** `scripts/calculate_cost.py` counts only the
542
> text in the dataset. For a prompt-only distillation dataset it leaves out the
543
> teacher's responses, which the student also trains on, and it does not include
544
> the teacher model calls, which are billed separately at the teacher's
545
> managed-model price. Present the figure as a lower bound.
546
547
> [!NOTE] **Handling Missing Dataset Errors:** If `scripts/calculate_cost.py`
548
> fails because the dataset file (e.g. `my_data.jsonl` or `dummy_data.jsonl`)
549
> cannot be found, you **MUST** inform the user that the dataset file does not
550
> exist or cannot be accessed. You **MUST** prompt the user to provide a valid
551
> dataset path, and stop tool execution immediately to wait for their response.
552
> Do **NOT** retry or loop, do **NOT** invent a specific cost number, and do
553
> **NOT** prompt for job submission approval before receiving a valid dataset
554
> from the user.
555
556
- **Prompt for Confirmation:** Present the recommended hyperparameter
557
configuration and estimated cost (with the concrete dollar figure calculated
558
above) to the user and ask for their approval before proceeding to job
559
submission. Make sure to note that the estimated cost is just an estimate
560
and can vary from actual billing costs.
561
562
## Phase 3: Tuning Job Execution {#phase-3-tuning-job-execution}
563
564
**CRITICAL Pre-Flight Check (GCS Verification):** Before you propose a
565
confirmation prompt or submit any tuning job, you **MUST** verify that the
566
specified training dataset GCS URI (e.g. `gs://dummy_bucket/dataset.jsonl` or
567
`gs://YOUR_BUCKET/...`) actually exists and is accessible. Run `gcloud storage
568
ls $DATASET_URI` (or `gsutil ls`).
569
570
* **If the verification fails** (e.g. `BucketNotFound`, `404`, `AccessDenied`,
571
or indicating a dummy/missing bucket), you **MUST** inform the user that the
572
GCS bucket or dataset does not exist or cannot be accessed. You **MUST**
573
prompt the user to provide a valid GCS URI for the dataset, and stop tool
574
execution immediately to wait for their response. Do **NOT** propose a
575
confirmation prompt and do **NOT** execute any tuning scripts before
576
receiving a valid dataset URI from the user.
577
* **If the verification succeeds**, proceed to propose the confirmation prompt
578
below.
579
580
### For Gemini Models
581
582
Submit the Gemini supervised fine-tuning job using the Python SDK
583
(`google.genai` or `vertexai.tuning.sft`):
584
585
```python
586
from google import genai
587
from google.genai import types
588
589
client = genai.Client(enterprise=True, project=PROJECT, location=LOCATION)
590
tuning_job = client.tunings.tune(
591
base_model=BASE_MODEL, # e.g. "gemini-2.5-flash"
592
training_dataset=types.TuningDataset(gcs_uri=TRAIN_DATASET_URI),
593
config=types.CreateTuningJobConfig(
594
epoch_count=EPOCHS, # e.g. 3
595
learning_rate_multiplier=LEARNING_RATE_MULTIPLIER, # e.g. 1.0
596
validation_dataset=(
597
types.TuningValidationDataset(gcs_uri=VAL_DATASET_URI)
598
if VAL_DATASET_URI
599
else None
600
),
601
),
602
)
603
print("Tuning Job Resource Name:", tuning_job.name)
604
```
605
606
Alternatively using `vertexai.tuning.sft`:
607
608
```python
609
import vertexai
610
from vertexai.tuning import sft
611
612
vertexai.init(project=PROJECT, location=LOCATION)
613
job = sft.train(
614
source_model=BASE_MODEL,
615
train_dataset=TRAIN_DATASET_URI,
616
validation_dataset=VAL_DATASET_URI,
617
epochs=EPOCHS,
618
learning_rate_multiplier=LEARNING_RATE_MULTIPLIER,
619
)
620
print("Tuning Job Resource Name:", job.resource_name)
621
```
622
623
Execute the Python script via `python3` (inline or written to
624
`/tmp/submit_gemini_tuning.py`). Report the returned operation name or trackable
625
resource identifier, and do NOT wait for the terminal state.
626
627
### For Open Models
628
629
Submit the open model tuning job using `scripts/tune_open_model.py` or the
630
Python SDK. Identify the model id using available models documentation
631
at
632
[documentation](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/open-model-tuning#supported-models).
633
634
635
`--base_model` takes a publisher model **resource name**
636
(`{publisher}/{model_id}@{version_id}`), not the display name shown in the
637
catalog. See "Model Resource Name Format" in `references/models.md` for the
638
format, verified examples, and how to look up a name you do not have.
639
640
Using `scripts/tune_open_model.py`:
641
642
```bash
643
python3 scripts/tune_open_model.py \
644
--project YOUR_PROJECT \
645
--location global \
646
--base_model BASE_MODEL_ID \
647
--train_dataset gs://YOUR_BUCKET/tuning_agent_job_<datetime>/train.jsonl \
648
--output_uri gs://YOUR_BUCKET/tuning_agent_job_<datetime>/output \
649
--epochs EPOCHS \
650
--learning_rate LR \
651
--tuning_mode MODE
652
```
653
654
*(Run `scripts/tune_open_model.py`, which maps `--tuning_mode` (`FULL` /
655
`PEFT_ADAPTER`) to `types.TuningMode`, sets adapter sizes and labels, and passes
656
`output_uri` into `CreateTuningJobConfig(output_uri=...)`.)*
657
658
This script is open model only, and `--location` falls back to `global` if
659
omitted. Always pass the location the user confirmed in section 0.2 explicitly,
660
so it is visible in the command string you present for approval. If job
661
submission fails (e.g., due to a missing or invalid parameter), report the error
662
verbatim and present a fresh confirmation prompt showing the updated command
663
before resubmitting.
664
665
#### Distillation
666
667
Add `--method DISTILLATION` and `--teacher_model`. `--base_model` is the
668
student. Use only the teacher and student models listed under "Distillation" in
669
`references/models.md`.
670
671
```bash
672
python3 scripts/tune_open_model.py \
673
--project YOUR_PROJECT \
674
--location global \
675
--method DISTILLATION \
676
--teacher_model TEACHER_MODEL_ID \
677
--base_model STUDENT_MODEL_ID \
678
--train_dataset gs://YOUR_BUCKET/tuning_agent_job_<datetime>/prompts.jsonl \
679
--output_uri gs://YOUR_BUCKET/tuning_agent_job_<datetime>/output \
680
--epochs EPOCHS \
681
--learning_rate LR \
682
--tuning_mode MODE
683
```
684
685
- The training dataset can contain prompts only; the teacher writes the
686
responses. A validation dataset must include responses.
687
- Teacher calls draw on the project's quota for the teacher model.
688
- The job writes the teacher-labeled data to
689
`distillation_labelled_dataset.jsonl` in the output directory.
690
691
> [!WARNING] **`--output_uri` / `output_uri` is required for open models.** The
692
> Python SDK declares it as `output_uri: Optional[str] = None`, but the tuning
693
> backend rejects open model jobs that omit it with `INVALID_ARGUMENT: The
694
> output_uri field is required for this model.` Treat the SDK's "optional"
695
> signature as wrong here and always pass a GCS destination (`output_uri`) both
696
> in CLI flags and in `CreateTuningJobConfig(output_uri=...)`.
697
698
Because the flag is mandatory, you must establish where the tuned model is
699
written before you can submit. **Never invent a bucket name, derive one from the
700
project number, or run `gcloud storage buckets create` unprompted.** Creating a
701
bucket is a mutating action and is subject to the Tier M confirmation policy
702
below.
703
704
- **The user named a bucket or URI** → use it EXACTLY as specified by the user
705
(verbatim), appending a unique per-job directory as in section 1.2.
706
**CRITICAL:** NEVER alter, prefix, or prepend the project number or anything
707
else to a user-specified bucket name! Even if `gcloud storage buckets list`
708
shows an existing bucket with a project-prefixed name (e.g.
709
`gs://PROJECT-mybucket` when the user asked for `gs://mybucket`), you MUST
710
use the user's exact bucket name `gs://mybucket` verbatim. Never silently
711
substitute an existing bucket.
712
- **A bucket was already used for the dataset upload in section 1.2** →
713
propose reusing it for the output and ask the user to confirm.
714
- **Neither or user states they have no bucket** → Check existing buckets in
715
the project (`gcloud storage buckets list --project=PROJECT`) or offer to
716
create a dedicated bucket. When proposing a bucket to create, ensure the
717
bucket name is unique by including a unique suffix or timestamp (e.g.
718
`gs://PROJECT-tuning-$(date +%s)` or
719
`gs://PROJECT-tuning-artifacts-<timestamp>` in LOCATION) to prevent HTTP 409
720
collisions with previously created buckets. Propose the destination bucket
721
in your configuration dry-run preview and ask the user for confirmation
722
before proceeding.
723
724
> [!IMPORTANT] **Interactive Confirmation Required (Tier M):** Before proceeding
725
> with job submission, you **MUST** present the proposed command string showing
726
> all literal flags (including `--output_uri` for open models and estimated
727
> cost) in a confirmation prompt to the user with 'Yes' and 'No' options. Do NOT
728
> execute the tuning job submission via `run_command` in the same turn as
729
> presenting the confirmation prompt; yield immediately for the user's reply.
730
731
## Phase 4: Monitoring {#phase-4-monitoring}
732
733
Monitor the job via the Cloud Console link provided in the script output.
734
`--location` is required and must be the same location you submitted with: an
735
open model job submitted on `global` is polled with `--location global`, even
736
though the work runs in a real region behind the scenes.
737
738
Additionally, ask the user if they want you to monitor the job status for them
739
in the background. If they agree, execute `scripts/monitor_tuning_job.py` as a
740
background task to periodically poll the job status and notify the user to show
741
the status. If the user declines, leave it completely to the user to check on
742
the status.
743
744
## Phase 5: Model Deployment {#phase-5-model-deployment}
745
746
Once the tuning job is `SUCCEEDED`, deploy the tuned checkpoint by registering
747
it in Model Registry with the base model's serving container, then deploying
748
that registered model to a new endpoint. **CRITICAL:** If the tuning job is
749
still pending/running (`tuned_model_name` is `None` or not yet generated),
750
**NEVER deploy the untuned base model (e.g., `google/gemma3@...`) as a
751
substitute!** Instead, explicitly inform the user that deployment of the tuned
752
model cannot proceed until the tuning job finishes (`JOB_STATE_SUCCEEDED`) and
753
generates the tuned model artifact.
754
755
Deployment requires a real region — `global` is not valid here. If the job ran
756
on `global`, read the region out of the tuned model's resource name
757
(`projects/.../locations/<REGION>/models/...`) and deploy there; do not guess.
758
759
If a deploy step is rejected for quota, report the API's error verbatim.
760
761
```bash
762
#!/bin/bash
763
# Deploy a tuned checkpoint by registering it in Model Registry with the base
764
# model's serving container, then deploying to a new endpoint. All four gcloud
765
# calls hit aiplatform.googleapis.com.
766
set -euo pipefail
767
PROJECT_ID="YOUR_PROJECT"
768
LOCATION_ID="YOUR_LOCATION" # e.g. us-central1; NOT global.
769
BASE_MODEL="<PUBLISHER>/<FAMILY>@<VERSION-ID>" # the base model you tuned; e.g. google/gemma3@gemma-3-4b-it
770
ARTIFACTS="gs://YOUR_BUCKET/tuning_agent_job_<datetime>/output/postprocess/node-0/checkpoints/final"
771
DISPLAY_NAME="my-tuned-model"
772
# Explicit IDs, so no step can pick up an older model or endpoint that shares
773
# the display name.
774
RUN_ID="tuned-$(date +%Y%m%d-%H%M%S)"
775
776
# 1. List the base model's verified deployment configs and pick the row that
777
# fits the user-approved cost/perf. CONFIG_INDEX is its 0-based table row.
778
gcloud ai model-garden models list-deployment-config \
779
--model="$BASE_MODEL" \
780
--project="$PROJECT_ID"
781
CONFIG_INDEX="<pick from step 1>"
782
783
# Turn that row into gcloud flags files. The table shows only the image, but
784
# the container also needs the row's args, env, ports and routes; its
785
# --model/--model-path arg points at the base weights and is repointed at
786
# $ARTIFACTS.
787
gcloud ai model-garden models list-deployment-config \
788
--model="$BASE_MODEL" \
789
--project="$PROJECT_ID" \
790
--format=json | python3 -c '
791
import json, sys
792
idx, artifacts = int(sys.argv[1]), sys.argv[2]
793
cfg = json.load(sys.stdin)[idx]
794
spec = dict(cfg["containerSpec"])
795
args, repointed = [], 0
796
for a in spec.pop("args", []):
797
flag = a.split("=", 1)[0]
798
if flag in ("--model", "--model-path"):
799
a, repointed = flag + "=" + artifacts, repointed + 1
800
args.append(a)
801
if repointed != 1:
802
sys.exit("expected exactly one --model/--model-path arg, found %d" % repointed)
803
upload = {"--container-image-uri": spec.pop("imageUri"), "--container-args": args}
804
if "command" in spec:
805
upload["--container-command"] = spec.pop("command")
806
if "env" in spec:
807
upload["--container-env-vars"] = {e["name"]: e["value"] for e in spec.pop("env")}
808
if "ports" in spec:
809
upload["--container-ports"] = [str(p["containerPort"]) for p in spec.pop("ports")]
810
for key, flag in (("predictRoute", "--container-predict-route"),
811
("healthRoute", "--container-health-route"),
812
("sharedMemorySizeMb", "--container-shared-memory-size-mb")):
813
if key in spec:
814
upload[flag] = str(spec.pop(key))
815
if "deploymentTimeout" in spec: # e.g. "7200s"
816
upload["--container-deployment-timeout-seconds"] = str(
817
int(float(spec.pop("deploymentTimeout").rstrip("s"))))
818
if spec:
819
sys.exit("unhandled containerSpec fields: %s" % sorted(spec))
820
m = cfg["dedicatedResources"]["machineSpec"]
821
deploy = {"--machine-type": m["machineType"]}
822
if "acceleratorType" in m:
823
deploy["--accelerator"] = {
824
"type": m["acceleratorType"].lower().replace("_", "-"),
825
"count": str(m.get("acceleratorCount", 1))}
826
json.dump(upload, open("/tmp/upload_flags.yaml", "w"), indent=1)
827
json.dump(deploy, open("/tmp/deploy_flags.yaml", "w"), indent=1)
828
' "$CONFIG_INDEX" "$ARTIFACTS"
829
cat /tmp/upload_flags.yaml /tmp/deploy_flags.yaml
830
831
# 2. Register the tuned checkpoint in Model Registry with the base model's
832
# serving container. Blocks until the upload finishes.
833
gcloud ai models upload \
834
--project="$PROJECT_ID" \
835
--region="$LOCATION_ID" \
836
--model-id="$RUN_ID" \
837
--display-name="$DISPLAY_NAME" \
838
--artifact-uri="$ARTIFACTS" \
839
--flags-file=/tmp/upload_flags.yaml
840
841
# 3. Create a dedicated endpoint.
842
gcloud ai endpoints create \
843
--project="$PROJECT_ID" \
844
--region="$LOCATION_ID" \
845
--endpoint-id="$RUN_ID" \
846
--display-name="$DISPLAY_NAME"
847
848
# 4. Deploy the registered model to the endpoint.
849
gcloud ai endpoints deploy-model "$RUN_ID" \
850
--project="$PROJECT_ID" \
851
--region="$LOCATION_ID" \
852
--model="$RUN_ID" \
853
--display-name="$DISPLAY_NAME" \
854
--flags-file=/tmp/deploy_flags.yaml
855
```
856
857
`set -e` stops the sequence at the first failed step. Step 4 blocks until the
858
model is serving, which can take 20 minutes or more; its progress output prints
859
the operation name, `projects/<PROJECT>/locations/<REGION>/operations/<OP_ID>`.
860
Pass that whole name to `gcloud ai operations describe <OPERATION_NAME>` for
861
status checks from another shell: a bare `<OP_ID>` works only when gcloud has a
862
project.
863
864
> [!IMPORTANT] **Interactive Confirmation Required (Tier M):** Before proceeding
865
> with deployment, you **MUST** present the three write commands (steps 2-4)
866
> with all literal values filled in, plus the generated flags files (container
867
> image, args, machine type, accelerator config), in a confirmation prompt to
868
> the user with 'Yes' and 'No' options. Do NOT execute the deployment commands
869
> via `run_command` in the same turn as presenting the confirmation prompt;
870
> yield immediately for the user's reply.
871
872
Refer to [Models Catalog](references/models.md) for hardware recommendations for
873
specific open models.
874
875
## Resources
876
877
- [Data Preparation Guide](references/data_prep.md)
878
- [Models Catalog](references/models.md)
879
- [Tuning Guide](references/tuning_guide.md)
880
- `scripts/prepare_dataset.py`: Data conversion & validation.
881
- `scripts/tune_open_model.py`: Open model tuning job submission.
882

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 11,602 prompts

More by @OpenSourceBuffGuy

See all
Y2K Streetwear Sticker Collage Style prompt image

Y2K Streetwear Sticker Collage Style

Defines a JSON style system for dense Y2K street-photo collages with oversized cutout subjects, sticker props, comic lettering and speech bubbles in yellow, blue and green.

image-prompt, json-prompt, placeholders, long-form, advanced, collage, y2k, sticker, poster, comics, typography, text-rendering, street-photography, fashion, vibrant-colors, structured-output, for-designers, social-media-graphic, cityscape

Azure Policy Analyzer prompt image

Azure Policy Analyzer

Analyzes Azure Policy compliance against NIST, MCSB, CIS, ISO 27001, PCI DSS and SOC 2 in one pass, returning a risk report with evidence and remediation commands.

sub-agent, audit, compliance, cloud-security, azure, cloud, for-security-professionals, for-devops-engineers, report, structured-output, guardrails, tool-use, risk-management, security-review, confidence-scoring, best-practices, advanced, devops, cybersecurity

Business Continuity Planner prompt image

Business Continuity Planner

Builds business continuity and disaster recovery plans: impact analysis, RTO and RPO targets, disruption scenarios, continuity strategies and crisis communication.

system-prompt, act-as, expert-advice, planner, risk-management, operations, incident-response, compliance, supply-chain, emergency-preparedness, site-reliability, for-managers, for-executives, report, runbook, policy-document, table, structured-output, xml-tags, guardrails, advanced, conditional-logic, communication

Reviews

Loading reviews…

Discussion

Loading comments…