Use when:
- Setting up BigQuery ML for SQL-based machine learning
- Configuring Vertex AI custom training jobs
- Setting up GCP authentication for ML workflows
- Selecting appropriate GPU/TPU configurations
- Estimating costs for GCP ML training
- Deploying models to Vertex AI endpoints
- Configuring distributed training on GCP
- Optimizing cost vs performance for cloud ML
Platform Overview
BigQuery ML
What it is: SQL-based machine learning directly in BigQuery
Best for:
- Quick ML prototypes using existing data warehouse data
- Classification, regression, forecasting on structured data
- Users familiar with SQL but not Python/ML frameworks
- Large-scale batch predictions
Available Models:
- Linear/Logistic Regression
- XGBoost (BOOSTED_TREE)
- Deep Neural Networks (DNN)
- AutoML Tables
- TensorFlow/PyTorch imported models
Pricing:
- Based on data processed (same as BigQuery queries)
- $5 per TB processed for analysis
- AutoML: $19.32/hour for training
Vertex AI Training
What it is: Fully managed ML training platform
Best for:
- Custom PyTorch/TensorFlow training
- Large-scale distributed training
- GPU/TPU-accelerated workloads
- Production ML pipelines
Available Compute:
- CPUs: n1-standard, n1-highmem, n1-highcpu
- GPUs: NVIDIA T4, P4, V100, P100, A100, L4
- TPUs: v2, v3, v4, v5e (8 cores to 512 cores)
Pricing:
- CPU: $0.05-0.30/hour depending on machine type
- GPU T4: $0.35/hour
- GPU A100: $3.67/hour (40GB) or $4.95/hour (80GB)
- TPU v3: $8.00/hour (8 cores)
- TPU v4: $11.00/hour (8 cores)
GPU/TPU Selection Guide
GPU Selection (Vertex AI)
T4 (16GB VRAM):
- Use case: Inference, light training, small models
- Cost: $0.35/hour
- Good for: BERT-base, small CNNs, inference serving
V100 (16GB VRAM):
- Use case: Mid-size training, mixed precision training
- Cost: $2.48/hour
- Good for: ResNet training, medium transformers
A100 (40GB/80GB VRAM):
- Use case: Large model training, distributed training
- Cost: $3.67/hour (40GB), $4.95/hour (80GB)
- Good for: GPT-style models, large vision models, multi-GPU training
L4 (24GB VRAM):
- Use case: Modern alternative to T4, better performance
- Cost: $0.66/hour
- Good for: Mid-size models, efficient inference
TPU Selection (Vertex AI)
TPU v2 (8 cores):
- Use case: TensorFlow/JAX training, matrix operations
- Cost: $4.50/hour
- Memory: 8GB per core (64GB total)
- Good for: Legacy TensorFlow models
TPU v3 (8 cores):
- Use case: Standard TPU training
- Cost: $8.00/hour
- Memory: 16GB per core (128GB total)
- Good for: BERT, T5, image classification
TPU v4 (8 cores):
- Use case: Latest generation, best performance
- Cost: $11.00/hour
- Memory: 32GB per core (256GB total)
- Good for: Large language models, cutting-edge research
TPU v5e (8 cores):
- Use case: Cost-optimized TPU
- Cost: $2.50/hour
- Good for: Development, training at scale on budget
Multi-node TPU Pods:
- v3-32: 32 cores, $32/hour
- v3-128: 128 cores, $128/hour
- v4-128: 128 cores, $176/hour
- Use for: Massive distributed training (GPT-3 scale)
Usage
Setup BigQuery ML Environment
bash scripts/setup-bigquery-ml.sh
Prompts for:
- GCP Project ID
- BigQuery dataset name
- Service account credentials
- Default model type preference
Creates:
bigquery_config.json - Project configuration
.bigqueryrc - CLI configuration
- Example training SQL in examples/
Setup Vertex AI Training Environment
bash scripts/setup-vertex-ai.sh
Prompts for:
- GCP Project ID
- Region (us-central1, europe-west4, etc.)
- Service account credentials
- Default machine type
- GPU/TPU preference
Creates:
vertex_config.yaml - Training job configuration
vertex_requirements.txt - Python dependencies
- Training script template
Configure GCP Authentication
bash scripts/configure-auth.sh
Prompts for:
- Authentication method (service account, user account, workload identity)
- Service account key path (if applicable)
- IAM roles needed
Creates:
.gcp_auth_config - Authentication configuration
- Sets GOOGLE_APPLICATION_CREDENTIALS environment variable
- Validates permissions
Required IAM Roles:
- BigQuery ML:
roles/bigquery.dataEditor, roles/bigquery.jobUser
- Vertex AI:
roles/aiplatform.user, roles/storage.objectAdmin
- Both:
roles/serviceusage.serviceUsageConsumer
Estimate GCP Training Costs
bash scripts/estimate-gcp-cost.sh
Interactive prompts:
- Platform: BigQuery ML or Vertex AI
- If BigQuery ML: Data size to process
- If Vertex AI:
- Machine type (CPU/GPU/TPU)
- Number of machines
- Training duration estimate
- Storage requirements
Output:
- Estimated compute cost
- Storage cost
- Data transfer cost (if applicable)
- Total estimated cost
- Cost comparison with other GCP options
Templates
BigQuery ML Training Template (templates/bigquery_ml_training.sql)
SQL template for creating and training models:
- Model creation syntax
- Feature engineering examples
- Training options (L1/L2 reg, learning rate, etc.)
- Evaluation queries
- Prediction queries
Supported model types:
- LINEAR_REG, LOGISTIC_REG
- BOOSTED_TREE_CLASSIFIER, BOOSTED_TREE_REGRESSOR
- DNN_CLASSIFIER, DNN_REGRESSOR
- AUTOML_CLASSIFIER, AUTOML_REGRESSOR
Vertex AI Training Job Template (templates/vertex_training_job.py)
Python template for custom training:
- Training loop structure
- Distributed training setup (PyTorch DDP)
- Checkpointing and model saving
- Metrics logging to Vertex AI
- Hyperparameter tuning integration
Includes:
- Single GPU training
- Multi-GPU training (DataParallel, DistributedDataParallel)
- TPU training with PyTorch/XLA
- Cloud Storage integration
GPU Configuration Template (templates/vertex_gpu_config.yaml)
YAML configuration for GPU training jobs:
- Machine type selection
- GPU type and count
- Disk configuration
- Network configuration
- Environment variables
Presets included:
- Single T4 (budget)
- Single A100 (standard)
- 4x A100 (distributed)
- 8x A100 (large-scale)
TPU Configuration Template (templates/vertex_tpu_config.yaml)
YAML configuration for TPU training jobs:
- TPU type and topology
- TPU version selection
- JAX/TensorFlow runtime
- XLA compilation flags
Presets included:
- v3-8 (single TPU)
- v4-32 (TPU pod slice)
- v5e-8 (cost-optimized)
GCP Authentication Template (templates/gcp_auth.json)
Service account configuration template:
- Project ID
- Service account email
- Key file path
- Required scopes
- IAM role assignments
Security notes:
- Uses placeholders only (never real keys)
- Documents how to create service accounts
- Includes
.gitignore protection
Examples
BigQuery ML Regression Example (examples/bigquery-regression-example.sql)
Complete example:
- Dataset: NYC taxi trip data
- Task: Predict trip duration
- Model: BOOSTED_TREE_REGRESSOR
- Includes feature engineering, training, evaluation
Demonstrates:
- CREATE MODEL syntax
- TRANSFORM clause for feature engineering
- MODEL evaluation
- Batch predictions
Vertex AI PyTorch Training Example (examples/vertex-pytorch-training.py)
Complete training script:
- Dataset: IMDB sentiment analysis
- Model: DistilBERT fine-tuning
- Training: Single GPU
- Logging: Vertex AI experiments
Demonstrates:
- Loading data from GCS
- Training loop with mixed precision
- Checkpointing to GCS
- Metrics logging
- Model export to Vertex AI
Vertex AI Distributed Training Example (examples/vertex-distributed-training.py)
Multi-GPU training example:
- Dataset: ImageNet subset
- Model: ResNet-50
- Training: 4x A100 with DDP
- Scaling: Linear scaling rule
Demonstrates:
- PyTorch DistributedDataParallel
- Gradient accumulation
- Learning rate scaling
- Synchronized batch norm
- Multi-node coordination
Hugging Face Fine-tuning on Vertex AI (examples/vertex-huggingface-finetuning.py)
Production fine-tuning template:
- Dataset: Custom text classification
- Model: BERT/RoBERTa/DeBERTa
- Training: Hugging Face Trainer API
- Deployment: Vertex AI endpoint
Demonstrates:
- Hugging Face Trainer integration
- Hyperparameter tuning with Vertex AI
- Model versioning
- Endpoint deployment
- Online predictions
Cost Optimization Tips
BigQuery ML
Reduce data processed:
- Use partitioned tables
- Filter data in WHERE clause before training
- Use table sampling for experimentation
- Cache intermediate results
Use appropriate model types:
- Start with LINEAR_REG/LOGISTIC_REG (cheapest)
- Use BOOSTED_TREE for better accuracy at moderate cost
- Reserve AutoML for when simpler models fail
Optimize queries:
- Avoid SELECT * (specify columns)
- Use clustering on filter columns
- Materialize views for repeated training
Vertex AI
Machine type selection:
- Start with CPU for prototyping
- Use T4 for small models (cheapest GPU)
- Use A100 only for large models that need it
- Consider TPU v5e for TensorFlow/JAX (very cost-effective)
Training optimization:
- Use preemptible instances (60-70% cheaper, can be interrupted)
- Enable automatic checkpoint/resume for preemptible
- Use mixed precision training (FP16/BF16) for faster training
- Profile to eliminate CPU bottlenecks
Storage optimization:
- Store datasets in Cloud Storage (cheaper than persistent disk)
- Use Filestore only if needed for POSIX filesystem
- Clean up old model artifacts
- Use lifecycle policies to archive old data
Multi-GPU efficiency:
- Ensure near-linear scaling before adding more GPUs
- Profile inter-GPU communication
- Use gradient accumulation instead of larger batch sizes
- Consider 2x GPUs instead of 1x larger GPU (often same cost, better availability)
Integration with ML Training Plugin
This skill integrates with other ml-training components:
- training-patterns: Provides GCP configs for generated training scripts
- cost-calculator: Uses GCP pricing data for budget planning
- monitoring-dashboard: Integrates with Vertex AI TensorBoard
- validation-scripts: Validates GCP credentials and permissions
- integration-helpers: Deploys trained models to Vertex AI endpoints
Common Workflows
Workflow 1: Quick BigQuery ML Prototype
- Run
bash scripts/setup-bigquery-ml.sh
- Copy
templates/bigquery_ml_training.sql to your project
- Modify SQL for your dataset and features
- Run training query in BigQuery console
- Evaluate with built-in ML.EVALUATE()
- Export predictions with ML.PREDICT()
Time: 30 minutes setup + training time
Cost: $5 per TB of data processed
Workflow 2: Custom PyTorch Training on Vertex AI
- Run
bash scripts/configure-auth.sh
- Run
bash scripts/setup-vertex-ai.sh
- Copy
templates/vertex_training_job.py
- Customize training loop for your model
- Copy
templates/vertex_gpu_config.yaml
- Submit job:
gcloud ai custom-jobs create ...
- Monitor in Vertex AI console
Time: 1 hour setup + training time
Cost: Depends on GPU/TPU selection
Workflow 3: Large-Scale Distributed Training
- Setup Vertex AI (workflow 2)
- Copy
examples/vertex-distributed-training.py
- Adapt for your model architecture
- Test locally with 1 GPU
- Test with 2 GPUs to verify scaling
- Scale to 4-8 GPUs for full training
- Use preemptible instances with checkpointing
Time: 2-4 hours setup + training time
Cost: $15-60/hour depending on GPU count
Troubleshooting
BigQuery ML Issues
"Insufficient permissions":
- Verify
roles/bigquery.dataEditor and roles/bigquery.jobUser
- Check dataset-level permissions
- Ensure billing is enabled
"Model training failed":
- Check for NULL values in features
- Verify data types match model expectations
- Review feature engineering TRANSFORM clause
- Check for sufficient training data
Vertex AI Issues
"Service account lacks permissions":
- Verify
roles/aiplatform.user
- Add
roles/storage.objectAdmin for GCS access
- Check project-level IAM policies
"GPU/TPU quota exceeded":
- Request quota increase in GCP console
- Use different region with availability
- Start with smaller GPU/TPU configuration
- Use preemptible instances (separate quota)
"Training job crashes":
- Check for CUDA OOM (reduce batch size)
- Verify dependencies in requirements.txt
- Review logs in Cloud Logging
- Test locally before submitting to Vertex
Security Best Practices
Credentials Management
DO:
- ✅ Use service accounts with minimal permissions
- ✅ Store credentials in Secret Manager
- ✅ Use Workload Identity for GKE deployments
- ✅ Rotate service account keys regularly
- ✅ Add
.gitignore for *.json key files
DON'T:
- ❌ Hardcode credentials in code
- ❌ Commit service account keys to git
- ❌ Use overly permissive roles (e.g., Owner)
- ❌ Share service account keys across projects
- ❌ Use personal credentials for production
IAM Best Practices
- Use separate service accounts for training vs serving
- Grant roles at resource level, not project level when possible
- Use Workload Identity Federation instead of keys when possible
- Enable Cloud Audit Logs for ML API usage
- Review IAM permissions quarterly
Performance Benchmarks
BigQuery ML vs Vertex AI
BigQuery ML:
- Best for: Structured data, SQL users, quick prototypes
- Training time: Minutes to hours (depends on data size)
- Scalability: Automatic (serverless)
- Cost: $5/TB processed
Vertex AI Custom Training:
- Best for: Deep learning, custom architectures, GPU/TPU workloads
- Training time: Hours to days (configurable hardware)
- Scalability: Manual (choose machine type)
- Cost: $0.35-20/hour depending on hardware
Rule of thumb:
- Use BigQuery ML for tabular data with < 100M rows
- Use Vertex AI for images, text, audio, or custom models
- Use Vertex AI for models requiring GPU/TPU acceleration
Additional Resources
1---2name: google-cloud-configs3description: Google Cloud Platform configuration templates for BigQuery ML and Vertex AI training with authentication setup, GPU/TPU configs, and cost estimation tools. Use when setting up GCP ML training, configuring BigQuery ML models, deploying Vertex AI training jobs, estimating GCP costs, configuring cloud authentication, selecting GPUs/TPUs for training, or when user mentions BigQuery ML, Vertex AI, GCP training, cloud ML setup, TPU training, or Google Cloud costs.4---5
6Use when:
7- Setting up BigQuery ML for SQL-based machine learning
8- Configuring Vertex AI custom training jobs
9- Setting up GCP authentication for ML workflows
10- Selecting appropriate GPU/TPU configurations
11- Estimating costs for GCP ML training
12- Deploying models to Vertex AI endpoints
13- Configuring distributed training on GCP
14- Optimizing cost vs performance for cloud ML
15
16## Platform Overview
17
18### BigQuery ML
19
20**What it is**: SQL-based machine learning directly in BigQuery
21**Best for**:
22- Quick ML prototypes using existing data warehouse data
23- Classification, regression, forecasting on structured data
24- Users familiar with SQL but not Python/ML frameworks
25- Large-scale batch predictions
26
27**Available Models**:
28- Linear/Logistic Regression
29- XGBoost (BOOSTED_TREE)
30- Deep Neural Networks (DNN)
31- AutoML Tables
32- TensorFlow/PyTorch imported models
33
34**Pricing**:
35- Based on data processed (same as BigQuery queries)
36- $5 per TB processed for analysis
37- AutoML: $19.32/hour for training
38
39### Vertex AI Training
40
41**What it is**: Fully managed ML training platform
42**Best for**:
43- Custom PyTorch/TensorFlow training
44- Large-scale distributed training
45- GPU/TPU-accelerated workloads
46- Production ML pipelines
47
48**Available Compute**:
49- **CPUs**: n1-standard, n1-highmem, n1-highcpu
50- **GPUs**: NVIDIA T4, P4, V100, P100, A100, L4
51- **TPUs**: v2, v3, v4, v5e (8 cores to 512 cores)
52
53**Pricing**:
54- CPU: $0.05-0.30/hour depending on machine type
55- GPU T4: $0.35/hour
56- GPU A100: $3.67/hour (40GB) or $4.95/hour (80GB)
57- TPU v3: $8.00/hour (8 cores)
58- TPU v4: $11.00/hour (8 cores)
59
60## GPU/TPU Selection Guide
61
62### GPU Selection (Vertex AI)
63
64**T4 (16GB VRAM)**:
65- Use case: Inference, light training, small models
66- Cost: $0.35/hour
67- Good for: BERT-base, small CNNs, inference serving
68
69**V100 (16GB VRAM)**:
70- Use case: Mid-size training, mixed precision training
71- Cost: $2.48/hour
72- Good for: ResNet training, medium transformers
73
74**A100 (40GB/80GB VRAM)**:
75- Use case: Large model training, distributed training
76- Cost: $3.67/hour (40GB), $4.95/hour (80GB)
77- Good for: GPT-style models, large vision models, multi-GPU training
78
79**L4 (24GB VRAM)**:
80- Use case: Modern alternative to T4, better performance
81- Cost: $0.66/hour
82- Good for: Mid-size models, efficient inference
83
84### TPU Selection (Vertex AI)
85
86**TPU v2 (8 cores)**:
87- Use case: TensorFlow/JAX training, matrix operations
88- Cost: $4.50/hour
89- Memory: 8GB per core (64GB total)
90- Good for: Legacy TensorFlow models
91
92**TPU v3 (8 cores)**:
93- Use case: Standard TPU training
94- Cost: $8.00/hour
95- Memory: 16GB per core (128GB total)
96- Good for: BERT, T5, image classification
97
98**TPU v4 (8 cores)**:
99- Use case: Latest generation, best performance
100- Cost: $11.00/hour
101- Memory: 32GB per core (256GB total)
102- Good for: Large language models, cutting-edge research
103
104**TPU v5e (8 cores)**:
105- Use case: Cost-optimized TPU
106- Cost: $2.50/hour
107- Good for: Development, training at scale on budget
108
109**Multi-node TPU Pods**:
110- v3-32: 32 cores, $32/hour
111- v3-128: 128 cores, $128/hour
112- v4-128: 128 cores, $176/hour
113- Use for: Massive distributed training (GPT-3 scale)
114
115## Usage
116
117### Setup BigQuery ML Environment
118
119```bash
120bash scripts/setup-bigquery-ml.sh
121```
122
123**Prompts for**:
124- GCP Project ID
125- BigQuery dataset name
126- Service account credentials
127- Default model type preference
128
129**Creates**:
130- `bigquery_config.json` - Project configuration
131- `.bigqueryrc` - CLI configuration
132- Example training SQL in examples/
133
134### Setup Vertex AI Training Environment
135
136```bash
137bash scripts/setup-vertex-ai.sh
138```
139
140**Prompts for**:
141- GCP Project ID
142- Region (us-central1, europe-west4, etc.)
143- Service account credentials
144- Default machine type
145- GPU/TPU preference
146
147**Creates**:
148- `vertex_config.yaml` - Training job configuration
149- `vertex_requirements.txt` - Python dependencies
150- Training script template
151
152### Configure GCP Authentication
153
154```bash
155bash scripts/configure-auth.sh
156```
157
158**Prompts for**:
159- Authentication method (service account, user account, workload identity)
160- Service account key path (if applicable)
161- IAM roles needed
162
163**Creates**:
164- `.gcp_auth_config` - Authentication configuration
165- Sets GOOGLE_APPLICATION_CREDENTIALS environment variable
166- Validates permissions
167
168**Required IAM Roles**:
169- BigQuery ML: `roles/bigquery.dataEditor`, `roles/bigquery.jobUser`
170- Vertex AI: `roles/aiplatform.user`, `roles/storage.objectAdmin`
171- Both: `roles/serviceusage.serviceUsageConsumer`
172
173### Estimate GCP Training Costs
174
175```bash
176bash scripts/estimate-gcp-cost.sh
177```
178
179**Interactive prompts**:
180- Platform: BigQuery ML or Vertex AI
181- If BigQuery ML: Data size to process
182- If Vertex AI:
183 - Machine type (CPU/GPU/TPU)
184 - Number of machines
185 - Training duration estimate
186 - Storage requirements
187
188**Output**:
189- Estimated compute cost
190- Storage cost
191- Data transfer cost (if applicable)
192- Total estimated cost
193- Cost comparison with other GCP options
194
195## Templates
196
197### BigQuery ML Training Template (`templates/bigquery_ml_training.sql`)
198
199SQL template for creating and training models:
200- Model creation syntax
201- Feature engineering examples
202- Training options (L1/L2 reg, learning rate, etc.)
203- Evaluation queries
204- Prediction queries
205
206**Supported model types**:
207- LINEAR_REG, LOGISTIC_REG
208- BOOSTED_TREE_CLASSIFIER, BOOSTED_TREE_REGRESSOR
209- DNN_CLASSIFIER, DNN_REGRESSOR
210- AUTOML_CLASSIFIER, AUTOML_REGRESSOR
211
212### Vertex AI Training Job Template (`templates/vertex_training_job.py`)
213
214Python template for custom training:
215- Training loop structure
216- Distributed training setup (PyTorch DDP)
217- Checkpointing and model saving
218- Metrics logging to Vertex AI
219- Hyperparameter tuning integration
220
221**Includes**:
222- Single GPU training
223- Multi-GPU training (DataParallel, DistributedDataParallel)
224- TPU training with PyTorch/XLA
225- Cloud Storage integration
226
227### GPU Configuration Template (`templates/vertex_gpu_config.yaml`)
228
229YAML configuration for GPU training jobs:
230- Machine type selection
231- GPU type and count
232- Disk configuration
233- Network configuration
234- Environment variables
235
236**Presets included**:
237- Single T4 (budget)
238- Single A100 (standard)
239- 4x A100 (distributed)
240- 8x A100 (large-scale)
241
242### TPU Configuration Template (`templates/vertex_tpu_config.yaml`)
243
244YAML configuration for TPU training jobs:
245- TPU type and topology
246- TPU version selection
247- JAX/TensorFlow runtime
248- XLA compilation flags
249
250**Presets included**:
251- v3-8 (single TPU)
252- v4-32 (TPU pod slice)
253- v5e-8 (cost-optimized)
254
255### GCP Authentication Template (`templates/gcp_auth.json`)
256
257Service account configuration template:
258- Project ID
259- Service account email
260- Key file path
261- Required scopes
262- IAM role assignments
263
264**Security notes**:
265- Uses placeholders only (never real keys)
266- Documents how to create service accounts
267- Includes `.gitignore` protection
268
269## Examples
270
271### BigQuery ML Regression Example (`examples/bigquery-regression-example.sql`)
272
273Complete example:
274- Dataset: NYC taxi trip data
275- Task: Predict trip duration
276- Model: BOOSTED_TREE_REGRESSOR
277- Includes feature engineering, training, evaluation
278
279**Demonstrates**:
280- CREATE MODEL syntax
281- TRANSFORM clause for feature engineering
282- MODEL evaluation
283- Batch predictions
284
285### Vertex AI PyTorch Training Example (`examples/vertex-pytorch-training.py`)
286
287Complete training script:
288- Dataset: IMDB sentiment analysis
289- Model: DistilBERT fine-tuning
290- Training: Single GPU
291- Logging: Vertex AI experiments
292
293**Demonstrates**:
294- Loading data from GCS
295- Training loop with mixed precision
296- Checkpointing to GCS
297- Metrics logging
298- Model export to Vertex AI
299
300### Vertex AI Distributed Training Example (`examples/vertex-distributed-training.py`)
301
302Multi-GPU training example:
303- Dataset: ImageNet subset
304- Model: ResNet-50
305- Training: 4x A100 with DDP
306- Scaling: Linear scaling rule
307
308**Demonstrates**:
309- PyTorch DistributedDataParallel
310- Gradient accumulation
311- Learning rate scaling
312- Synchronized batch norm
313- Multi-node coordination
314
315### Hugging Face Fine-tuning on Vertex AI (`examples/vertex-huggingface-finetuning.py`)
316
317Production fine-tuning template:
318- Dataset: Custom text classification
319- Model: BERT/RoBERTa/DeBERTa
320- Training: Hugging Face Trainer API
321- Deployment: Vertex AI endpoint
322
323**Demonstrates**:
324- Hugging Face Trainer integration
325- Hyperparameter tuning with Vertex AI
326- Model versioning
327- Endpoint deployment
328- Online predictions
329
330## Cost Optimization Tips
331
332### BigQuery ML
333
334**Reduce data processed**:
335- Use partitioned tables
336- Filter data in WHERE clause before training
337- Use table sampling for experimentation
338- Cache intermediate results
339
340**Use appropriate model types**:
341- Start with LINEAR_REG/LOGISTIC_REG (cheapest)
342- Use BOOSTED_TREE for better accuracy at moderate cost
343- Reserve AutoML for when simpler models fail
344
345**Optimize queries**:
346- Avoid SELECT * (specify columns)
347- Use clustering on filter columns
348- Materialize views for repeated training
349
350### Vertex AI
351
352**Machine type selection**:
353- Start with CPU for prototyping
354- Use T4 for small models (cheapest GPU)
355- Use A100 only for large models that need it
356- Consider TPU v5e for TensorFlow/JAX (very cost-effective)
357
358**Training optimization**:
359- Use preemptible instances (60-70% cheaper, can be interrupted)
360- Enable automatic checkpoint/resume for preemptible
361- Use mixed precision training (FP16/BF16) for faster training
362- Profile to eliminate CPU bottlenecks
363
364**Storage optimization**:
365- Store datasets in Cloud Storage (cheaper than persistent disk)
366- Use Filestore only if needed for POSIX filesystem
367- Clean up old model artifacts
368- Use lifecycle policies to archive old data
369
370**Multi-GPU efficiency**:
371- Ensure near-linear scaling before adding more GPUs
372- Profile inter-GPU communication
373- Use gradient accumulation instead of larger batch sizes
374- Consider 2x GPUs instead of 1x larger GPU (often same cost, better availability)
375
376## Integration with ML Training Plugin
377
378This skill integrates with other ml-training components:
379
380- **training-patterns**: Provides GCP configs for generated training scripts
381- **cost-calculator**: Uses GCP pricing data for budget planning
382- **monitoring-dashboard**: Integrates with Vertex AI TensorBoard
383- **validation-scripts**: Validates GCP credentials and permissions
384- **integration-helpers**: Deploys trained models to Vertex AI endpoints
385
386## Common Workflows
387
388### Workflow 1: Quick BigQuery ML Prototype
389
3901. Run `bash scripts/setup-bigquery-ml.sh`
3912. Copy `templates/bigquery_ml_training.sql` to your project
3923. Modify SQL for your dataset and features
3934. Run training query in BigQuery console
3945. Evaluate with built-in ML.EVALUATE()
3956. Export predictions with ML.PREDICT()
396
397**Time**: 30 minutes setup + training time
398**Cost**: $5 per TB of data processed
399
400### Workflow 2: Custom PyTorch Training on Vertex AI
401
4021. Run `bash scripts/configure-auth.sh`
4032. Run `bash scripts/setup-vertex-ai.sh`
4043. Copy `templates/vertex_training_job.py`
4054. Customize training loop for your model
4065. Copy `templates/vertex_gpu_config.yaml`
4076. Submit job: `gcloud ai custom-jobs create ...`
4087. Monitor in Vertex AI console
409
410**Time**: 1 hour setup + training time
411**Cost**: Depends on GPU/TPU selection
412
413### Workflow 3: Large-Scale Distributed Training
414
4151. Setup Vertex AI (workflow 2)
4162. Copy `examples/vertex-distributed-training.py`
4173. Adapt for your model architecture
4184. Test locally with 1 GPU
4195. Test with 2 GPUs to verify scaling
4206. Scale to 4-8 GPUs for full training
4217. Use preemptible instances with checkpointing
422
423**Time**: 2-4 hours setup + training time
424**Cost**: $15-60/hour depending on GPU count
425
426## Troubleshooting
427
428### BigQuery ML Issues
429
430**"Insufficient permissions"**:
431- Verify `roles/bigquery.dataEditor` and `roles/bigquery.jobUser`
432- Check dataset-level permissions
433- Ensure billing is enabled
434
435**"Model training failed"**:
436- Check for NULL values in features
437- Verify data types match model expectations
438- Review feature engineering TRANSFORM clause
439- Check for sufficient training data
440
441### Vertex AI Issues
442
443**"Service account lacks permissions"**:
444- Verify `roles/aiplatform.user`
445- Add `roles/storage.objectAdmin` for GCS access
446- Check project-level IAM policies
447
448**"GPU/TPU quota exceeded"**:
449- Request quota increase in GCP console
450- Use different region with availability
451- Start with smaller GPU/TPU configuration
452- Use preemptible instances (separate quota)
453
454**"Training job crashes"**:
455- Check for CUDA OOM (reduce batch size)
456- Verify dependencies in requirements.txt
457- Review logs in Cloud Logging
458- Test locally before submitting to Vertex
459
460## Security Best Practices
461
462### Credentials Management
463
464**DO**:
465- ✅ Use service accounts with minimal permissions
466- ✅ Store credentials in Secret Manager
467- ✅ Use Workload Identity for GKE deployments
468- ✅ Rotate service account keys regularly
469- ✅ Add `.gitignore` for `*.json` key files
470
471**DON'T**:
472- ❌ Hardcode credentials in code
473- ❌ Commit service account keys to git
474- ❌ Use overly permissive roles (e.g., Owner)
475- ❌ Share service account keys across projects
476- ❌ Use personal credentials for production
477
478### IAM Best Practices
479
480- Use separate service accounts for training vs serving
481- Grant roles at resource level, not project level when possible
482- Use Workload Identity Federation instead of keys when possible
483- Enable Cloud Audit Logs for ML API usage
484- Review IAM permissions quarterly
485
486## Performance Benchmarks
487
488### BigQuery ML vs Vertex AI
489
490**BigQuery ML**:
491- Best for: Structured data, SQL users, quick prototypes
492- Training time: Minutes to hours (depends on data size)
493- Scalability: Automatic (serverless)
494- Cost: $5/TB processed
495
496**Vertex AI Custom Training**:
497- Best for: Deep learning, custom architectures, GPU/TPU workloads
498- Training time: Hours to days (configurable hardware)
499- Scalability: Manual (choose machine type)
500- Cost: $0.35-20/hour depending on hardware
501
502**Rule of thumb**:
503- Use BigQuery ML for tabular data with < 100M rows
504- Use Vertex AI for images, text, audio, or custom models
505- Use Vertex AI for models requiring GPU/TPU acceleration
506
507## Additional Resources
508
509- **GCP ML Documentation**: https://cloud.google.com/vertex-ai/docs
510- **BigQuery ML Reference**: https://cloud.google.com/bigquery-ml/docs
511- **Pricing Calculator**: https://cloud.google.com/products/calculator
512- **TPU Best Practices**: https://cloud.google.com/tpu/docs/best-practices
513- **Vertex AI Samples**: https://github.com/GoogleCloudPlatform/vertex-ai-samples