Compare commits

...
269 Commits
Author SHA1 Message Date
Andrew Ferlitsch b653712a6a debug: internal error 2023-07-14 22:29:41 +00:00
dstnluong-googleandGitHub 2f7078e6a8 Cleanup IOD proprietary notebook. (#2035)
* Cleanup proprietary IOD notebook

* lint

* fix: aip to aiplatform
2023-07-14 18:18:45 +00:00
dstnluong-googleandGitHub 393bb67645 Cleanup ICN proprietary notebook. (#2034)
* Clean up ICN proprietary notebook

* Lint

* add back region check
2023-07-14 18:18:06 +00:00
genquan9andGitHub b945549ec4 minor updates for peft notebooks with BERT supports (#2089)
* fix typos in keras model deployment

* minor updates for peft notebooks with BERT supports
2023-07-14 18:05:45 +00:00
Xiang XuandGitHub d963893088 remove t5 (#2088) 2023-07-14 18:05:03 +00:00
dstnluong-googleandGitHub 7ffbf0cde7 Add pylintrc to model_oss (#2085) 2023-07-14 18:04:21 +00:00
Sebastian SchmidtandGitHub fb978444f7 Update wording in MediaPipe notebooks (#2084) 2023-07-14 18:03:40 +00:00
dstnluong-googleandGitHub de35525c70 Install entire diffusers repository rather than diffusers package (#2081)
* Install entire diffusers repository rather than diffusers package

* Remove google3 references

* Update diffuser install for serve.Dockerfile

* Add video_utils

* Move common functions to util and video_util.

* Fix dockerfile commands by adding $
2023-07-14 18:02:53 +00:00
Andrew FerlitschandGitHub feb0e6410d feat: add arg for max concurrent notebooks (#2080) 2023-07-14 18:02:01 +00:00
Andrew FerlitschandGitHub 6b1c0b35e8 fix help msg (#2079)
* feat: make rate limit a cmdarg

* review: rename cmd arg

* fix: replace rate_limit with max_threads

* fix: docstring typo
2023-07-14 18:01:36 +00:00
dstnluong-googleandGitHub 04540495f0 Add transformers serve files. (#2075)
* Add transformers serve files.

* Add transformer files to CODEOWNERS

* Add image_format_converter.py to utils

* Add $ to dockerfile example commands.
2023-07-14 18:01:04 +00:00
bingatgoogleandGitHub ad6e554984 Add the stable diffusion 2.1 notebook (#2087) 2023-07-12 20:09:48 +00:00
Andrew FerlitschandGitHub ee52b0487c feat: make rate limit a cmdarg (#2078)
* feat: make rate limit a cmdarg

* review: rename cmd arg

* fix: replace rate_limit with max_threads
2023-07-07 15:58:48 +00:00
Andrew FerlitschandGitHub 89b494b96d Attempt to fix CI/CD issue (#2074)
* Attempt to fix CI/CD issue

* Fix TF import
2023-07-06 21:50:39 +00:00
genquan9andGitHub 5cc8751c20 fix typos in keras model deployment (#2070) 2023-07-06 15:53:11 +00:00
genquan9andGitHub 0a22ad7578 Add model garden peft notebooks for LLMs (#2063)
* add model garden peft notebooks for LLMs

* fix comments and minor update peft notebook descriptions
2023-07-05 15:27:31 +00:00
dstnluong-googleandGitHub 792313cce5 Remove bad parameters for local stable diffusion. (#2062) 2023-06-30 19:52:18 +00:00
Andrew FerlitschandGitHub 27e87047bb fix: lint (#2065) 2023-06-30 17:53:05 +00:00
Xiang XuandGitHub 145b2cab33 add restart (#2064) 2023-06-30 16:22:06 +00:00
Andrew FerlitschandGitHub ca65becfe3 debug: lint (#2061) 2023-06-29 01:36:53 +00:00
Andrew FerlitschandGitHub eeb5a9f6e4 fix: lint (#2059) 2023-06-29 01:35:45 +00:00
Andrew FerlitschandGitHub c5f11d35d5 debug: lint (#2060) 2023-06-29 01:34:23 +00:00
Andrew FerlitschandGitHub 91beb065ff next try at resolving lint issue (#2057) 2023-06-28 19:19:49 +00:00
Huguens JeanandGitHub c22fe20973 add missing pycocotools import (#2058) 2023-06-28 16:27:42 +00:00
Andrew FerlitschandGitHub e97e5ed7cc debug: check if passes 29 (#2053) 2023-06-28 12:55:48 +00:00
Andrew FerlitschandGitHub be98093169 fix: check if passes 24 (#2048)
* fix: check if passes 24

* fix: lint
2023-06-28 12:54:58 +00:00
Andrew FerlitschandGitHub ea8bc3f993 debug: check if passes 23 (#2047) 2023-06-28 12:54:19 +00:00
Andrew FerlitschandGitHub bcacc0d0d4 set pyupgrade to use Python 3.10 for consistency with Docker version (#2055) 2023-06-27 22:01:09 +00:00
Andrew FerlitschandGitHub 656afd3cff debug: check if passes 28 (#2052) 2023-06-27 20:11:13 +00:00
Andrew FerlitschandGitHub e6ae1b185c debug: check if passes 27 (#2051) 2023-06-27 20:10:47 +00:00
Andrew FerlitschandGitHub b0fdf128c3 debug: check if passes 25 (#2049) 2023-06-27 19:40:44 +00:00
Huguens JeanandGitHub 99c4f80558 SAM notebook final qa. (#2039) 2023-06-27 17:43:05 +00:00
Andrew FerlitschandGitHub 71436766d2 debug: check if passes 22 (#2046) 2023-06-27 17:39:30 +00:00
Andrew FerlitschandGitHub 2ad5331658 debug: check if passes 19 (#2043) 2023-06-27 17:13:24 +00:00
Andrew FerlitschandGitHub 83d231ada8 debug: check if passes 18 (#2042) 2023-06-27 17:12:48 +00:00
Andrew FerlitschandGitHub 6479533e29 Check if passes 17 (#2041)
* fix: boulerplate reduction

* fix: IS_COLAB

* fix: IS_COLAB

* debug: check if passes 17
2023-06-27 17:12:22 +00:00
Andrew FerlitschandGitHub 6e7ec746d1 update: lower rate limit (#2036)
per Ivan suggested, change greedy=True to greedy=False
2023-06-27 16:46:05 +00:00
Mend RenovateandGitHub efd08571df chore(deps): update dependency pyupgrade to v3.7.0 (#1986) 2023-06-27 15:38:19 +00:00
Andrew FerlitschandGitHub 44c868c4b4 fix: boilerplate reduction (#2032)
* fix: boulerplate reduction

* fix: IS_COLAB

* fix: IS_COLAB
2023-06-27 15:34:50 +00:00
Alicia WilliamsandGitHub 59f7fa0fd9 Remove allowlist note (#2033) 2023-06-26 23:39:45 +00:00
Andrew FerlitschandGitHub 2c3f2736eb fix: check if passes 16 (#2031) 2023-06-26 19:40:25 +00:00
Andrew FerlitschandGitHub ed54360fc7 fix: check if passes 15 (#2030) 2023-06-26 19:39:48 +00:00
Sebastian SchmidtandGitHub 66506d4269 Add MediaPipe Object Detection Colab to Model Garden (#2025) 2023-06-26 16:20:19 +00:00
099876c411 Remove VIT from the model_type list since it is not supported yet. (#2009)
* Add diffusers train/serve docker files.

* Add two notebook examples for model garden google proprietary ICN/IOD models.

* Reformat the icn/iod notebooks.

* Format the notebook files.

* Remove VIT from the  list since it is not supported yet.

---------

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2023-06-26 16:14:33 +00:00
Huguens JeanandGitHub bfd36eecbb Cleanup SAM segmentation notebook (#2027)
* Cleanup SAM notebook to:
 - run endpoint/model deployment in separate cell and results visualization in another.
 - add show_predictions function to show overlayed masks.

* Fix typo in SAM model garden notebook.

* Fix typo and cleanup SAM notebook with linter.
2023-06-26 16:13:47 +00:00
Andrew FerlitschandGitHub b82ade00bb fix: stale dataset > 24hrs (#1928)
* fix: stale dataset

* fix: project ID
2023-06-26 12:14:22 +00:00
Andrew FerlitschandGitHub 68f3500196 fix: boilerplate reduction 112 (#2023)
* fix: boilerplate reduction 112

* fix: machine type

* fix: cleanup

* fix: cleanup

* fix: lint

* fix: lint

* fix: exception
2023-06-26 12:13:04 +00:00
Andrew FerlitschandGitHub 74b5b8ce59 fix: boilerplate reduction 18 - > 24hrs (#1844)
* fix: boilerplate reduction 18

* fix: boilerplate reduction 18

* missing import

* fix: create AR repo

* fix: gcloud update
2023-06-23 23:38:38 +00:00
Andrew FerlitschandGitHub 6627f58dac fix: boilerplate reduction 19 - >24hrs (#1845)
* fix: boilerplate reduction 19

* fix: create AR repo

* fix: fb install

* fix: install gcloud

* fix: syntax error
2023-06-23 22:01:39 +00:00
Andrew FerlitschandGitHub 31fdffd56a fix: boilerplate reduction 49 - import protobuf (#1884)
* fix: boilerplate reduction 49

* fix: syntax error

* fix: install

* fix indent

* Update model_monitoring.ipynb

* fix TF install

* TF install

* fix: pin protobuf

* install protobuf

* another attempt at fixing import

* fix: pin versions

* fix: imports

* debug: TF conflict

* fix: user email
2023-06-23 22:01:06 +00:00
Andrew FerlitschandGitHub 15bec0d5ba fix: boilerplate reduction 71 - model path (#1943)
* fix: boilerplate reduction 71

* bucket name

* bucket name

* fix: bucket

* fix: bucket

* fix: storage path

* fix: model path
2023-06-23 22:00:43 +00:00
Andrew FerlitschandGitHub f0a2b16f75 fix: boiletplate reduction 105 (#2016)
* fix: boiletplate reduction 105

* fix: missing REGION

* fix: missing import

* Fix: cleanup
2023-06-23 22:00:28 +00:00
Andrew FerlitschandGitHub 3c6a5b3245 fix: boilerplate reduction 106 (#2017)
* fix: boilerplate reduction 105

* fix: bucket name

* fix: cleanup
2023-06-23 22:00:25 +00:00
Sebastian SchmidtandGitHub 21ba3b0f71 Small content updates for ImageClassification notebook (#2024) 2023-06-23 19:07:33 +00:00
Andrew FerlitschandGitHub d15a635917 fix: boilerplate reduction 111 (#2022)
* fix: boilerplate reduction 111

* fix: TIMESTAMP
2023-06-23 18:36:48 +00:00
dstnluong-googleandGitHub ce18d2a32a Add MaxViT to the TFVision ICN Notebook. (#1974)
* Add MaxViT to TFVision ICN Notebook

* Lint
2023-06-23 17:55:51 +00:00
Andrew FerlitschandGitHub 12cbd5a082 fix: boilerplate 103 (#2010)
* fix: boilerplate 103

* fix: REGION
2023-06-23 17:08:05 +00:00
Andrew FerlitschandGitHub 86fbbdbe01 fix: boilerplate reduction 109 (#2020)
* fix: boilerplate reduction 109

* fix: remove unused code

* fix: train image
2023-06-23 12:34:09 +00:00
Andrew FerlitschandGitHub 191424175e fix: boilerplate reduction 110 (#2021) 2023-06-23 12:32:53 +00:00
Andrew FerlitschandGitHub c544933d44 fix: boilerplate reduction 108 (#2019)
* fix: boilerplate reduction 108

* fix: missing import

* fix: missing import
2023-06-23 12:32:06 +00:00
Andrew FerlitschandGitHub fff8aad453 fix: boilerplate reduction 107 (#2018) 2023-06-23 12:30:58 +00:00
Andrew FerlitschandGitHub 3c3c924917 fix: boilerplate reduction 104 (#2015) 2023-06-23 12:30:01 +00:00
Andrew FerlitschandGitHub a874825e61 fix: check if passes 11 (#2013) 2023-06-23 12:28:58 +00:00
Andrew FerlitschandGitHub 10ca70f9b3 fix: boilerplate reduction 100 (#2005) 2023-06-23 12:27:24 +00:00
Andrew FerlitschandGitHub b640558e09 fix: check if passes 7 (#2004) 2023-06-23 12:26:20 +00:00
Andrew FerlitschandGitHub b5169f96b7 Check passes 10 (#2012)
* fix: check if passes 9

* fix: check if passes 10
2023-06-22 21:19:44 +00:00
Andrew FerlitschandGitHub b7a3c3faed fix: check if passes 9 (#2011) 2023-06-22 19:35:47 +00:00
weigaryandGitHub 9ae5ce3276 Updates to the vision diffusers. (#2008)
* Add diffusers train/serve docker files.

* Updates to the vision diffusers.
2023-06-22 18:11:06 +00:00
Andrew FerlitschandGitHub bce7d73867 fix: check if passes 8 (#2006) 2023-06-22 17:57:16 +00:00
Sebastian SchmidtandGitHub 708861b55c Add MediaPipe Image Classification notebook (#1991)
* Add MediaPipe Image Classification notebook

* Add to Codeowners

* Move to MG Community

* Update notebook

* Remove mediapipe-model-maker
2023-06-22 15:55:10 +00:00
Andrew FerlitschandGitHub 93f36606a2 fix: check if passes #5 (#2001) 2023-06-22 14:48:06 +00:00
Andrew FerlitschandGitHub 373795f9f8 fix: check if passes #4 (#2000) 2023-06-22 14:47:22 +00:00
Andrew FerlitschandGitHub d9bb986997 fix: boilerplate reduction 99 (#2003) 2023-06-22 12:41:40 +00:00
Andrew FerlitschandGitHub 048336b6d2 900 sec timeout - Model.upload (#1984)
* check if passes

* lint: fix

* fix: fix XAI issue
2023-06-22 02:21:46 +00:00
Andrew FerlitschandGitHub 9340737a8e feat: boilerplate reduction 60 - DAG failed (#1918)
* feat: boilerplate reduction 60

* fix: CI/CD failure
2023-06-22 02:20:34 +00:00
dstnluong-googleandGitHub e801ede0c8 Remove "--allow_compression" flag on serving for Yolo models. (#1994)
* Remove --allow_compression for Yolo models.

* Lint
2023-06-21 22:23:02 +00:00
Lav RaiandGitHub 7fce82b608 Add ViT JAX notebook. (#1997)
* Add ViT JAX notebook.

* Add ViT JAX notebook.
2023-06-21 19:06:46 +00:00
Andrew FerlitschandGitHub 20440b6418 fix: boilerplate reduction 72 - DAG failed (#1944)
* fix: boilerplate reduction 72

* fix: region

* data region

* fix: import os

* fix: lint

* fix: lint

* fix: lint
2023-06-21 18:37:11 +00:00
Andrew FerlitschandGitHub ef69968160 fix: boilerplate reduction 82 : custom job not created (#1953)
* fix: boilerplate reduction 82

* fix: IS_COLAB

* fix: AR repo

* fix: indent

* fix: import os

* fix: enable api

* fix: delete AR

* fix: longer pause

* fix: pause
2023-06-21 17:52:46 +00:00
Andrew FerlitschandGitHub 9bbe7c6643 fix: boilerplate reduction 84: NumPy array to a Tensor (#1955)
* fix: boilerplate reduction 84

* install numpy

* fix: numpy type

* add import numpy

* fix: np type

* fix: syntax error
2023-06-21 16:48:24 +00:00
weigaryandGitHub 84875c4814 Notebook (#1996)
* Add diffusers train/serve docker files.

* Add two notebook examples for model garden google proprietary ICN/IOD models.

* Reformat the icn/iod notebooks.

* Format the notebook files.
2023-06-21 16:23:05 +00:00
Anthony TripaldiandGitHub 28fb284400 Update broken link for data format (#1992) 2023-06-21 15:37:41 +00:00
Andrew FerlitschandGitHub 441e4e7965 fix: check if passes - training failed - no model (#1988)
* fix: check if passes

* fix: import tf
2023-06-21 12:27:04 +00:00
weigaryandGitHub 52d1fe548e Add diffusers train/serve docker files. (#1995) 2023-06-21 00:17:03 +00:00
71921231dc Fixed typo and linkback - 900 sec timeout (#1551)
* Update automl_text_classification_model_evaluation.ipynb

* pin components

---------

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2023-06-21 00:10:35 +00:00
Andrew FerlitschandGitHub 0553f768eb boilerplate reduction #97 (#1990)
* boilerplate reduction #100

* fix: import os

* fix: AR stuff

* fix: syntax error
2023-06-20 23:52:33 +00:00
Andrew FerlitschandGitHub 9a0037bb64 fix: cleanup AR > 24hrs (#1929)
* fix: repo cleanup

* fix: delete AR

* fix: unique repo name

* fix: enable service

* fix: artifact repo create

* fix: create AR repo

* fix: AR create

* fix: IS_COLAB

* fix: gcloud install components

* --quiet option
2023-06-20 21:57:19 +00:00
Andrew FerlitschandGitHub 68aad86385 Check passes 4 (#1989)
* check if passes

* fix: bucket name
2023-06-20 19:14:06 +00:00
Andrew FerlitschandGitHub 520a0b0ae8 fix: boilerplate reduction 85 - BUCKET_NAME (#1956)
* fix: boilerplate reduction 85

* db-dtypes

* fix: pin seaborn

* handle exception

* fix: bucket name
2023-06-20 16:04:00 +00:00
Andrew FerlitschandGitHub 8e817a4ece check if passes (#1985) 2023-06-19 16:05:51 +00:00
Andrew FerlitschandGitHub 7391eed85c Update sdk_custom_tabular_regression_online_explain.ipynb (#1983) 2023-06-19 14:03:23 +00:00
Andrew FerlitschandGitHub 578b118329 Check if passes (#1982) 2023-06-19 14:02:49 +00:00
Andrew FerlitschandGitHub 4bd9d4c54b fix: boilerplate reduction 29 - XAI issue (#1856)
* fix: boilerplate reduction 29

* Fix TF issue, upgrade to 2.11

* Fix: missing cv install

* Update sdk_custom_image_classification_online_explain.ipynb
2023-06-16 19:31:08 +00:00
weigaryandGitHub c97aedf227 Add two additional files to the util directory. (#1981)
* Add the first util class to the vertex-vision-model-garden repo

* Updated file names.

* Delete the 1st incorrect file set.

* Add the codeowners

* Revised the file folder structures.

* Add two additional files to the util directory.
2023-06-16 19:23:32 +00:00
weigaryandGitHub 6bb255bc5f Add the first util class to the vertex_vision_model_garden repo. (#1978)
* Add the first util class to the vertex-vision-model-garden repo

* Updated file names.

* Delete the 1st incorrect file set.

* Add the codeowners

* Revised the file folder structures.
2023-06-16 19:22:51 +00:00
Eric DongandGitHub 5a96b4a335 fix: pin protobuf version to address a dependency compatibility issue (#1980)
* fix: pin protobuf version to address a dependency compability issue

* removed --user install

* update protobuf version

* workaround an artifact registry
2023-06-16 19:18:35 +00:00
Andrew FerlitschandGitHub b502254a10 Weekly index (#1972)
* feat: add build to generate web index of official notebooks

* fix: review comments

* fix: store results

* fix: store results

* fix: --steps

* fix: --steps

* fix: moved to its own dir
2023-06-16 18:26:54 +00:00
ec6ba9ecf0 Add the text2video-zero notebook (#1977)
* Add the text2video-zero notebook.

* Add code owner for text2video-zero.

---------

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2023-06-16 17:38:36 +00:00
KCFindstrandGitHub 709745f405 Add #ModelGarden text-to-video notebook. (#1973) 2023-06-16 17:36:51 +00:00
Huguens JeanandGitHub 0b1046e6c6 Add Segment Anything (SAM) notebook to model garden community folder. (#1975)
* Add Segment Anything (SAM) notebook to model garden community folder.

* Added SAM notebook to the CODEOWNERS file.
2023-06-16 17:34:19 +00:00
Andrew FerlitschandGitHub f6ae1205dc fix: create AR repo > 24hrs (#1937)
* fix: create AR repo

* fix: gcloud install
2023-06-15 20:53:16 +00:00
ab98cf8b36 fix: boilerplate reduction 67 : training pipeline failed (#1939)
* fix: boilerplate reduction 67

* fix: pin transformers version to avoid Pytorch breaking change (#1979)

---------

Co-authored-by: Eric Dong <itseric@google.com>
2023-06-15 16:41:53 +00:00
Andrew FerlitschandGitHub c60e8d1e3d feat: add build to generate web index of official notebooks (#1971)
* feat: add build to generate web index of official notebooks

* fix: review comments

* fix: store results
2023-06-13 20:08:04 +00:00
Andrew FerlitschandGitHub f1e3b02eb0 fix: boilerplate reduction 73 - DAG failed (#1945)
* fix: boilerplate reduction 73

* fix: region

* import os

* fix: import uuid

* fix: lint
2023-06-13 12:38:39 +00:00
Mend RenovateandGitHub 5885cb3724 chore(deps): update dependency pyupgrade to v3.6.0 (#1969) 2023-06-11 13:40:09 +00:00
Andrew FerlitschandGitHub 9827ae0218 fix: boilerplate reduction 27 - Internal error (#1854)
* fix: boilerplate reduction 27

* fix: import os
2023-06-10 00:19:55 +00:00
Andrew FerlitschandGitHub 712a066981 fix: boilerplate reduction 28 - internal error, try again (#1855)
* fix: boilerplate reduction 28

* fix: import

* fix: XAI TF conflict
2023-06-09 19:34:48 +00:00
Lav RaiandGitHub 5528d1cedc Add llm notebooks (#1968)
* Add Bart-large-cnn and dolly-v2 serving notebooks.

* Add Bart-large-cnn and dolly-v2 serving notebooks.

* Add Bart-large-cnn and dolly-v2 serving notebooks.
2023-06-09 18:35:13 +00:00
Andrew FerlitschandGitHub 155f316588 fix: boilerplate reduction 95 (#1966)
* fix: boilerplate reduction 95

* fix: import os

* fix: install pyspark

* fix: numpy bool
2023-06-09 12:31:40 +00:00
Xiang XuandGitHub 50d13e004d add new (#1961) 2023-06-08 19:44:23 +00:00
Andrew FerlitschandGitHub 03a2717248 fix: boilerplate reduction 94 (#1965)
* fix: boilerplate reduction 95

* fix:  import os

* fix: install pyspark
2023-06-08 17:37:35 +00:00
Andrew FerlitschandGitHub 3d7e0c2861 fix: boilerplate reduction 91 (#1963)
* fix: boilerplate reduction 91

* fix: install scikit-learn
2023-06-08 17:36:45 +00:00
Andrew FerlitschandGitHub de54c3d2dd fix: boilerplate reduction 81 (#1952)
* fix: boilerplate reduction 81

* fix: import os

* fix: import sys
2023-06-08 17:35:39 +00:00
Andrew FerlitschandGitHub d3e066a1ee fix: boilerplate reduction 80 - AR (#1951)
* fix: boilerplate reduction 80

* fix: AR

* fix: AR
2023-06-08 17:31:57 +00:00
Andrew FerlitschandGitHub 669eb0f2e7 fix: boilerplate reduction 83 (#1954) 2023-06-08 17:30:44 +00:00
Andrew FerlitschandGitHub 3618721baf fix: boilerplate reduction 86 (#1957)
* fix: boilerplate reduction 86

* fix: install
2023-06-08 16:17:55 +00:00
Andrew FerlitschandGitHub 9fad2cf0eb fix: boilerplate reduction 87 (#1958) 2023-06-08 16:16:50 +00:00
Andrew FerlitschandGitHub 9b625c143b fix: boilerplate reduction 89 (#1960) 2023-06-08 16:15:36 +00:00
Andrew FerlitschandGitHub 6600309c4a fix: boilerplate reduction 90 (#1962)
* fix: boilerplate reduction 90

* fix: install db-dtypes
2023-06-08 16:14:34 +00:00
Andrew FerlitschandGitHub 1091ec83b4 fix: boilerplate reduction 92 (#1964) 2023-06-08 16:13:39 +00:00
Andrew FerlitschandGitHub a29e1dd50a fix: boilerplate reduction 79 (#1950)
* fix: boilerplate reduction 79

* fix: import os

* fix: IS_COLAB
2023-06-08 16:12:37 +00:00
Andrew FerlitschandGitHub ef7959a7d8 fix: boilerplate reduction 77: TF (#1948)
* fix: boilerplate reduction 77

* TF

* Fix install TF
2023-06-07 20:23:04 +00:00
Andrew FerlitschandGitHub 2d38e7fc3b fix: boilerplate reduction 78 (#1949) 2023-06-07 20:21:41 +00:00
Andrew FerlitschandGitHub 5ac40786f1 fix: create AR repo (#1936) 2023-06-07 19:53:04 +00:00
Andrew FerlitschandGitHub 91ea9c7d4e fix: boilerplate reduction 74 (#1946)
* fix: boilerplate reduction 74

* fix: region

* import os

* fix: import uuid
2023-06-07 19:05:35 +00:00
Andrew FerlitschandGitHub 7de2195b1c fix: boilerplate reduction 70 (#1942) 2023-06-07 14:28:28 +00:00
Andrew FerlitschandGitHub a9ba2062b1 fix: boilerplate reduction 68 (#1940)
* fix: boilerplate reduction 68

* fix: install os

* import sys
2023-06-07 14:27:29 +00:00
Andrew FerlitschandGitHub de46d815b9 fix: train job not using TRAIN_IMAGE (#1938) 2023-06-06 19:36:47 +00:00
Andrew FerlitschandGitHub 6e4fb5396a tune: AR repeaper (#1935) 2023-06-06 17:15:16 +00:00
Andrew FerlitschandGitHub 3d9a462528 feat: delete AR repos (#1932) 2023-06-05 21:31:51 +00:00
Andrew FerlitschandGitHub d0de4f9340 feat: boilerplate reduction 66 (#1926)
* feat: boilerplate reduction 66

* fix bucket name
2023-06-05 21:29:21 +00:00
Andrew FerlitschandGitHub fb42792527 feat: boilerplate reduction 56 (#1914)
* feat: boilerplate reduction 56

* fix: bucket
2023-06-05 15:28:56 +00:00
Andrew FerlitschandGitHub cfaa10834c feat: boilerplate reduction 58 (#1916)
* feat: boilerplate reduction 58

* fix: bucket
2023-06-05 15:28:12 +00:00
Andrew FerlitschandGitHub 5dfc3c29d0 feat: boilerplate reduction 65 (#1924) 2023-06-05 15:27:15 +00:00
rachael-dsandGitHub 91aa0822b9 Updated notebook and readme to include link of now published blog (#1927) 2023-06-05 15:18:16 +00:00
Andrew FerlitschandGitHub b002e7ba2c tune: selecting notebooks (#1908)
* tune: selecting notebooks

* test: add test for select_notebook

* fix: random algo

* test: convert to pytest

* fix: review

* fix: remove path ..

* fix: assert
2023-06-01 21:34:14 +00:00
dstnluong-googleandGitHub c273a4c3a9 Add instructions for selecting operating system (#1920) 2023-06-01 19:33:39 +00:00
Andrew FerlitschandGitHub 07ae15d2e2 feat: boilerplate reduction 56 (#1915) 2023-06-01 12:27:00 +00:00
Andrew FerlitschandGitHub d3e1ede5d2 feat: boilerplate reduction 55 (#1913) 2023-06-01 12:26:03 +00:00
Andrew FerlitschandGitHub 010d294439 feat: boiler plate reduction 53 (#1911) 2023-06-01 12:25:12 +00:00
Andrew FerlitschandGitHub 8b019191b6 feat: boiler plate reduction 52 (#1910)
* feat: boiler plate reduction 52

* fix: install
2023-06-01 12:24:24 +00:00
Andrew FerlitschandGitHub f4cf4339a8 feat: boiler plate reduction 51 (#1909)
* feat: boiler plate reduction 51

* fix: bucket

* fix missing import

* fix: import

* fix: import os
2023-06-01 12:23:28 +00:00
Andrew FerlitschandGitHub fad5a00754 fix: links after rename UJ8 (#1790) 2023-05-30 16:00:50 +00:00
Andrew FerlitschandGitHub c94be301cb feat: results viewer (#1905)
* feat: results viewer

* tune: comment
2023-05-30 15:21:23 +00:00
Andrew FerlitschandGitHub d219a0cae7 cleanup (#1906) 2023-05-26 15:43:15 +00:00
dstnluong-googleandGitHub 879422219c Add notebook for local huggingface inferences. (#1890)
* Add notebook for local inferences for models on huggingface

* lint

* add notebook to CODEOWNERS

* update link

* Add objective section. Add brief description of each code block.
2023-05-26 14:53:07 +00:00
Andrew FerlitschandGitHub ae884f48ba fix: links after rename UJ15 (#1774) 2023-05-26 14:46:03 +00:00
reznitskiiandGitHub c52e657c88 Update sdk-metric-parameter-tracking-for-custom-jobs.ipynb (#1903) 2023-05-25 18:58:35 +00:00
Andrew FerlitschandGitHub 6da5cb1d74 fix: git rendering issue (#1900) 2023-05-25 18:52:47 +00:00
dstnluong-googleandGitHub fb56adc633 Refactor stable diffusion notebook layout (#1895) 2023-05-25 17:08:18 +00:00
reznitskiiandGitHub 8304d32e76 Update sdk-metric-parameter-tracking-for-custom-jobs.ipynb (#1896) 2023-05-25 17:07:08 +00:00
Aaron DietzandGitHub 811f06f992 Updated link and link text to Dataproc Serverless (#1873) 2023-05-25 17:05:53 +00:00
dstnluong-googleandGitHub f092fce2db Update stable_diffusion inpainting notebook with steps for local inference. (#1860)
* Update stable_diffusion notebook with steps for local inference.

* Lint

* Move comments to top and shorten line.

* Lint

* Make code comment titles, add print statements, and update Objective

* change print to display

* lint

* change training dockers to serving dockers

* Add local inferences instructions for stable diffusion inpainting.

* Lint

* remove extra libraries and add GPU

* remove re-imports
2023-05-25 17:04:59 +00:00
Mend RenovateandGitHub c26a7d19c7 chore(deps): update dependency black to v23 (#1498) 2023-05-25 16:59:05 +00:00
Mend RenovateandGitHub e7baf06290 chore(deps): update dependency nbqa to v1.7.0 (#1396) 2023-05-25 16:56:46 +00:00
Andrew FerlitschandGitHub 114a113cb3 add REGION setting to bqclient (#1901)
replace PR 1546
2023-05-25 16:56:16 +00:00
genquan9andGitHub e78068bb79 Update Keras stable diffusion notebooks with cloud notebook template and fix bugs (#1894)
* Update Keras stable diffusion notebooks with cloud notebook template style and fix bugs.

* fix minor typos
2023-05-19 16:21:26 +00:00
d940c93f47 Add new notebook to community folder for BQML inference engine / Vertex AI API integration (#1820)
* Added new bq_ml_with_vision_translation_nlp notebook. Added README. Updated community CODEOWNERS file

* review comment changes - renamed folder, updated headers, reformatted to be more in line with template

* review comment changes - renamed folder, updated headers, reformatted to be more in line with template

* lint formatting fixes

---------

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2023-05-18 18:12:53 +00:00
genquan9andGitHub 9b336a72f3 Add Keras stable diffusion notebook for model garden (#1891)
* Add Keras stable diffusion notebook for model garden

* Fix minor typos in Keras Stable Diffusion

* Fix format after minor typo fixes

* Update the objective structure

* update minor comments
2023-05-17 23:36:12 +00:00
dstnluong-googleandGitHub dfec25bde7 Add a local inference section to model_garden_pytorch_timm.ipynb (#1888)
* add local inference section to timm notebook

* Lint
2023-05-15 17:12:23 +00:00
Ivan NardiniandGitHub 3fe0889b9a feat: Add custom training integration with experiments notebook (#1887)
* add notebook. linter test passed

* add codeower and fix a typo

* linter test passed

* adding andy reviews

* linter passed
2023-05-15 17:10:28 +00:00
Andrew FerlitschandGitHub 5df1dfcc37 fix: boilerplate reduction 43 (#1874)
* fix: boilerplate reduction 43

* fix: install

* fix: install

* fix: install

* fix: install
2023-05-15 16:28:23 +00:00
Ivan CheungGitHubivanmkc@google.com <ivanmkc@google.com>
2303f110da Fixed incorrect text (#1886)
Co-authored-by: ivanmkc@google.com <ivanmkc@google.com>
2023-05-12 23:56:48 +00:00
Ivan CheungGitHubivanmkc@google.com <ivanmkc@google.com>
9ba17b5227 Added Matching Engine + "Vertex Text Embedding API" notebook (#1876)
* Added PaLM ME notebook

* Fixed import error and linted

* More cleanup

* Fixed embedding model

* Added comments

* Renamed and fixed links

* Linted

---------

Co-authored-by: ivanmkc@google.com <ivanmkc@google.com>
2023-05-12 22:41:08 +00:00
Andrew FerlitschandGitHub 6ea28621ac feat: read accumulative result files (#1837)
* feat: read accumulative result files

* fix: build results dir

* fix: build results dir

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: selection algo

* fix: debug

* fix: debug

* fix: debug

* fix: debug

* fix: debug

* fix: debug

* fix: debug select algo

* fix: debug select algo

* fix: debug select algo

* fix: debug select algo

* fix: filtering

* fix: review comments

* fix: rm test_filter
2023-05-12 17:44:54 +00:00
Andrew FerlitschandGitHub 5c2bd2a13a fix: boilerplate reduction 50 (#1885) 2023-05-12 17:09:22 +00:00
Andrew FerlitschandGitHub 675a98a005 fix: boilerplate reduction 48 (#1880)
* fix: boilerplate reduction 48

* fix: os

* fix: lint

* fix: import
2023-05-12 14:11:33 +00:00
Andrew FerlitschandGitHub 3d2518b177 fix: boilerplate reduction 47 (#1879)
* fix: boilerplate reduction 47

* fix: dependency
2023-05-12 14:10:34 +00:00
Andrew FerlitschandGitHub cc1a25733b fix: boilerplate reduction 46 (#1878)
* fix: boilerplate reduction 46

* fix: os
2023-05-12 14:09:14 +00:00
Andrew FerlitschandGitHub 2ac6a917af fix: boilerplate reduction 45 (#1877)
* fix: boilerplate reduction 45

* fix: os

* fix: colab
2023-05-12 14:08:05 +00:00
Andrew FerlitschandGitHub 3440690fa8 fix: boilerplate reduction 44 (#1875) 2023-05-12 14:06:19 +00:00
Andrew FerlitschandGitHub 1a4373c3c4 fix: boilerplate reduction 42 (#1872)
* fix: boilerplate reduction 42

* fix: install
2023-05-12 14:05:21 +00:00
Andrew FerlitschandGitHub 529ad0dd8e fix: bolierplate reduction 40 (#1869) 2023-05-12 12:39:32 +00:00
Andrew FerlitschandGitHub beaef16d62 fix: bolierplate reduction 39 (#1868)
* fix: bolierplate reduction 39

* fix: missing os

* fix: missing sys
2023-05-12 12:37:49 +00:00
Andrew FerlitschandGitHub 80d25ef87f upgrade: boilerplate reduction 37 (#1866)
* upgrade: boilerplate reduction 37

* fix: UUID
2023-05-12 12:36:58 +00:00
Andrew FerlitschandGitHub f21ac67fb2 upgrade: boilerplate reduction 36 (#1864)
* upgrade: boilerplate reduction 36

* missing import
2023-05-12 12:35:50 +00:00
Andrew FerlitschandGitHub 8be5a069eb update: boilerplate reduction 35 (#1863) 2023-05-12 12:34:53 +00:00
Andrew FerlitschandGitHub 721269538d Reduction 24 (#1851)
* fix: boilerplate reduction 23

* fix: boilerplate reduction 24
2023-05-10 12:47:10 +00:00
Andrew FerlitschandGitHub 240811979e fix: boilerplate reduction 25 (#1852)
* fix: boilerplate reduction 25

* fix: import

* fix: experiment name

* fix: experiment name

* fix: experiment name

* fix: delete

* fix: log link
2023-05-10 12:45:44 +00:00
Andrew FerlitschandGitHub 435e58884d fix: boiletplate reduction 25 (#1853) 2023-05-10 12:44:33 +00:00
Andrew FerlitschandGitHub f716600b44 fix: boilerplate reduction 30 (#1857)
* fix: boilerplate reduction 30

* fix:missing os
2023-05-10 12:43:27 +00:00
Andrew FerlitschandGitHub c7c573bae3 fix: boilerplate reduction 31 (#1859)
* fix: boilerplate reduction 31

* fix: bucket name
2023-05-10 12:42:44 +00:00
Andrew FerlitschandGitHub ee7dd9b5d8 fix: boilerplate reduction 32 (#1861)
* fix: boilerplate reduction 32

* fix: missing os
2023-05-10 12:41:38 +00:00
Andrew FerlitschandGitHub 42956223f2 fix: boilerplate reduction 23 (#1850) 2023-05-10 12:40:47 +00:00
Andrew FerlitschandGitHub 3b736a24a9 fix: boilerplate reduction 21 (#1848) 2023-05-10 12:39:15 +00:00
henrytanandGitHub 1ab839ac47 Text embedding api (#1858)
* Add text_embedding_api_semantic_search_with_scann notebook.

* Linted version.

* Updating the cell moving the pip install to the top

* Adding shapely<2.0.0.
2023-05-10 00:20:02 +00:00
Mend RenovateandGitHub fe7d3e4b8e chore(deps): update dependency pyupgrade to v3 (#1346) 2023-05-09 21:37:29 +00:00
Andrew FerlitschandGitHub 2c987c1949 fix: boilerplate reduction 20 (#1846) 2023-05-09 21:16:52 +00:00
Andrew FerlitschandGitHub 3f7b3292c1 fix: reduction 17 (#1842)
* fix: reduction 17

* fix: missing installs

* fix: missing installs
2023-05-09 21:16:00 +00:00
Andrew FerlitschandGitHub aaba9fe4e1 fix: reduction 16 (#1841)
* fix: reduction 16

* fix: exception
2023-05-09 21:15:03 +00:00
henrytanandGitHub aa04d7a60d Add text_embedding_api_semantic_search_with_scann notebook. (#1847)
* Add text_embedding_api_semantic_search_with_scann notebook.

* Linted version.
2023-05-09 20:57:10 +00:00
b17709785d Add Dataflow Flex Template component sample (#1839)
* Add Dataflow Flex Template component notebook

* Add get_started_with_dataflow_flex_template_component.ipynb to CODEOWNERS

---------

Co-authored-by: Win Woo <wwoo@google.com>
2023-05-09 19:27:00 +00:00
Andrew FerlitschandGitHub 5362c4ff61 fix: reduction 15 (#1840)
* fix: reduction 15

* fix: reduction 15

* fix: UUID issue
2023-05-09 18:37:54 +00:00
Andrew FerlitschandGitHub 4ce6dbc450 upgrade: boilerplate reduction 6 (#1827)
* upgrade: boilerplate reduction 6

* fix: install

* fix: install

* fix: install

* fix: rm output
2023-05-09 14:52:19 +00:00
Andrew FerlitschandGitHub a5270054b2 update: boilerplate reduction 13 (#1834)
* update: boilerplate reduction 13

* fix: bucket var
2023-05-09 13:12:44 +00:00
Andrew FerlitschandGitHub 30fe41eb2e upgrade: boilerplate reduction #1 (#1822)
* upgrade: boilerplate reduction

* add missing import

* missing DATAREGION

* fix: lint

* fix: unique job id
2023-05-09 13:10:59 +00:00
Xiang XuandGitHub 17b898bd15 fix controlnet (#1838) 2023-05-08 20:44:56 +00:00
Andrew FerlitschandGitHub 6415b1406d update: boilerplate reduction 12 (#1833)
* update: boilerplate reduction 12

* fix: missing bucket
2023-05-08 20:35:45 +00:00
Xiang XuandGitHub bbfddc2dfe fix controlnet (#1836) 2023-05-08 20:14:31 +00:00
Andrew FerlitschandGitHub 59da0b7fa4 update: boilerplate reduction 14 (#1835) 2023-05-08 19:03:10 +00:00
Andrew FerlitschandGitHub 321a7c7deb update: boilerplate reduction 11 (#1832) 2023-05-08 19:02:15 +00:00
Andrew FerlitschandGitHub 386c2f7ab9 update: boiler plate reduction 10 (#1831) 2023-05-08 19:01:07 +00:00
Andrew FerlitschandGitHub feb14aa36c update: boiler plate reduction 9 (#1830)
* update: boiler plate reduction 9

* fix: UUID
2023-05-08 19:00:01 +00:00
Andrew FerlitschandGitHub 44e0c77ddb update: boiler plate reduction 8 (#1829)
* update: boiler plate reduction 8

* fix: rm TIMESTAMP

* fix: import
2023-05-08 18:58:38 +00:00
Andrew FerlitschandGitHub cec6321027 upgrade: boilerplate reduction 7 (#1828) 2023-05-08 18:57:18 +00:00
Andrew FerlitschandGitHub 3cde0c8eab upgrade: boilerplate reduction 2 (#1823)
* upgrade: boilerplate reduction 2

* fix import os
2023-05-08 18:53:29 +00:00
Andrew FerlitschandGitHub 16c010a859 upgrade: boilerplate reduction 5 (#1826) 2023-05-06 00:37:10 +00:00
Andrew FerlitschandGitHub 11bad82468 upgrade: boilerplate reduction 4 (#1825)
* upgrade: boilerplate reduction 4

* fix: os
2023-05-06 00:36:49 +00:00
Andrew FerlitschandGitHub 9a7197a774 upgrade: boilerplate reduction 3 (#1824) 2023-05-06 00:36:05 +00:00
Andrew FerlitschandGitHub c638e6d983 fix: add test percent param (#1821) 2023-05-05 23:07:13 +00:00
dstnluong-googleandGitHub 5651427a97 Update stable_diffusion notebook with steps for local inference. (#1813)
* Update stable_diffusion notebook with steps for local inference.

* Lint

* Move comments to top and shorten line.

* Lint

* Make code comment titles, add print statements, and update Objective

* change print to display

* lint

* change training dockers to serving dockers
2023-05-05 20:04:46 +00:00
Andrew FerlitschandGitHub 6195e7bbf9 Ci cd 2 (#1802)
* update: record tallied results to GCS bucket

* fix: test percent

* update: accumulator support

* fix: use args for where to store results

* fix: args for results file

* fix: gs bucket ptrfix

* fix: tuning args

* fix: ci/cd test on openin artifacts bucket

* fix: 2nd try at bucket issue

* fix: 2nd try at bucket issue

* debug: bucket issue

* debug: bucket issue

* debug: bucket issue

* debug: bucket issue

* debug: bucket issue

* debug: bucket issue

* debug: no entries written

* debug: no entries written

* debug: not accumulating

* debug: not accumulating

* debug: not accumulating

* debug: not accumulating

* Update requirements.txt

* debug: not accumulating

* debug: not accumulating

* debug: matching notebook name

* debug: pandas problem

* debug: import issues

* debug: load

* Update requirements.txt

* Update requirements.txt

* debug: read csv

* debug: read csv

* debug: read csv

* debug: indxer

* debug: indexer

* debug: accum

* debug: accum

* debug: accum

* debug: accum

* debug: accum

* debug: accum

* debug: accum

* debug: casting

* debug: casting

* debug: casting

* debug: casting

* debug: duration nit

* debug: duration nit

* fix: flaky

* fix: BUILD_ID

* fix: BUILD_ID

* fix: BUILD_ID

* fix: BUILD_ID

* fix: BUILD_ID

* fix: BUILD_ID

* fix: BUILD_ID

* fix: review

* fix: review

* fix: review

* fix: biz logic

* fix: biz logic

* fix: review

* fix: build_id required

* fix: use json format

* review: JSON simplifing

* review: JSON simplifing

* update: NotbookExecutionResult updates

* fix: revert to JSON

* update: use util to read from bucket

* fix: remove pandas inmport
2023-05-05 20:03:49 +00:00
Andrew FerlitschandGitHub 2b4f7834b8 feat: MG notebook to finetune BERT (#1815)
* feat: MG notebook to finetune BERT

* review updates
2023-05-05 18:23:48 +00:00
Andrew FerlitschandGitHub 6eadb9199d feat: MG notebook to finetune T5X (#1816)
* feat: MG notebook to finetune T5X

* fix: review comments
2023-05-05 18:23:06 +00:00
Bernie OngeweandGitHub cf9ba17c7d Update tabular_optimized_online_prediction.ipynb (#1819)
Can only set up one Service Networking configuration per _network_. However, we can have multiple VPC networks per project, each with its own Service Networking configuration
2023-05-05 15:22:31 +00:00
KCFindstrandGitHub 384fa2c1b6 Add service account config to TIMM notebook (#1818) 2023-05-05 14:55:29 +00:00
Xiang XuandGitHub 4d24324cc6 fix controlnet (#1817) 2023-05-04 22:45:16 +00:00
Lav RaiandGitHub b1331406a0 Fix format-check and size-check error for detectron2. (#1814)
* Fix format-check and size-check error for detectron2.

* Fix format-check and size-check error for detectron2.
2023-05-04 19:02:19 +00:00
KCFindstrandGitHub cf00491bdc Update Model Garden TFVision notebooks. (#1808)
* Update #ModelGarden TFVision notebooks.

1. Added checkpoints for resnet-50, scaled_yolov4, deeplabv3+
2. Supported launching dockers in europe and asia region.

* Use a smaller batch size to resolve OOM issue
2023-05-04 15:39:53 +00:00
Huguens JeanandGitHub b24de2c375 Add notebook to trigger model garden training with model descriptions. (#1792)
* Trigger Model Garden Training

* Add notebook to trigger model garden training with model descriptions for ip sensitive checkpoints.

* Remove notebook in official folder.

* Fix type in notebook filename.

* Updated notebook description to reflect ip sensitive model garden training for EFFICIENTNET v2 using CLOUD key.

* Updated notebook with model garden specific configs for proprietary checkpoints.

* Linter check.

* Clear notebook's output.
2023-05-04 15:39:24 +00:00
Lav RaiandGitHub 79d80a1f4f Fix format-check and size-check error for stable diffusion inpainting. (#1812) 2023-05-04 00:01:31 +00:00
Xiang XuandGitHub de3e31e037 fix serve (#1811) 2023-05-03 23:20:00 +00:00
Andrew FerlitschandGitHub d45d5fad51 fix links (#1807) 2023-05-01 15:59:33 +00:00
Andrew FerlitschandGitHub 10a9e776b7 there is a regression in later packages (#1809) 2023-04-28 16:37:14 +00:00
Andrew FerlitschandGitHub db80aa4953 Revert "outdated (#1798)" (#1806)
This reverts commit 3d461a8458.
2023-04-27 21:07:59 +00:00
Xiang XuandGitHub f4345ed935 fix gs (#1804) 2023-04-26 22:00:11 +00:00
Lav RaiandGitHub b191b93c7e Fix detectron2 permission errors. (#1803) 2023-04-26 19:55:37 +00:00
gericdongandGitHub 8acf15cccb feat: notebook for text models for explainable AI feature attribution - sampled shapley (#1801)
* feat:notebook for text models for explanable AI feature attribution - sampled shapley

* addressed review comments
2023-04-25 17:52:39 +00:00
Andrew FerlitschandGitHub 8cd372c2d1 fix: nan (#1799)
* fix: nan

* fix: syntax error

* fix: syntax error

* fix: syntax error
2023-04-25 17:31:09 +00:00
Xiang XuandGitHub 447d79a165 add feature to clip (#1800) 2023-04-24 23:58:06 +00:00
Andrew FerlitschandGitHub 3d461a8458 outdated (#1798) 2023-04-24 23:54:49 +00:00
228e2034f7 Add detectron2 notebook (#1783)
* Add model garden pytorch detectron2 notebook

* Add model garden pytorch detectron2 notebook

* Add model garden pytorch detectron2 notebook

* Add model garden pytorch detectron2 notebook

---------

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2023-04-24 22:03:56 +00:00
Andrew FerlitschandGitHub fd3cc2a2cc update: test_percent and dry_run for weekly regr (#1795)
* update: test_percent for weekly regr

* update: add dry_run and test_percent

* fix: review comment
2023-04-24 21:41:21 +00:00
Andrew FerlitschandGitHub 76a1f49aaa improve install (#1797) 2023-04-24 19:49:46 +00:00
Andrew FerlitschandGitHub cb41dfc8bd test: flaky script (#1794) 2023-04-22 14:53:19 +00:00
Andrew FerlitschandGitHub 9b5e734dca test: list of passing notebooks (#1785)
* test: list of passing notebooks

* test: list of failing notebooks
2023-04-21 19:17:43 +00:00
Andrew FerlitschandGitHub 274ed4ef49 update: search index for migration (#1793) 2023-04-21 15:45:13 +00:00
dstnluong-googleandGitHub 92498e8148 Add 5 additional models to list of verified models. (#1791) 2023-04-21 15:23:50 +00:00
Andrew FerlitschandGitHub ce48820cc1 fix: links after rename UJ7 (#1789) 2023-04-21 12:46:03 +00:00
Andrew FerlitschandGitHub b59e74be8a fix: links after rename UJ9 (#1780) 2023-04-21 12:45:28 +00:00
Andrew FerlitschandGitHub 47579bdb10 fix: links after rename UJ10 (#1779) 2023-04-21 12:44:57 +00:00
Andrew FerlitschandGitHub 761ffc7b17 fix: links after rename UJ2 (#1778) 2023-04-21 12:44:23 +00:00
Andrew FerlitschandGitHub 99cd99b385 fix: links after rename UJ3 (#1777) 2023-04-21 12:43:48 +00:00
Andrew FerlitschandGitHub be783a2ed1 fix: links after rename UJ6 (#1776) 2023-04-21 12:43:25 +00:00
Andrew FerlitschandGitHub 7523b575ab fix: links after rename UJ4 (#1775) 2023-04-21 12:42:39 +00:00
Andrew FerlitschandGitHub 4f5a637cd0 fix: links after rename UJ5 (#1773) 2023-04-21 12:42:06 +00:00
Andrew FerlitschandGitHub 0701ca01a8 fix: links after rename 1 (#1772) 2023-04-21 12:41:39 +00:00
Andrew FerlitschandGitHub 78e0a67cd9 fix: links after rename UJ11 (#1781) 2023-04-20 22:59:08 +00:00
KCFindstrandGitHub 4ef75656a1 Fix typos and invalid properties in TIMM notebook (#1786) 2023-04-20 22:38:43 +00:00
Xiang XuandGitHub f5299da9b0 fix notes (#1787) 2023-04-20 22:37:19 +00:00
Andrew FerlitschandGitHub b986daa72d update: searchable index (#1784) 2023-04-20 20:46:54 +00:00
KCFindstrandGitHub e987dce2ad Add Model Garden Pytorch TIMM notebook (#1760)
* Add model garden pytorch timm notebook

* Add CODEOWNERS for model garden timm notebook

* Fix lint errors on TIMM notebook

* Fix TIMM notebook
2023-04-20 20:02:22 +00:00
Andrew FerlitschandGitHub f2f98cc8ed update: next round of index (#1782) 2023-04-20 19:57:30 +00:00
Xiang XuandGitHub 0661fcc121 fix blip2 (#1771) 2023-04-20 19:20:47 +00:00
Andrew FerlitschandGitHub f4c0fc7781 fix: rename UJ1 (#1757)
* fix: rename UJ1

* fix: lint
2023-04-20 18:22:47 +00:00
Andrew FerlitschandGitHub 8e3db693cb fix: UJ9 (#1770) 2023-04-20 18:22:15 +00:00
Andrew FerlitschandGitHub 0349a9552d fix: UJ8 (#1769) 2023-04-20 18:21:45 +00:00
Andrew FerlitschandGitHub ac1f03dd71 fix: rename UJ7 (#1768) 2023-04-20 18:21:16 +00:00
Andrew FerlitschandGitHub cb18a37b0a fix: rename UJ6 (#1767) 2023-04-20 18:20:51 +00:00
Andrew FerlitschandGitHub 4c8ec05f22 fix: rename UJ5 (#1766) 2023-04-20 18:20:28 +00:00
Andrew FerlitschandGitHub c17df33c7c fix: rename UJ4 (#1765)
* fix: rename UJ4

* fix: lint
2023-04-20 18:20:03 +00:00
Andrew FerlitschandGitHub 543cd66c16 fix: rename UJ3 (#1764) 2023-04-20 18:19:36 +00:00
Andrew FerlitschandGitHub f50dac63eb fix: rename UJ2 (#1763) 2023-04-20 18:19:08 +00:00
Andrew FerlitschandGitHub df979c1c65 fix: rename UJ15 (#1762) 2023-04-20 18:18:21 +00:00
Andrew FerlitschandGitHub 7b49c23eb6 fix: rename UJ14 (#1761)
* fix: rename UJ14

* fix: lint
2023-04-20 18:17:51 +00:00
Andrew FerlitschandGitHub 965835122b fix: rename UJ11 (#1759) 2023-04-20 18:17:22 +00:00
Andrew FerlitschandGitHub 54a34a7122 fix: rename UJ10 (#1758) 2023-04-20 18:17:00 +00:00
Xiang XuandGitHub a701f3b08c fix controlnet (#1756) 2023-04-20 04:44:53 +00:00
59a220cb58 fix: pin kfp and gcpc < 2.0 in rapid_prototyping_bqml_automl (#1755)
* pin kfp in rapid_prototyping_bqml_automl

* downgrade component version

---------

Co-authored-by: Andrew Ferlitsch <aferlitsch@gmail.com>
2023-04-20 04:36:39 +00:00
201 changed files with 28686 additions and 23073 deletions
+15 -6
View File
@@ -1,5 +1,14 @@
from typing import List
from ratemate import RateLimit
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--dry_run",
type=bool,
default=False)
args = parser.parse_args()
from resource_cleanup_manager import (
DatasetResourceCleanupManager,
ModelResourceCleanupManager,
@@ -13,7 +22,8 @@ from resource_cleanup_manager import (
HyperparameterTuningCleanupManager,
BatchPredictionJobCleanupManager,
ExperimentCleanupManager,
BucketCleanupManager
BucketCleanupManager,
ArtifactRegistryCleanupManager
)
rate_limit = RateLimit(max_count=25, per=60, greedy=False)
@@ -42,9 +52,7 @@ def run_cleanup_managers(managers: List[ResourceCleanupManager], is_dry_run: boo
print("")
is_dry_run = False
if is_dry_run:
if args.dry_run:
print("Starting cleanup in dry run mode...")
# List of all cleanup managers
@@ -60,7 +68,8 @@ managers: List[ResourceCleanupManager] = [
HyperparameterTuningCleanupManager(),
BatchPredictionJobCleanupManager(),
ExperimentCleanupManager(), # Experiment missing _resource_noun
BucketCleanupManager()
BucketCleanupManager(),
ArtifactRegistryCleanupManager()
]
run_cleanup_managers(managers=managers, is_dry_run=is_dry_run)
run_cleanup_managers(managers=managers, is_dry_run=args.dry_run)
@@ -6,6 +6,7 @@ READ FIRST BEFORE MAKING CHANGES
- Add --dry-run option to the clean-up script. This option will just output the list of resources the script will delete instead of actually deleting the resources.
- Have a larger conversation in DEE before touching any resources that were not created as part of vertex-ai-samples
'''
import os
import abc
from typing import Any, Type
@@ -220,5 +221,40 @@ class BucketCleanupManager(ResourceCleanupManager):
f"Skipping '{resource}' due to update_time being '{time_difference}', which is less than '{RESOURCE_UPDATE_BUFFER_IN_SECONDS}'."
)
return False
return True
class ArtifactRegistryCleanupManager(ResourceCleanupManager):
vertex_ai_resource = "Artifact Registry"
def list(self) -> Any:
import subprocess
result = subprocess.run(["gcloud artifacts repositories list --location=us-central1"],
shell=True, capture_output=True, text=True)
ret = []
lines = result.stdout.split('\n')[2:]
for line in lines:
repo = line.split(' ')[0]
if repo.startswith("my-docker-repo"):
ret.append(repo)
return ret
def delete(self, resource):
os.system(f"! gcloud artifacts repositories delete {resource} --location=us-central1")
@property
def type_name(self) -> str:
return "ArtifactRepository"
def resource_name(self, resource: Any) -> str:
return resource
# delete repository regardless of age
def get_seconds_since_modification(self, resource: Any) -> float:
return RESOURCE_UPDATE_BUFFER_IN_SECONDS + 1
def is_deleteable(self, resource: Any) -> bool:
return True
+63 -13
View File
@@ -17,6 +17,7 @@
import argparse
import pathlib
import os
import execute_changed_notebooks_helper
@@ -39,6 +40,19 @@ parser.add_argument(
help="The path to the file that has newline-limited folders of notebooks that should be tested.",
required=True,
)
parser.add_argument(
"--test_percent",
type=int,
help="The percent of notebooks to be tested (between 1 and 100).",
required=False,
default=100,
)
parser.add_argument(
"--build_id",
type=str,
help="The build id (which may be a Cloud Build job specific or user explicit.",
required=True
)
parser.add_argument(
"--base_branch",
help="The base git branch to diff against to find changed files.",
@@ -107,24 +121,60 @@ parser.add_argument(
default=True,
help="Should run notebooks in parallel.",
)
parser.add_argument(
"--concurrent_notebooks",
type=int,
help="Maximum number of parallel notebook executions per minute",
default=10,
required=False,
)
parser.add_argument(
"--dry_run",
type=str2bool,
default=False,
help="Dry run for testing - no execution",
)
args = parser.parse_args()
notebooks = execute_changed_notebooks_helper.get_changed_notebooks(
changed_notebooks = execute_changed_notebooks_helper.get_changed_notebooks(
test_paths_file=args.test_paths_file,
base_branch=args.base_branch,
)
execute_changed_notebooks_helper.process_and_execute_notebooks(
notebooks=notebooks,
container_uri=args.container_uri,
staging_bucket=args.staging_bucket,
artifacts_bucket=args.artifacts_bucket,
should_parallelize=args.should_parallelize,
timeout=args.timeout,
variable_project_id=args.variable_project_id,
variable_region=args.variable_region,
variable_service_account=args.variable_service_account,
variable_vpc_network=args.variable_vpc_network,
private_pool_id=args.private_pool_id,
results_bucket = f"{args.artifacts_bucket}"
# artifacts_bucket may get set by trigger to a full gs:// folder path
if results_bucket.startswith("gs://"):
results_bucket = results_bucket[5:]
results_bucket = results_bucket.split('/')[0]
results_file = f"build_results/{args.build_id}.json"
if args.test_percent == 100:
notebooks = changed_notebooks
accumulative_results = {}
else:
accumulative_results = execute_changed_notebooks_helper.load_results(results_bucket, results_file)
notebooks = [changed_notebook for changed_notebook in changed_notebooks if execute_changed_notebooks_helper.select_notebook(changed_notebook, accumulative_results, args.test_percent)]
if args.dry_run:
print("Dry run ...\n")
for notebook in notebooks:
print(f"Would execute: {notebook}")
else:
execute_changed_notebooks_helper.process_and_execute_notebooks(
notebooks=notebooks,
container_uri=args.container_uri,
staging_bucket=args.staging_bucket,
artifacts_bucket=args.artifacts_bucket,
results_file=results_file,
should_parallelize=args.should_parallelize,
timeout=args.timeout,
variable_project_id=args.variable_project_id,
variable_region=args.variable_region,
variable_service_account=args.variable_service_account,
variable_vpc_network=args.variable_vpc_network,
private_pool_id=args.private_pool_id,
concurrent_notebooks=args.concurrent_notebooks,
)
@@ -21,18 +21,21 @@ import json
import git
import operator
import os
import io
import json
import pathlib
import re
import subprocess
import random
from google.cloud import storage
import utils
from typing import List, Optional
from typing import List, Optional, Dict, Any
from utils import util
import execute_notebook_helper
import execute_notebook_remote
import nbformat
from google.cloud.devtools.cloudbuild_v1.types import BuildOperationMetadata
from ratemate import RateLimit
from tabulate import tabulate
from utils import NotebookProcessors, util
@@ -40,6 +43,9 @@ from utils import NotebookProcessors, util
WORKER_TIMEOUT_BUFFER_IN_SECONDS: int = 60 * 60
PYTHON_VERSION = "3.9" # Set default python version
# rolling time window for accumulating build results for selecting notebooks
MAX_RESULTS_AGE_SECONDS: int = (60 * 60) * 24 * 60 # 60 days
def format_timedelta(delta: datetime.timedelta) -> str:
"""Formats a timedelta duration to [N days] %H:%M:%S format"""
@@ -65,7 +71,9 @@ def format_timedelta(delta: datetime.timedelta) -> str:
@dataclasses.dataclass
class NotebookExecutionResult:
name: str
path: str
duration: datetime.timedelta
start_time: datetime.datetime
is_pass: bool
log_url: str
output_uri: str
@@ -81,6 +89,75 @@ class NotebookExecutionResult:
return None
def load_results(results_bucket: str,
results_file: str) -> Dict[str, Any]:
'''
Load accumulated notebook test results
'''
print("Loading existing accumulative results ...")
accumulative_results = {}
try:
client = storage.Client()
bucket = client.bucket(results_bucket)
build_results_dir = os.path.dirname(results_file)
blobs = client.list_blobs(results_bucket, prefix=build_results_dir)
for blob in blobs:
time_created = blob.time_created.replace(tzinfo=None)
if (datetime.datetime.now().replace(tzinfo=None) - time_created).total_seconds() > MAX_RESULTS_AGE_SECONDS:
continue
content = util.download_blob_into_memory(results_bucket, blob.name, download_as_text=True)
try:
build_results = json.loads(content)
except:
continue # skip corrupted build results files
for notebook in build_results:
if notebook in accumulative_results:
accumulative_results[notebook]['passed'] += build_results[notebook]['passed']
accumulative_results[notebook]['failed'] += build_results[notebook]['failed']
else:
accumulative_results[notebook] = build_results[notebook]
print(accumulative_results)
except Exception as e:
print(e)
# If there are no accumulative results, an empty dict is returned
return accumulative_results
def select_notebook(changed_notebook: str,
accumulative_results: Dict[str, Any],
test_percent: int) -> bool:
'''
Algorithm to randomly select a notebook, but weight the propbability of selected based on past failures
'''
if changed_notebook in accumulative_results:
pass_count = accumulative_results[changed_notebook]['passed']
fail_count = accumulative_results[changed_notebook]['failed']
else:
pass_count = 1
fail_count = 0
inferred_failure_rate = fail_count / (pass_count + fail_count)
# If failure rate is high, the chance of testing should be higher
should_test_due_to_failure = random.uniform(0, 1) <= inferred_failure_rate
# Additionally, only test a percentage of these
should_test_due_to_random_subset = random.uniform(0, 1) <= (test_percent / 100)
if should_test_due_to_failure or should_test_due_to_random_subset:
print(f"Selected: {changed_notebook}, {should_test_due_to_failure}, {should_test_due_to_random_subset}")
return True
else:
print(f"Not Selected: {changed_notebook}, pass {pass_count}, fail {fail_count}")
return False
def _process_notebook(
notebook_path: str,
variable_project_id: str,
@@ -156,7 +233,6 @@ def _create_tag(filepath: str) -> str:
return tag
rate_limit = RateLimit(max_count=10, per=60, greedy=True)
def process_and_execute_notebook(
@@ -172,7 +248,6 @@ def process_and_execute_notebook(
notebook: str,
should_get_tail_logs: bool = False,
) -> NotebookExecutionResult:
rate_limit.wait() # wait before creating the task
print(f"Running notebook: {notebook}")
@@ -191,7 +266,9 @@ def process_and_execute_notebook(
result = NotebookExecutionResult(
name=tag,
path=notebook,
duration=datetime.timedelta(seconds=0),
start_time=datetime.datetime.now(),
is_pass=False,
output_uri=notebook_output_uri,
log_url="",
@@ -201,7 +278,6 @@ def process_and_execute_notebook(
)
# TODO: Handle cases where multiple notebooks have the same name
time_start = datetime.datetime.now()
operation = None
try:
# Get the python version for running the notebook if specified
@@ -247,9 +323,10 @@ def process_and_execute_notebook(
# Block and wait for the result
operation_result = operation.result(timeout=timeout_in_seconds)
result.duration = datetime.datetime.now() - time_start
result.duration = datetime.datetime.now() - result.start_time
result.is_pass = True
print(f"{notebook} PASSED in {format_timedelta(result.duration)}.")
except Exception as error:
result.error_message = str(error)
@@ -268,7 +345,7 @@ def process_and_execute_notebook(
except Exception as error:
result.error_message = str(error)
result.duration = datetime.datetime.now() - time_start
result.duration = datetime.datetime.now() - result.start_time
result.is_pass = False
print(
@@ -336,12 +413,44 @@ def get_changed_notebooks(
return notebooks
def _save_results(results: List[NotebookExecutionResult],
artifacts_bucket: str,
results_file: str):
artifacts_bucket = artifacts_bucket.replace("gs://", "").split('/')[0]
print("Updating build results ...")
build_results = {}
for result in results:
if result.is_pass:
pass_count = 1
fail_count = 0
else:
pass_count = 0
fail_count = 1
build_results[result.path] = {
'duration': result.duration.total_seconds(),
'start_time': str(result.start_time),
'passed': pass_count,
'failed': fail_count
}
print(f"adding {result.path}")
print("Saving accumulative results ...")
content = json.dumps(build_results)
client = storage.Client()
bucket = client.get_bucket(artifacts_bucket)
bucket.blob(str(results_file)).upload_from_string(content, 'text/json')
def process_and_execute_notebooks(
notebooks: List[str],
container_uri: str,
staging_bucket: str,
artifacts_bucket: str,
results_file: str,
should_parallelize: bool,
timeout: int,
variable_project_id: str,
@@ -349,6 +458,7 @@ def process_and_execute_notebooks(
variable_service_account: str,
variable_vpc_network: Optional[str] = None,
private_pool_id: Optional[str] = None,
concurrent_notebooks: Optional[int] = 10,
):
"""
Run the notebooks that exist under the folders defined in the test_paths_file.
@@ -369,6 +479,8 @@ def process_and_execute_notebooks(
Required. The GCS staging bucket to write source code to.
artifacts_bucket (str):
Required. The GCS staging bucket to write executed notebooks to.
results_file (str):
Required: The path to the artifacts bucket to save results
variable_project_id (str):
Required. The value for PROJECT_ID to inject into notebooks.
variable_region (str):
@@ -377,6 +489,7 @@ def process_and_execute_notebooks(
Required. Should run notebooks in parallel using a thread pool as opposed to in sequence.
timeout (str):
Required. Timeout string according to https://cloud.google.com/build/docs/build-config-file-schema#timeout.
concurrent_notebooks (int): Max number of notebooks per minute to run in parallel.
"""
# Calculate deadline
@@ -393,7 +506,9 @@ def process_and_execute_notebooks(
print(
"Running notebooks in parallel, so no logs will be displayed. Please wait..."
)
with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrent_notebooks) as executor:
print(f"Max workers: {executor._max_workers}")
notebook_execution_results = list(
@@ -471,7 +586,7 @@ def process_and_execute_notebooks(
print("=" * 100)
build_id = results_sorted[0].build_id
logs_bucket_name = (results_sorted[0].logs_bucket).removeprefix("gs://")
logs_bucket_name = (results_sorted[0].logs_bucket).replace("gs://", "")
log_file_name = f"log-{build_id}.txt"
log_contents = util.download_blob_into_memory(
@@ -489,6 +604,10 @@ def process_and_execute_notebooks(
else:
print(log_contents)
_save_results(results_sorted,
artifacts_bucket,
results_file)
print("\n=== END RESULTS===\n")
total_notebook_duration = functools.reduce(
@@ -36,7 +36,7 @@ steps:
- -c
- |
. workspace/env/bin/activate &&
python3 .cloud-build/execute_changed_notebooks_cli.py --test_paths_file "${_TEST_PATHS_FILE}" --base_branch "${_FORCED_BASE_BRANCH}" --container_uri ${_PYTHON_IMAGE} --staging_bucket ${_GCS_STAGING_BUCKET} --artifacts_bucket ${_GCS_STAGING_BUCKET}/executed_notebooks/PR_${_PR_NUMBER}/BUILD_${BUILD_ID} --variable_project_id ${PROJECT_ID} --variable_region ${_GCP_REGION} --variable_service_account ${_GCP_SERVICE_ACCOUNT} --variable_vpc_network "${_GPC_VPC_NETWORK_NAME}" `if [ ! -z "${_PRIVATE_POOL_NAME}" ]; then echo "--private_pool_id ${_PRIVATE_POOL_NAME}"; fi`
python3 .cloud-build/execute_changed_notebooks_cli.py --test_paths_file "${_TEST_PATHS_FILE}" --base_branch "${_FORCED_BASE_BRANCH}" --container_uri ${_PYTHON_IMAGE} --staging_bucket ${_GCS_STAGING_BUCKET} --artifacts_bucket ${_GCS_STAGING_BUCKET}/executed_notebooks/PR_${_PR_NUMBER}/BUILD_${BUILD_ID} --variable_project_id ${PROJECT_ID} --variable_region ${_GCP_REGION} --variable_service_account ${_GCP_SERVICE_ACCOUNT} --variable_vpc_network "${_GPC_VPC_NETWORK_NAME}" `if [ ! -z "${_PRIVATE_POOL_NAME}" ]; then echo "--private_pool_id ${_PRIVATE_POOL_NAME}"; fi` --build_id ${BUILD_ID} --test_percent=${_TEST_PERCENT} --concurrent_notebooks=${_CONCURRENT_NOTEBOOKS}
env:
- 'IS_TESTING=1'
timeout: 86400s
+5 -2
View File
@@ -3,12 +3,15 @@ numpy
jupyter
nbconvert
papermill
pandas
matplotlib
tabulate
google-cloud-aiplatform
google-cloud-storage
google-cloud-build
google-cloud-storage
ratemate
GitPython
tqdm
tqdm
fsspec
pandas
+40
View File
@@ -0,0 +1,40 @@
notebooks/official/training/pytorch_gcs_data_training.ipynb
notebooks/official/custom/custom_training_tensorboard_profiler.ipynb
notebooks/official/custom/custom-tabular-bq-managed-dataset.ipynb
notebooks/official/ml_metadata/sdk-metric-parameter-tracking-for-locally-trained-models.ipynb
notebooks/official/ml_metadata/sdk-metric-parameter-tracking-for-custom-jobs.ipynb
notebooks/official/tabnet/tabnet_vertex_tutorial.ipynb
notebooks/official/tabnet/get_started_with_tabnet.ipynb
notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb
notebooks/official/pipelines/multicontender_vs_champion_deployment_method.ipynb
notebooks/official/pipelines/google_cloud_pipeline_components_automl_images.ipynb
notebooks/official/pipelines/rapid_prototyping_bqml_automl.ipynb
notebooks/official/pipelines/challenger_vs_blessed_deployment_method.ipynb
notebooks/official/matching_engine/sdk_matching_engine_create_stack_overflow_embeddings.ipynb
notebooks/official/matching_engine/sdk_matching_engine_for_indexing.ipynb
notebooks/official/matching_engine/sdk_matching_engine_create_text_to_image_embeddings.ipynb
notebooks/official/explainable_ai/sdk_custom_image_classification_online_explain.ipynb
notebooks/official/explainable_ai/xai_image_classification_feature_attributions.ipynb
notebooks/official/explainable_ai/sdk_custom_image_classification_batch_explain.ipynb
notebooks/official/tabular_workflows/tabnet_on_vertex_pipelines.ipynb
notebooks/official/model_registry/get_started_with_model_registry.ipynb
notebooks/official/model_registry/bqml_vertexai_model_registry.ipynb
notebooks/official/sdk/SDK_Custom_Training_Python_Package_Managed_Text_Dataset_Tensorflow_Serving_Container.ipynb
notebooks/official/model_monitoring/batch_prediction_model_monitoring.ipynb
notebooks/official/model_monitoring/get_started_with_model_monitoring_setup.ipynb
notebooks/official/model_monitoring/get_started_with_model_monitoring_custom.ipynb
notebooks/official/model_monitoring/get_started_with_model_monitoring_custom_tf_serving.ipynb
notebooks/official/model_monitoring/model_monitoring.ipynb
notebooks/official/tensorboard/tensorboard_profiler_custom_training_with_prebuilt_container.ipynb
notebooks/official/tensorboard/tensorboard_hyperparameter_tuning_with_hparams.ipynb
notebooks/official/tensorboard/tensorboard_profiler_custom_training.ipynb
notebooks/official/model_evaluation/custom_tabular_regression_model_evaluation.ipynb
notebooks/official/model_evaluation/custom_tabular_classification_model_evaluation.ipynb
notebooks/official/model_evaluation/automl_video_classification_model_evaluation.ipynb
notebooks/official/experiments/comparing_local_trained_models.ipynb
notebooks/official/automl/automl_image_classification_online_online_prediction.ipynb
notebooks/official/automl/automl-text-classification.ipynb
notebooks/official/automl/sdk_automl_video_object_tracking_batch.ipynb
notebooks/official/feature_store/sdk-feature-store-pandas.ipynb
notebooks/official/prediction/custom_batch_prediction_feature_filter.ipynb
notebooks/official/prediction/pytorch_image_classification_with_prebuilt_serving_containers.ipynb
+80
View File
@@ -0,0 +1,80 @@
notebooks/official/training/hyperparameter_tuning_tensorflow.ipynb
notebooks/official/training/get_started_with_vertex_distributed_training.ipynb
notebooks/official/training/hyperparameter_tuning_xgboost.ipynb
notebooks/official/training/multi_node_ddp_gloo_vertex_training_with_custom_container.ipynb
notebooks/official/training/distributed_hyperparameter_tuning.ipynb
notebooks/official/training/pytorch-text-sentiment-classification-custom-train-deploy.ipynb
notebooks/official/training/xgboost_data_parallel_training_on_cpu_using_dask.ipynb
notebooks/official/training/multi_node_ddp_nccl_vertex_training_with_custom_container.ipynb
notebooks/official/bigquery_ml/get_started_with_bqml_training.ipynb
notebooks/official/bigquery_ml/bqml-online-prediction.ipynb
notebooks/official/custom/custom_training_container_and_model_registry.ipynb
notebooks/official/custom/sdk-custom-image-classification-online.ipynb
notebooks/official/custom/sdk-custom-image-classification-batch.ipynb
notebooks/official/custom/SDK_FBProphet_Forecasting_Online.ipynb
notebooks/official/custom/get_started_vertex_training_xgboost.ipynb
notebooks/official/custom/get_started_with_vertex_endpoint_and_shared_vm.ipynb
notebooks/official/custom/SDK_Custom_Container_Prediction.ipynb
notebooks/official/reduction_server/pytorch_distributed_training_reduction_server.ipynb
notebooks/official/tabnet/ai-explanations-tabnet-algorithm.ipynb
notebooks/official/vizier/get_started_vertex_vizier.ipynb
notebooks/official/vizier/gapic-vizier-multi-objective-optimization.ipynb
notebooks/official/pipelines/get_started_with_hpt_pipeline_components.ipynb
notebooks/official/pipelines/google_cloud_pipeline_components_automl_tabular.ipynb
notebooks/official/pipelines/custom_tabular_train_batch_pred_bq_pipeline.ipynb
notebooks/official/pipelines/metrics_viz_run_compare_kfp.ipynb
notebooks/official/pipelines/google_cloud_pipeline_components_model_upload_predict_evaluate.ipynb
notebooks/official/pipelines/google_cloud_pipeline_components_model_train_upload_deploy.ipynb
notebooks/official/pipelines/get_started_with_machine_management.ipynb
notebooks/official/pipelines/custom_model_training_and_batch_prediction.ipynb
notebooks/official/pipelines/control_flow_kfp.ipynb
notebooks/official/pipelines/lightweight_functions_component_io_kfp.ipynb
notebooks/official/pipelines/google_cloud_pipeline_components_bqml_text.ipynb
notebooks/official/pipelines/pipelines_intro_kfp.ipynb
notebooks/official/pipelines/automl_tabular_classification_beans.ipynb
notebooks/official/pipelines/google_cloud_pipeline_components_dataproc_tabular.ipynb
notebooks/official/explainable_ai/sdk_automl_tabular_classification_online_explain.ipynb
notebooks/official/explainable_ai/sdk_custom_tabular_regression_online_explain.ipynb
notebooks/official/explainable_ai/sdk_automl_tabular_binary_classification_batch_explain.ipynb
notebooks/official/explainable_ai/sdk_custom_tabular_regression_online_explain_get_metadata.ipynb
notebooks/official/explainable_ai/sdk_custom_tabular_regression_batch_explain.ipynb
notebooks/official/tabular_workflows/prophet_on_vertex_pipelines.ipynb
notebooks/official/tabular_workflows/wide_and_deep_on_vertex_pipelines.ipynb
notebooks/official/sdk/SDK_AutoML_Video_Classification.ipynb
notebooks/official/model_monitoring/get_started_with_model_monitoring_automl.ipynb
notebooks/official/model_monitoring/get_started_with_model_monitoring_automl_image_batch.ipynb
notebooks/official/model_monitoring/get_started_with_model_monitoring_automl_image_online.ipynb
notebooks/official/model_monitoring/get_started_with_model_monitoring_xgboost.ipynb
notebooks/official/tensorboard/tensorboard_custom_training_with_custom_container.ipynb
notebooks/official/tensorboard/tensorboard_custom_training_with_prebuilt_container.ipynb
notebooks/official/tensorboard/tensorboard_vertex_ai_pipelines_integration.ipynb
notebooks/official/model_evaluation/automl_text_classification_model_evaluation.ipynb
notebooks/official/model_evaluation/get_started_with_custom_model_evaluation_import.ipynb
notebooks/official/model_evaluation/automl_tabular_classification_model_evaluation.ipynb
notebooks/official/model_evaluation/automl_tabular_regression_model_evaluation.ipynb
notebooks/official/experiments/get_started_with_vertex_experiments.ipynb
notebooks/official/experiments/comparing_pipeline_runs.ipynb
notebooks/official/experiments/get_started_with_vertex_experiments_autologging.ipynb
notebooks/official/experiments/build_model_experimentation_lineage_with_prebuild_code.ipynb
notebooks/official/experiments/delete_outdated_tensorboard_experiments.ipynb
notebooks/official/automl/sdk_automl_tabular_regression_batch_bq.ipynb
notebooks/official/automl/sdk_automl_text_sentiment_analysis_online.ipynb
notebooks/official/automl/sdk_automl_text_entity_extraction_online.ipynb
notebooks/official/automl/sdk_automl_forecasting_hierarchical_batch.ipynb
notebooks/official/automl/automl_text_entity_extraction_batch_prediction.ipynb
notebooks/official/automl/automl_image_classification_batch_prediction.ipynb
notebooks/official/automl/automl_text_sentiment_analysis_batch_prediction.ipynb
notebooks/official/automl/sdk_automl_tabular_regression_online_bq.ipynb
notebooks/official/automl/get_started_automl_training.ipynb
notebooks/official/automl/automl-tabular-classification.ipynb
notebooks/official/automl/automl_image_object_detection_export_edge.ipynb
notebooks/official/automl/sdk_automl_image_object_detection_batch.ipynb
notebooks/official/automl/automl_tabular_on_vertex_pipelines.ipynb
notebooks/official/automl/sdk_automl_video_classification_batch.ipynb
notebooks/official/automl/sdk_automl_video_action_recognition_batch.ipynb
notebooks/official/automl/sdk_automl_tabular_forecasting_batch.ipynb
notebooks/official/automl/automl_image_object_detection_online_prediction.ipynb
notebooks/official/automl/automl_forecasting_bqml_arima_plus_comparison.ipynb
notebooks/official/datasets/get_started_bq_datasets.ipynb
notebooks/official/datasets/get_started_with_data_labeling.ipynb
notebooks/official/feature_store/feature_store_streaming_ingestion_sdk.ipynb
+46
View File
@@ -0,0 +1,46 @@
# grep PASSED tests.txt | cut -c 10-100 >passed.txt
import os
repo_dir = '/home/jupyter/vertex-ai-samples/'
repo_dir_len = len(repo_dir)
official_dir = repo_dir + 'notebooks/official'
entries = os.scandir(official_dir)
folders = []
for entry in entries:
if entry.is_dir():
folders.append(entry.path)
# Passing
with open('passed.txt', 'r') as pass_file:
notebook_names = pass_file.readlines()
notebooks = []
for folder in folders:
entries = os.scandir(folder)
for entry in entries:
for notebook in notebook_names:
if entry.name == notebook.rstrip():
notebooks.append(entry.path[repo_dir_len:])
with open('passing_tests.txt', 'w') as f:
for notebook in notebooks:
f.write(notebook + '\n')
# Failing
with open('failed.txt', 'r') as fail_file:
notebook_names = fail_file.readlines()
notebooks = []
for folder in folders:
entries = os.scandir(folder)
for entry in entries:
for notebook in notebook_names:
if entry.name == notebook.rstrip():
notebooks.append(entry.path[repo_dir_len:])
with open('failing_tests.txt', 'w') as f:
for notebook in notebooks:
f.write(notebook + '\n')
@@ -0,0 +1,33 @@
import sys
from execute_changed_notebooks_helper import (load_results, select_notebook)
def test_load_results():
bucket: str = "cloud-build-notebooks-presubmit"
bucket_file: str = "build_results"
accum = load_results(bucket, bucket_file)
print(accum)
assert len(accum) > 0
def test_select_notebook():
bucket: str = "cloud-build-notebooks-presubmit"
bucket_file: str = "build_results"
accum = load_results(bucket, bucket_file)
n_select = 0
n_notselect = 0
for notebook in accum:
if select_notebook(notebook, accum, 50):
n_select += 1
else:
n_notselect += 1
print(f"SELECTED {n_select}, NOT SELECTED {n_notselect}")
assert n_select > 0
assert n_notselect > 0
@@ -0,0 +1,22 @@
'''
Viewer for the weekly regression testing of the official notebooks
Cloud Storage location: gs://cloud-build-notebooks-presubmit/build_results/
'''
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument('--file', dest='file',
default='build.json', type=str, help='build results file')
import json
with open('build.json', 'r') as f:
results = json.load(f)
for item in results.items():
if item[1]['passed']:
print(f"{item[0]},PASSED")
else:
print(f"{item[0]},FAILED")
@@ -0,0 +1,23 @@
steps:
# Fetch full repo for diff purposes
- name: gcr.io/cloud-builders/git
args: [fetch, --unshallow, --quiet]
# Create a virtual environment
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- python3 -m venv workspace/env
# Install Python dependencies and run testing script
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- |
. workspace/env/bin/activate &&
python3 notebooks/notebook_template_review.py --web --title --steps --desc --linkback --notebook-dir=notebooks/official >web.html
artifacts:
objects:
location: gs://${_GCS_ARTIFACTS_BUCKET}/webdoc
paths: ['web.html']
timeout: 86400s
+3 -3
View File
@@ -2,9 +2,9 @@ git+https://github.com/tensorflow/docs
ipython
jupyter
nbconvert
black==22.12.0
pyupgrade==2.38.4
black==23.3.0
pyupgrade==3.7.0
isort==5.12.0
flake8==6.0.0
nbqa==1.5.3
nbqa==1.7.0
+2 -2
View File
@@ -84,7 +84,7 @@ if [ ${#notebooks[@]} -gt 0 ]; then
# python3 -m nbqa black "$notebook" --check
# BLACK_RTN=$?
echo "Running pyupgrade..."
python3 -m nbqa pyupgrade "$notebook"
python3 -m nbqa pyupgrade --exit-zero-even-if-changed "$notebook"
PYUPGRADE_RTN=$?
echo "Running isort..."
python3 -m nbqa isort "$notebook" --check
@@ -97,7 +97,7 @@ if [ ${#notebooks[@]} -gt 0 ]; then
python3 -m nbqa black "$notebook"
BLACK_RTN=$?
echo "Running pyupgrade..."
python3 -m nbqa pyupgrade "$notebook"
python3 -m nbqa pyupgrade --exit-zero-even-if-changed "$notebook"
PYUPGRADE_RTN=$?
echo "Running isort..."
python3 -m nbqa isort "$notebook"
+3
View File
@@ -10,3 +10,6 @@
/pipeline_components @Ark-kun
/pipeline_components/image_ml_model_training @lakeyk
/prediction_featurestore_integration @googleapis/vertex-prediction-team
/vertex_vision_model_garden/model_oss/util @weigary
/vertex_vision_model_garden/model_oss/diffusers @weigary
/vertex_vision_model_garden/model_oss/transformers @dstnluong-google
@@ -0,0 +1,4 @@
[MASTER]
generated-members=get_concrete_function,cv2.*
ignored-modules=tensorflow,google.cloud
@@ -0,0 +1,74 @@
# Dockerfile for Diffuser Serving.
#
# To build:
# docker build -f model_oss/diffusers/dockerfile/serve.Dockerfile . -t ${YOUR_IMAGE_TAG}
#
# To push to gcr:
# docker tag ${YOUR_IMAGE_TAG} gcr.io/${YOUR_PROJECT}/${YOUR_IMAGE_TAG}
# docker push gcr.io/${YOUR_PROJECT}/${YOUR_IMAGE_TAG}
FROM pytorch/torchserve:0.7.0-gpu
USER root
ENV infer_port=7080
ENV mng_port=7081
ENV model_name="diffusers_serving"
ENV PATH="/home/model-server/:${PATH}"
# Install libraries.
ENV PIP_ROOT_USER_ACTION=ignore
RUN python3 -m pip install --upgrade pip
RUN pip install torch==1.13.1
RUN pip install torchvision==0.14.1
RUN pip install transformers==4.27.4
RUN pip install datasets==2.9.0
RUN pip install accelerate==0.17.0
RUN pip install triton==2.0.0.dev20221120
RUN pip install xformers==0.0.16
RUN pip install google-cloud-storage==2.7.0
RUN pip install imageio[ffmpeg]==2.31.0
RUN pip install absl-py==1.4.0
# Copy LICENSE file
RUN apt-get update && apt-get install wget
RUN wget https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/LICENSE
# Install diffusers from main branch source code with a pinned commit.
RUN git clone --depth 1 --branch v0.18.1 https://github.com/huggingface/diffusers.git
WORKDIR diffusers
RUN pip install -e .
# Copy model artifacts.
COPY model_oss/diffusers/handler.py /home/model-server/handler.py
COPY model_oss/util/ /home/model-server/util/
ENV PYTHONPATH /home/model-server/
# Create torchserve configuration file.
RUN echo \
"default_response_timeout=1800\n" \
"service_envelope=json\n" \
"inference_address=http://0.0.0.0:${infer_port}\n" \
"management_address=http://0.0.0.0:${mng_port}" >> /home/model-server/config.properties
# Expose ports.
EXPOSE ${infer_port}
EXPOSE ${mng_port}
# Archive model artifacts and dependencies.
# Do not set --model-file and --serialized-file because model and checkpoint
# will be dynamically loaded in handler.py.
RUN torch-model-archiver \
--model-name=${model_name} \
--version=1.0 \
--handler=/home/model-server/handler.py \
--runtime=python3 \
--export-path=/home/model-server/model-store \
--archive-format=default \
--force
# Run Torchserve HTTP serve to respond to prediction requests.
CMD ["torchserve", "--start", \
"--ts-config", "/home/model-server/config.properties", \
"--models", "${model_name}=${model_name}.mar", \
"--model-store", "/home/model-server/model-store"]
@@ -0,0 +1,47 @@
# Dockerfile for Diffuser Training.
#
# To build:
# docker build -f model_oss/diffusers/dockerfile/train.Dockerfile . -t ${YOUR_IMAGE_TAG}
#
# To push to gcr:
# docker tag ${YOUR_IMAGE_TAG} gcr.io/${YOUR_PROJECT}/${YOUR_IMAGE_TAG}
# docker push gcr.io/${YOUR_PROJECT}/${YOUR_IMAGE_TAG}
# Base on pytorch-cuda image.
FROM pytorch/pytorch:1.13.0-cuda11.6-cudnn8-runtime
# Install tools.
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
wget \
git \
vim
# Copy license.
RUN wget https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/LICENSE
# Install libraries.
RUN pip install torchvision==0.14.1
RUN pip install transformers==4.26.1
RUN pip install datasets==2.9.0
RUN pip install accelerate==0.17.0
RUN pip install triton==2.0.0.dev20221120
RUN pip install xformers==0.0.16
RUN pip install Jinja2==3.1.2
RUN pip install ftfy==6.1.1
RUN pip install cloudml-hypertune==0.1.0.dev6
RUN pip install tensorboard==2.12.0
# Install diffusers from main branch source code with a pinned commit.
RUN git clone --depth 1 --branch v0.18.1 https://github.com/huggingface/diffusers.git
WORKDIR diffusers
RUN pip install -e .
# Switch to diffusers examples folder.
WORKDIR examples
# Config accelerate.
COPY model_oss/diffusers/train.sh train.sh
# Generate accelerate config at the beginning of docker run.
ENTRYPOINT ["/bin/bash", "train.sh"]
@@ -0,0 +1,247 @@
"""Custom handler for huggingface/diffusers models."""
# pylint: disable=g-importing-member
# pylint: disable=logging-fstring-interpolation
import base64
import logging
import os
from typing import Any, List, Tuple
from diffusers import ControlNetModel
from diffusers import DiffusionPipeline
from diffusers import DPMSolverMultistepScheduler
from diffusers import EulerAncestralDiscreteScheduler
from diffusers import StableDiffusionControlNetPipeline
from diffusers import StableDiffusionImg2ImgPipeline
from diffusers import StableDiffusionInpaintPipeline
from diffusers import StableDiffusionInstructPix2PixPipeline
from diffusers import StableDiffusionPipeline
from diffusers import StableDiffusionUpscalePipeline
from diffusers import TextToVideoZeroPipeline
from diffusers import UniPCMultistepScheduler
import numpy as np
from PIL import Image
import torch
from ts.torch_handler.base_handler import BaseHandler
from util import constants
from util import fileutils
from util import image_format_converter
from video_util import video_format_converter
STABLE_DIFFUSION_MODEL = "runwayml/stable-diffusion-v1-5"
# Tasks
TEXT_TO_IMAGE = "text-to-image"
IMAGE_TO_IMAGE = "image-to-image"
IMAGE_INPAINTING = "image-inpainting"
INSTRUCT_PIX2PIX = "instruct-pix2pix"
CONTROLNET = "controlnet"
CONDITIONED_SUPER_RES = "conditioned-super-res"
TEXT_TO_VIDEO_ZERO_SHOT = "text-to-video-zero-shot"
TEXT_TO_VIDEO = "text-to-video"
class DiffusersHandler(BaseHandler):
"""Custom handler for TIMM models."""
def initialize(self, context: Any):
"""Custom initialize."""
properties = context.system_properties
self.map_location = (
"cuda"
if torch.cuda.is_available() and properties.get("gpu_id") is not None
else "cpu"
)
self.device = torch.device(
self.map_location + ":" + str(properties.get("gpu_id"))
if torch.cuda.is_available() and properties.get("gpu_id") is not None
else self.map_location
)
self.manifest = context.manifest
self.model_id = os.environ["MODEL_ID"]
if self.model_id.startswith(constants.GCS_URI_PREFIX):
gcs_path = self.model_id[len(constants.GCS_URI_PREFIX) :]
local_model_dir = os.path.join(constants.LOCAL_MODEL_DIR, gcs_path)
logging.info(f"Download {self.model_id} to {local_model_dir}")
fileutils.download_gcs_dir_to_local(self.model_id, local_model_dir)
self.model_id = local_model_dir
self.task = os.environ.get("TASK", TEXT_TO_IMAGE)
logging.info(f"Using task:{self.task}, model:{self.model_id}")
if self.task == TEXT_TO_IMAGE:
pipeline = StableDiffusionPipeline.from_pretrained(
self.model_id, torch_dtype=torch.float16
)
pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
pipeline.scheduler.config
)
pipeline = pipeline.to(self.map_location)
# Reduce memory footprint.
pipeline.enable_attention_slicing()
elif self.task == IMAGE_TO_IMAGE:
pipeline = StableDiffusionImg2ImgPipeline.from_pretrained(
self.model_id, torch_dtype=torch.float16
)
pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
pipeline.scheduler.config
)
pipeline = pipeline.to(self.map_location)
# Reduce memory footprint.
pipeline.enable_attention_slicing()
elif self.task == IMAGE_INPAINTING:
pipeline = StableDiffusionInpaintPipeline.from_pretrained(
self.model_id, torch_dtype=torch.float16
)
pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
pipeline.scheduler.config
)
pipeline = pipeline.to(self.map_location)
# Reduce memory footprint.
pipeline.enable_attention_slicing()
elif self.task == INSTRUCT_PIX2PIX:
pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
self.model_id, torch_dtype=torch.float16
)
pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
pipeline.scheduler.config
)
pipeline = pipeline.to(self.map_location)
# Reduce memory footprint.
pipeline.enable_attention_slicing()
elif self.task == CONTROLNET:
controlnet = ControlNetModel.from_pretrained(
self.model_id, torch_dtype=torch.float16
)
pipeline = StableDiffusionControlNetPipeline.from_pretrained(
STABLE_DIFFUSION_MODEL,
controlnet=controlnet,
torch_dtype=torch.float16,
)
pipeline.scheduler = UniPCMultistepScheduler.from_config(
pipeline.scheduler.config
)
pipeline.enable_xformers_memory_efficient_attention()
pipeline.enable_model_cpu_offload()
pipeline = pipeline.to(self.map_location)
# Reduce memory footprint.
pipeline.enable_attention_slicing()
elif self.task == CONDITIONED_SUPER_RES:
pipeline = StableDiffusionUpscalePipeline.from_pretrained(
self.model_id, torch_dtype=torch.float16
)
pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
pipeline.scheduler.config
)
# This is necessary to 4x upscale >=256x256 input images with V100.
logging.info("Enable xformers memory efficient attention for inference.")
pipeline.enable_xformers_memory_efficient_attention()
pipeline = pipeline.to(self.map_location)
# Reduce memory footprint.
pipeline.enable_attention_slicing()
elif self.task == TEXT_TO_VIDEO_ZERO_SHOT:
pipeline = TextToVideoZeroPipeline.from_pretrained(
STABLE_DIFFUSION_MODEL, torch_dtype=torch.float16
)
# Memory optimization.
pipeline.enable_xformers_memory_efficient_attention()
pipeline.enable_model_cpu_offload()
pipeline = pipeline.to(self.map_location)
elif self.task == TEXT_TO_VIDEO:
pipeline = DiffusionPipeline.from_pretrained(
self.model_id, torch_dtype=torch.float16, variant="fp16"
)
pipeline.enable_model_cpu_offload()
# Memory optimization.
pipeline.enable_vae_slicing()
pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
pipeline.scheduler.config
)
else:
raise ValueError(f"Invalid TASK: {self.task}")
self.pipeline = pipeline
self.initialized = True
logging.info("Handler initialization done.")
def preprocess(self, data: Any) -> Tuple[Any, Any, Any]:
"""Preprocess input data."""
prompts = [item["prompt"] for item in data]
images = None
mask_images = None
if "image" in data[0]:
images = [
image_format_converter.base64_to_image(item["image"]) for item in data
]
if "mask_image" in data[0]:
mask_images = [
image_format_converter.base64_to_image(item["mask_image"])
for item in data
]
return prompts, images, mask_images
def inference(self, data: Any, *args, **kwargs) -> List[Image.Image]:
"""Run the inference."""
prompts, images, mask_images = data
if self.task == TEXT_TO_IMAGE:
predicted_images = self.pipeline(prompt=prompts).images
elif self.task == IMAGE_TO_IMAGE:
predicted_images = self.pipeline(prompt=prompts, image=images).images
elif self.task == IMAGE_INPAINTING:
predicted_images = self.pipeline(
prompt=prompts, image=images, mask_image=mask_images
).images
elif self.task == INSTRUCT_PIX2PIX:
predicted_images = self.pipeline(prompt=prompts, image=images).images
elif self.task == CONTROLNET:
predicted_images = self.pipeline(
prompt=prompts, image=images, num_inference_steps=20
).images
elif self.task == CONDITIONED_SUPER_RES:
predicted_images = self.pipeline(
prompt=prompts, image=images, num_inference_steps=20
).images
elif self.task == TEXT_TO_VIDEO_ZERO_SHOT:
# For each given prompt, generate a short video.
# The pipeline doesn't support multiple prompts in one run yet.
videos = []
for prompt in prompts:
numpy_arrays = self.pipeline(prompt=prompt).images
numpy_arrays = [(i * 255).astype("uint8") for i in numpy_arrays]
videos.append(
video_format_converter.frames_to_video_bytes(numpy_arrays, fps=4)
)
return videos
elif self.task == TEXT_TO_VIDEO:
predicted_images = np.asarray(self.pipeline(prompt=prompts).frames)
# For multiple prompts, the model concatenates video frames, i.e. the
# output shape is (num_frames, height, width * len(prompts), channels).
# Therefore we need to split the output into different videos.
predicted_images = np.array_split(predicted_images, len(prompts), axis=2)
videos = [
video_format_converter.frames_to_video_bytes(images, fps=8)
for images in predicted_images
]
return videos
else:
raise ValueError(f"Invalid TASK: {self.task}")
return predicted_images
def postprocess(self, data: Any) -> List[str]:
"""Convert the images to base64 string."""
outputs = []
for prediction in data:
if isinstance(prediction, bytes):
# This is the video bytes.
outputs.append(base64.b64encode(prediction).decode("utf-8"))
else:
outputs.append(image_format_converter.image_to_base64(prediction))
return outputs
# pylint: enable=logging-fstring-interpolation
@@ -0,0 +1,6 @@
#!/bin/bash
# Setup accelerate config before running trainer.
python -c "from accelerate.utils import write_basic_config; write_basic_config(mixed_precision='fp16')"
accelerate launch "$@"
@@ -0,0 +1,79 @@
# Dockerfile for serving dockers for transformers.
#
# To build:
# docker build -f model_oss/transformers/dockerfile/serve.Dockerfile . -t ${YOUR_IMAGE_TAG}
#
# To push to gcr:
# docker tag ${YOUR_IMAGE_TAG} gcr.io/${YOUR_PROJECT}/${YOUR_IMAGE_TAG}
# docker push gcr.io/${YOUR_PROJECT}/${YOUR_IMAGE_TAG}
# Switch to this base image for gpu serve.
FROM pytorch/torchserve:0.7.0-gpu
USER root
ENV infer_port=7080
ENV mng_port=7081
ENV model_name="transformers_serving"
ENV PATH="/home/model-server/:${PATH}"
# Install libraries.
ENV PIP_ROOT_USER_ACTION=ignore
RUN python3 -m pip install --upgrade pip
RUN pip install torch==1.13.1
RUN pip install torchvision==0.14.1
RUN pip install transformers==4.27.4
RUN pip install datasets==2.9.0
RUN pip install accelerate==0.17.0
RUN pip install triton==2.0.0.dev20221120
RUN pip install xformers==0.0.16
RUN pip install google-cloud-storage==2.7.0
RUN pip install absl-py==1.4.0
# Install libraries for document-question-answering.
RUN apt-get update
RUN apt-get install -y --no-install-recommends tesseract-ocr
RUN pip install tesseract==0.1.3
RUN pip install pytesseract==0.3.10
# Install tools.
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
wget \
vim
# Copy license.
RUN wget https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/LICENSE
# Copy model artifacts.
COPY model_oss/transformers/handler.py /home/model-server/handler.py
COPY model_oss/util/ /home/model-server/util/
ENV PYTHONPATH /home/model-server/
# Create torchserve configuration file.
RUN echo \
"default_response_timeout=1800\n" \
"service_envelope=json\n" \
"inference_address=http://0.0.0.0:${infer_port}\n" \
"management_address=http://0.0.0.0:${mng_port}" >> /home/model-server/config.properties
# Expose ports.
EXPOSE ${infer_port}
EXPOSE ${mng_port}
# Archive model artifacts and dependencies.
# Do not set --model-file and --serialized-file because model and checkpoint will be dynamically loaded in handler.py.
RUN torch-model-archiver \
--model-name=${model_name} \
--version=1.0 \
--handler=/home/model-server/handler.py \
--runtime=python3 \
--export-path=/home/model-server/model-store \
--archive-format=default \
--force
# Run Torchserve HTTP serve to respond to prediction requests.
CMD ["torchserve", "--start", \
"--ts-config", "/home/model-server/config.properties", \
"--models", "${model_name}=${model_name}.mar", \
"--model-store", "/home/model-server/model-store"]
@@ -0,0 +1,233 @@
"""Custom handler for huggingface/transformers models."""
# pylint: disable=g-multiple-import
# pylint: disable=g-importing-member
import logging
import os
from typing import Any, List, Optional, Tuple
from PIL import Image
import torch
from transformers import (
AutoProcessor,
AutoTokenizer,
Blip2ForConditionalGeneration,
Blip2Processor,
BlipForConditionalGeneration,
BlipForQuestionAnswering,
BlipProcessor,
CLIPModel,
)
from transformers import pipeline
from ts.torch_handler.base_handler import BaseHandler
from util import constants
from util import fileutils
from util import image_format_converter
DEFAULT_MODEL_ID = "openai/clip-vit-base-patch32"
SALESFORCE_BLIP = "Salesforce/blip"
SALESFORCE_BLIP2 = "Salesforce/blip2"
FLAN_T5 = "flan-t5"
BART_LARGE_CNN = "facebook/bart-large-cnn"
ZERO_CLASSIFICATION = "zero-shot-image-classification"
FEATURE_EMBEDDING = "feature-embedding"
ZERO_DETECTION = "zero-shot-object-detection"
IMAGE_CAPTIONING = "image-to-text"
VQA = "visual-question-answering"
DQA = "document-question-answering"
SUMMARIZATION = "summarization"
SUMMARIZATION_TEMPLATE = (
"Summarize the following news article:\n{input}\nSummary:\n"
)
class TransformersHandler(BaseHandler):
"""Custom handler for huggingface/transformers models."""
def initialize(self, context: Any):
"""Custom initialize."""
properties = context.system_properties
self.map_location = (
"cuda"
if torch.cuda.is_available() and properties.get("gpu_id") is not None
else "cpu"
)
self.device = torch.device(
self.map_location + ":" + str(properties.get("gpu_id"))
if torch.cuda.is_available() and properties.get("gpu_id") is not None
else self.map_location
)
self.manifest = context.manifest
# The model id is can be either:
# 1) a huggingface model card id, like "Salesforce/blip", or
# 2) a GCS path to the model files, like "gs://foo/bar".
# If it's a model card id, the model will be loaded from huggingface.
self.model_id = (
DEFAULT_MODEL_ID
if os.environ.get("MODEL_ID") is None
else os.environ["MODEL_ID"]
)
# Else it will be downloaded from GCS to local first.
# Since the transformers from_pretrained API can't read from GCS.
if self.model_id.startswith(constants.GCS_URI_PREFIX):
gcs_path = self.model_id[len(constants.GCS_URI_PREFIX) :]
local_model_dir = os.path.join(constants.LOCAL_MODEL_DIR, gcs_path)
logging.info("Download %s to %s", self.model_id, local_model_dir)
fileutils.download_gcs_dir_to_local(self.model_id, local_model_dir)
self.model_id = local_model_dir
self.task = (
ZERO_CLASSIFICATION
if os.environ.get("TASK") is None
else os.environ["TASK"]
)
logging.info(
"Handler initializing task:%s, model:%s", self.task, self.model_id
)
if SALESFORCE_BLIP in self.model_id:
# pipeline() hasn't been ready for Salesforce/blip models.
self.salesforce_blip = True
self._create_blip_model()
else:
self.salesforce_blip = False
if self.task == FEATURE_EMBEDDING:
self.model = CLIPModel.from_pretrained(self.model_id).to(
self.map_location
)
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
self.processor = AutoProcessor.from_pretrained(self.model_id)
elif self.task == SUMMARIZATION and FLAN_T5 in self.model_id:
self.pipeline = pipeline(
task=self.task,
model=self.model_id,
torch_dtype=torch.bfloat16,
device_map="auto",
)
else:
self.pipeline = pipeline(
task=self.task, model=self.model_id, device=self.device
)
self.initialized = True
logging.info("Handler initialization done.")
def _create_blip_model(self):
"""A helper for creating BLIP and BLIP2 models."""
if SALESFORCE_BLIP2 in self.model_id:
self.torch_type = torch.float16
self.processor = Blip2Processor.from_pretrained(self.model_id)
self.model = Blip2ForConditionalGeneration.from_pretrained(
self.model_id, torch_dtype=self.torch_type
).to(self.map_location)
else:
self.torch_type = torch.float32
self.processor = BlipProcessor.from_pretrained(self.model_id)
if self.task == IMAGE_CAPTIONING:
self.model = BlipForConditionalGeneration.from_pretrained(
self.model_id
).to(self.map_location)
elif self.task == VQA:
self.model = BlipForQuestionAnswering.from_pretrained(self.model_id).to(
self.map_location
)
def _reformat_detection_result(self, data: List[Any]) -> List[Any]:
"""Reformat zero-shot-object-detection output."""
if not data:
return [data]
boxes = {}
boxes["label"] = data[0]["label"]
boxes["boxes"] = []
for item in data:
box = {}
box["score"] = item["score"]
box.update(item["box"])
boxes["boxes"].append(box)
outputs = [boxes]
return outputs
def preprocess(
self, data: Any
) -> Tuple[Optional[List[str]], Optional[List[Image.Image]]]:
"""Preprocess input data."""
texts = None
images = None
if "text" in data[0]:
texts = [item["text"] for item in data]
if "image" in data[0]:
images = [
image_format_converter.base64_to_image(item["image"]) for item in data
]
return texts, images
def inference(self, data: Any, *args, **kwargs) -> List[Any]:
"""Run the inference."""
texts, images = data
preds = None
if self.task == ZERO_CLASSIFICATION:
preds = self.pipeline(images=images, candidate_labels=texts)
elif self.task == ZERO_DETECTION:
# The object detection pipeline doesn't support batch prediction.
preds = self.pipeline(image=images[0], candidate_labels=texts[0])
elif self.task == IMAGE_CAPTIONING:
if self.salesforce_blip:
inputs = self.processor(images[0], return_tensors="pt").to(
self.map_location, self.torch_type
)
preds = self.model.generate(**inputs)
preds = [
self.processor.decode(preds[0], skip_special_tokens=True).strip()
]
else:
preds = self.pipeline(images=images)
elif self.task == VQA:
# The VQA pipelines doesn't support batch prediction.
if self.salesforce_blip:
inputs = self.processor(images[0], texts[0], return_tensors="pt").to(
self.map_location, self.torch_type
)
preds = self.model.generate(**inputs)
preds = [
self.processor.decode(preds[0], skip_special_tokens=True).strip()
]
else:
preds = self.pipeline(image=images[0], question=texts[0])
elif self.task == DQA:
# The DQA pipelines doesn't support batch prediction.
preds = self.pipeline(image=images[0], question=texts[0])
elif self.task == FEATURE_EMBEDDING:
preds = {}
if texts:
inputs = self.tokenizer(
text=texts, padding=True, return_tensors="pt"
).to(self.map_location)
text_features = self.model.get_text_features(**inputs)
preds["text_features"] = text_features.detach().cpu().numpy().tolist()
if images:
inputs = self.processor(images=images, return_tensors="pt").to(
self.map_location
)
image_features = self.model.get_image_features(**inputs)
preds["image_features"] = image_features.detach().cpu().numpy().tolist()
preds = [preds]
elif self.task == SUMMARIZATION and FLAN_T5 in self.model_id:
texts = [SUMMARIZATION_TEMPLATE.format(input=text) for text in texts]
preds = self.pipeline(texts, max_length=130)
elif self.task == SUMMARIZATION and self.model_id == BART_LARGE_CNN:
preds = self.pipeline(
texts[0], max_length=130, min_length=30, do_sample=False
)
else:
raise ValueError(f"Invalid TASK: {self.task}")
return preds
def postprocess(self, data: Any) -> List[Any]:
if self.task == ZERO_DETECTION:
data = self._reformat_detection_result(data)
return data
@@ -0,0 +1,64 @@
"""Vertex vision model garden util constants."""
# Objectives.
OBJECTIVE_IMAGE_CLASSIFICATION = 'icn'
OBJECTIVE_IMAGE_OBJECT_DETECTION = 'iod'
OBJECTIVE_IMAGE_SEGMENTATION = 'isg'
# Input file types.
INPUT_FILE_TYPE_CSV = 'csv'
INPUT_FILE_TYPE_JSONL = 'jsonl'
INPUT_FILE_TYPE_COCO_JSON = 'coco_json'
# Output file types.
OUTPUT_FILE_TYPE_TFRECORD = 'tfrecord'
OUTPUT_FILE_TYPE_COCO_JSON = 'coco_json'
# Best evaluation metrics.
IMAGE_CLASSIFICATION_SINGLE_LABEL_BEST_EVAL_METRIC = 'accuracy'
IMAGE_CLASSIFICATION_MULTI_LABEL_BEST_EVAL_METRIC = 'meanPR-AUC'
IMAGE_OBJECT_DETECTION_BEST_EVAL_METRIC = 'AP50'
IMAGE_SEGMENTATION_BEST_EVAL_METRIC = 'mean_iou'
VIDEO_CLASSIFICATION_BEST_EVAL_METRIC = 'accuracy'
# Best checkpoints.
BEST_CKPT_DIRNAME = 'best_ckpt'
BEST_CKPT_EVAL_FILENAME = 'info.json'
BEST_CKPT_STEP_NAME = 'best_ckpt_global_step'
BEST_CKPT_METRIC_COMP = 'higher'
# Reported hyperparameter tuning metric tag.
HP_METRIC_TAG = 'model_performance'
# HPT trial prefix.
TRIAL_PREFIX = 'trial_'
# ML uses from user input.
ML_USE_TRAINING = 'training'
ML_USE_VALIDATION = 'validation'
ML_USE_TEST = 'test'
# COCO json keys
COCO_JSON_ANNOTATIONS = 'annotations'
COCO_JSON_ANNOTATION_IMAGE_ID = 'image_id'
COCO_JSON_ANNOTATION_CATEGORY_ID = 'category_id'
COCO_JSON_CATEGORIES = 'categories'
COCO_JSON_CATEGORY_ID = 'id'
COCO_JSON_CATEGORY_NAME = 'name'
COCO_JSON_FILE_NAME = 'file_name'
COCO_JSON_IMAGES = 'images'
COCO_JSON_IMAGE_ID = 'id'
COCO_JSON_IMAGE_WIDTH = 'width'
COCO_JSON_IMAGE_HEIGHT = 'height'
COCO_JSON_IMAGE_COCO_URL = 'coco_url'
COCO_ANNOTATION_BBOX = 'bbox'
# GCS prefixes
GCS_URI_PREFIX = 'gs://'
GCSFUSE_URI_PREFIX = '/gcs/'
LOCAL_EVALUATION_RESULT_DIR = '/tmp/evaluation_result_dir'
LOCAL_MODEL_DIR = '/tmp/model_dir'
LOCAL_DATA_DIR = '/tmp/data'
@@ -0,0 +1,79 @@
"""Fileutil lib to copy files between gcs and local."""
import glob
import os
from absl import logging
from google.cloud import storage
from util import constants
def download_gcs_file_to_local(gcs_uri: str, local_path: str):
"""Download a gcs file to a local path.
Args:
gcs_uri: A string of file path on GCS.
local_path: A string of local file path.
"""
if not gcs_uri.startswith(constants.GCS_URI_PREFIX):
raise ValueError(
f'{gcs_uri} is not a GCS path starting with {constants.GCS_URI_PREFIX}.'
)
client = storage.Client()
os.makedirs(os.path.dirname(local_path), exist_ok=True)
with open(local_path, 'wb') as f:
client.download_blob_to_file(gcs_uri, f)
def download_gcs_dir_to_local(gcs_dir: str, local_dir: str):
"""Downloads files in a GCS directory to a local directory.
For example:
download_gcs_dir_to_local(gs://bucket/foo, /tmp/bar)
gs://bucket/foo/a -> /tmp/bar/a
gs://bucket/foo/b/c -> /tmp/bar/b/c
Arguments:
gcs_dir: A string of directory path on GCS.
local_dir: A string of local directory path.
"""
bucket_name = gcs_dir.split('/')[2]
prefix = gcs_dir[len(constants.GCS_URI_PREFIX + bucket_name) :].strip('/')
client = storage.Client()
blobs = client.list_blobs(bucket_name, prefix=prefix)
for blob in blobs:
if blob.name[-1] == '/':
continue
file_path = blob.name[len(prefix) :].strip('/')
local_file_path = os.path.join(local_dir, file_path)
os.makedirs(os.path.dirname(local_file_path), exist_ok=True)
logging.info('Downloading %s to %s', file_path, local_file_path)
blob.download_to_filename(local_file_path)
def upload_local_dir_to_gcs(local_dir: str, gcs_dir: str):
"""Uploads local dir to gcs.
For example:
upload_local_dir_to_gcs(/tmp/bar, gs://bucket/foo)
gs://bucket/foo/a -> /tmp/bar/a
gs://bucket/foo/b/c -> /tmp/bar/b/c
Arguments:
local_dir: A string of local directory path.
gcs_dir: A string of directory path on GCS.
"""
bucket_name = gcs_dir.split('/')[2]
blob_dir = '/'.join(gcs_dir.split('/')[3:])
client = storage.Client()
bucket = client.bucket(bucket_name)
for local_file in glob.glob(local_dir + '/**'):
if os.path.isfile(local_file):
logging.info(
'Uploading %s to %s',
local_file,
os.path.join(constants.GCS_URI_PREFIX, bucket_name, blob_dir),
)
blob = bucket.blob(os.path.join(blob_dir, os.path.basename(local_file)))
blob.upload_from_filename(local_file)
@@ -0,0 +1,21 @@
"""Utility functions for Vertex Hyperparameter Tuning Jobs."""
import os
from absl import logging
_ENVIRONMENT_VARIABLE_FOR_TRIAL_ID = 'CLOUD_ML_TRIAL_ID'
def get_trial_id_from_environment() -> str:
"""Gets the trial id from environment variable.
Returns:
The trial id from environement or '0' if not found.
"""
if _ENVIRONMENT_VARIABLE_FOR_TRIAL_ID not in os.environ:
logging.warning(
'Environment variable %s not found, return 0 as default trial id.',
_ENVIRONMENT_VARIABLE_FOR_TRIAL_ID,
)
return os.environ.get(_ENVIRONMENT_VARIABLE_FOR_TRIAL_ID, '0')
@@ -0,0 +1,20 @@
"""Image format converter util lib."""
import base64
import io
from PIL import Image
def image_to_base64(image: Image.Image) -> str:
"""Convert a PIL image to a base64 string."""
buffer = io.BytesIO()
image.save(buffer, format="JPEG")
image_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
return image_str
def base64_to_image(image_str: str) -> Image.Image:
"""Convert a base64 string to a PIL image."""
image = Image.open(io.BytesIO(base64.b64decode(image_str)))
return image
@@ -0,0 +1,14 @@
"""Video format converter util lib."""
import io
from typing import Sequence
import imageio
import numpy as np
from PIL import Image
def frames_to_video_bytes(frames: Sequence[np.ndarray], fps: int) -> bytes:
images = [Image.fromarray(array) for array in frames]
io_obj = io.BytesIO()
imageio.mimsave(io_obj, images, format=".mp4", fps=fps)
return io_obj.getvalue()
+18
View File
@@ -33,6 +33,7 @@
/notebooks/community/cohere/cohere_embedding_with_matching_engine.ipynb @stewart-co
/notebooks/community/ml_ops/stage2/get_started_vertex_hpt_r_kernel.ipynb @fhirschmann
/notebooks/community/ml_ops/stage2/get_started_vertex_training_r_using_r_kernel.ipynb @fhirschmann
/notebooks/community/ml_ops/stage3/get_started_with_dataflow_flex_template_component.ipynb @wintwoo
/notebooks/community/vertex-ai-samples/notebooks/community/model_registry/vertex_ai_model_registry_bqml_custom_model_versioning.ipynb @inardini
/notebooks/community/vertex-ai-samples/notebooks/community/model_registry/vertex_ai_model_registry_automl_model_versioning.ipynb @inardini
/notebooks/community/vizier/conversions_vertex_vizier_and_open_source_vizier.ipynb @halio-g
@@ -41,10 +42,16 @@
/notebooks/community/pipelines/google_cloud_pipeline_components_cloud_natural_language_pipeline.ipynb @Narwhalprime
/notebooks/community/pipelines/google_cloud_pipeline_components_ready_to_go_text_classification_pipeline.ipynb @Narwhalprime
/notebooks/community/feature_store/get_started_vertex_feature_store.ipynb @junkourata
/notebooks/community/model_garden/model_garden_huggingface_local_inference.ipynb @dstnluong-google
/notebooks/community/model_garden/model_garden_mediapipe_image_classification.ipynb @schmidt-sebastian
/notebooks/community/model_garden/model_garden_mediapipe_object_detection.ipynb @schmidt-sebastian
/notebooks/community/model_garden/model_garden_proprietary_image_classification.ipynb @weigary
/notebooks/community/model_garden/model_garden_proprietary_image_object_detection.ipynb @weigary
/notebooks/community/model_garden/model_garden_tfvision_image_classification.ipynb @genquan9
/notebooks/community/model_garden/model_garden_tfvision_image_object_detection.ipynb @genquan9
/notebooks/community/model_garden/model_garden_tfvision_image_segmentation.ipynb @genquan9
/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion.ipynb @xiangxu-google
/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_2_1.ipynb @bingatgoogle
/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_inpainting.ipynb @xiangxu-google
/notebooks/community/model_garden/model_garden_pytorch_instructpix2pix.ipynb @xiangxu-google
/notebooks/community/model_garden/model_garden_pytorch_controlnet.ipynb @xiangxu-google
@@ -56,3 +63,14 @@
/notebooks/community/model_garden/model_garden_pytorch_owlvit.ipynb @xiangxu-google
/notebooks/community/model_garden/model_garden_pytorch_layoutml_document_qa.ipynb @xiangxu-google
/notebooks/community/model_garden/model_garden_pytorch_blip2.ipynb @xiangxu-google
/notebooks/community/model_garden/model_garden_pytorch_detectron2.ipynb @lavraicse
/notebooks/community/model_garden/model_garden_pytorch_dolly_v2.ipynb @lavraicse
/notebooks/community/model_garden/model_garden_pytorch_bart_large_cnn.ipynb @lavraicse
/notebooks/community/model_garden/model_garden_jax_vision_transformer.ipynb @lavraicse
/notebooks/community/model_garden/model_garden_pytorch_text_to_video_zero_shot.ipynb @bingatgoogle
/notebooks/community/model_garden/model_garden_pytorch_text_to_video.ipynb @KCFindstr
/notebooks/community/generative_ai/text_embedding_api_semantic_search_with_scann.ipynb @henrytansetiawan
/notebooks/community/bigquery_ml_inference/bq_ml_with_vision_translation_nlp.ipynb @deaconsmith
/notebooks/community/model_garden/model_garden_keras_stable_diffusion.ipynb @genquan9
/notebooks/community/model_garden/model_garden_pytorch_sam.ipynb @huguensjean
/notebooks/community/model_garden/model_garden_pytorch_peft.ipynb @genquan9
+19
View File
@@ -0,0 +1,19 @@
[Unstructured data analytics with BigQuery ML and Vertex AI pre-trained models](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/bigquery_ml/bq_ml_with_vision_translation_nlp.ipynb)
```
Learn how to analyze unstructured data within BigQuery using BigQuery's inference engine. You will use BigQuery ML to connect to three pretrained Vertex AI APIs - Vision API, Translation API and Natural Language Processing API.
The steps performed include:
- Define pre-trained models for Vision AI, Translation AI and NLP AI in BigQuery ML
- Call the Vision API (`ML.ANNOTATE_IMAGE`) to detect text in images stored in Cloud Storage
You will need to create an object table in BigQuery to do this
- Call the Translation API (`ML.TRANSLATE`) to detect the language of text, and translate non-English movie titles to English
- Call the Natural Language API (`ML.UNDERSTAND_TEXT`) to run sentiment analysis over movie reviews stored in BigQuery
```
&nbsp;&nbsp;&nbsp;Check out the [blog for this notebook](https://cloud.google.com/blog/products/data-analytics/how-simplify-unstructured-data-analytics-using-bigquery-ml-and-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [BigQuery ML inference engine](https://cloud.google.com/bigquery/docs/reference/standard-sql/inference-overview).
File diff suppressed because one or more lines are too long
@@ -0,0 +1,373 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "KSP1duKDeaDR",
"metadata": {
"id": "KSP1duKDeaDR"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"id": "67b2c5cc-8fc6-4082-9052-69fa0377d770",
"metadata": {
"id": "67b2c5cc-8fc6-4082-9052-69fa0377d770"
},
"source": [
"# Semantic Search using Embeddings\n",
"\n",
"Semantic search is a type of search that uses the meaning of words and phrases to find relevant results.\n",
"\n",
"In this tutorial, we will demonstrate how to do semantic search with embeddings generated from the news text and using [Google ScaNN: Efficient Vector Similarity Search](https://ai.googleblog.com/2020/07/announcing-scann-efficient-vector.html) to retrieve the most relevant news semantically.\n",
"\n",
"## Pre-requisites:\n",
"- Vertex LLM SDK\n",
"- ScaNN [github](https://github.com/google-research/google-research/tree/master/scann)"
]
},
{
"cell_type": "markdown",
"id": "FyyMdUeAJIVv",
"metadata": {
"id": "FyyMdUeAJIVv"
},
"source": [
"## Install Vertex LLM SDK\n",
"\n",
"DISCLAIMER: Text Embedding API is now in Experimental Preview. This release focuses on validating model prototypes and these models are not guaranteed to be released. Use of Text Embedding API is governed by the Google Cloud Terms of Service, the Pre-GA Offerings Terms of the GCP Service Specific Terms. The Acceptance Use Policy, and the Generative AI Prohibited Use Policy. Vertex Text Embedding API’s features may be unstable, change in backward-incompatible ways, and are not guaranteed to be released. There are no SLAs provided and no technical support obligations. GCP’s Cloud Data Processing Addendum does not apply to Pre-GA Offerings and customers should not use Text Embedding API to process personal data or other data subject to legal or regulatory compliance requirements. See description of launch stage for details.\n",
"\n",
"The information in this documentation is provided to the customer on an “as is” and “with all faults” basis without any warranty of any kind, either express or implied. Google does not warrant or guarantee the correctness, accuracy or reliability of the information in here. In no event will Google or its affiliates or licensors be liable for any damage or harm to customers from customer’s use of these materials."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "h6KaE3XRJdxc",
"metadata": {
"id": "h6KaE3XRJdxc"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "snBUuUamoJPz",
"metadata": {
"id": "snBUuUamoJPz"
},
"outputs": [],
"source": [
"!pip3 install google-cloud-aiplatform>=1.25 \"shapely<2.0.0\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "zgVQcE0ewO8W",
"metadata": {
"id": "zgVQcE0ewO8W"
},
"outputs": [],
"source": [
"PROJECT_ID = \"cloud-nl-llm-embedding\" # @param {type:\"string\"}\n",
"LOCATION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"import vertexai\n",
"\n",
"vertexai.init(project=PROJECT_ID, location=LOCATION)"
]
},
{
"cell_type": "markdown",
"id": "4xFzXmPbY7FC",
"metadata": {
"id": "4xFzXmPbY7FC"
},
"source": [
"**Attention**: you would need to restart runtime so that the right package is installed."
]
},
{
"cell_type": "markdown",
"id": "xnfG88OPZI18",
"metadata": {
"id": "xnfG88OPZI18"
},
"source": [
"## Import TextEmbeddingModel"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1e6e1b98-a632-44a2-afb8-fc212018ef4f",
"metadata": {
"id": "1e6e1b98-a632-44a2-afb8-fc212018ef4f"
},
"outputs": [],
"source": [
"from vertexai.preview.language_models import TextEmbeddingModel\n",
"\n",
"model = TextEmbeddingModel.from_pretrained(\"textembedding-gecko@001\")"
]
},
{
"cell_type": "markdown",
"id": "1suA-1HuaGj6",
"metadata": {
"id": "1suA-1HuaGj6"
},
"source": [
"## Install ScaNN Package"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "770255d3-54dd-48c8-bbdd-fbc0be41f085",
"metadata": {
"id": "770255d3-54dd-48c8-bbdd-fbc0be41f085"
},
"outputs": [],
"source": [
"!pip install scann"
]
},
{
"cell_type": "markdown",
"id": "dae340cb-0583-4e7e-a562-6817ee4d7f6d",
"metadata": {
"id": "dae340cb-0583-4e7e-a562-6817ee4d7f6d"
},
"source": [
"## Imports packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "412d00f1-08db-4880-8ced-52a9583757b8",
"metadata": {
"id": "412d00f1-08db-4880-8ced-52a9583757b8"
},
"outputs": [],
"source": [
"import json\n",
"import time\n",
"\n",
"import numpy as np\n",
"import pandas as pd\n",
"import scann"
]
},
{
"cell_type": "markdown",
"id": "f50f22f3-ec85-463e-b6fe-5c8e6b80b07b",
"metadata": {
"id": "f50f22f3-ec85-463e-b6fe-5c8e6b80b07b"
},
"source": [
"## Create Embedding Dataset.\n",
"\n",
"The dataset is solely to demonstrate the use of the Text Embedding API with a vector database. It is not intended to be used for any other purpose, such as evaluating models. The dataset is small and does not represent a comprehensive sample of all possible text."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2OUg-Qf8iFta",
"metadata": {
"id": "2OUg-Qf8iFta"
},
"outputs": [],
"source": [
"!gsutil cp gs://cloud-samples-data/vertex-ai/dataset-management/datasets/bert_finetuning/wide_and_deep_trainer_container_tests_input.jsonl ."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "BNPapKXviHlE",
"metadata": {
"id": "BNPapKXviHlE"
},
"outputs": [],
"source": [
"records = []\n",
"with open(\"wide_and_deep_trainer_container_tests_input.jsonl\") as f:\n",
" for line in f:\n",
" record = json.loads(line)\n",
" records.append(record)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "Z1Y9Bx2miJba",
"metadata": {
"id": "Z1Y9Bx2miJba"
},
"outputs": [],
"source": [
"# Peek at the data.\n",
"df = pd.DataFrame(records)\n",
"df.head(50)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1v7zUwoWiPl-",
"metadata": {
"id": "1v7zUwoWiPl-"
},
"outputs": [],
"source": [
"def get_embedding(text):\n",
" get_embedding.counter += 1\n",
" try:\n",
" if get_embedding.counter % 100 == 0:\n",
" time.sleep(3)\n",
" return model.get_embeddings([text])[0].values\n",
" except:\n",
" return []\n",
"\n",
"\n",
"get_embedding.counter = 0\n",
"\n",
"# This may take several minutes to complete.\n",
"df[\"embedding\"] = df[\"textContent\"].apply(lambda x: get_embedding(x))"
]
},
{
"cell_type": "markdown",
"id": "ba4f49b6-65e1-49ea-988b-c4e195219deb",
"metadata": {
"id": "ba4f49b6-65e1-49ea-988b-c4e195219deb"
},
"source": [
"## Create an Index"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "245bc8cd-038b-484a-acb2-3a705d4cc4cf",
"metadata": {
"id": "245bc8cd-038b-484a-acb2-3a705d4cc4cf"
},
"outputs": [],
"source": [
"record_count = len(records)\n",
"dataset = np.empty((record_count, 768))\n",
"for i in range(record_count):\n",
" dataset[i] = df.embedding[i]\n",
"\n",
"normalized_dataset = dataset / np.linalg.norm(dataset, axis=1)[:, np.newaxis]\n",
"# configure ScaNN as a tree - asymmetric hash hybrid with reordering\n",
"# anisotropic quantization as described in the paper; see README\n",
"\n",
"# use scann.scann_ops.build() to instead create a TensorFlow-compatible searcher\n",
"searcher = (\n",
" scann.scann_ops_pybind.builder(normalized_dataset, 10, \"dot_product\")\n",
" .tree(\n",
" num_leaves=record_count,\n",
" num_leaves_to_search=record_count,\n",
" training_sample_size=record_count,\n",
" )\n",
" .score_ah(2, anisotropic_quantization_threshold=0.2)\n",
" .reorder(100)\n",
" .build()\n",
")"
]
},
{
"cell_type": "markdown",
"id": "9f1689eb-c27c-4566-afc7-7fbc55552aad",
"metadata": {
"id": "9f1689eb-c27c-4566-afc7-7fbc55552aad"
},
"source": [
"## Queries the Index"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "494079df-d8f6-4a6a-b26b-0b0477791adc",
"metadata": {
"id": "494079df-d8f6-4a6a-b26b-0b0477791adc"
},
"outputs": [],
"source": [
"def search(query):\n",
" start = time.time()\n",
" query = model.get_embeddings([query])[0].values\n",
" neighbors, distances = searcher.search(query, final_num_neighbors=3)\n",
" end = time.time()\n",
"\n",
" for id, dist in zip(neighbors, distances):\n",
" print(f\"[docid:{id}] [{dist}] -- {df.textContent[int(id)][:125]}...\")\n",
" print(\"Latency (ms):\", 1000 * (end - start))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "50497681-6112-4147-a13e-afedb72b54f5",
"metadata": {
"id": "50497681-6112-4147-a13e-afedb72b54f5"
},
"outputs": [],
"source": [
"search(\"tell me about shark or animal\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c814f835-3e2a-4366-a334-ccc636f00b83",
"metadata": {
"id": "c814f835-3e2a-4366-a334-ccc636f00b83"
},
"outputs": [],
"source": [
"search(\"tell me about an important moment or event in your life\")"
]
}
],
"metadata": {
"colab": {
"name": "text_embedding_api_semantic_search_with_scann.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -196,7 +196,7 @@
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install {USER_FLAG} --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-pipeline-components \\\n",
" google-cloud-pipeline-components==1.0.25 \\\n",
" kfp "
]
},
@@ -0,0 +1,832 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "copyright"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 3 : formalization: get started with the Dataflow Flex Template component\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage3/get_started_with_dataflow_pipeline_components.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage3/get_started_with_dataflow_pipeline_components.ipynb\">\n",
"<img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> \n",
" Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/ml_ops/stage3/get_started_with_dataflow_pipeline_components.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td> \n",
" \n",
"</table>\n",
"<br/><br/><br/>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "overview:mlops"
},
"source": [
"## Overview\n",
"\n",
"\n",
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : formalization: get started with the Dataflow Flex Template component."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "objective:mlops,stage3,get_started_dataflow_pipeline_components"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to use prebuilt `Google Cloud Pipeline Components` to execute `Dataflow` [Flex Template](https://cloud.google.com/dataflow/docs/guides/templates/using-flex-templates) jobs.\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
"- `Vertex AI Pipelines`\n",
"- `Google Cloud Pipeline Components`\n",
"- `Dataflow`\n",
"\n",
"The steps performed include:\n",
"\n",
"- Defining a pipeline step to execute a Dataflow Flex Template job within a Vertex AI pipeline.\n",
"- Execute a Vertex AI pipeline."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:gsod,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the sample data from the [Apache Beam Mobile Gaming Pipeline example](https://beam.apache.org/get-started/mobile-gaming-example/)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c997d8d92ce"
},
"source": [
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"* Dataflow\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and [Dataflow pricing](https://cloud.google.com/dataflow/pricing)\n",
"and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "install_mlops"
},
"source": [
"## Installations\n",
"\n",
"Install the required packages for executing the notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_mlops"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --pre --upgrade google-cloud-pipeline-components $USER_FLAG -q"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Dataflow API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,dataflow.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "project_id"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "250cb8c648d5"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "927085b84a07"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"**Click Create service account**.\n",
"\n",
"In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "89788a802687"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "40ed98f5cc48"
},
"source": [
"#### If you are using Colab Notebooks, set the project using gcloud config."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fde1a355f1e9"
},
"outputs": [],
"source": [
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
" if \"google.colab\" in sys.modules:\n",
" ! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_URI = \"gs://[your-bucket-name]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_URI = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "set_service_account"
},
"source": [
"#### Service Account\n",
"\n",
"**If you don't know your service account**, try to get your service account using `gcloud` command by executing the second cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_service_account"
},
"outputs": [],
"source": [
"SERVICE_ACCOUNT = \"[your-service-account]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_service_account"
},
"outputs": [],
"source": [
"if (\n",
" SERVICE_ACCOUNT == \"\"\n",
" or SERVICE_ACCOUNT is None\n",
" or SERVICE_ACCOUNT == \"[your-service-account]\"\n",
"):\n",
" # Get your service account from gcloud\n",
" if not IS_COLAB:\n",
" shell_output = !gcloud auth list 2>/dev/null\n",
" SERVICE_ACCOUNT = shell_output[2].replace(\"*\", \"\").strip()\n",
"\n",
" if IS_COLAB:\n",
" shell_output = ! gcloud projects describe $PROJECT_ID\n",
" project_number = shell_output[-1].split(\":\")[1].strip().replace(\"'\", \"\")\n",
" SERVICE_ACCOUNT = f\"{project_number}-compute@developer.gserviceaccount.com\"\n",
"\n",
" print(\"Service Account:\", SERVICE_ACCOUNT)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "set_service_account:pipelines"
},
"source": [
"#### Set service account access for Vertex AI Pipelines\n",
"\n",
"Run the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_service_account:pipelines"
},
"outputs": [],
"source": [
"! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_URI\n",
"\n",
"! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_vars"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries and define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "import_aip:mbsdk"
},
"outputs": [],
"source": [
"import google.cloud.aiplatform as aip\n",
"from google_cloud_pipeline_components.experimental.dataflow import \\\n",
" DataflowFlexTemplateJobOp\n",
"from google_cloud_pipeline_components.v1.wait_gcp_resources import \\\n",
" WaitGcpResourcesOp\n",
"from kfp import dsl\n",
"from kfp.v2 import compiler"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "init_aip:mbsdk"
},
"source": [
"### Initialize Vertex AI SDK for Python\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project and corresponding bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "init_aip:mbsdk"
},
"outputs": [],
"source": [
"aip.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "writefile:wc.py"
},
"source": [
"### Prepare a Flex Template job to convert a CSV file to Parquet\n",
"\n",
"In this tutorial, you use the Google-provided [File Format Conversion template](https://cloud.google.com/dataflow/docs/guides/templates/provided/file-format-conversion) to convert a CSV file to Parquet format."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "writefile:requirements,wc"
},
"source": [
"#### Create the Avro schema file\n",
"\n",
"First, create an Avro schema file that describes the example data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "writefile:requirements,wc"
},
"outputs": [],
"source": [
"%%writefile gaming_schema.avsc\n",
"\n",
"{\n",
" \"type\" : \"record\",\n",
" \"name\" : \"user_score\",\n",
" \"fields\" : [\n",
" { \"name\" : \"user\" , \"type\" : \"string\" },\n",
" { \"name\" : \"team\" , \"type\" : \"string\" },\n",
" { \"name\" : \"score\" , \"type\" : \"int\" },\n",
" { \"name\" : \"ts_epoch\" , \"type\" : \"long\" },\n",
" { \"name\" : \"ts_str\" , \"type\" : \"string\" }\n",
" ]\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "copy_to_gcs:wc"
},
"source": [
"#### Copy the Avro schema file to Cloud Storage\n",
"\n",
"Next, you copy the Avro schema file to your Cloud Storage bucket.\n",
"\n",
"Additional, you set the following:\n",
"\n",
"- The Cloud Storage location of the Flex Template definition file. In this tutorial, you use the location of the File Conversion template.\n",
"- A `Dict` containing the user parameters required by the Flex Template. These parameters include:\n",
"\n",
" - `inputFileFormat`: The file format of the input files.\n",
" - `outputFileFormat`: The file format of the output files.\n",
" - `inputFileSpec`: The input filepattern to read from.\n",
" - `outputBucket`: The Cloud Storage path to write the output files.\n",
" - `schema`: The Cloud Storage path top the avro schema file used for the conversion.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "copy_to_gcs:wc"
},
"outputs": [],
"source": [
"GCS_AVRO_SCHEMA = BUCKET_URI + \"/gaming_schema.avsc\"\n",
"! gsutil cp gaming_schema.avsc $GCS_AVRO_SCHEMA\n",
"\n",
"GCS_FLEX_TEMPLATE_PATH = \"gs://dataflow-templates/latest/flex/File_Format_Conversion\"\n",
"GCS_CONVERT_IN = \"gs://dataflow-samples/game/5000_gaming_data.csv\"\n",
"GCS_CONVERT_OUT = BUCKET_URI + \"/parquet_out/\"\n",
"\n",
"TEMPLATE_PARAMETERS = {\n",
" \"inputFileFormat\": \"csv\",\n",
" \"outputFileFormat\": \"parquet\",\n",
" \"inputFileSpec\": GCS_CONVERT_IN,\n",
" \"outputBucket\": GCS_CONVERT_OUT,\n",
" \"schema\": GCS_AVRO_SCHEMA,\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_dataflow_pipeline:wc"
},
"source": [
"### Create and execute the pipeline job\n",
"\n",
"In this example, the `DataflowFlexTemplateJobOp` component takes the following parameters:\n",
"\n",
"- `project_id`: The project ID.\n",
"- `location`: The region.\n",
"- `container_spec_gcs_path`: The Cloud Storage path to a file that contains the Flex Template definition. This file contains a json serialized `ContainerSpec` as content.\n",
"- `temp_location`: The Cloud Storage path to use for temporary files.\n",
"- `parameters`: The parameters for the Flex Template.\n",
"\n",
"Learn more about [Google Cloud Pipeline Components for Dataflow](https://google-cloud-pipeline-components.readthedocs.io/en/google-cloud-pipeline-components-2.0.0b2/google_cloud_pipeline_components.experimental.dataflow.html)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "create_dataflow_pipeline:wc"
},
"outputs": [],
"source": [
"PIPELINE_ROOT = \"{}/pipeline_root/dataflow_file_conversion\".format(BUCKET_URI)\n",
"\n",
"\n",
"@dsl.pipeline(\n",
" name=\"dataflow-file-conversion\", description=\"Dataflow file format conversion\"\n",
")\n",
"def pipeline(\n",
" project_id: str = PROJECT_ID,\n",
" location: str = REGION,\n",
" container_spec_gcs_path: str = GCS_FLEX_TEMPLATE_PATH,\n",
" temp_location: str = PIPELINE_ROOT,\n",
" parameters: dict = TEMPLATE_PARAMETERS,\n",
"):\n",
" flex_template_op = DataflowFlexTemplateJobOp(\n",
" project=project_id,\n",
" location=location,\n",
" container_spec_gcs_path=container_spec_gcs_path,\n",
" temp_location=temp_location,\n",
" parameters=parameters,\n",
" )\n",
"\n",
" _ = WaitGcpResourcesOp(gcp_resources=flex_template_op.outputs[\"gcp_resources\"])\n",
"\n",
"\n",
"compiler.Compiler().compile(\n",
" pipeline_func=pipeline, package_path=\"dataflow_file_conversion.yaml\"\n",
")\n",
"\n",
"pipeline = aip.PipelineJob(\n",
" display_name=\"dataflow_file_conversion\",\n",
" template_path=\"dataflow_file_conversion.yaml\",\n",
" pipeline_root=PIPELINE_ROOT,\n",
" enable_caching=False,\n",
")\n",
"\n",
"pipeline.run()\n",
"\n",
"! gsutil ls $GCS_CONVERT_OUT\n",
"\n",
"! rm -f dataflow_file_conversion.yaml gaming_schema.avsc"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "delete_pipeline"
},
"source": [
"### Delete a pipeline job\n",
"\n",
"After a pipeline job is completed, you can delete the pipeline job with the method `delete()`. Prior to completion, a pipeline job can be canceled with the method `cancel()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "delete_pipeline"
},
"outputs": [],
"source": [
"pipeline.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cleanup:mbsdk"
},
"source": [
"# Cleaning up\n",
"\n",
"To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial:\n",
"\n",
"- Dataset\n",
"- Cloud Storage Bucket"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cleanup:mbsdk"
},
"outputs": [],
"source": [
"# Warning: Setting this to true will delete everything in your bucket\n",
"delete_bucket = False\n",
"\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil rm -r $BUCKET_URI"
]
}
],
"metadata": {
"colab": {
"name": "get_started_with_dataflow_flex_template_component.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,358 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7d9bbf86da5e"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "4dc4391f6be7"
},
"source": [
"# Vertex AI Model Garden - Hugging Face Local Inference\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_huggingface_local_inference.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_huggingface_local_inference.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_huggingface_local_inference.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 GPU notebook with preinstalled HuggingFace/transformer libraries is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "4e8a0fdd6f44"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates how to run local inference with various Hugging Face models by using [Colab](https://colab.research.google.com/) and installing the necessary libraries or by deploying a [Vertex AI Workbench Instance](https://cloud.google.com/vertex-ai-workbench) with preinstalled transformer and diffuser libraries.\n",
"\n",
"### Objective\n",
"\n",
"* Run local inference with various transformer or diffusion models.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "69453bf7230e"
},
"source": [
"## Before you begin"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "68990d91bc5f"
},
"source": [
"### Colab only"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3d342b32fb08"
},
"outputs": [],
"source": [
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
" ! pip3 install --upgrade pip\n",
" ! pip3 install torchvision==0.14.1\n",
" ! pip3 install transformers==4.27.1\n",
" ! pip3 install diffusers==0.15.1\n",
" ! apt-get update\n",
" ! apt-get install -y --no-install-recommends tesseract-ocr\n",
" ! pip3 install tesseract==0.1.3\n",
" ! pip3 install pytesseract==0.3.10\n",
" ! pip3 install datasets==2.9.0\n",
" ! pip3 install accelerate==0.18.0\n",
" ! pip3 install triton==2.0.0.dev20221120\n",
" ! pip3 install xformers==0.0.16\n",
" ! pip3 install modelscope==1.4.2\n",
" ! pip3 install open_clip_torch==2.17.1\n",
" ! pip3 install pytorch-lightning==1.9.5\n",
" ! pip3 install opencv-python-headless==4.7.0.72\n",
" # Install gdown for downloading example training images.\n",
" ! pip3 install gdown\n",
" # Remove wrong cublas version.\n",
" ! pip3 uninstall nvidia_cublas_cu11 --yes\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "05e23144b125"
},
"source": [
"### Workbench only\n",
"\n",
"1. Follow [this link](https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_huggingfacE_local_inference.ipynb) to deploy the notebook to a Vertex AI Workbench Instance.\n",
"2. Select `Create a new Notebook`.\n",
"3. Click `Advanced Options`.\n",
"4. In the **Environment** tab, select `Debian 10` for **Operating System** and select `Custom Container` for **Environment**.\n",
"5. Set the **Docker container image** field to `us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/transformers-notebook`.\n",
"6. In the **Machine Type** tab, select a 1 `T4` GPU and select `Install NVIDIA GPU driver automatically for me`.\n",
"7. Click `Create` to create the Vertex AI Workbench instance.\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ad1a690839d5"
},
"source": [
"## Sample code"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "0a4008240483"
},
"source": [
"#### [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5) (Text-to-image)\n",
"Generate photo-realistic images given any text input."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5ec6b474d1be"
},
"outputs": [],
"source": [
"import torch\n",
"from diffusers import StableDiffusionPipeline\n",
"\n",
"model_id = \"runwayml/stable-diffusion-v1-5\"\n",
"pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)\n",
"pipe = pipe.to(\"cuda\")\n",
"\n",
"prompt = \"a photo of an astronaut riding a horse on mars\"\n",
"image = pipe(prompt).images[0]\n",
"\n",
"display(image)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ae94b9b23a52"
},
"source": [
"#### [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5) (Text guided image-to-image)\n",
"Generate an image based on an initial image and a text prompt."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0acd70f4d08a"
},
"outputs": [],
"source": [
"from io import BytesIO\n",
"\n",
"import requests\n",
"import torch\n",
"from diffusers import StableDiffusionImg2ImgPipeline\n",
"from PIL import Image\n",
"\n",
"device = \"cuda\"\n",
"model_id_or_path = \"runwayml/stable-diffusion-v1-5\"\n",
"pipe = StableDiffusionImg2ImgPipeline.from_pretrained(\n",
" model_id_or_path, torch_dtype=torch.float16\n",
")\n",
"pipe = pipe.to(device)\n",
"\n",
"url = \"https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg\"\n",
"\n",
"response = requests.get(url)\n",
"init_image = Image.open(BytesIO(response.content)).convert(\"RGB\")\n",
"init_image = init_image.resize((768, 512))\n",
"\n",
"prompt = \"A fantasy landscape, trending on artstation\"\n",
"\n",
"images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images\n",
"display(images[0])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "e76b3fe8d10c"
},
"source": [
"#### [runwayml/stable-diffusion-inpainting](https://huggingface.co/runwayml/stable-diffusion-inpainting) (Image-inpainting)\n",
"Generate an image based on an original image and prompt, only editing the areas denoted by a mask image."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8bc3238be4e7"
},
"outputs": [],
"source": [
"from io import BytesIO\n",
"\n",
"import requests\n",
"import torch\n",
"from diffusers import StableDiffusionInpaintPipeline\n",
"from PIL import Image\n",
"\n",
"image_url = \"https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png\"\n",
"image_response = requests.get(image_url)\n",
"init_image = Image.open(BytesIO(image_response.content)).convert(\"RGB\")\n",
"display(init_image)\n",
"\n",
"mask_url = \"https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png\"\n",
"mask_response = requests.get(mask_url)\n",
"mask_image = Image.open(BytesIO(mask_response.content)).convert(\"RGB\")\n",
"\n",
"pipe = StableDiffusionInpaintPipeline.from_pretrained(\n",
" \"runwayml/stable-diffusion-inpainting\",\n",
" revision=\"fp16\",\n",
" torch_dtype=torch.float16,\n",
")\n",
"pipe.to(\"cuda\")\n",
"\n",
"prompt = \"Face of a yellow cat, high resolution, sitting on a park bench\"\n",
"images = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images\n",
"display(images[0])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "1ade95a9b20e"
},
"source": [
"#### [impira/layoutlm-document-qa](https://huggingface.co/impira/layoutlm-document-qa) (Document question answering)\n",
"Answer questions about a given document."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "492d9f1de3f2"
},
"outputs": [],
"source": [
"from transformers import pipeline\n",
"\n",
"nlp = pipeline(\n",
" \"document-question-answering\",\n",
" model=\"impira/layoutlm-document-qa\",\n",
")\n",
"\n",
"print(\n",
" nlp(\n",
" \"https://templates.invoicehome.com/invoice-template-us-neat-750px.png\",\n",
" \"What is the invoice number?\",\n",
" )\n",
")\n",
"# [{'score': 0.9943977, 'answer': 'us-001', 'start': 15, 'end': 15}]\n",
"\n",
"print(\n",
" nlp(\n",
" \"https://miro.medium.com/max/787/1*iECQRIiOGTmEFLdWkVIH2g.jpeg\",\n",
" \"What is the purchase amount?\",\n",
" )\n",
")\n",
"# [{'score': 0.9912159, 'answer': '$1,000,000,000', 'start': 97, 'end': 97}]\n",
"\n",
"print(\n",
" nlp(\n",
" \"https://www.accountingcoach.com/wp-content/uploads/2013/10/income-statement-example@2x.png\",\n",
" \"What are the 2020 net sales?\",\n",
" )\n",
")\n",
"# [{'score': 0.978011429309845, 'answer': '$ 3,980', 'start': 15, 'end': 16}]"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_huggingface_local_inference.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,874 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ur8xi4C7S06n"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "99c1c3fc2ca5"
},
"source": [
"# Vertex AI Model Garden - JAX Vision Transformer\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_jax_vision_transformer.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
"\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_jax_vision_transformer.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td> <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_jax_vision_transformer.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "24743cf4a1e1"
},
"source": [
"**_NOTE_**: This notebook has been tested in the following environment:\n",
"\n",
"* Python version = 3.9"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates finetuning a [JAX ViT-B16 model](https://github.com/google-research/vision_transformer#available-vit-models) for image classification task on GPU and deploying them on Vertex AI for online prediction."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d975e698c9a4"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to:\n",
"\n",
"- Finetune a JAX Vision Transformer based model.\n",
"- Upload the model to [Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model on [Endpoint](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for image classification.\n",
"\n",
"This tutorial uses the following Google Cloud ML services and resources:\n",
"\n",
"- Vertex AI Training\n",
"- Vertex AI Model Registry\n",
"- Vertex AI Online Prediction"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "08d289fa873f"
},
"source": [
"### Dataset\n",
"\n",
"This notebook uses the [tf_flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) and has a section which shows how to download and prepare it. You can follow similar process to use your own custom dataset too."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aed92deeb4a0"
},
"source": [
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "i7EUnXsZhAGF"
},
"source": [
"## Installation\n",
"\n",
"Install the following packages required to execute this notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2b4ef9b72d43"
},
"outputs": [],
"source": [
"# Install the packages.\n",
"! pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "58707a750154"
},
"source": [
"### Colab only"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f200f10a1da3"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs so that your environment can access the new packages.\n",
"import IPython\n",
"\n",
"app = IPython.Application.instance()\n",
"app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
},
"outputs": [],
"source": [
"PROJECT_ID = \"your-project-id\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "twgKk-LsLmX3"
},
"outputs": [],
"source": [
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sBCra4QMA2wR"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "74ccc9e52986"
},
"source": [
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "de775a3773ba"
},
"source": [
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "254614fa0c46"
},
"outputs": [],
"source": [
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ef21552ccea8"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "603adbbf0532"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f6b2ccc891ed"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zgPO1eR3CYjk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MzGDU7TWdts_"
},
"outputs": [],
"source": [
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-EcIXiGsCePi"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NIq7R4HZCfIc"
},
"outputs": [],
"source": [
"! gsutil mb -l {REGION} -p {PROJECT_ID} {BUCKET_URI}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "960505627ddf"
},
"source": [
"### Import libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PyQmSRbKA8r-"
},
"outputs": [],
"source": [
"import base64\n",
"import glob\n",
"import os\n",
"import random\n",
"import shutil\n",
"from datetime import datetime\n",
"from io import BytesIO\n",
"\n",
"import numpy as np\n",
"from google.cloud import aiplatform\n",
"from google.protobuf import json_format\n",
"from google.protobuf.struct_pb2 import Value\n",
"from PIL import Image"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "init_aip:mbsdk,all"
},
"source": [
"### Initialize Vertex AI SDK for Python\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vS1hQiGuLmX4"
},
"outputs": [],
"source": [
"staging_bucket = os.path.join(BUCKET_URI, \"jax_vit_staging\")\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=staging_bucket)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2cc825514deb"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b42bd4fa2b2d"
},
"outputs": [],
"source": [
"# The pre-built training docker image.\n",
"TRAIN_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/jax-vit-train-gpu\"\n",
"# The pre-built TF SavedModel conversion docker image.\n",
"MODEL_CONVERSION_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/jax-vit-model-conversion\"\n",
"# The pre-built prediction docker image.\n",
"OPTIMIZED_TF_RUNTIME_IMAGE_URI = (\n",
" \"us-docker.pkg.dev/vertex-ai-restricted/prediction/tf_opt-gpu.nightly:latest\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c250872074f"
},
"source": [
"### Define common functions\n",
"\n",
"This section defines functions for:\n",
"\n",
"- Splitting the [tf_flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) images into `train` and `test` folders.\n",
"- Converting a Cloud Storage path such as `gs://bucket-name` to GCSFuse path format such as `/gcsfuse/bucket-name`.\n",
"- Encoding a local image file to a string for prediction input."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XcYUGwr-AJGY"
},
"outputs": [],
"source": [
"def split(base_dir, test_ratio=0.1):\n",
" \"\"\"Splits images and moves them to train and test folders.\"\"\"\n",
" paths = glob.glob(f\"{base_dir}/*/*.jpg\")\n",
" random.shuffle(paths)\n",
" counts = dict(test=0, train=0)\n",
" for i, path in enumerate(paths):\n",
" split = \"test\" if i < test_ratio * len(paths) else \"train\"\n",
" *_, class_name, basename = path.split(\"/\")\n",
" dst = f\"{base_dir}/{split}/{class_name}/{basename}\"\n",
" if not os.path.isdir(os.path.dirname(dst)):\n",
" os.makedirs(os.path.dirname(dst))\n",
" shutil.move(path, dst)\n",
" counts[split] += 1\n",
" print(f'Moved {counts[\"train\"]:,} train and {counts[\"test\"]:,} test images.')\n",
"\n",
"\n",
"def gcs_fuse_path(path: str) -> str:\n",
" \"\"\"Try to convert path to gcsfuse path if it starts with gs:// else do not modify it.\"\"\"\n",
" path = path.strip()\n",
" if path.startswith(\"gs://\"):\n",
" return \"/gcs/\" + path[5:]\n",
" return path\n",
"\n",
"\n",
"def load_bytes_from_local_image(local_image_path, new_width=-1):\n",
" \"\"\"Returns encoded image string for prediction input.\"\"\"\n",
" image = Image.open(local_image_path)\n",
" if new_width <= 0:\n",
" new_image = image\n",
" else:\n",
" width, height = image.size\n",
" print(\"original input image size: \", width, \" , \", height)\n",
" new_height = int(height * new_width / width)\n",
" print(\"new input image size: \", new_width, \" , \", new_height)\n",
" new_image = image.resize((new_width, new_height))\n",
" buffered = BytesIO()\n",
" new_image.save(buffered, format=\"JPEG\")\n",
" encoded_string = base64.b64encode(buffered.getvalue()).decode(\"utf-8\")\n",
" return encoded_string"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "X0wWrfhDC8ni"
},
"source": [
"### Prepare dataset\n",
"\n",
"If you are not using [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview#all_datasets), then you need to prepare your dataset and store it on Cloud Storage. The following example shows\n",
"how to do this for the [tf_flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers). If using TensorFlow Datasets, you can just pass\n",
"the dataset name such as `tf_flowers` to the `--config.dataset` flag and bypass this section."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LW31Ws1RN9AC"
},
"outputs": [],
"source": [
"local_flower_data_directory = \"./flower_photos\" # @param {type:\"string\"}\n",
"FLOWER_DATA_GCS_PATH = os.path.join(BUCKET_URI, \"flower_dataset\")\n",
"# The flower dataset has 5 classes.\n",
"NUM_CLASSES = 5\n",
"# NOTE: For custom dataset, the training code picks the class names\n",
"# from the folder structure and then sorts them to create a mapping\n",
"# from class-index to class-name. This is why the mapping below\n",
"# looks different from default `tf_flowers` documentation.\n",
"LABEL_IDX_TO_STR = {\n",
" 0: \"daisy\",\n",
" 1: \"dandelion\",\n",
" 2: \"roses\",\n",
" 3: \"sunflowers\",\n",
" 4: \"tulips\",\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "heMhYO-DD4II"
},
"outputs": [],
"source": [
"# Download flower data to a local directory.\n",
"! rm -rf $local_flower_data_directory;\n",
"! (cd \"./\" && curl https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz | tar xz)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YtWxe2y8Gqzl"
},
"outputs": [],
"source": [
"# Since the default file format of above \"tf_flowers\" dataset is\n",
"# flower_photos/{class_name}/{filename}.jpg\n",
"# we first need to split it into a \"train\" (90%) and a \"test\" (10%) set:\n",
"# flower_photos/train/{class_name}/{filename}.jpg\n",
"# flower_photos/test/{class_name}/{filename}.jpg\n",
"\n",
"split(local_flower_data_directory)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "g043ydQ_wlpk"
},
"outputs": [],
"source": [
"# Move Flower data from local directory to Cloud Storage.\n",
"# This step takes around 2 mins to finish.\n",
"! gsutil -m cp -R $local_flower_data_directory/train/* $FLOWER_DATA_GCS_PATH/train/\n",
"! gsutil -m cp -R $local_flower_data_directory/test/* $FLOWER_DATA_GCS_PATH/test/"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aCpLmWPMpJQ8"
},
"source": [
"## Finetune with JAX Vision Transformer\n",
"\n",
"Create and run the training job with the model-garden JAX vision transformer training docker using the Vertex AI SDK. The training uses one V100 GPU and runs for around 10 mins once the training job begins."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aec22792ee84"
},
"outputs": [],
"source": [
"# Set up training docker arguments.\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
"JOB_NAME = \"jax_vision_transformer\" + TIMESTAMP\n",
"\n",
"finetuning_workdir = os.path.join(BUCKET_URI, JOB_NAME)\n",
"pre_trained_dir = \"gs://vit_models/imagenet21k\"\n",
"docker_args_list = [\n",
" \"--config\",\n",
" \"vit_jax/configs/vit.py:b16\",\n",
" \"--config.dataset\",\n",
" f\"{gcs_fuse_path(FLOWER_DATA_GCS_PATH)}\",\n",
" \"--config.pp.train\",\n",
" \"train\",\n",
" \"--config.pp.test\",\n",
" \"test\",\n",
" \"--config.pretrained_dir\",\n",
" f\"{gcs_fuse_path(pre_trained_dir)}\",\n",
" \"--config.batch\",\n",
" \"128\",\n",
" \"--config.batch_eval\",\n",
" \"128\",\n",
" \"--config.base_lr\",\n",
" \"0.01\",\n",
" \"--config.shuffle_buffer\",\n",
" \"1000\",\n",
" \"--config.total_steps\",\n",
" \"100\",\n",
" \"--config.warmup_steps\",\n",
" \"10\",\n",
" \"--config.pp.crop\",\n",
" \"224\",\n",
" \"--workdir\",\n",
" f\"{gcs_fuse_path(finetuning_workdir)}\",\n",
"]\n",
"print(docker_args_list)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2ELphfgj1f3Q"
},
"outputs": [],
"source": [
"# Create and run the training job.\n",
"# Click on the generated link in the output under \"View backing custom job:\" to see your run in the Cloud Console.\n",
"NUM_GPU = 1\n",
"container_uri = TRAIN_DOCKER_URI\n",
"job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=JOB_NAME,\n",
" container_uri=container_uri,\n",
")\n",
"model = job.run(\n",
" args=docker_args_list,\n",
" base_output_dir=f\"{finetuning_workdir}\",\n",
" replica_count=1,\n",
" machine_type=\"n1-standard-4\",\n",
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=NUM_GPU,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-2qiROKIONnI"
},
"source": [
"## Convert JAX Vision Transformer model to TF SavedModel\n",
"\n",
"Convert the previously fine-tuned JAX model to a TF SavedModel for online prediction."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6Y7slAFLOwlV"
},
"outputs": [],
"source": [
"# Set up model conversion docker arguments.\n",
"# Note: Many of the arguments below are similar to the training job\n",
"# such as the model name and train and test data related parameters.\n",
"\n",
"jax_checkpoint_dir = finetuning_workdir\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
"JOB_NAME = \"jax_model_conversion\" + TIMESTAMP\n",
"saved_model_dir = os.path.join(BUCKET_URI, \"jax2tf_\" + TIMESTAMP)\n",
"\n",
"docker_args_list = [\n",
" \"--config\",\n",
" \"vit_jax/configs/vit.py:b16\",\n",
" \"--num_classes\",\n",
" f\"{NUM_CLASSES}\",\n",
" \"--saved_model_dir\",\n",
" f\"{saved_model_dir}\",\n",
" \"--jax_checkpoint_dir\",\n",
" f\"{jax_checkpoint_dir}\",\n",
" \"--config.pretrained_dir\",\n",
" f\"{pre_trained_dir}\",\n",
" \"--config.dataset\",\n",
" f\"{gcs_fuse_path(FLOWER_DATA_GCS_PATH)}\",\n",
" \"--config.pp.train\",\n",
" \"train\",\n",
" \"--config.pp.test\",\n",
" \"test\",\n",
" \"--config.pp.crop\",\n",
" \"224\",\n",
"]\n",
"print(docker_args_list)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0Acfh1VWUsTL"
},
"outputs": [],
"source": [
"# Create and run the model conversion job.\n",
"# Click on the generated link in the output under \"View backing custom job:\" to see your run in the Cloud Console.\n",
"container_uri = MODEL_CONVERSION_DOCKER_URI\n",
"job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=JOB_NAME,\n",
" container_uri=container_uri,\n",
")\n",
"model_conversion_workdir = os.path.join(BUCKET_URI, JOB_NAME)\n",
"model = job.run(\n",
" args=docker_args_list,\n",
" base_output_dir=f\"{model_conversion_workdir}\",\n",
" replica_count=1,\n",
" machine_type=\"n1-standard-4\",\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iILhhP3TfO8B"
},
"source": [
"## Run online prediction\n",
"\n",
"Run online prediction with the converted TF SavedModel."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XswgX6JqRwFK"
},
"source": [
"Upload TF SavedModel and deploy it to an endpoint for prediction. This step takes around 15 minutes to finish."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "74yqis5ufO8B"
},
"outputs": [],
"source": [
"jax_vit_model = aiplatform.Model.upload(\n",
" display_name=\"jax_vit\",\n",
" artifact_uri=saved_model_dir,\n",
" serving_container_image_uri=OPTIMIZED_TF_RUNTIME_IMAGE_URI,\n",
" serving_container_args=[],\n",
" location=REGION,\n",
")\n",
"\n",
"jax_vit_endpoint = jax_vit_model.deploy(\n",
" deployed_model_display_name=\"jax_vit_deployed\",\n",
" traffic_split={\"0\": 100},\n",
" machine_type=\"n1-standard-4\",\n",
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=1,\n",
" min_replica_count=1,\n",
" max_replica_count=1,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iiozz1aVR7Pe"
},
"source": [
"Load a local test image file, encode it into a string, send it to the endpoint for prediction, and then generate the final class label from the predicted class probabilities."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qxj4Xv_DhHXj"
},
"outputs": [],
"source": [
"test_directory = os.path.join(local_flower_data_directory, \"test/tulips\")\n",
"local_test_image_path = os.path.join(test_directory, os.listdir(test_directory)[0])\n",
"print(local_test_image_path)\n",
"instances_list = [\n",
" {\n",
" \"bytes_inputs\": {\n",
" \"b64\": load_bytes_from_local_image(local_test_image_path, new_width=240)\n",
" }\n",
" }\n",
"]\n",
"instances = [json_format.ParseDict(s, Value()) for s in instances_list]\n",
"results = jax_vit_endpoint.predict(instances=instances)\n",
"logits = results.predictions[0]\n",
"predicted_label = LABEL_IDX_TO_STR[int(np.argmax(logits))]\n",
"print(\"predicted_label: \", predicted_label)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TpV-iwP9qw9c"
},
"source": [
"## Cleaning up\n",
"\n",
"To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "sx_vKniMq9ZX"
},
"outputs": [],
"source": [
"# Delete endpoint resource.\n",
"jax_vit_endpoint.delete(force=True)\n",
"\n",
"# Delete model resource.\n",
"jax_vit_model.delete()\n",
"\n",
"# Delete Cloud Storage objects that were created.\n",
"delete_bucket = False\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil -m rm -r $BUCKET_URI"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_jax_vision_transformer.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,723 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ur8xi4C7S06n"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TirJ-SGQseby"
},
"source": [
"# Vertex AI Model Garden Keras Stable Diffusion\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_keras_stable_diffusion.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
"\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_keras_stable_diffusion.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td> <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_keras_stable_diffusion.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dwGLvtIeECLK"
},
"source": [
"**_NOTE_**: This notebook has been tested in the following environment:\n",
"\n",
"* Python version = 3.9\n",
"\n",
"You can open this notebook directly in colab, or create [google managed](https://cloud.google.com/vertex-ai/docs/workbench/managed/create-instance) or [user managed](https://cloud.google.com/vertex-ai/docs/workbench/user-managed/create-new) workbench instances."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates how to use [Keras Stable Diffusion](https://keras.io/api/keras_cv/models/stable_diffusion) in Vertex AI Model Garden."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0z9r_mBmDeYh"
},
"source": [
"### Objective\n",
"\n",
"* Run local inferences for pretrained or customized models\n",
"\n",
"* Deploy pretrained or customized models in Google Cloud Vertex AI\n",
"\n",
"* Finetune models in Google Cloud Vertex AI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xxo28lDtDxn-"
},
"source": [
"### Dataset\n",
"\n",
"We use the dataset\n",
"[Pokémon BLIP captions](https://huggingface.co/datasets/lambdalabs/pokemon-blip-captions) to show how to finetune the stable diffusion models.\n",
"However, we'll use a slightly different version which was derived from the original\n",
"dataset to fit better with `tf.data`. Refer to\n",
"[the documentation](https://huggingface.co/datasets/sayakpaul/pokemon-blip-original-version)\n",
"for more details."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "AEnkHABrDijz"
},
"source": [
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "z__i0w0lCAsW"
},
"source": [
"## Installation\n",
"\n",
"Install the following packages required to execute this notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Jvqs-ehKlaYh"
},
"outputs": [],
"source": [
"if \"google.colab\" in str(get_ipython()):\n",
" # Configs for colab notebooks.\n",
" ! pip3 install --upgrade --quiet google-cloud-aiplatform\n",
"\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)\n",
"\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
"# Configs for all notebooks.\n",
"! pip3 install --quiet keras-cv==0.4.1"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KEukV6uRk_S3"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. [Create a service account](https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console) with `Vertex AI User` and `Storage Object Admin` roles for deploying fine tuned model to Vertex AI endpoint.\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set your project, region and buckets\n",
"\n",
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)\n",
"\n",
"You can change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations).\n",
"\n",
"You can create a storage bucket to store intermediate artifacts such as datasets, trained models etc."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YjNCFxq0JxlA"
},
"outputs": [],
"source": [
"# The project and bucket are for experiments below.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
"# The form for BUCKET_URI is gs://<bucket-name>.\n",
"BUCKET_URI = \"\" # @param {type:\"string\"}\n",
"REGION = \"us-central1\" # @param {type: \"string\"}\n",
"\n",
"import os\n",
"\n",
"STAGING_BUCKET = os.path.join(BUCKET_URI, \"temporal\")\n",
"EXPERIMENT_BUCKET = os.path.join(BUCKET_URI, \"keras\")\n",
"DATA_BUCKET = os.path.join(EXPERIMENT_BUCKET, \"data\")\n",
"MODEL_BUCKET = os.path.join(EXPERIMENT_BUCKET, \"model\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uDjp76aaLZY9"
},
"source": [
"### Initialize Vertex AI SDK for Python\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5uv7-iDKLbO0"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=STAGING_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ZZFPe_GezXg8"
},
"source": [
"### Define constants and common functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XcYUGwr-AJGY"
},
"outputs": [],
"source": [
"import base64\n",
"import os\n",
"from datetime import datetime\n",
"from io import BytesIO\n",
"\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image\n",
"\n",
"# Training constants.\n",
"TRAINING_JOB_PREFIX = \"train\"\n",
"TRAIN_CONTAINER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/keras-train:latest\"\n",
"TRAIN_MACHINE_TYPE = \"a2-highgpu-1g\"\n",
"TRAIN_ACCELERATOR_TYPE = \"NVIDIA_TESLA_A100\"\n",
"TRAIN_NUM_GPU = 1\n",
"RESOLUTION = 512\n",
"\n",
"# Prediction constants.\n",
"PREDICTION_CONTAINER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/keras-serve:latest\"\n",
"PREDICTION_ACCELERATOR_TYPE = \"NVIDIA_TESLA_V100\"\n",
"PREDICTION_MACHINE_TYPE = \"n1-standard-8\"\n",
"DEPLOY_JOB_PREFIX = \"deploy\"\n",
"\n",
"\n",
"def get_job_name_with_datetime(prefix: str):\n",
" return prefix + datetime.now().strftime(\"_%Y%m%d_%H%M%S\")\n",
"\n",
"\n",
"def download_data_to_gcs(tar_filepath, gcs_bucket):\n",
" filename_with_ext = os.path.basename(tar_filepath)\n",
" filename_without_ext = filename_with_ext.replace(\".tar.gz\", \"\")\n",
" print(\"Download files from: \", tar_filepath)\n",
" ! wget $tar_filepath -O $filename_with_ext\n",
" ! mkdir -p $filename_without_ext\n",
" ! tar -xvf $filename_with_ext -C .\n",
"\n",
" ! gsutil -m cp -r $filename_without_ext $gcs_bucket/\n",
" gcs_path = os.path.join(gcs_bucket, filename_without_ext)\n",
" print(\"Upload files to: \", gcs_path)\n",
" return gcs_path\n",
"\n",
"\n",
"def deploy_model(model_path, service_account):\n",
"\n",
" deploy_model_name = get_job_name_with_datetime(DEPLOY_JOB_PREFIX)\n",
" print(\"The deployed job name is: \", deploy_model_name)\n",
" serving_env = {\n",
" \"MODEL_PATH\": f\"{model_path}\",\n",
" \"IMAGE_WIDTH\": f\"{RESOLUTION}\",\n",
" \"IMAGE_HEIGHT\": f\"{RESOLUTION}\",\n",
" }\n",
"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{deploy_model_name}-endpoint\")\n",
" model = aiplatform.Model.upload(\n",
" display_name=deploy_model_name,\n",
" serving_container_image_uri=PREDICTION_CONTAINER_URI,\n",
" serving_container_ports=[8501],\n",
" serving_container_predict_route=\"/predict\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=PREDICTION_MACHINE_TYPE,\n",
" accelerator_type=PREDICTION_ACCELERATOR_TYPE,\n",
" accelerator_count=1,\n",
" min_replica_count=1,\n",
" max_replica_count=1,\n",
" deploy_request_timeout=1800,\n",
" service_account=service_account,\n",
" )\n",
" return model, endpoint\n",
"\n",
"\n",
"def base64_to_image(image_str):\n",
" image = Image.open(BytesIO(base64.b64decode(image_str)))\n",
" return image\n",
"\n",
"\n",
"def display_image(image):\n",
" _ = plt.figure(figsize=(20, 15))\n",
" plt.grid(False)\n",
" plt.imshow(image)\n",
"\n",
"\n",
"def display_image_grid(imgs, rows=2, cols=2):\n",
" w, h = imgs[0].size\n",
" grid = Image.new(\"RGB\", size=(cols * w, rows * h))\n",
" for i, img in enumerate(imgs):\n",
" grid.paste(img, box=(i % cols * w, i // cols * h))\n",
" return grid"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "epo-RHXzcBBT"
},
"source": [
"## Run inferences\n",
"\n",
"This section shows how to run inferences with Keras Stable Diffusion models.\n",
"\n",
"1. Run inferences locally\n",
"2. Run inferences with serving dockers\n",
"\n",
"You can run inferences with pre-trained models from Keras team, or your own finetuned models.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6zsa9vnBHhvO"
},
"outputs": [],
"source": [
"# Sets the model_path to empty to load the pre-trained model from Keras team.\n",
"# Sets the model_path to a gcs uri to load the finetuned models.\n",
"model_path = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ld39hkcIceE2"
},
"source": [
"### Run inferences locally\n",
"Local inferences can finish in seconds with GPUs.\n",
"\n",
"Load models first."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "G1nCKVSac3Y5"
},
"outputs": [],
"source": [
"from keras_cv.models import StableDiffusion\n",
"\n",
"model = StableDiffusion(img_height=RESOLUTION, img_width=RESOLUTION, jit_compile=True)\n",
"if model_path:\n",
" model.diffusion_model.load_weights(model_path)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ABaCSIWuP-_G"
},
"source": [
"Then run inferences."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pnyeVsh8RNI5"
},
"outputs": [],
"source": [
"batch_size = 1\n",
"img = model.text_to_image(\n",
" prompt=\"a squirrel in Picasso style\",\n",
" batch_size=batch_size, # How many images to generate at once\n",
" num_steps=25, # Number of iterations (controls image quality)\n",
" seed=123, # A fixed seed guarantees the same prompt always generates the same image\n",
")\n",
"for i in range(batch_size):\n",
" display_image(img[i])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kY87SU9Adq4o"
},
"source": [
"### Serve models with dockers\n",
"When serve models with dockers, we will deploy models in Google Cloud Vertex AI. The default setting will use 1 V100 GPU for deployment.\n",
"\n",
"Please create a Service Account for serving with dockers if you do not have one yet.\n",
"\n",
"The model deployment will take ~10 minutes to finish."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yCB9vu7RenY6"
},
"outputs": [],
"source": [
"# The service account looks like:\n",
"# '<account_name>@<project>.iam.gserviceaccount.com'\n",
"# Please go to https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console\n",
"# and create service account with `Vertex AI User` and `Storage Object Admin` roles.\n",
"SERVICE_ACCOUNT = \"\" # @param {type:\"string\"}\n",
"\n",
"model, endpoint = deploy_model(\n",
" model_path=model_path,\n",
" service_account=SERVICE_ACCOUNT,\n",
")\n",
"\n",
"endpoint_id = endpoint.name\n",
"print(\"endpoint id is: \", endpoint_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "72_BW_BgfvYT"
},
"source": [
"Once deployed, you can send a batch of text prompts to the endpoint to generate images.\n",
"\n",
"Note, the inference time for the first request for a fresh deployment will need more time to process and take ~45 seconds on one V100 GPU. The inferences for further request is ~12 seconds on one V100 GPU per image."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "U_jrNcZ5eVbH"
},
"outputs": [],
"source": [
"# # Loads an existing endpoint as below.\n",
"# endpoint_id = <An Existing Endpoint ID>\n",
"# aip_endpoint_name = (\n",
"# f\"projects/{PROJECT_ID}/locations/{REGION}/endpoints/{endpoint_id}\"\n",
"# )\n",
"# endpoint = aiplatform.Endpoint(aip_endpoint_name)\n",
"\n",
"instances = [\n",
" {\"prompt\": \"a squirrel in Picasso style\"},\n",
" {\"prompt\": \"a dog in Picasso style\"},\n",
" {\"prompt\": \"a cat in Picasso style\"},\n",
" {\"prompt\": \"a deer in Picasso style\"},\n",
"]\n",
"\n",
"parameters = {\n",
" \"batch_size\": 1, # How many images to generate at once\n",
" \"num_steps\": 25, # Number of iterations (controls image quality)\n",
" \"seed\": 123, # A fixed seed guarantees the same prompt always generates the same image\n",
"}\n",
"response = endpoint.predict(instances=instances, parameters=parameters)\n",
"# prediction['predicted_image'] will contains the prediction images in a batch.\n",
"# The batch size in this example is 1, and the visualization only parses the\n",
"# first predicted image.\n",
"images = [\n",
" base64_to_image(prediction[\"predicted_image\"][0])\n",
" for prediction in response.predictions\n",
"]\n",
"display_image_grid(images, rows=2, cols=2)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LiQF7fm6f842"
},
"source": [
"### Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eqJyypt-f9K6"
},
"outputs": [],
"source": [
"# Undeploys models and deletes endpoints.\n",
"endpoint.delete(force=True)\n",
"# Deletes models.\n",
"model.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RB_xY9ipr7ZU"
},
"source": [
"## Finetune models\n",
"This section shows how to finetune Keras Stable diffusion models with trainig dockers.\n",
"\n",
"If you would like to use finetuned models, please go to the section `Run inferences`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OD3TtaWs5b4v"
},
"source": [
"### Download data\n",
" We download the data to GCS storage for the experiments with training dockers."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2TVB8MU-5i-q"
},
"outputs": [],
"source": [
"# Skips this step if you have already downloaded the dataset.\n",
"download_data_to_gcs(\n",
" \"https://huggingface.co/datasets/sayakpaul/pokemon-blip-original-version/resolve/main/pokemon_dataset.tar.gz\",\n",
" DATA_BUCKET,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ee7Hzq8O5jgF"
},
"source": [
"### Start training jobs\n",
"We finetune 512*512 stable diffusion models with 1 epoch and it takes ~15 minutes to finish using 1 A100 GPU with default settings."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"data_csv = os.path.join(DATA_BUCKET, \"pokemon_dataset/data.csv\")\n",
"epochs = 1\n",
"\n",
"train_job_name = get_job_name_with_datetime(TRAINING_JOB_PREFIX)\n",
"model_dir = os.path.join(MODEL_BUCKET, train_job_name)\n",
"worker_pool_specs = [\n",
" {\n",
" \"machine_spec\": {\n",
" \"machine_type\": TRAIN_MACHINE_TYPE,\n",
" \"accelerator_type\": TRAIN_ACCELERATOR_TYPE,\n",
" \"accelerator_count\": TRAIN_NUM_GPU,\n",
" },\n",
" \"replica_count\": 1,\n",
" \"disk_spec\": {\n",
" \"boot_disk_type\": \"pd-ssd\",\n",
" \"boot_disk_size_gb\": 500,\n",
" },\n",
" \"container_spec\": {\n",
" \"image_uri\": TRAIN_CONTAINER_URI,\n",
" \"command\": [],\n",
" \"env\": [\n",
" {\n",
" \"name\": \"RESOLUTION\",\n",
" \"value\": f\"{RESOLUTION}\",\n",
" },\n",
" ],\n",
" \"args\": [\n",
" f\"--epochs={epochs}\",\n",
" f\"--input_csv_path={data_csv}\",\n",
" f\"--output_model_dir={model_dir}\",\n",
" ],\n",
" },\n",
" }\n",
"]\n",
"\n",
"train_job = aiplatform.CustomJob(\n",
" display_name=train_job_name,\n",
" project=PROJECT_ID,\n",
" worker_pool_specs=worker_pool_specs,\n",
" staging_bucket=STAGING_BUCKET,\n",
")\n",
"\n",
"train_job.run()\n",
"\n",
"model_path = os.path.join(model_dir, \"saved_model.h5\")\n",
"print(\"The trained model is saved as: \", model_path)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wBlQ6FQlJhBi"
},
"source": [
"After the training finishes, you can use `model_path` and then go to the `Run inferences` section above to run predictions."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kkH2nrpdp4sp"
},
"source": [
"### Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ax6vQVZhp9pR"
},
"outputs": [],
"source": [
"train_job.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1dijQDiZWegt"
},
"source": [
"## References\n",
"\n",
"- [Fine-tuning Stable Diffusion](https://keras.io/examples/generative/finetune_stable_diffusion/)\n",
"- [StableDiffusion image-generation model](https://keras.io/api/keras_cv/models/stable_diffusion/)\n",
"- [High-performance image generation using Stable Diffusion in KerasCV](https://keras.io/guides/keras_cv/generate_images_with_stable_diffusion/)"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"name": "model_garden_keras_stable_diffusion.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,518 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ur8xi4C7S06n"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TirJ-SGQseby"
},
"source": [
"# Vertex AI Model Garden MediaPipe With Image Classification\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_mediapipe_image_classification.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
"\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_mediapipe_image_classification.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td> <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_mediapipe_image_classification.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dwGLvtIeECLK"
},
"source": [
"**_NOTE_**: This notebook has been tested in the following environment:\n",
"\n",
"* Python version = 3.9"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates how to use [MediaPipe Model Maker](https://developers.google.com/mediapipe/solutions/model_maker) to train an on-device image classification model in Vertex AI Model Garden.\n",
"\n",
"### Objective\n",
"\n",
"* Train new models\n",
" * Convert input data to training formats\n",
" * Create [custom jobs](https://cloud.google.com/vertex-ai/docs/training/create-custom-job) to train new models\n",
" * Export models\n",
"\n",
"* Cleanup resources\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KEukV6uRk_S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "z__i0w0lCAsW"
},
"source": [
"### Colab only\n",
"Run the following commands to install dependencies and to authenticate with Google Cloud if running on Colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Jvqs-ehKlaYh"
},
"outputs": [],
"source": [
"! pip3 install --upgrade pip\n",
"\n",
"import sys\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
"\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)\n",
"\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9wExiMUxFk91"
},
"outputs": [],
"source": [
"import json\n",
"import os\n",
"from datetime import datetime\n",
"\n",
"import tensorflow\n",
"from google.cloud import aiplatform\n",
"\n",
"now = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n",
"\n",
"# The project and bucket are for experiments below.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"# The form for BUCKET_URI is gs://<bucket-name>.\\n\",\n",
"BUCKET_URI = \"gs://\" # @param {type:\"string\"}\n",
"\n",
"# You can choose a region from https://cloud.google.com/about/locations.\n",
"# Only regions prefixed by \"us\", \"asia\", or \"europe\" are supported.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"REGION_PREFIX = REGION.split(\"-\")[0]\n",
"assert REGION_PREFIX in (\n",
" \"us\",\n",
" \"europe\",\n",
" \"asia\",\n",
"), f'{REGION} is not supported. It must be prefixed by \"us\", \"asia\", or \"europe\".'\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
"STAGING_BUCKET = os.path.join(BUCKET_URI, \"temp/%s\" % now)\n",
"\n",
"EVALUATION_RESULT_OUTPUT_DIRECTORY = os.path.join(STAGING_BUCKET, \"evaluation\")\n",
"EVALUATION_RESULT_OUTPUT_FILE = os.path.join(\n",
" EVALUATION_RESULT_OUTPUT_DIRECTORY, \"evaluation.json\"\n",
")\n",
"\n",
"EXPORTED_MODEL_OUTPUT_DIRECTORY = os.path.join(STAGING_BUCKET, \"model\")\n",
"EXPORTED_MODEL_OUTPUT_FILE = os.path.join(\n",
" EXPORTED_MODEL_OUTPUT_DIRECTORY, \"model.tflite\"\n",
")\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=STAGING_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "n6IFz75WGCam"
},
"source": [
"### Define training machine specs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"TRAINING_JOB_DISPLAY_NAME = \"mediapipe_image_classifier_%s\" % now\n",
"TRAINING_CONTAINER = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/mediapipe-train\"\n",
"TRAINING_MACHINE_TYPE = \"n1-highmem-16\"\n",
"TRAINING_ACCELARATOR_TYPE = \"NVIDIA_TESLA_V100\"\n",
"TRAINING_ACCELERATOR_COUNT = 2"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-rsdAcBV-vlf"
},
"source": [
"## Train your customized models"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zgPO1eR3CYjk"
},
"source": [
"### Prepare input data for training\n",
"\n",
"Finetuning a model for image classification requires a dataset that includes all kinds of items, or classes, that you want the completed model to be able to identify. You can do this by trimming down a public dataset to only the classes that are relevant to your usecase, compiling your own data, or some combination of both. The dataset can be significantly smaller than what would be required to train a new model from scratch. For example, the [ImageNet](https://www.image-net.org/) dataset used to train many reference models contains millions of images with thousands of categories. Transfer learning with Model Maker can finetune an existing model with a smaller dataset and still perform well, depending on your inference accuracy goals.\n",
"\n",
"You can re-use an existing dataset such as `gs://cloud-samples-data-us-central1/vision/automl_classification/flowers` to finetune the model or you can upload your own dataset to GCS. If you are using your own dataset, ensure that your image directory contains several subdirectories, each corresponding to specific class labels. Your training data should also follow this pattern: <image_path>/<label_name>/<image_names>.*."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IndQ_m6ddUEM"
},
"outputs": [],
"source": [
"training_data_path = \"gs://cloud-samples-data-us-central1/vision/automl_classification/flowers\" # @param {type:\"string\"}\n",
"split_ratio = \"0.8,0.1,0.1\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aaff6f5be7f6"
},
"source": [
"### Set fine-tuning options\n",
"\n",
"There are a few required settings to run fine-tuning aside from your training dataset: output directory for the model and the model architecture. Use HParams object export_dir parameter to specify a model output directory. Use the SupportedModels class to specify the model architecture. The image classifier solution supports the following model architectures:\n",
"\n",
"* MobileNet-V2\n",
"* EfficientNet-Lite0\n",
"* EfficientNet-Lite2\n",
"* EfficientNet-Lite4\n",
"\n",
"To set the required parameters, use the following code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "um_XKbmpTaHx"
},
"outputs": [],
"source": [
"model_architecture = \"mobilenet_v2\" # @param [\"mobilenet_v2\", \"efficientnet_lite0\", \"efficientnet_lite2\", \"efficientnet_lite4\"]\n",
"\n",
"# The learning rate to use for gradient descent training.\n",
"learning_rate: float = 0.01 # @param {type:\"number\"}\n",
"# Batch size for training.\n",
"batch_size: int = 2 # @param {type:\"number\"}\n",
"# Number of training iterations over the dataset.\n",
"epochs: int = 10 # @param {type:\"slider\", min:0, max:100, step:1}\n",
"# If true, the base module is trained together with the classification layer on\n",
"# top.\n",
"do_fine_tuning: bool = False # @param {type:\"boolean\"}\n",
"# A regularizer that applies a L1 regularization penalty.\n",
"l1_regularizer: float = 0.0 # @param {type:\"number\"}\n",
"# A regularizer that applies a L2 regularization penalty.\n",
"l2_regularizer: float = 0.0001 # @param {type:\"number\"}\n",
"# Amount of label smoothing to apply. See tf.keras.losses for more details.\n",
"label_smoothing: float = 0.1 # @param {type:\"number\"}\n",
"# A boolean controlling whether the training dataset is augmented by randomly\n",
"# distorting input images, including random cropping, flipping, etc. See\n",
"# utils.image_preprocessing documentation for details.\n",
"do_data_augmentation: bool = True # @param {type:\"boolean\"}\n",
"# Number of training samples used to calculate the decay steps\n",
"# and create the training optimizer.\n",
"decay_samples: int = 2560000 # @param {type:\"number\"}\n",
"# Number of warmup steps for a linear increasing warmup schedule on learning\n",
"# rate. Used to set up warmup schedule by model_util.WarmUp.\n",
"warmup_epochs: int = 2 # @param {type:\"number\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HwcCjwlBTQIz"
},
"source": [
"### Run fine-tuning\n",
"With your training dataset and fine-tuning options prepared, you are ready to start the fine-tuning process. This process is resource intensive and can take a few minutes to a few hours depending on your available compute resources. On Vertex AI with GPU processing, the example fine-tuning below takes between 4-6 minutes to train on approximately 3700 images.\n",
"\n",
"To begin the fine-tuning process, use the following code:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aec22792ee84"
},
"outputs": [],
"source": [
"model_export_path = EXPORTED_MODEL_OUTPUT_DIRECTORY\n",
"evaluation_result_path = EVALUATION_RESULT_OUTPUT_DIRECTORY\n",
"\n",
"worker_pool_specs = [\n",
" {\n",
" \"machine_spec\": {\n",
" \"machine_type\": TRAINING_MACHINE_TYPE,\n",
" \"accelerator_type\": TRAINING_ACCELARATOR_TYPE,\n",
" \"accelerator_count\": TRAINING_ACCELERATOR_COUNT,\n",
" },\n",
" \"replica_count\": 1,\n",
" \"container_spec\": {\n",
" \"image_uri\": TRAINING_CONTAINER,\n",
" \"command\": [],\n",
" \"args\": [\n",
" \"--task_name=image_classifier\",\n",
" \"--training_data_path=%s\" % training_data_path,\n",
" \"--model_export_path=%s\" % model_export_path,\n",
" \"--evaluation_result_path=%s\" % evaluation_result_path,\n",
" \"--split_ratio=%s\" % split_ratio,\n",
" \"--model_architecture=%s\" % model_architecture,\n",
" \"--hparams=%s\"\n",
" % json.dumps(\n",
" {\n",
" \"learning_rate\": learning_rate,\n",
" \"batch_size\": batch_size,\n",
" \"epochs\": epochs,\n",
" \"do_fine_tuning\": do_fine_tuning,\n",
" \"l1_regularizer\": l1_regularizer,\n",
" \"l2_regularizer\": l2_regularizer,\n",
" \"label_smoothing\": label_smoothing,\n",
" \"do_data_augmentation\": do_data_augmentation,\n",
" \"decay_samples\": decay_samples,\n",
" \"warmup_epochs\": warmup_epochs,\n",
" }\n",
" ),\n",
" ],\n",
" },\n",
" }\n",
"]\n",
"\n",
"training_job = aiplatform.CustomJob(\n",
" display_name=TRAINING_JOB_DISPLAY_NAME,\n",
" project=PROJECT_ID,\n",
" worker_pool_specs=worker_pool_specs,\n",
" staging_bucket=STAGING_BUCKET,\n",
")\n",
"\n",
"training_job.run()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rXMF2tnV_WS0"
},
"source": [
"## Evaluate and export model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "mV-Djz-frBni"
},
"source": [
"### Evaluate performance\n",
"\n",
"After fine-tuning the model, we evaluate the training result on a test dataset, which is typically a portion of your original dataset not used during training. Accuracy levels between 0.8 and 0.9 are generally considered very good, but your use case requirements may differ. You should also consider how fast the model can produce an inference. Higher accuracy frequently comes at the cost of longer inference times.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "09Rz1AYspK19"
},
"outputs": [],
"source": [
"def get_evaluation_result(evaluation_result_path):\n",
" try:\n",
" with tensorflow.io.gfile.GFile(evaluation_result_path, \"r\") as input_file:\n",
" evalutation_result = json.loads(input_file.read())\n",
" return evalutation_result[\"accuracy\"], evalutation_result[\"loss\"]\n",
" except:\n",
" print(\n",
" \"Evaluation result not found. Your test dataset is likely \"\n",
" + \"empty. You can adjust the size of your test dataset or adjust \"\n",
" + \"how you split your dataset.\"\n",
" )\n",
" return None\n",
"\n",
"\n",
"evaluation_result = get_evaluation_result(EVALUATION_RESULT_OUTPUT_FILE)\n",
"\n",
"if evaluation_result is not None:\n",
" print(\"Accuracy:\", evaluation_result[0])\n",
" print(\"Loss:\", evaluation_result[1])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "g0BGaofgsMsy"
},
"source": [
"### Export model\n",
"After finetuning and evaluating the model, you can save the Tensorflow Lite model, try it out in the [Image Classification](https://mediapipe-studio.webapps.google.com/demo/image_classifier) demo in MediaPipe Studio or integrate it with your on-device application by following the [Image classification task guide](https://developers.google.com/mediapipe/solutions/vision/image_classifier). The exported model contains the generates required model metadata, as well as a classification label file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NYuQowyZEtxK"
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"def copy_model(model_source, model_dest):\n",
" ! gsutil cp {model_source} {model_dest}\n",
"\n",
"copy_model(EXPORTED_MODEL_OUTPUT_FILE, \"image_classification_model.tflite\")\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
" from google.colab import files\n",
"\n",
" files.download(\"image_classification_model.tflite\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kkH2nrpdp4sp"
},
"source": [
"## Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ax6vQVZhp9pR"
},
"outputs": [],
"source": [
"# Delete training data and jobs.\n",
"if training_job.list(filter=f'display_name=\"{TRAINING_JOB_DISPLAY_NAME}\"'):\n",
" training_job.delete()\n",
"\n",
"!gsutil rm -r {STAGING_BUCKET}"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_mediapipe_image_classification.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,597 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ur8xi4C7S06n"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TirJ-SGQseby"
},
"source": [
"# Vertex AI Model Garden MediaPipe With Object Detection\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_mediapipe_object_detection.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
"\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_mediapipe_object_detection.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td> <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_mediapipe_object_detection.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dwGLvtIeECLK"
},
"source": [
"**_NOTE_**: This notebook has been tested in the following environment:\n",
"\n",
"* Python version = 3.9"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates how to use [MediaPipe Model Maker](https://developers.google.com/mediapipe/solutions/model_maker) in Vertex AI Model Garden.\n",
"\n",
"### Objective\n",
"\n",
"* Train new models\n",
" * Convert input data to training formats\n",
" * Create [custom jobs](https://cloud.google.com/vertex-ai/docs/training/create-custom-job) to train new models\n",
" * Export models\n",
"\n",
"* Cleanup resources\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KEukV6uRk_S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "z__i0w0lCAsW"
},
"source": [
"### Colab Only\n",
"Run the following commands to install dependencies and to authenticate with Google Cloud if running on Colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Jvqs-ehKlaYh"
},
"outputs": [],
"source": [
"! pip3 install --upgrade pip\n",
"\n",
"import sys\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
"\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)\n",
"\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9wExiMUxFk91"
},
"outputs": [],
"source": [
"import json\n",
"import os\n",
"from datetime import datetime\n",
"\n",
"import tensorflow\n",
"from google.cloud import aiplatform\n",
"\n",
"now = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n",
"\n",
"# The project and bucket are for experiments below.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"# The form for BUCKET_URI is gs://<bucket-name>.\\n\",\n",
"BUCKET_URI = \"gs://\" # @param {type:\"string\"}\n",
"\n",
"# You can choose a region from https://cloud.google.com/about/locations.\n",
"# Only regions prefixed by \"us\", \"asia\", or \"europe\" are supported.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"REGION_PREFIX = REGION.split(\"-\")[0]\n",
"assert REGION_PREFIX in (\n",
" \"us\",\n",
" \"europe\",\n",
" \"asia\",\n",
"), f'{REGION} is not supported. It must be prefixed by \"us\", \"asia\", or \"europe\".'\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
"STAGING_BUCKET = os.path.join(BUCKET_URI, \"temp/%s\" % now)\n",
"\n",
"EVALUATION_RESULT_OUTPUT_DIRECTORY = os.path.join(STAGING_BUCKET, \"evaluation\")\n",
"EVALUATION_RESULT_OUTPUT_FILE = os.path.join(\n",
" EVALUATION_RESULT_OUTPUT_DIRECTORY, \"evaluation.json\"\n",
")\n",
"\n",
"EXPORTED_MODEL_OUTPUT_DIRECTORY = os.path.join(STAGING_BUCKET, \"model\")\n",
"EXPORTED_MODEL_OUTPUT_FILE = os.path.join(\n",
" EXPORTED_MODEL_OUTPUT_DIRECTORY, \"model.tflite\"\n",
")\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=STAGING_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "n6IFz75WGCam"
},
"source": [
"### Define training machine specs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"TRAINING_JOB_DISPLAY_NAME = \"mediapipe_object_detector_%s\" % now\n",
"TRAINING_CONTAINER = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/mediapipe-train\"\n",
"TRAINING_MACHINE_TYPE = \"n1-highmem-16\"\n",
"TRAINING_ACCELARATOR_TYPE = \"NVIDIA_TESLA_V100\"\n",
"TRAINING_ACCELERATOR_COUNT = 2"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XDq9TiRUc7dV"
},
"source": [
"## Train your customized models"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zgPO1eR3CYjk"
},
"source": [
"### Prepare input data for training\n",
"\n",
"Fine-tuning a model for object detection requires a dataset that includes the items, or classes, that you want the completed model to be able to identify. You can do this by trimming down a public dataset to only the classes that are relevant to your usecase, compiling your own dataset, or some combination of both, The dataset can be significantly smaller than what would be required to train a new model from scratch. For example, the [COCO](https://cocodataset.org/) dataset used to train many reference models contains hundreds of thousands of images with 91 classes of objects. Transfer learning with Model Maker can finetune an existing model with a smaller dataset and still perform well, depending on your inference accuracy goals. These instructions use a smaller dataset containing 2 types of android figurines, or 2 classes, with 62 total training images.\n",
"\n",
"You can re-use an existing dataset such as `gs://mediapipe-tasks/object_detector/android_figurine` to finetune the model. The directory contains two subdirectories for the training and validation datasets, located in android_figurine/train and android_figurine/validation respectively. Each of the train and validation datasets follow the COCO Dataset format described below. If you are using your own dataset, ensure that that it adheres to the format specifications before uploading it to Google Cloud Storage.\n",
"\n",
"\n",
"### Supported dataset formats\n",
"Model Maker Object Detection API supports reading the following dataset formats:\n",
"\n",
"#### COCO format\n",
"The COCO dataset format has a `data` directory which stores all of the images and a single `labels.json` file which contains the object annotations for all images.\n",
"```\n",
"<dataset_dir>/\n",
" data/\n",
" <img0>.<jpg/jpeg>\n",
" <img1>.<jpg/jpeg>\n",
" ...\n",
" labels.json\n",
"```\n",
"where `labels.json` is formatted as:\n",
"```\n",
"{\n",
" \"categories\":[\n",
" {\"id\":1, \"name\":<cat1_name>},\n",
" ...\n",
" ],\n",
" \"images\":[\n",
" {\"id\":0, \"file_name\":\"<img0>.<jpg/jpeg>\"},\n",
" ...\n",
" ],\n",
" \"annotations\":[\n",
" {\"id\":0, \"image_id\":0, \"category_id\":1, \"bbox\":[x-top left, y-top left, width, height]},\n",
" ...\n",
" ]\n",
"}\n",
"```\n",
"\n",
"#### PASCAL VOC format\n",
"\n",
"The PASCAL VOC dataset format also has a `data` directory which stores all of the images, however the annotations are split up per image into corresponding xml files in the `Annotations` directory.\n",
"```\n",
"<dataset_dir>/\n",
" data/\n",
" <file0>.<jpg/jpeg>\n",
" ...\n",
" Annotations/\n",
" <file0>.xml\n",
" ...\n",
"```\n",
"where the xml files are formatted as:\n",
"```\n",
"<annotation>\n",
" <filename>file0.jpg</filename>\n",
" <object>\n",
" <name>kangaroo</name>\n",
" <bndbox>\n",
" <xmin>233</xmin>\n",
" <ymin>89</ymin>\n",
" <xmax>386</xmax>\n",
" <ymax>262</ymax>\n",
" </bndbox>\n",
" </object>\n",
" <object>\n",
" ...\n",
" </object>\n",
" ...\n",
"</annotation>\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "O32DU5RRGhdV"
},
"source": [
"### Configure training dataset\n",
"\n",
"Once you have completed preparing your data, you can begin fine-tuning a model to recognize the new objects, or classes, defined by your training data. The instructions below use the data prepared in the previous section to finetune an object detection model to recognize the two types of android figurines.\n",
"\n",
"You can leave the path to the test data empty if you do not have a separate test data set."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IndQ_m6ddUEM"
},
"outputs": [],
"source": [
"training_data_path = \"gs://mediapipe-tasks/object_detector/android_figurine/train\" # @param {type:\"string\"}\n",
"validation_data_path = \"gs://mediapipe-tasks/object_detector/android_figurine/validation\" # @param {type:\"string\"}\n",
"test_data_path = \"\" # @param {type:\"string\"}\n",
"data_format = \"coco\" # @param [\"coco\", \"pascal_voc\"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aaff6f5be7f6"
},
"source": [
"### Set fine-tuning options\n",
"\n",
"There are a few required settings to run fine-tuning aside from your training dataset: output directory for the model, and the model architecture. Use HParams to specify the export_dir parameter for the output directory. Use the SupportedModels class to specify the model architecture. The object detector solution supports the following model architectures:\n",
"\n",
"* MobileNet-V2\n",
"* MobileNet-MultiHW-AVG\n",
"\n",
"To set the parameters, use the following code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "um_XKbmpTaHx"
},
"outputs": [],
"source": [
"model_architecture = \"mobilenet_v2\" # @param [\"mobilenet_v2\", \"mobilenet_multihw_avg\"]\n",
"\n",
"# The learning rate to use for gradient descent training.\n",
"learning_rate: float = 0.01 # @param {type:\"number\"}\n",
"# Batch size for training.\n",
"batch_size: int = 2 # @param {type:\"number\"}\n",
"# Number of training iterations over the dataset.\n",
"epochs: int = 10 # @param {type:\"slider\", min:0, max:100, step:1}\n",
"# If true, the base module is trained together with the classification layer on\n",
"# top.\n",
"do_fine_tuning: bool = False # @param {type:\"boolean\"}\n",
"# A regularizer that applies a L1 regularization penalty.\n",
"l1_regularizer: float = 0.0 # @param {type:\"number\"}\n",
"# A regularizer that applies a L2 regularization penalty.\n",
"l2_regularizer: float = 0.0001 # @param {type:\"number\"}\n",
"# A boolean controlling whether the training dataset is augmented by randomly\n",
"# distorting input images, including random cropping, flipping, etc. See\n",
"# utils.image_preprocessing documentation for details.\n",
"do_data_augmentation: bool = True # @param {type:\"boolean\"}\n",
"# Number of training samples used to calculate the decay steps\n",
"# and create the training optimizer.\n",
"decay_samples: int = 2560000 # @param {type:\"number\"}\n",
"# Number of warmup steps for a linear increasing warmup schedule on learning\n",
"# rate. Used to set up warmup schedule by model_util.WarmUp.\n",
"warmup_epochs: int = 2 # @param {type:\"number\"}\n",
"# The number of epochs for cosine decay learning rate.\n",
"cosine_decay_epochs: int = 5 # @param {type:\"number\"}\n",
"# The alpha value for cosine decay learning rate.\n",
"cosine_decay_alpha: float = 5 # @param {type:\"number\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HwcCjwlBTQIz"
},
"source": [
"### Run fine-tuning\n",
"With your training dataset and fine-tuning options prepared, you are ready to start the fine-tuning process. This process is resource intensive and can take a few minutes to a few hours depending on your available compute resources. This process is resource intensive and can take a few minutes to a few hours depending on your available compute resources. On Vertex AI with GPU processing, the example fine-tuning below takes about 3 to 4 minutes.\n",
"\n",
"To begin the fine-tuning process, use the following code:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aec22792ee84"
},
"outputs": [],
"source": [
"model_export_path = EXPORTED_MODEL_OUTPUT_DIRECTORY\n",
"evaluation_result_path = EVALUATION_RESULT_OUTPUT_DIRECTORY\n",
"\n",
"worker_pool_specs = [\n",
" {\n",
" \"machine_spec\": {\n",
" \"machine_type\": TRAINING_MACHINE_TYPE,\n",
" \"accelerator_type\": TRAINING_ACCELARATOR_TYPE,\n",
" \"accelerator_count\": TRAINING_ACCELERATOR_COUNT,\n",
" },\n",
" \"replica_count\": 1,\n",
" \"container_spec\": {\n",
" \"image_uri\": TRAINING_CONTAINER,\n",
" \"command\": [],\n",
" \"args\": [\n",
" \"--task_name=object_detector\",\n",
" \"--training_data_path=%s\" % training_data_path,\n",
" \"--validation_data_path=%s\" % validation_data_path,\n",
" \"--test_data_path=%s\" % test_data_path,\n",
" \"--data_format=%s\" % data_format,\n",
" \"--model_export_path=%s\" % model_export_path,\n",
" \"--evaluation_result_path=%s\" % evaluation_result_path,\n",
" \"--model_architecture=%s\" % model_architecture,\n",
" \"--hparams=%s\"\n",
" % json.dumps(\n",
" {\n",
" \"learning_rate\": learning_rate,\n",
" \"batch_size\": batch_size,\n",
" \"epochs\": epochs,\n",
" \"do_fine_tuning\": do_fine_tuning,\n",
" \"l1_regularizer\": l1_regularizer,\n",
" \"l2_regularizer\": l2_regularizer,\n",
" \"do_data_augmentation\": do_data_augmentation,\n",
" \"decay_samples\": decay_samples,\n",
" \"warmup_epochs\": warmup_epochs,\n",
" \"cosine_decay_epochs\": cosine_decay_epochs,\n",
" \"cosine_decay_alpha\": cosine_decay_alpha,\n",
" }\n",
" ),\n",
" ],\n",
" },\n",
" }\n",
"]\n",
"\n",
"training_job = aiplatform.CustomJob(\n",
" display_name=TRAINING_JOB_DISPLAY_NAME,\n",
" project=PROJECT_ID,\n",
" worker_pool_specs=worker_pool_specs,\n",
" staging_bucket=STAGING_BUCKET,\n",
")\n",
"\n",
"training_job.run()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zcKzIa5QeIIU"
},
"source": [
"## Evaluate and export model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "mV-Djz-frBni"
},
"source": [
"### Evaluate performance\n",
"\n",
"If you have specified test data, you can evaluate it on the test dataset and print the loss and coco metrics. The most important metric for evaluating the model performance is typically the \"AP\" coco metric for Average Precision.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "09Rz1AYspK19"
},
"outputs": [],
"source": [
"def get_evaluation_result(evaluation_result_path):\n",
" try:\n",
" with tensorflow.io.gfile.GFile(evaluation_result_path, \"r\") as input_file:\n",
" evalutation_result = json.loads(input_file.read())\n",
" return evalutation_result[\"loss\"], evalutation_result[\"coco_metrics\"]\n",
" except:\n",
" print(\"Evaluation result not found. Did you provide a test dataset?\")\n",
" return None\n",
"\n",
"\n",
"evaluation_result = get_evaluation_result(EVALUATION_RESULT_OUTPUT_FILE)\n",
"\n",
"if evaluation_result is not None:\n",
" print(f\"Validation loss: {evaluation_result[0]}\")\n",
" print(f\"Validation coco metrics: {evaluation_result[1]}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "g0BGaofgsMsy"
},
"source": [
"### Export model\n",
"After fine-tuning and evaluating the model, you can save it as Tensorflow Lite model, try it out in the [Object Detector](https://mediapipe-studio.webapps.google.com/demo/object_detector) demo in MediaPipe Studio or integrate it with your application by following the [Object detection task guide](https://developers.google.com/mediapipe/solutions/vision/object_detector). The exported model also includes metadata and the label map."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NYuQowyZEtxK"
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"\n",
"def copy_model(model_source, model_dest):\n",
" ! gsutil cp {model_source} {model_dest}\n",
"\n",
"copy_model(EXPORTED_MODEL_OUTPUT_FILE, \"object_detection_model.tflite\")\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
" from google.colab import files\n",
"\n",
" files.download(\"object_detection_model.tflite\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kkH2nrpdp4sp"
},
"source": [
"## Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ax6vQVZhp9pR"
},
"outputs": [],
"source": [
"# Delete training data and jobs.\n",
"if training_job.list(filter=f'display_name=\"{TRAINING_JOB_DISPLAY_NAME}\"'):\n",
" training_job.delete()\n",
"\n",
"!gsutil rm -r {STAGING_BUCKET}"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_mediapipe_object_detection.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,852 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "copyright"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "title:generic,gcp"
},
"source": [
"# Get started with Model Garden Pipeline Templates for BERT models\n",
"\n",
"\n",
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_template_pipelines_bert.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_template_pipelines_bert.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/communitymodel_garden/model_garden_template_pipelines_bert.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td> \n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "overview:mlops"
},
"source": [
"## Overview\n",
"\n",
"\n",
"This tutorial demonstrates how to modify, compile and execute a prebuilt Vertex AI Model Garden pipeline template with Vertex AI Pipelines.\n",
"\n",
"Learn more about [Create a pipeline template](https://cloud.google.com/vertex-ai/docs/pipelines/create-pipeline-template)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "objective:mlops,stage4,get_started_vertex_model_evaluation"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to use a prebuilt pipeline template with `Vertex AI Pipelines` to fine-tune a BERT text classification model, where the model is accessed from `Vertex AI Model Garden`.\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
"- `Vertex AI Pipelines`\n",
"- `Vertex AI Training`\n",
"- `Vertex AI Model Garden`\n",
"- `Google Cloud Pipeline Components`\n",
"\n",
"\n",
"The steps performed include:\n",
"\n",
"- Create a user-defined repository in the `Artifact Registry`.\n",
"- Upload the prebuilt pipeline template to the `Artifact Registry`.\n",
"- Create a pipeline job with the prebuilt pipeline template to fine-tune a BERT model.\n",
"- Execute the pipeline using `Vertex AI Pipelines`.\n",
" - Load BERT model from Vertex AI Model Garden\n",
" - Fine-tune train the model\n",
" - Do batch prediction\n",
" - Evaluate the model from the batch prediction results\n",
"- Obtain the Vertex AI Model resource from the pipeline artifacts.\n",
"- Deploy the model to a Vertex AI Endpoint\n",
"- Make a prediction"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:bank,lbn"
},
"source": [
"### Model\n",
"\n",
"This tutorial uses a pre-trained BERT text classification model from `Vertex AI Model Garden`, which is then fine-tuned (transfer learning) on a dataset of text phrases which are classified as either FirstClass or SecondClass.\n",
"\n",
"Learn more about [BERT pretrained encoder model]( https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3). "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "costs"
},
"source": [
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"* Dataflow\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and [Dataflow pricing](https://cloud.google.com/dataflow/pricing)\n",
"and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "install_mlops"
},
"source": [
"## Installations\n",
"\n",
"Install the packages required for executing this notebook.\n",
"\n",
"*Note:* This tutorial requires KFP 2.x."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_mlops"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform \\\n",
" google-cloud-pipeline-components \\\n",
" kfp==2.0.0b15"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "restart"
},
"source": [
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin"
},
"source": [
"## Before you begin\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin:nogpu"
},
"source": [
"### Set your project ID\n",
"\n",
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c4ccf556d4ea"
},
"source": [
"### Enable APIs\n",
"\n",
"You can enable the required APIs using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "619529337e6d"
},
"outputs": [],
"source": [
"! gcloud services enable compute.googleapis.com \\\n",
" containerregistry.googleapis.com \\\n",
" aiplatform.googleapis.com \\\n",
" artifactregistry.googleapis.com"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FvQeFm3Gv5mR"
},
"source": [
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"IS_COLAB = False\n",
"# from google.colab import auth\n",
"# auth.authenticate_user()\n",
"# IS_COLAB=True"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "set_service_account"
},
"source": [
"#### Service Account\n",
"\n",
"**If you don't know your service account**, try to get your service account using `gcloud` command by executing the second cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_service_account"
},
"outputs": [],
"source": [
"SERVICE_ACCOUNT = \"[your-service-account]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_service_account"
},
"outputs": [],
"source": [
"if (\n",
" SERVICE_ACCOUNT == \"\"\n",
" or SERVICE_ACCOUNT is None\n",
" or SERVICE_ACCOUNT == \"[your-service-account]\"\n",
"):\n",
" # Get your service account from gcloud\n",
" if not IS_COLAB:\n",
" shell_output = !gcloud auth list 2>/dev/null\n",
" SERVICE_ACCOUNT = shell_output[2].replace(\"*\", \"\").strip()\n",
"\n",
" if IS_COLAB:\n",
" shell_output = ! gcloud projects describe $PROJECT_ID\n",
" project_number = shell_output[-1].split(\":\")[1].strip().replace(\"'\", \"\")\n",
" SERVICE_ACCOUNT = f\"{project_number}-compute@developer.gserviceaccount.com\"\n",
"\n",
" print(\"Service Account:\", SERVICE_ACCOUNT)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "set_service_account:pipelines"
},
"source": [
"#### Set service account access for Vertex AI Pipelines\n",
"\n",
"Run the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_service_account:pipelines"
},
"outputs": [],
"source": [
"! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator \n",
"! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_vars"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries and define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "import_kfp"
},
"outputs": [],
"source": [
"import json\n",
"\n",
"import google.cloud.aiplatform as aiplatform\n",
"from kfp.registry import RegistryClient"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "init_aip:mbsdk,all"
},
"source": [
"### Initialize Vertex AI SDK for Python\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project and corresponding bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "init_aip:mbsdk,all"
},
"outputs": [],
"source": [
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9b773e8d2bd2"
},
"source": [
"## Create repo in Artifact Registry\n",
"\n",
"First, you create your own (user-defined) repository in the `Artifact Registry`. You use this repository to upload and retrieve your pipeline templates.\n",
"\n",
"The name of your repo is `quickstart-kfp-repo`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "520de849cee2"
},
"outputs": [],
"source": [
"REPO_NAME = \"quickstart-kfp-repo\"\n",
"\n",
"! gcloud artifacts repositories create {REPO_NAME} --location={REGION} --repository-format=KFP"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1611d3517c0f"
},
"source": [
"### Upload the pipeline template\n",
"\n",
"Next, you instantiate a client interface to the Artifact Registry. Then with the `upload_pipeline()` method you upload your pipeline template."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "72db37f6d67c"
},
"outputs": [],
"source": [
"BERT_YAML = \"gs://cloud-samples-data/vertex-ai/dataset-management/datasets/bert_finetuning/pipeline.yaml\"\n",
"\n",
"! gsutil cp {BERT_YAML} pipeline.yaml\n",
"\n",
"client = RegistryClient(\n",
" host=f\"https://{REGION}-kfp.pkg.dev/{PROJECT_ID}/quickstart-kfp-repo\"\n",
")\n",
"\n",
"templateName, versionName = client.upload_pipeline(\n",
" file_name=\"pipeline.yaml\",\n",
" tags=[\"v1\", \"latest\"],\n",
" extra_headers={\n",
" \"description\": \"This is a pipeline template for fine-tuning a BERT model.\"\n",
" },\n",
")\n",
"\n",
"! rm pipeline.yaml"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "02f82754fc0d"
},
"source": [
"### View your artifacts in your registry\n",
"\n",
"Next, using the `gcloud artifacts files` command you view the artifacts, inclusive of the pipeline template, in your artifacts repository."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b2f641eb2056"
},
"outputs": [],
"source": [
"! gcloud artifacts files list --repository={REPO_NAME} --location={REGION}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9d5296831cfb"
},
"source": [
"## Load and execute the pipeline job\n",
"\n",
"Next, you create a Vertex AI Pipeline job from your BERT pipeline template by instantiating a PipelineJob(), with the following parameters:\n",
"\n",
"- `display_name`: The human readable name for the pipeline job.\n",
"- `template_path`: The path to the pipeline template in the Artifact Registry.\n",
"- `enable_caching`: On re-runs, use the results from previous successful and unchanged steps.\n",
"- `pipeline_root`: A Cloud storage location for storing pipeline results.\n",
"- `parameter_values`: The parameters and values that are input to the template pipeline. In this example, they are:\n",
" - `project`: Your project ID.\n",
" - `class_labels`: A list of valid class labels, in cardinal order.\n",
" - `root_dir`: A Cloud Storage scratch area.\n",
" - `training_data_path`: A Cloud Storage location to the training data.\n",
" - `ground_truth_gcs_source_uris`: A Cloud Storage location to evaluation data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a3c502fc7e41"
},
"outputs": [],
"source": [
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/bert-finetuning\"\n",
"\n",
"job = aiplatform.PipelineJob(\n",
" display_name=\"bert-finetuning\",\n",
" template_path=f\"https://{REGION}-kfp.pkg.dev/{PROJECT_ID}/quickstart-kfp-repo/{templateName}/{versionName}\",\n",
" pipeline_root=PIPELINE_ROOT,\n",
" enable_caching=False,\n",
" parameter_values={\n",
" \"project\": PROJECT_ID,\n",
" \"class_labels\": [\"FirstClass\", \"SecondClass\", \"[UNK]\"],\n",
" \"root_dir\": BUCKET_URI,\n",
" \"ground_truth_gcs_source_uris\": [\n",
" \"gs://cloud-samples-data/vertex-ai/dataset-management/datasets/bert_finetuning/wide_and_deep_trainer_container_tests_input.jsonl\"\n",
" ],\n",
" \"training_data_path\": \"gs://cloud-samples-data/vertex-ai/dataset-management/datasets/bert_finetuning/wide_and_deep_trainer_container_tests_input.jsonl\",\n",
" },\n",
")\n",
"\n",
"job.run()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "view_pipleline_results:bqml"
},
"source": [
"### View the pipeline results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "view_pipleline_results:bqml"
},
"outputs": [],
"source": [
"PROJECT_NUMBER = job.gca_resource.name.split(\"/\")[1]\n",
"print(PROJECT_NUMBER)\n",
"\n",
"\n",
"def print_pipeline_output(job, output_task_name):\n",
" JOB_ID = job.name\n",
" print(JOB_ID)\n",
" artifact = \"\"\n",
" for _ in range(len(job.gca_resource.job_detail.task_details)):\n",
" TASK_ID = job.gca_resource.job_detail.task_details[_].task_id\n",
" EXECUTE_OUTPUT = (\n",
" PIPELINE_ROOT\n",
" + \"/\"\n",
" + PROJECT_NUMBER\n",
" + \"/\"\n",
" + JOB_ID\n",
" + \"/\"\n",
" + output_task_name\n",
" + \"_\"\n",
" + str(TASK_ID)\n",
" + \"/executor_output.json\"\n",
" )\n",
" GCP_RESOURCES = (\n",
" PIPELINE_ROOT\n",
" + \"/\"\n",
" + PROJECT_NUMBER\n",
" + \"/\"\n",
" + JOB_ID\n",
" + \"/\"\n",
" + output_task_name\n",
" + \"_\"\n",
" + str(TASK_ID)\n",
" + \"/gcp_resources\"\n",
" )\n",
" EVALUATION_METRICS = (\n",
" PIPELINE_ROOT\n",
" + \"/\"\n",
" + PROJECT_NUMBER\n",
" + \"/\"\n",
" + JOB_ID\n",
" + \"/\"\n",
" + output_task_name\n",
" + \"_\"\n",
" + str(TASK_ID)\n",
" + \"/evaluation_metrics\"\n",
" )\n",
" # Check if file exists, 0 is success\n",
" !gsutil -q stat $EXECUTE_OUTPUT\n",
" if _exit_code == 0:\n",
" ! gsutil cat $EXECUTE_OUTPUT\n",
" artifact = EXECUTE_OUTPUT\n",
" break\n",
" !gsutil -q stat $GCP_RESOURCES\n",
" if _exit_code == 0:\n",
" ! gsutil cat $GCP_RESOURCES\n",
" artifact = GCP_RESOURCES\n",
" break\n",
" !gsutil -q stat $EVALUATION_METRICS\n",
" if _exit_code == 0:\n",
" ! gsutil cat $EVALUATION_METRICS\n",
" artifact = EVALUATION_METRICS\n",
" break\n",
"\n",
" return artifact\n",
"\n",
"\n",
"print(\"get-vertex-model\")\n",
"artifacts = print_pipeline_output(job, \"get-vertex-model\")\n",
"output = !gsutil cat $artifacts\n",
"print(output)\n",
"output = json.loads(output[0])\n",
"model_id = output[\"artifacts\"][\"model\"][\"artifacts\"][0][\"metadata\"][\"resourceName\"]\n",
"print(\"\\n\\n\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f431a9e6f025"
},
"source": [
"### Delete the pipeline job\n",
"\n",
"The method 'delete()' will delete the pipeline job."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "00bf554abbc6"
},
"outputs": [],
"source": [
"job.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3d183db57ae2"
},
"source": [
"### Deploy the model\n",
"\n",
"Next, you deploy the model to an endpoint:\n",
"\n",
"- Use the `model_id` obtained from the pipeline artifacts to instaniate a Vertex AI Model resource instance.\n",
"- Deploy the Vertex AI Model resource to a Vertex AI Endpoint resource.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "591ccc049ce5"
},
"outputs": [],
"source": [
"model = aiplatform.Model(model_id)\n",
"endpoint = model.deploy(\n",
" accelerator_count=1,\n",
" accelerator_type=aiplatform.gapic.AcceleratorType.NVIDIA_TESLA_T4.name,\n",
" machine_type=\"n1-standard-4\",\n",
")\n",
"print(endpoint)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "edb781a92864"
},
"source": [
"### Make a prediction\n",
"\n",
"Finally, you make a prediction with the deployed model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "72d94012a987"
},
"outputs": [],
"source": [
"endpoint.predict([\"this is a test\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cleanup:mbsdk"
},
"source": [
"# Cleaning up\n",
"\n",
"To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cleanup:mbsdk"
},
"outputs": [],
"source": [
"delete_bucket = False\n",
"\n",
"endpoint.undeploy_all()\n",
"endpoint.delete()\n",
"model.delete()\n",
"\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil rm -r $BUCKET_URI\n",
"\n",
"! rm -rf custom custom.tar.gz"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_pipeline_templates_bert.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,850 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "copyright"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "title:generic,gcp"
},
"source": [
"# Get started with Model Garden Pipeline Templates for T5X models\n",
"\n",
"\n",
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_template_pipelines_t5x.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_template_pipelines_t5x.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/communitymodel_garden/model_garden_template_pipelines_t5x.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td> \n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "overview:mlops"
},
"source": [
"## Overview\n",
"\n",
"\n",
"This tutorial demonstrates how to modify, compile and execute a prebuilt Vertex AI Model Garden pipeline template with Vertex AI Pipelines.\n",
"\n",
"Learn more about [Create a pipeline template](https://cloud.google.com/vertex-ai/docs/pipelines/create-pipeline-template)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "objective:mlops,stage4,get_started_vertex_model_evaluation"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to use a prebuilt pipeline template with `Vertex AI Pipelines` to fine-tune a T5X text classification model, where the model is accessed from `Vertex AI Model Garden`.\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
"- `Vertex AI Pipelines`\n",
"- `Vertex AI Training`\n",
"- `Vertex AI Model Garden`\n",
"- `Google Cloud Pipeline Components`\n",
"\n",
"\n",
"The steps performed include:\n",
"\n",
"- Create a user-defined repository in the `Artifact Registry`.\n",
"- Upload the prebuilt pipeline template to the `Artifact Registry`.\n",
"- Create a pipeline job with the prebuilt pipeline template to fine-tune a T5X model.\n",
"- Execute the pipeline using `Vertex AI Pipelines`.\n",
" - Load T5X model from Vertex AI Model Garden\n",
" - Fine-tune train the model\n",
"- Obtain the Vertex AI Model resource from the pipeline artifacts.\n",
"- Deploy the model to a Vertex AI Endpoint\n",
"- Make a prediction"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:bank,lbn"
},
"source": [
"### Model\n",
"\n",
"This tutorial uses a pre-trained T5 text classification model from `Vertex AI Model Garden`, which is then fine-tuned (transfer learning) on a dataset of text phrases which are classified as either FirstClass or SecondClass.\n",
"\n",
"Learn more about [Text-to-text transfer transformer](https://github.com/google-research/text-to-text-transfer-transformer). "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "costs"
},
"source": [
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"* Dataflow\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and [Dataflow pricing](https://cloud.google.com/dataflow/pricing)\n",
"and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "install_mlops"
},
"source": [
"## Installations\n",
"\n",
"Install the packages required for executing this notebook.\n",
"\n",
"*Note:* This tutorial requires KFP 2.x."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_mlops"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform \\\n",
" google-cloud-pipeline-components \\\n",
" kfp==2.0.0b15"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "restart"
},
"source": [
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin"
},
"source": [
"## Before you begin\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin:nogpu"
},
"source": [
"### Set your project ID\n",
"\n",
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c4ccf556d4ea"
},
"source": [
"### Enable APIs\n",
"\n",
"You can enable the required APIs using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "619529337e6d"
},
"outputs": [],
"source": [
"! gcloud services enable compute.googleapis.com \\\n",
" containerregistry.googleapis.com \\\n",
" aiplatform.googleapis.com \\\n",
" artifactregistry.googleapis.com"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FvQeFm3Gv5mR"
},
"source": [
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"IS_COLAB = False\n",
"# from google.colab import auth\n",
"# auth.authenticate_user()\n",
"# IS_COLAB=True"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "set_service_account"
},
"source": [
"#### Service Account\n",
"\n",
"**If you don't know your service account**, try to get your service account using `gcloud` command by executing the second cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_service_account"
},
"outputs": [],
"source": [
"SERVICE_ACCOUNT = \"[your-service-account]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_service_account"
},
"outputs": [],
"source": [
"if (\n",
" SERVICE_ACCOUNT == \"\"\n",
" or SERVICE_ACCOUNT is None\n",
" or SERVICE_ACCOUNT == \"[your-service-account]\"\n",
"):\n",
" # Get your service account from gcloud\n",
" if not IS_COLAB:\n",
" shell_output = !gcloud auth list 2>/dev/null\n",
" SERVICE_ACCOUNT = shell_output[2].replace(\"*\", \"\").strip()\n",
"\n",
" if IS_COLAB:\n",
" shell_output = ! gcloud projects describe $PROJECT_ID\n",
" project_number = shell_output[-1].split(\":\")[1].strip().replace(\"'\", \"\")\n",
" SERVICE_ACCOUNT = f\"{project_number}-compute@developer.gserviceaccount.com\"\n",
"\n",
" print(\"Service Account:\", SERVICE_ACCOUNT)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "set_service_account:pipelines"
},
"source": [
"#### Set service account access for Vertex AI Pipelines\n",
"\n",
"Run the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_service_account:pipelines"
},
"outputs": [],
"source": [
"! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator \n",
"! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_vars"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries and define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "import_kfp"
},
"outputs": [],
"source": [
"import json\n",
"\n",
"import google.cloud.aiplatform as aiplatform\n",
"from kfp.registry import RegistryClient"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "init_aip:mbsdk,all"
},
"source": [
"### Initialize Vertex AI SDK for Python\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project and corresponding bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "init_aip:mbsdk,all"
},
"outputs": [],
"source": [
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9b773e8d2bd2"
},
"source": [
"## Create repo in Artifact Registry\n",
"\n",
"First, you create your own (user-defined) repository in the `Artifact Registry`. You use this repository to upload and retreive your pipeline templates.\n",
"\n",
"The name of your repo is `quickstart-kfp-repo`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "520de849cee2"
},
"outputs": [],
"source": [
"REPO_NAME = \"quickstart-kfp-repo\"\n",
"\n",
"! gcloud artifacts repositories create {REPO_NAME} --location={REGION} --repository-format=KFP"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1611d3517c0f"
},
"source": [
"### Upload the pipeline template\n",
"\n",
"Next, you instantiate a client interface to the Artifact Registry. Then with the `upload_pipeline()` method you upload your pipeline template."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7f002e57998a"
},
"outputs": [],
"source": [
"T5X_YAML = \"gs://cloud-samples-data/vertex-ai/dataset-management/datasets/t5_finetuning/pipeline.yaml\"\n",
"\n",
"! gsutil cp {T5X_YAML} pipeline.yaml\n",
"\n",
"client = RegistryClient(\n",
" host=f\"https://{REGION}-kfp.pkg.dev/{PROJECT_ID}/quickstart-kfp-repo\"\n",
")\n",
"\n",
"templateName, versionName = client.upload_pipeline(\n",
" file_name=\"pipeline.yaml\",\n",
" tags=[\"v1\", \"latest\"],\n",
" extra_headers={\n",
" \"description\": \"This is a pipeline template for fine-tuning a T5 model.\"\n",
" },\n",
")\n",
"\n",
"! rm pipeline.yaml"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "02f82754fc0d"
},
"source": [
"### View your artifacts in your registry\n",
"\n",
"Next, using the `gcloud artifacts files` command you view the artifacts, inclusive of the pipeline template, in your artifacts repository."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b2f641eb2056"
},
"outputs": [],
"source": [
"! gcloud artifacts files list --repository={REPO_NAME} --location={REGION}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "968a46a3cb6d"
},
"source": [
"## Load and execute the pipeline job\n",
"\n",
"Next, you create a Vertex AI Pipeline job from your T5 pipeline template by instantiating a PipelineJob(), with the following parameters:\n",
"\n",
"- `display_name`: The human readable name for the pipeline job.\n",
"- `template_path`: The path to the pipeline template in the Artifact Registry.\n",
"- `enable_caching`: On re-runs, use the results from previous successful and unchanged steps.\n",
"- `pipeline_root`: A Cloud storage location for storing pipeline results.\n",
"- `parameter_values`: The parameters and values that are input to the template pipeline. In this example, they are:\n",
"TODO\n",
" - `project`: Your project ID.\n",
" - `class_labels`: A list of valid class labels, in cardinal order.\n",
" - `root_dir`: A Cloud Storage scratch area.\n",
" - `training_data_path`: A Cloud Storage location to the training data.\n",
" - `ground_truth_gcs_source_uris`: A Cloud Storage location to evaluation data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a3c502fc7e41"
},
"outputs": [],
"source": [
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/t5_finetuning\"\n",
"\n",
"job = aiplatform.PipelineJob(\n",
" display_name=\"t5x-finetuning\",\n",
" template_path=f\"https://{REGION}-kfp.pkg.dev/{PROJECT_ID}/quickstart-kfp-repo/{templateName}/{versionName}\",\n",
" pipeline_root=PIPELINE_ROOT,\n",
" enable_caching=False,\n",
" parameter_values={\n",
" \"project_id\": PROJECT_ID,\n",
" \"accelerator_count\": 32,\n",
" \"feature_keys\": \"question\",\n",
" \"label_key\": \"answer\",\n",
" \"training_data_path\": \"gs://cloud-llm-public/tfds/natural_questions_open/1.0.0_shortened/natural_questions_open-train.tfrecord-00000-of-00001\",\n",
" \"validation_data_path\": \"gs://cloud-llm-public/tfds/natural_questions_open/1.0.0_shortened/natural_questions_open-validation.tfrecord-00000-of-00001\",\n",
" },\n",
")\n",
"\n",
"job.run()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "view_pipleline_results:bqml"
},
"source": [
"### View the pipeline results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "view_pipleline_results:bqml"
},
"outputs": [],
"source": [
"PROJECT_NUMBER = job.gca_resource.name.split(\"/\")[1]\n",
"print(PROJECT_NUMBER)\n",
"\n",
"\n",
"def print_pipeline_output(job, output_task_name):\n",
" JOB_ID = job.name\n",
" print(JOB_ID)\n",
" artifact = \"\"\n",
" for _ in range(len(job.gca_resource.job_detail.task_details)):\n",
" TASK_ID = job.gca_resource.job_detail.task_details[_].task_id\n",
" EXECUTE_OUTPUT = (\n",
" PIPELINE_ROOT\n",
" + \"/\"\n",
" + PROJECT_NUMBER\n",
" + \"/\"\n",
" + JOB_ID\n",
" + \"/\"\n",
" + output_task_name\n",
" + \"_\"\n",
" + str(TASK_ID)\n",
" + \"/executor_output.json\"\n",
" )\n",
" GCP_RESOURCES = (\n",
" PIPELINE_ROOT\n",
" + \"/\"\n",
" + PROJECT_NUMBER\n",
" + \"/\"\n",
" + JOB_ID\n",
" + \"/\"\n",
" + output_task_name\n",
" + \"_\"\n",
" + str(TASK_ID)\n",
" + \"/gcp_resources\"\n",
" )\n",
" EVALUATION_METRICS = (\n",
" PIPELINE_ROOT\n",
" + \"/\"\n",
" + PROJECT_NUMBER\n",
" + \"/\"\n",
" + JOB_ID\n",
" + \"/\"\n",
" + output_task_name\n",
" + \"_\"\n",
" + str(TASK_ID)\n",
" + \"/evaluation_metrics\"\n",
" )\n",
" # Check if file exists, 0 is success\n",
" !gsutil -q stat $EXECUTE_OUTPUT\n",
" if _exit_code == 0:\n",
" ! gsutil cat $EXECUTE_OUTPUT\n",
" artifact = EXECUTE_OUTPUT\n",
" break\n",
" !gsutil -q stat $GCP_RESOURCES\n",
" if _exit_code == 0:\n",
" ! gsutil cat $GCP_RESOURCES\n",
" artifact = GCP_RESOURCES\n",
" break\n",
" !gsutil -q stat $EVALUATION_METRICS\n",
" if _exit_code == 0:\n",
" ! gsutil cat $EVALUATION_METRICS\n",
" artifact = EVALUATION_METRICS\n",
" break\n",
"\n",
" return artifact\n",
"\n",
"\n",
"print(\"model-upload\")\n",
"artifacts = print_pipeline_output(job, \"model-upload\")\n",
"output = !gsutil cat $artifacts\n",
"print(output)\n",
"output = json.loads(output[0])\n",
"model_id = output[\"artifacts\"][\"model\"][\"artifacts\"][0][\"metadata\"][\"resourceName\"]\n",
"print(\"\\n\\n\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f431a9e6f025"
},
"source": [
"### Delete the pipeline job\n",
"\n",
"The method 'delete()' will delete the pipeline job."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "00bf554abbc6"
},
"outputs": [],
"source": [
"job.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3d183db57ae2"
},
"source": [
"### Deploy the model\n",
"\n",
"Next, you deploy the model to an endpoint:\n",
"\n",
"- Use the `model_id` obtained from the pipeline artifacts to instantiate a Vertex AI Model resource instance.\n",
"- Deploy the Vertex AI Model resource to a Vertex AI Endpoint resource.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "591ccc049ce5"
},
"outputs": [],
"source": [
"model = aiplatform.Model(model_id)\n",
"endpoint = model.deploy(\n",
" accelerator_count=1,\n",
" accelerator_type=aiplatform.gapic.AcceleratorType.NVIDIA_TESLA_T4.name,\n",
" machine_type=\"n1-standard-4\",\n",
")\n",
"print(endpoint)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "edb781a92864"
},
"source": [
"### Make a prediction\n",
"\n",
"Finally, you make a prediction with the deployed model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "72d94012a987"
},
"outputs": [],
"source": [
"endpoint.predict([\"this is a test\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cleanup:mbsdk"
},
"source": [
"# Cleaning up\n",
"\n",
"To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cleanup:mbsdk"
},
"outputs": [],
"source": [
"delete_bucket = True\n",
"\n",
"endpoint.undeploy_all()\n",
"endpoint.delete()\n",
"model.delete()\n",
"\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil rm -r $BUCKET_URI\n",
"\n",
"! rm -rf custom custom.tar.gz"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_pipeline_templates_t5x.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,630 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ur8xi4C7S06n"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "TirJ-SGQseby"
},
"source": [
"# Vertex AI Model Garden: Google Proprietary Model Image Classification\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_proprietary_image_classification.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
"\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_proprietary_image_classification.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_proprietary_image_classification.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "dwGLvtIeECLK"
},
"source": [
"**_NOTE_**: This notebook has been tested in the following environment:\n",
"\n",
"* Python version = 3.9"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates how to use Google proprietary image classification model training/deployment in [Vertex AI Model Garden](https://cloud.google.com/model-garden).\n",
"\n",
"### Objective\n",
"\n",
"* Train new models using Vertex SDK\n",
"\n",
"* Test trained models\n",
" * View the trained model in [Vertex Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction)\n",
" * Deploy uploaded models\n",
" * Run predictions\n",
"\n",
"* Cleanup resources\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage.\n",
"\n",
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "KEukV6uRk_S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Jvqs-ehKlaYh"
},
"outputs": [],
"source": [
"! pip3 install --upgrade google-cloud-aiplatform\n",
"\n",
"# Automatically restart kernel after installs\n",
"import IPython\n",
"\n",
"app = IPython.Application.instance()\n",
"app.kernel.do_shutdown(True)\n",
"if \"google.colab\" in str(get_ipython()):\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9wExiMUxFk91"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"from google.cloud import aiplatform\n",
"\n",
"# The project and bucket are for experiments below.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"BUCKET_URI = \"\" # @param {type:\"string\"}\n",
"\n",
"# You can choose a region from https://cloud.google.com/about/locations.\n",
"# Only regions prefixed by \"us\", \"europe\", or \"asia\" are supported.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"REGION_PREFIX = REGION.split(\"-\")[0]\n",
"assert REGION_PREFIX in (\n",
" \"us\",\n",
" \"europe\",\n",
" \"asia\",\n",
"), f'{REGION} is not supported. It must be prefixed by \"us\", \"europe\", or \"asia\".'\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
"STAGING_BUCKET = os.path.join(BUCKET_URI, \"temporal\")\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=STAGING_BUCKET)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "n6IFz75WGCam"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"OBJECTIVE = \"icn\"\n",
"\n",
"# Dataset constants\n",
"DATASET_PREFIX = \"dataset-icn\"\n",
"\n",
"# Training constants.\n",
"TRAINING_JOB_PREFIX = \"train\"\n",
"\n",
"# The image classification flowers dataset used to train the model.\n",
"DATASET_FILE = (\n",
" \"gs://cloud-samples-data/vision/automl_classification/flowers/all_data_v2.csv\"\n",
")\n",
"\n",
"# Evaluation constants.\n",
"EVALUATION_METRIC = \"accuracy\"\n",
"\n",
"# Prediction constants.\n",
"# The example in this notebook uses optimized tensorflow runtime dockers.\n",
"# You can adjust accelerator types and machine types to get faster predictions.\n",
"PREDICTION_ACCELERATOR_TYPE = \"NVIDIA_TESLA_T4\"\n",
"PREDICTION_MACHINE_TYPE = \"n1-standard-4\"\n",
"DEPLOY_JOB_PREFIX = \"deploy\""
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ZZFPe_GezXg8"
},
"source": [
"### Define common libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XcYUGwr-AJGY"
},
"outputs": [],
"source": [
"import base64\n",
"from datetime import datetime\n",
"from io import BytesIO\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy\n",
"import tensorflow as tf\n",
"from PIL import Image\n",
"\n",
"\n",
"def get_job_name_with_datetime(prefix: str):\n",
" return prefix + datetime.now().strftime(\"_%Y%m%d_%H%M%S\")\n",
"\n",
"\n",
"def load_img(path):\n",
" img = tf.io.read_file(path)\n",
" img = tf.image.decode_jpeg(img, channels=3)\n",
" return Image.fromarray(numpy.uint8(img)).convert(\"RGB\")\n",
"\n",
"\n",
"def display_image(image):\n",
" _ = plt.figure(figsize=(20, 15))\n",
" plt.grid(False)\n",
" plt.imshow(image)\n",
"\n",
"\n",
"def get_prediction_instances(test_filepath, new_width=-1):\n",
" if new_width <= 0:\n",
" with tf.io.gfile.GFile(test_filepath, \"rb\") as input_file:\n",
" encoded_string = base64.b64encode(input_file.read()).decode(\"utf-8\")\n",
" else:\n",
" img = load_img(test_filepath)\n",
" width, height = img.size\n",
" print(\"original input image size: \", width, \" , \", height)\n",
" new_height = int(height * new_width / width)\n",
" new_img = img.resize((new_width, new_height))\n",
" print(\"resized input image size: \", new_width, \" , \", new_height)\n",
" buffered = BytesIO()\n",
" new_img.save(buffered, format=\"JPEG\")\n",
" encoded_string = base64.b64encode(buffered.getvalue()).decode(\"utf-8\")\n",
"\n",
" instances = [{\"content\": encoded_string}]\n",
" return instances"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "Q149N3V6Uynm"
},
"source": [
"## Create a dataset\n",
"\n",
"This tutorial uses a version of the Flowers dataset that is stored in a public Cloud Storage bucket, using a CSV index file.\n",
"\n",
"Start by doing a quick peek at the data. You count the number of examples by counting the number of rows in the CSV index file (`wc -l`) and then peek at the first few rows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yR4x-5XiVIlv"
},
"outputs": [],
"source": [
"count = ! gsutil cat $DATASET_FILE | wc -l\n",
"print(\"Number of Examples\", int(count[0]))\n",
"\n",
"print(\"First 10 rows\")\n",
"! gsutil cat $DATASET_FILE | head"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "8yfBZ1_8VZvq"
},
"source": [
"Next, create the `Dataset` resource using the `create` method for the `ImageDataset` class, which takes the following parameters:\n",
"\n",
"- `display_name`: The human readable name for the `Dataset` resource.\n",
"- `gcs_source`: A list of one or more dataset index files to import the data items into the `Dataset` resource.\n",
"- `import_schema_uri`: The data labeling schema for the data items.\n",
"\n",
"This operation may take several minutes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eehB1gwHVfRh"
},
"outputs": [],
"source": [
"dataset = aiplatform.ImageDataset.create(\n",
" display_name=DATASET_PREFIX + \"_flowers\",\n",
" gcs_source=[DATASET_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.image.single_label_classification,\n",
")\n",
"\n",
"print(dataset.resource_name)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "RB_xY9ipr7ZU"
},
"source": [
"## Train new models\n",
"\n",
"### Create and run training pipeline\n",
"\n",
"To train an AutoML model, you perform two steps:\n",
"1. Create a training pipeline.\n",
"2. Run the pipeline.\n",
"\n",
"#### Create training pipeline\n",
"\n",
"An AutoML training pipeline is created with the `AutoMLImageTrainingJob` class, with the following parameters:\n",
"\n",
"- `display_name`: The human readable name for the `TrainingJob` resource.\n",
"- `prediction_type`: The type task to train the model for.\n",
" - `classification`: An image classification model.\n",
" - `object_detection`: An image object detection model.\n",
"- `multi_label`: If a classification task is single (`False`) or multi-labeled (`True`).\n",
"- `model_type`: The type of model for deployment.\n",
" - `EFFICIENTNET`: A model that is available in Vertex Model Garden image classification training with customizable hyperparameters. Best tailored to be used within Google Cloud, and cannot be exported externally.\n",
" - `MAXVIT`: A model that is available in Vertex Model Garden image classification training with customizable hyperparameters. Best tailored to be used within Google Cloud, and cannot be exported externally.\n",
" - `COCA`: A model that is available in Vertex Model Garden image classification training with customizable hyperparameters. Best tailored to be used within Google Cloud, and cannot be exported externally.\n",
"- `checkpoint_name`: Optional. The field is reserved for Model Garden model training, based on the provided pre-trained model checkpoint.\n",
"- `trainer_config`: Optional. The field is usually used together with the Model Garden model training when passing the customized configs for the trainer.\n",
"\n",
" Example with all supported parameters:\n",
"```\n",
" trainer_config = {\n",
" 'global_batch_size': '8',\n",
" 'learning_rate': '0.001',\n",
" 'optimizer_type': 'sgd',\n",
" 'optimizer_momentum': '0.9',\n",
" 'train_steps': '10000',\n",
" 'accelerator_count': '1',\n",
" }\n",
"```\n",
"- `metric_spec`: Dictionary representing metrics to optimize. The dictionary key is the `metric_id`, which is reported by your training job, with possible values being ('loss', 'accuracy') and the dictionary value is the optimization goal of the metric ('minimize' or 'maximize').\n",
"For example: `metric_spec = {'loss': 'minimize', 'accuracy': 'maximize'}`\n",
"- `parameter_spec`: Dictionary representing parameters to optimize. The dictionary key is the `metric_id`, which is passed into your training job as a command line key word argument, and the dictionary value is the parameter\n",
"specification of the metric. Supported parameter specifications can be found in aiplatform.hyperparameter_tuning.\n",
"```\n",
" from google.cloud.aiplatform.aiplatform import hpt as hpt\n",
"\n",
" parameter_spec = {\n",
" 'learning_rate': hpt.DoubleParameterSpec(min=1e-7, max=1, scale='linear'),\n",
" }\n",
"```\n",
"- `search_algorithm`: The search algorithm specified for the Study. Accepts one of the following:\n",
" - `None`: If you do not specify an algorithm, your job uses the default\n",
" Vertex AI algorithm. The default algorithm applies Bayesian optimization\n",
" to arrive at the optimal solution with a more effective search over the\n",
" parameter space.\n",
" - `grid`: A simple grid search within the feasible space. This option is\n",
" particularly useful if you want to specify a quantity of trials that is greater than the number of points in the feasible space. In such cases, if you do not specify a grid search, the Vertex AI default algorithm may generate duplicate suggestions. To use grid search, all parameter specs must be of type `IntegerParameterSpec`, `CategoricalParameterSpec`, or `DiscreteParameterSpec`.\n",
" - `random`: A simple random search within the feasible space.\n",
"- `measurement_selection`: This indicates which measurement to use\n",
"if/when the service automatically selects the final measurement from\n",
"previously reported intermediate measurements.\n",
" Accepts: `best`, `last` Choose this based on two considerations:\n",
" - A): Do you expect your measurements to monotonically improve? If so,\n",
" choose `last`. On the other hand, if you\\'re in a situation where\n",
" your system can **over-train** and you expect the performance to get\n",
" better for a while but then start declining, choose `best`.\n",
" - B): Are your measurements significantly noisy and/or irreproducible? If\n",
" so, `best` will tend to be over-optimistic, and it may be better\n",
" to choose `last`. If both or neither of (A) and (B) apply, it\n",
" doesn't matter which selection type is chosen.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "un0tyqU7We_A"
},
"outputs": [],
"source": [
"from google.cloud.aiplatform import hyperparameter_tuning as hpt\n",
"\n",
"TRAINER_CONFIG = {\n",
" \"global_batch_size\": \"8\",\n",
" \"learning_rate\": \"0.001\",\n",
" \"train_steps\": \"10000\",\n",
" \"accelerator_count\": \"1\",\n",
"}\n",
"METRIC_SPEC_KEY = \"accuracy\"\n",
"METRIC_SPEC_VALUE = \"maximize\"\n",
"SEARCH_ALGORITHM = \"random\"\n",
"MEASUREMENT_SELECTION = \"best\"\n",
"MODEL_TYPE = \"COCA\" # @param {type:\"string\"} one of the values [\"COCA\", \"MAXVIT\", \"EFFICIENTNET\"]\n",
"\n",
"job = aiplatform.AutoMLImageTrainingJob(\n",
" display_name=get_job_name_with_datetime(TRAINING_JOB_PREFIX),\n",
" prediction_type=\"classification\",\n",
" multi_label=False,\n",
" model_type=MODEL_TYPE,\n",
" base_model=None,\n",
" trainer_config=TRAINER_CONFIG,\n",
" metric_spec={METRIC_SPEC_KEY: METRIC_SPEC_VALUE},\n",
" parameter_spec={\n",
" \"learning_rate\": hpt.DoubleParameterSpec(min=0.001, max=0.1, scale=\"log\"),\n",
" },\n",
" search_algorithm=SEARCH_ALGORITHM,\n",
" measurement_selection=MEASUREMENT_SELECTION,\n",
")\n",
"\n",
"print(job)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "HwcCjwlBTQIz"
},
"source": [
"#### Run the training pipeline\n",
"\n",
"Next, run the DAG to start the training job by invoking the method `run`, with the following parameters:\n",
"\n",
"- `dataset`: The `Dataset` resource to train the model.\n",
"- `model_display_name`: The human readable name for the trained model.\n",
"- `training_fraction_split`: The percentage of the dataset to use for training.\n",
"- `validation_fraction_split`: The percentage of the dataset to use for validation.\n",
"- `test_fraction_split`: The percentage of the dataset to use for test (holdout data).\n",
"- `budget_milli_node_hours`: (optional) Maximum training time specified in unit of millihours (1000 = hour).\n",
"- `disable_early_stopping`: If `True`, training may be completed before using the entire budget if the service believes it cannot further improve on the model objective measurements.\n",
"\n",
"The `run` method, when completed, returns the `Model` resource.\n",
"\n",
"The execution of the training pipeline will take up to 60 minutes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aec22792ee84"
},
"outputs": [],
"source": [
"model = job.run(\n",
" dataset=dataset,\n",
" model_display_name=get_job_name_with_datetime(\"flowers\"),\n",
" training_fraction_split=0.8,\n",
" validation_fraction_split=0.1,\n",
" test_fraction_split=0.1,\n",
" budget_milli_node_hours=8000,\n",
" disable_early_stopping=False,\n",
")\n",
"\n",
"print(\"Model is: \", model)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "g0BGaofgsMsy"
},
"source": [
"## Test trained models\n",
"This section shows how to test the trained models.\n",
"1. Deploy model from Model Registry\n",
"2. Run online predictions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NYuQowyZEtxK"
},
"outputs": [],
"source": [
"# @title Deploy model from Model Registry\n",
"\n",
"deploy_model_name = get_job_name_with_datetime(DEPLOY_JOB_PREFIX + \"_\" + OBJECTIVE)\n",
"print(\"The deployed job name is: \", deploy_model_name)\n",
"\n",
"endpoint = model.deploy(\n",
" deployed_model_display_name=deploy_model_name,\n",
" machine_type=PREDICTION_MACHINE_TYPE,\n",
" traffic_split={\"0\": 100},\n",
" accelerator_type=PREDICTION_ACCELERATOR_TYPE,\n",
" accelerator_count=1,\n",
" min_replica_count=1,\n",
" max_replica_count=1,\n",
")\n",
"\n",
"endpoint_id = endpoint.name\n",
"print(\"endpoint id is: \", endpoint_id)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vbIW9me1F2RY"
},
"outputs": [],
"source": [
"# @title Run online predictions\n",
"\n",
"# test image file path from a GCS bucket\n",
"test_filepath = \"\" # @param {type:\"string\"}\n",
"\n",
"with tf.io.gfile.GFile(test_filepath, \"rb\") as f:\n",
" content = f.read()\n",
"\n",
"# The format of each instance should conform to the deployed model's prediction input schema.\n",
"instances = [{\"content\": base64.b64encode(content).decode(\"utf-8\")}]\n",
"\n",
"prediction = endpoint.predict(instances=instances)\n",
"\n",
"img = load_img(test_filepath)\n",
"display_image(img)\n",
"print(prediction)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "kkH2nrpdp4sp"
},
"source": [
"## Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ax6vQVZhp9pR"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.undeploy_all()\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_proprietary_image_classification.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,702 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ur8xi4C7S06n"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "TirJ-SGQseby"
},
"source": [
"# Vertex AI Model Garden: Google Proprietary Model Image Object Detection\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_proprietary_image_object_detection.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
"\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_proprietary_image_object_detection.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_proprietary_image_object_detection.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "dwGLvtIeECLK"
},
"source": [
"**_NOTE_**: This notebook has been tested in the following environment:\n",
"\n",
"* Python version = 3.9"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates how to use Google proprietary image object detection model training/deployment in [Vertex AI Model Garden](https://cloud.google.com/model-garden).\n",
"\n",
"### Objective\n",
"\n",
"* Train new models using Vertex SDK\n",
"\n",
"* Test trained models\n",
" * View the trained model in [Vertex AI Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction)\n",
" * Deploy uploaded models\n",
" * Run predictions\n",
"\n",
"* Cleanup resources\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage.\n",
"\n",
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the Salads category of the [OpenImages dataset](https://www.tensorflow.org/datasets/catalog/open_images_v4) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). This dataset does not require any feature engineering. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the bounding box locations and corresponding type of salad items in an image from a class of five items: salad, seafood, tomato, baked goods, or cheese."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "KEukV6uRk_S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Jvqs-ehKlaYh"
},
"outputs": [],
"source": [
"! pip3 install --upgrade google-cloud-aiplatform\n",
"\n",
"# Automatically restart kernel after installs\n",
"import IPython\n",
"\n",
"app = IPython.Application.instance()\n",
"app.kernel.do_shutdown(True)\n",
"if \"google.colab\" in str(get_ipython()):\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9wExiMUxFk91"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"from google.cloud import aiplatform\n",
"\n",
"# The project and bucket are for experiments below.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"BUCKET_URI = \"\" # @param {type:\"string\"}\n",
"\n",
"# You can choose a region from https://cloud.google.com/about/locations.\n",
"# Only regions prefixed by \"us\", \"europe\", or \"asia\" are supported.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"REGION_PREFIX = REGION.split('-')[0]\n",
"assert REGION_PREFIX in (\n",
" \"us\",\n",
" \"europe\",\n",
" \"asia\"\n",
"), f'{REGION} is not supported. It must be prefixed by \"us\", \"europe\", or \"asia\".'\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
"STAGING_BUCKET = os.path.join(BUCKET_URI, \"temporal\")\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=STAGING_BUCKET)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "n6IFz75WGCam"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"OBJECTIVE = \"iod\"\n",
"\n",
"# Dataset constants.\n",
"DATASET_PREFIX = \"dataset-iod\"\n",
"\n",
"# Training constants.\n",
"TRAINING_JOB_PREFIX = \"train\"\n",
"# The image object detection salad dataset used to train the model\n",
"DATASET_FILE = \"gs://cloud-samples-data/vision/salads.csv\"\n",
"\n",
"# Evaluation constants.\n",
"EVALUATION_METRIC = \"AP50\"\n",
"\n",
"# Prediction constants.\n",
"# You can adjust accelerator types and machine types to get faster predictions.\n",
"PREDICTION_ACCELERATOR_TYPE = \"NVIDIA_TESLA_T4\"\n",
"PREDICTION_MACHINE_TYPE = \"n1-standard-4\"\n",
"DEPLOY_JOB_PREFIX = \"deploy\""
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ZZFPe_GezXg8"
},
"source": [
"### Define common libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XcYUGwr-AJGY"
},
"outputs": [],
"source": [
"import base64\n",
"import os\n",
"from datetime import datetime\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import tensorflow as tf\n",
"from google.cloud import aiplatform\n",
"from PIL import Image, ImageColor, ImageDraw, ImageFont\n",
"\n",
"\n",
"def get_job_name_with_datetime(prefix: str):\n",
" return prefix + datetime.now().strftime(\"_%Y%m%d_%H%M%S\")\n",
"\n",
"\n",
"def load_img(path):\n",
" img = tf.io.read_file(path)\n",
" img = tf.image.decode_jpeg(img, channels=3)\n",
" return Image.fromarray(np.uint8(img)).convert(\"RGB\")\n",
"\n",
"\n",
"def display_image(image):\n",
" _ = plt.figure(figsize=(20, 15))\n",
" plt.grid(False)\n",
" plt.imshow(image)\n",
"\n",
"\n",
"def draw_bounding_box_on_image(\n",
" image, ymin, xmin, ymax, xmax, color, font, thickness=4, display_str_list=()\n",
"):\n",
" \"\"\"Adds a bounding box to an image.\"\"\"\n",
" draw = ImageDraw.Draw(image)\n",
" im_width, im_height = image.size\n",
" (left, right, top, bottom) = (\n",
" xmin * im_width,\n",
" xmax * im_width,\n",
" ymin * im_height,\n",
" ymax * im_height,\n",
" )\n",
" draw.line(\n",
" [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)],\n",
" width=thickness,\n",
" fill=color,\n",
" )\n",
"\n",
" # If the total height of the display strings added to the top of the bounding\n",
" # box exceeds the top of the image, stack the strings below the bounding box\n",
" # instead of above.\n",
" display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]\n",
" # Each display_str has a top and bottom margin of 0.05x.\n",
" total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)\n",
"\n",
" if top > total_display_str_height:\n",
" text_bottom = top\n",
" else:\n",
" text_bottom = top + total_display_str_height\n",
" # Reverse list and print from bottom to top.\n",
" for display_str in display_str_list[::-1]:\n",
" text_width, text_height = font.getsize(display_str)\n",
" margin = np.ceil(0.05 * text_height)\n",
" draw.rectangle(\n",
" [\n",
" (left, text_bottom - text_height - 2 * margin),\n",
" (left + text_width, text_bottom),\n",
" ],\n",
" fill=color,\n",
" )\n",
" draw.text(\n",
" (left + margin, text_bottom - text_height - margin),\n",
" display_str,\n",
" fill=\"black\",\n",
" font=font,\n",
" )\n",
" text_bottom -= text_height - 2 * margin\n",
"\n",
"\n",
"def draw_boxes(image, boxes, class_names, scores, max_boxes=40, min_score=0.05):\n",
" \"\"\"Overlay labeled boxes on an image with formatted scores and label names.\"\"\"\n",
" colors = list(ImageColor.colormap.values())\n",
" try:\n",
" font = ImageFont.truetype(\n",
" \"/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Regular.ttf\", 25\n",
" )\n",
" except OSError:\n",
" print(\"Font not found, using default font.\")\n",
" font = ImageFont.load_default()\n",
"\n",
" for i in range(min(len(boxes), max_boxes)):\n",
" if scores[i] >= min_score:\n",
" ymin, xmin, ymax, xmax = boxes[i]\n",
" display_str = \"{}: {}%\".format(class_names[i], int(100 * scores[i]))\n",
" color = colors[hash(class_names[i]) % len(colors)]\n",
" draw_bounding_box_on_image(\n",
" image,\n",
" ymin,\n",
" xmin,\n",
" ymax,\n",
" xmax,\n",
" color,\n",
" font,\n",
" display_str_list=[display_str],\n",
" )\n",
" return image"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "nZLVI9TtUuif"
},
"source": [
"## Create a dataset\n",
"\n",
"This tutorial uses a version of the Salads dataset that is stored in a public Cloud Storage bucket, using a CSV index file.\n",
"\n",
"Start by doing a quick peek at the data. You count the number of examples by counting the number of rows in the CSV index file (`wc -l`) and then peek at the first few rows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Pr60Y1fpUuO9"
},
"outputs": [],
"source": [
"count = ! gsutil cat $DATASET_FILE | wc -l\n",
"print(\"Number of Examples\", int(count[0]))\n",
"\n",
"print(\"First 10 rows\")\n",
"! gsutil cat $DATASET_FILE | head"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "SZEdBfNZUxQn"
},
"source": [
"Next, create the `Dataset` resource using the `create` method for the `ImageDataset` class, which takes the following parameters:\n",
"\n",
"- `display_name`: The human readable name for the `Dataset` resource.\n",
"- `gcs_source`: A list of one or more dataset index files to import the data items into the `Dataset` resource.\n",
"- `import_schema_uri`: The data labeling schema for the data items.\n",
"\n",
"This operation may take several minutes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FlDqM5APU0As"
},
"outputs": [],
"source": [
"dataset = aiplatform.ImageDataset.create(\n",
" display_name=DATASET_PREFIX + \"_salads\",\n",
" gcs_source=[DATASET_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.image.bounding_box,\n",
")\n",
"\n",
"print(dataset.resource_name)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "RB_xY9ipr7ZU"
},
"source": [
"## Train new models\n",
"\n",
"### Create and run training pipeline\n",
"\n",
"To train an AutoML model, you perform two steps:\n",
"1. Create a training pipeline.\n",
"2. Run the pipeline.\n",
"\n",
"#### Create training pipeline\n",
"\n",
"An AutoML training pipeline is created with the `AutoMLImageTrainingJob` class, with the following parameters:\n",
"\n",
"- `display_name`: The human readable name for the `TrainingJob` resource.\n",
"- `prediction_type`: The type task to train the model for.\n",
" - `classification`: An image classification model.\n",
" - `object_detection`: An image object detection model.\n",
"- `model_type`: The type of model for deployment. For image object detection, we current support the following:\n",
" - `SPINENET`: A model that is available in Vertex Model Garden image object detection training with customizable hyperparameters. Best tailored to be used within Google Cloud, and cannot be exported externally.\n",
" - `YOLO`: A model that is available in Vertex Model Garden image object detection training with customizable hyperparameters. Best tailored to be used within Google Cloud, and cannot be exported externally.\n",
"- `checkpoint_name`: Optional. The field is reserved for Model Garden model training, based on the provided pre-trained model checkpoint.\n",
"- `trainer_config`: Optional. The field is usually used together with the Model Garden model training, when passing the customized configs for the trainer. `anchor_size` cannot be used with `YOLO`.\n",
"\n",
" Example with all supported parameters:\n",
"```\n",
" trainer_config = {\n",
" 'global_batch_size': '8',\n",
" 'learning_rate': '0.001',\n",
" 'optimizer_type': 'sgd',\n",
" 'optimizer_momentum': '0.9',\n",
" 'train_steps': '10000',\n",
" 'accelerator_count': '1',\n",
" 'anchor_size': '8',\n",
" }\n",
"```\n",
"- `metric_spec`: Dictionary representing metrics to optimize. The dictionary key is the metric_id, which is reported by your training job, with possible values being ('loss', 'AP50') and the dictionary value is the optimization goal of the metric('minimize' or 'maximize').\n",
"For example: `metric_spec = {'loss': 'minimize', 'AP50': 'maximize'}`\n",
"- `parameter_spec`:Dictionary representing parameters to optimize. The dictionary key is the `metric_id`, which is passed into your training job as a command line key word argument, and the dictionary value is the parameter\n",
"specification of the metric. Supported parameter specifications can be found in aiplatform.hyperparameter_tuning.\n",
"```\n",
" from google.cloud.aiplatform.aiplatform import hpt as hpt\n",
"\n",
" parameter_spec = {\n",
" 'learning_rate': hpt.DoubleParameterSpec(min=1e-7, max=1, scale='linear'), \\\n",
" }\n",
"```\n",
"- `search_algorithm`: The search algorithm specified for the Study. Accepts one of the following:\n",
" - `None`: If you do not specify an algorithm, your job uses the default\n",
" Vertex AI algorithm. The default algorithm applies Bayesian optimization\n",
" to arrive at the optimal solution with a more effective search over the\n",
" parameter space.\n",
" - `grid`: A simple grid search within the feasible space. This option is\n",
" particularly useful if you want to specify a quantity of trials that is greater than the number of points in the feasible space. In such cases, if you do not specify a grid search, the Vertex AI default algorithm may generate duplicate suggestions. To use grid search, all parameter specs must be of type `IntegerParameterSpec`, `CategoricalParameterSpec`, or `DiscreteParameterSpec`.\n",
" - `random`: A simple random search within the feasible space.\n",
"- `measurement_selection`: This indicates which measurement to use\n",
"if/when the service automatically selects the final measurement from\n",
"previously reported intermediate measurements.\n",
" Accepts: `best`, `last` Choose this based on two considerations:\n",
" - A): Do you expect your measurements to monotonically improve? If so,\n",
" choose `last`. On the other hand, if you\\'re in a situation where\n",
" your system can **over-train** and you expect the performance to get\n",
" better for a while but then start declining, choose `best`.\n",
" - B): Are your measurements significantly noisy and/or irreproducible? If\n",
" so, `best` will tend to be over-optimistic, and it may be better\n",
" to choose `last`. If both or neither of (A) and (B) apply, it\n",
" doesn't matter which selection type is chosen.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "um_XKbmpTaHx"
},
"outputs": [],
"source": [
"from google.cloud.aiplatform import hyperparameter_tuning as hpt\n",
"\n",
"TRAINER_CONFIG = {\n",
" \"global_batch_size\": \"8\",\n",
" \"learning_rate\": \"0.001\",\n",
" \"train_steps\": \"10000\",\n",
" \"accelerator_count\": \"1\",\n",
"}\n",
"METRIC_SPEC_KEY = \"AP50\"\n",
"METRIC_SPEC_VALUE = \"maximize\"\n",
"SEARCH_ALGORITHM = \"random\"\n",
"MEASUREMENT_SELECTION = \"best\"\n",
"MODEL_TYPE = \"SPINENET\" # @param {type:\"string\"} one of the values [\"SPINENET\", \"YOLO\"]\n",
"\n",
"PARAMETER_SPEC = {}\n",
"if MODEL_TYPE == \"YOLO\":\n",
" PARAMETER_SPEC = {\n",
" \"learning_rate\": hpt.DiscreteParameterSpec(\n",
" values=[0.001, 0.1],\n",
" scale=\"linear\",\n",
" ),\n",
" \"weight_decay\": hpt.DiscreteParameterSpec(\n",
" values=[0.0001, 0.001],\n",
" scale=\"linear\",\n",
" ),\n",
" }\n",
"else:\n",
" PARAMETER_SPEC = {\n",
" \"learning_rate\": hpt.DiscreteParameterSpec(\n",
" values=[0.001, 0.01], scale=\"linear\"\n",
" ),\n",
" \"anchor_size\": hpt.DiscreteParameterSpec(values=[2, 4], scale=\"reverse_log\"),\n",
" }\n",
"\n",
"job = aiplatform.AutoMLImageTrainingJob(\n",
" display_name=get_job_name_with_datetime(TRAINING_JOB_PREFIX),\n",
" prediction_type=\"object_detection\",\n",
" model_type=MODEL_TYPE,\n",
" base_model=None,\n",
" trainer_config=TRAINER_CONFIG,\n",
" metric_spec={METRIC_SPEC_KEY: METRIC_SPEC_VALUE},\n",
" parameter_spec=PARAMETER_SPEC,\n",
" search_algorithm=SEARCH_ALGORITHM,\n",
" measurement_selection=MEASUREMENT_SELECTION,\n",
")\n",
"\n",
"print(job)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "HwcCjwlBTQIz"
},
"source": [
"#### Run the training pipeline\n",
"\n",
"Next, run the DAG to start the training job by invoking the method `run`, with the following parameters:\n",
"\n",
"- `dataset`: The `Dataset` resource to train the model.\n",
"- `model_display_name`: The human readable name for the trained model.\n",
"- `training_fraction_split`: The percentage of the dataset to use for training.\n",
"- `test_fraction_split`: The percentage of the dataset to use for test (holdout data).\n",
"- `validation_fraction_split`: The percentage of the dataset to use for validation.\n",
"- `budget_milli_node_hours`: (optional) Maximum training time specified in unit of millihours (1000 = hour).\n",
"- `disable_early_stopping`: If `True`, training may be completed before using the entire budget if the service believes it cannot further improve on the model objective measurements.\n",
"\n",
"The `run` method when completed returns the `Model` resource.\n",
"\n",
"The execution of the training pipeline will take up to 60 minutes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aec22792ee84"
},
"outputs": [],
"source": [
"model = job.run(\n",
" dataset=dataset,\n",
" model_display_name=get_job_name_with_datetime(\"salads\"),\n",
" training_fraction_split=0.8,\n",
" validation_fraction_split=0.1,\n",
" test_fraction_split=0.1,\n",
" budget_milli_node_hours=20000,\n",
" disable_early_stopping=False,\n",
")\n",
"\n",
"print(\"Model is: \", model)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "g0BGaofgsMsy"
},
"source": [
"## Test trained models\n",
"This section shows how to test the trained models.\n",
"1. Deploy models from Model Registry\n",
"2. Run online predictions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mj723H4NXu4v"
},
"outputs": [],
"source": [
"# @title Deploy model from Model Registry\n",
"\n",
"deploy_model_name = get_job_name_with_datetime(DEPLOY_JOB_PREFIX + \"_\" + OBJECTIVE)\n",
"print(\"The deployed job name is: \", deploy_model_name)\n",
"\n",
"endpoint = model.deploy(\n",
" deployed_model_display_name=deploy_model_name,\n",
" machine_type=PREDICTION_MACHINE_TYPE,\n",
" traffic_split={\"0\": 100},\n",
" accelerator_type=PREDICTION_ACCELERATOR_TYPE,\n",
" accelerator_count=1,\n",
" min_replica_count=1,\n",
" max_replica_count=1,\n",
")\n",
"\n",
"endpoint_id = endpoint.name\n",
"print(\"endpoint id is: \", endpoint_id)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NTYvgFv6XyEe"
},
"outputs": [],
"source": [
"# @title Run online predictions\n",
"\n",
"# test image file path from a GCS bucket\n",
"test_filepath = \"\" # @param {type:\"string\"}\n",
"\n",
"with tf.io.gfile.GFile(test_filepath, \"rb\") as f:\n",
" content = f.read()\n",
"\n",
"# The format of each instance should conform to the deployed model's prediction input schema.\n",
"instances = [{\"content\": base64.b64encode(content).decode(\"utf-8\")}]\n",
"\n",
"prediction = endpoint.predict(instances=instances)\n",
"\n",
"img = load_img(test_filepath)\n",
"display_image(img)\n",
"print(prediction)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "frcGP5HFX1XN"
},
"source": [
"## Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "H2m8-u0IX4dX"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.undeploy_all()\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_proprietary_image_object_detection.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,371 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7d9bbf86da5e"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2bd716bf3e39"
},
"source": [
"# Vertex AI Model Garden - Bart Large CNN\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_bart_large_cnn.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_bart_large_cnn.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_bart_large_cnn.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 CPU notebook is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d8cd12648da4"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates deploying the pre-trained [Bart Large CNN](https://huggingface.co/facebook/bart-large-cnn) model on Vertex AI for online prediction.\n",
"\n",
"### Objective\n",
"\n",
"- Upload the model to [Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model on [Endpoint](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for image captioning.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "264c07757582"
},
"source": [
"## Setup environment\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d73ffa0c0b83"
},
"source": [
"### Colab only"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2707b02ef5df"
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0f826ff482a2"
},
"source": [
"### Setup Google Cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8958ebc71868"
},
"source": [
"Fill following variables for experiments environment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9db30f827a65"
},
"outputs": [],
"source": [
"# Cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"# The region you want to launch jobs in.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "92f16e22c20b"
},
"source": [
"Initialize Vertex AI API:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1680c257acfb"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6ca48b699d17"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "de9882ea89ea"
},
"outputs": [],
"source": [
"# The pre-built serving docker image.\n",
"# The model artifacts are embedded within the container, except for model weights which will be downloaded during deployment.\n",
"SERVE_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-transformers-serve\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "10188266a5cd"
},
"source": [
"### Define common functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cac4478ae098"
},
"outputs": [],
"source": [
"def deploy_model(model_id, task):\n",
" \"\"\"Uploads and deploys the model to Vertex AI endpoint for prediction.\"\"\"\n",
" model_name = \"bart_large_cnn\"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{model_name}-endpoint\")\n",
" serving_env = {\n",
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" # If the model_id is a GCS path, use artifact_uri to pass it to serving docker.\n",
" artifact_uri = model_id if model_id.startswith(\"gs://\") else None\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
" serving_container_ports=[7080],\n",
" serving_container_predict_route=\"/predictions/transformers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" artifact_uri=artifact_uri,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=\"n1-standard-8\",\n",
" accelerator_type=\"NVIDIA_TESLA_T4\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" )\n",
" return model, endpoint"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d2d72ecdb8c9"
},
"source": [
"## Upload and deploy models"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9448c5f545fa"
},
"source": [
"This section uploads the pre-trained model to Model Registry and deploys it on the Endpoint with 1 T4 GPU.\n",
"\n",
"The model deployment step will take ~15 minutes to complete."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b4b46c28d8b1"
},
"outputs": [],
"source": [
"model, endpoint = deploy_model(model_id=\"facebook/bart-large-cnn\", task=\"summarization\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nTs3JBT3W_lJ"
},
"source": [
"## Send prediction request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6be655247cb1"
},
"outputs": [],
"source": [
"ARTICLE = \"\"\" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.\n",
"A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.\n",
"Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared \"I do\" five more times, sometimes only within two weeks of each other.\n",
"In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her \"first and only\" marriage.\n",
"Barrientos, now 39, is facing two criminal counts of \"offering a false instrument for filing in the first degree,\" referring to her false statements on the\n",
"2010 marriage license application, according to court documents.\n",
"Prosecutors said the marriages were part of an immigration scam.\n",
"On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.\n",
"After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective\n",
"Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.\n",
"All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.\n",
"Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.\n",
"Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.\n",
"The case was referred to the Bronx District Attorney\\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\\'s\n",
"Investigation Division. Seven of the men are from so-called \"red-flagged\" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.\n",
"Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.\n",
"If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18.\n",
"\"\"\"\n",
"\n",
"instances = [\n",
" {\"text\": ARTICLE},\n",
"]\n",
"preds = endpoint.predict(instances=instances).predictions\n",
"print(preds)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xKj4wBQNWuHT"
},
"source": [
"## Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2ccf3714dbe9"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_pytorch_bart_large_cnn.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -271,7 +268,7 @@
"\n",
"\n",
"def deploy_model(model_id, task):\n",
" model_name = \"blip-image-captioning\"\n",
" model_name = \"blip2\"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{model_name}-endpoint\")\n",
" serving_env = {\n",
" \"MODEL_ID\": model_id,\n",
@@ -345,10 +342,10 @@
{
"cell_type": "markdown",
"metadata": {
"id": "12893aa2c5af"
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. When the model is very large it could add 5~15mins additional time before the endpoint is ready for prediction."
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 10 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
@@ -409,10 +406,10 @@
{
"cell_type": "markdown",
"metadata": {
"id": "0ac7f8d945e3"
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. When the model is very large it could add 5~15mins additional time before the endpoint is ready for prediction."
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 10 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -332,6 +329,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -332,6 +329,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -314,9 +311,16 @@
"source": [
"This section uploads the pre-trained model to Model Registry and deploys it on the Endpoint with 1 T4 GPU.\n",
"\n",
"The model deployment step will take ~15 minutes to complete.\n",
"\n",
"Once deployed, you can send images and object texts to get classification results."
"The model deployment step will take ~15 minutes to complete."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "99f3c6b404b5"
},
"source": [
"### Zero-shot image classification"
]
},
{
@@ -332,6 +336,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -353,20 +366,87 @@
"print(preds)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2ccf3714dbe9"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "db7ffebdb4be"
"id": "ddf9e9ec7b58"
},
"source": [
"### Clean up resources"
"### Image/text feature embedding"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2ccf3714dbe9"
"id": "8897bbac6887"
},
"outputs": [],
"source": [
"model, endpoint = deploy_model(\n",
" model_id=\"openai/clip-vit-base-patch32\", task=\"feature-embedding\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9f854c45f8f3"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed after the above model deployment step succeeds and before you run the next step below. Otherwise you might see a ServiceUnavailable: 503 502:Bad Gateway error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2abd54335f36"
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"# Extract feature embedding of images.\n",
"image = download_image(\"http://images.cocodataset.org/val2017/000000039769.jpg\")\n",
"display(image)\n",
"instances = [\n",
" {\"image\": image_to_base64(image)},\n",
"]\n",
"preds = endpoint.predict(instances=instances).predictions\n",
"image_features = np.array(preds[0][\"image_features\"])\n",
"print(image_features.shape)\n",
"\n",
"# Extract feature embedding of texts.\n",
"instances = [\n",
" {\"text\": \"two cats\"},\n",
" {\"text\": \"hello world\"},\n",
"]\n",
"preds = endpoint.predict(instances=instances).predictions\n",
"text_features = np.array(preds[0][\"text_features\"])\n",
"print(text_features.shape)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "712eb9d0b336"
},
"outputs": [],
"source": [
@@ -184,7 +184,9 @@
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs."
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs.\n",
"\n",
"1. [Create a service account](https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console) with `Vertex AI User` and `Storage Object Admin` roles for deploying fine tuned model to Vertex AI endpoint."
]
},
{
@@ -211,7 +213,10 @@
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
"GCS_BUCKET = \"\" # @param {type:\"string\"}\n",
"\n",
"# The service account you created in step-5 above, it's like \"<account_name>@<project>.iam.gserviceaccount.com\"\n",
"SERVICE_ACCOUNT = \"\" # @param {type:\"string\"}"
]
},
{
@@ -271,13 +276,15 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": null,
"metadata": {
"id": "354da31189dc"
},
"outputs": [],
"source": [
"import base64\n",
"import os\n",
"from datetime import datetime\n",
"from io import BytesIO\n",
"\n",
"import cv2\n",
@@ -334,8 +341,6 @@
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" # If the model_id is a GCS path, use artifact_uri to pass it to serving docker.\n",
" artifact_uri = model_id if model_id.startswith(\"gs://\") else None\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
@@ -343,7 +348,6 @@
" serving_container_predict_route=\"/predictions/diffusers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" artifact_uri=artifact_uri,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
@@ -351,6 +355,7 @@
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" service_account=SERVICE_ACCOUNT,\n",
" )\n",
" return model, endpoint"
]
@@ -391,6 +396,10 @@
"dataset_id = \"fusing/fill50k\"\n",
"# The output path.\n",
"output_dir = f\"/gcs/{GCS_BUCKET}/controlnet/output\"\n",
"# The training steps. If provided, it overrides num_train_epochs. Set it to None to use num_train_epochs only.\n",
"max_train_steps = 10 # @param {type:\"integer\"}\n",
"# The training epochs. Set it to a bigger number, like 10, to make training converge better.\n",
"num_train_epochs = 1 # @param {type:\"integer\"}\n",
"\n",
"# Worker pool spec.\n",
"machine_type = \"a2-highgpu-1g\"\n",
@@ -410,14 +419,25 @@
"# for a full list of training arguments.\n",
"model = job.run(\n",
" args=[\n",
" f\"--num_machines={num_nodes}\",\n",
" f\"--num_processes={num_gpus}\",\n",
" \"--machine_rank=0\",\n",
" \"--mixed_precision=no\",\n",
" \"--gpu_ids=all\",\n",
" \"--same_network\",\n",
" \"--dynamo_backend=no\",\n",
" \"controlnet/train_controlnet.py\",\n",
" \"--tracker_project_name=train_controlnet\",\n",
" f\"--pretrained_model_name_or_path={stable_diffusion_model_id}\",\n",
" f\"--output_dir={output_dir}\",\n",
" f\"--dataset_name={dataset_id}\",\n",
" f\"--max_train_steps={max_train_steps}\",\n",
" f\"--num_train_epochs={num_train_epochs}\",\n",
" \"--resolution=512\",\n",
" \"--learning_rate=1e-5\",\n",
" \"--train_batch_size=2\",\n",
" \"--checkpointing_steps=50000\",\n",
" \"--checkpoints_total_limit=1\",\n",
" ],\n",
" replica_count=num_nodes,\n",
" machine_type=machine_type,\n",
@@ -477,6 +497,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -520,11 +549,11 @@
},
"outputs": [],
"source": [
"# Delete models.\n",
"model.delete()\n",
"\n",
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)"
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
},
{
@@ -554,10 +583,19 @@
"outputs": [],
"source": [
"model, endpoint = deploy_model(\n",
" model_id=f\"gs://{GCS_BUCKET}/controlnet/output\", task=\"image-to-image\"\n",
" model_id=f\"gs://{GCS_BUCKET}/controlnet/output\", task=\"controlnet\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,362 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7d9bbf86da5e"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2bd716bf3e39"
},
"source": [
"# Vertex AI Model Garden - Dolly V2\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_dolly_v2.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_dolly_v2.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_dolly_v2.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 CPU notebook is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d8cd12648da4"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates deploying the pre-trained [Dolly-V2-7b](https://huggingface.co/databricks/dolly-v2-7b) model on Vertex AI for online prediction.\n",
"\n",
"### Objective\n",
"\n",
"- Upload the model to [Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model on [Endpoint](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for image captioning.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "264c07757582"
},
"source": [
"## Setup environment\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d73ffa0c0b83"
},
"source": [
"### Colab only"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2707b02ef5df"
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0f826ff482a2"
},
"source": [
"### Setup Google Cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8958ebc71868"
},
"source": [
"Fill following variables for experiments environment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9db30f827a65"
},
"outputs": [],
"source": [
"# Cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"# The region you want to launch jobs in.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "92f16e22c20b"
},
"source": [
"Initialize Vertex AI API:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1680c257acfb"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6ca48b699d17"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "de9882ea89ea"
},
"outputs": [],
"source": [
"# The pre-built serving docker image.\n",
"# The model artifacts are embedded within the container, except for model weights which will be downloaded during deployment.\n",
"SERVE_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-dolly-v2-serve\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "10188266a5cd"
},
"source": [
"### Define common functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cac4478ae098"
},
"outputs": [],
"source": [
"def deploy_model(model_id):\n",
" \"\"\"Uploads and deploys the model to Vertex AI endpoint for prediction.\"\"\"\n",
" model_name = \"dolly_v2_7b\"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{model_name}-endpoint\")\n",
" serving_env = {\n",
" \"MODEL_ID\": model_id,\n",
" }\n",
" # If the model_id is a GCS path, use artifact_uri to pass it to serving docker.\n",
" artifact_uri = model_id if model_id.startswith(\"gs://\") else None\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
" serving_container_ports=[7080],\n",
" serving_container_predict_route=\"/predictions/transformers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" artifact_uri=artifact_uri,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=\"a2-highgpu-1g\",\n",
" accelerator_type=\"NVIDIA_TESLA_A100\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" )\n",
" return model, endpoint"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d2d72ecdb8c9"
},
"source": [
"## Upload and deploy models"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9448c5f545fa"
},
"source": [
"This section uploads the pre-trained model to Model Registry and deploys it on the Endpoint with 1 A100 GPU.\n",
"\n",
"The model deployment step will take ~15 minutes to complete."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b4b46c28d8b1"
},
"outputs": [],
"source": [
"model, endpoint = deploy_model(model_id=\"databricks/dolly-v2-7b\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 10 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ohPQGAawXtAf"
},
"source": [
"## Send prediction request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6be655247cb1"
},
"outputs": [],
"source": [
"input_text = \"Explain to me the difference between nuclear fission and fusion.\"\n",
"\n",
"instances = [\n",
" {\"text\": input_text},\n",
"]\n",
"preds = endpoint.predict(instances=instances).predictions\n",
"print(preds)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uXLWt43CXMgj"
},
"source": [
"## Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2ccf3714dbe9"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_pytorch_dolly_v2.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -352,6 +349,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -332,6 +329,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -351,6 +348,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -0,0 +1,954 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7d9bbf86da5e"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "99c1c3fc2ca5"
},
"source": [
"# Vertex AI Model Garden - PEFT\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_peft.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_peft.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_peft.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a> (A Python-3 CPU notebook is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3de7470326a2"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates finetuning models with performance efficient finetuning libaries ([PEFT](https://github.com/huggingface/peft)), and running inferences with containers in Vertex AI. There are various models supported in [PEFT](https://github.com/huggingface/peft). This notebook shows examples with some models, such as OpenLLaMA, Falcon-instruct, BERT, RoBERTa-large, and XLM-RoBERTa-large, etc.\n",
"\n",
"### Objective\n",
"\n",
"- Finetune causal language models with PEFT and run inferences with Vertex AI, supporting\n",
"\n",
"| Models | LoRA |\n",
"| :- | :- |\n",
"| [openlm-research/open_llama_3b](https://huggingface.co/openlm-research/open_llama_3b) | Y |\n",
"| [openlm-research/open_llama_7b](https://huggingface.co/openlm-research/open_llama_7b) | Y |\n",
"| [openlm-research/open_llama_13b](https://huggingface.co/openlm-research/open_llama_13b) | Y |\n",
"\n",
"- Finetune instruct models with PEFT and run inferences with Vertex AI, supporting\n",
"\n",
"| Models | LoRA |\n",
"| :- | :- |\n",
"| [tiiuae/falcon-7b-instruct](https://huggingface.co/tiiuae/falcon-7b-instruct) | Y |\n",
"| [tiiuae/falcon-40b-instruct](https://huggingface.co/tiiuae/falcon-40b-instruct) | Y |\n",
"\n",
"\n",
"- Finetune sequence classification models with PEFT and run inferences with Vertex AI, supporting\n",
"\n",
"| Models | LoRA |\n",
"| :- | :- |\n",
"| [bert-base-uncase](https://huggingface.co/bert-base-uncased) | Y |\n",
"| [RoBERTa-large](https://huggingface.co/roberta-large) | Y |\n",
"| [XLM-RoBERTa-large](https://huggingface.co/xlm-roberta-large) | Y |\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "264c07757582"
},
"source": [
"## Before you begin\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ioensNKM8ned"
},
"source": [
"### Colab only\n",
"Run the following commands for Colab and skip this section if you are using Workbench."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2707b02ef5df"
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
" # Install gdown for downloading example training images.\n",
" ! pip3 install gdown\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bb7adab99e41"
},
"source": [
"### Setup Google Cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs.\n",
"\n",
"1. [Create a service account](https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console) with `Vertex AI User` and `Storage Object Admin` roles for deploying fine tuned model to Vertex AI endpoint."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6c460088b873"
},
"source": [
"Fill following variables for experiments environment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "855d6b96f291"
},
"outputs": [],
"source": [
"# Cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"# The region you want to launch jobs in.\n",
"REGION = \"\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output.\n",
"BUCKET_URI = \"\" # @param {type:\"string\"}\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
"import os\n",
"\n",
"STAGING_BUCKET = os.path.join(BUCKET_URI, \"temporal\")\n",
"EXPERIMENT_BUCKET = os.path.join(BUCKET_URI, \"peft\")\n",
"DATA_BUCKET = os.path.join(EXPERIMENT_BUCKET, \"data\")\n",
"MODEL_BUCKET = os.path.join(EXPERIMENT_BUCKET, \"model\")\n",
"\n",
"# The service account looks like:\n",
"# '@.iam.gserviceaccount.com'\n",
"# Please go to https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console\n",
"# and create service account with `Vertex AI User` and `Storage Object Admin` roles.\n",
"# The service account for deploying fine tuned model.\n",
"SERVICE_ACCOUNT = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e828eb320337"
},
"source": [
"### Initialize Vertex AI API"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "12cd25839741"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=STAGING_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2cc825514deb"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b42bd4fa2b2d"
},
"outputs": [],
"source": [
"# The pre-built training and serving docker images.\n",
"TRAIN_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-peft-train\"\n",
"PREDICTION_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-peft-serve\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c250872074f"
},
"source": [
"### Define common functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "354da31189dc"
},
"outputs": [],
"source": [
"import os\n",
"from datetime import datetime\n",
"\n",
"from google.cloud import aiplatform\n",
"\n",
"\n",
"def get_job_name_with_datetime(prefix: str):\n",
" \"\"\"Gets the job name with date time when triggering training or deployment\n",
" jobs in Vertex AI.\n",
" \"\"\"\n",
" return prefix + datetime.now().strftime(\"_%Y%m%d_%H%M%S\")\n",
"\n",
"\n",
"def deploy_model(\n",
" model_name,\n",
" base_model_id,\n",
" finetuned_lora_model_path,\n",
" service_account,\n",
" task,\n",
" machine_type=\"n1-standard-8\",\n",
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
"):\n",
" \"\"\"Deploys trained models into Vertex AI.\"\"\"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{model_name}-endpoint\")\n",
" serving_env = {\n",
" \"BASE_MODEL_ID\": base_model_id,\n",
" \"FINETUNED_LORA_MODEL_PATH\": finetuned_lora_model_path,\n",
" \"TASK\": task,\n",
" }\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=PREDICTION_DOCKER_URI,\n",
" serving_container_ports=[7080],\n",
" serving_container_predict_route=\"/predictions/peft_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=machine_type,\n",
" accelerator_type=accelerator_type,\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" service_account=service_account,\n",
" )\n",
" return model, endpoint"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e70e3519ff8b"
},
"source": [
"## Casual Language Modeling + PEFT\n",
"\n",
"This section demonstrates how to finetune OpenLLaMA with PEFT LoRA, including [openlm-research/open_llama_3b](https://huggingface.co/openlm-research/open_llama_3b), [openlm-research/open_llama_7b](https://huggingface.co/openlm-research/open_llama_7b), and [openlm-research/open_llama_13b](https://huggingface.co/openlm-research/open_llama_13b)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iWGwJHqI7LMs"
},
"source": [
"### Finetune with LoRA"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5qCrm_kJH5cz"
},
"source": [
"Set the base model id."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "N3UBLiYrM3sU"
},
"outputs": [],
"source": [
"base_model_id = \"openlm-research/open_llama_3b\" # @param [\"openlm-research/open_llama_3b\", \"openlm-research/open_llama_7b\", \"openlm-research/open_llama_13b\"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KKEYoRfiHDVv"
},
"source": [
"Use the Vertex AI SDK to create and run the custom training jobs with Vertex AI Model Garden training images.\n",
"\n",
"This example uses the dataset [Abirate/english_quotes](https://huggingface.co/datasets/Abirate/english_quotes).\n",
"\n",
"In order to make the finetunig efficiently, we enabled quantization (8bits) when loading pretrained models for finetuning LoRA models. The peak GPU memory usages are ~7G, ~10G and ~16G for finetuning LoRA models for [openlm-research/open_llama_3b](https://huggingface.co/openlm-research/open_llama_3b), [openlm-research/open_llama_7b](https://huggingface.co/openlm-research/open_llama_7b), and [openlm-research/open_llama_13b](https://huggingface.co/openlm-research/open_llama_13b) separately with default training parameters and the example dataset. In theory, open_llama_3b and open_llama_7b can be finetuned on 1 V100, and open_llama_13b can be finetuned on 1 A100 (40G). We choose to use 1 A100 (40G) by default to support all these models in this notebook for simplicity."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "65467b361315"
},
"outputs": [],
"source": [
"dataset_name = \"Abirate/english_quotes\" # @param {type:\"string\"}\n",
"\n",
"# Worker pool spec.\n",
"# machine_type = \"n1-standard-8\"\n",
"# accelerator_type = \"NVIDIA_TESLA_V100\"\n",
"machine_type = \"a2-highgpu-1g\"\n",
"accelerator_type = \"NVIDIA_TESLA_A100\"\n",
"replica_count = 1\n",
"accelerator_count = 1\n",
"\n",
"# Setup training job.\n",
"job_name = get_job_name_with_datetime(\"openllama-lora-train\")\n",
"train_job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=job_name,\n",
" container_uri=TRAIN_DOCKER_URI,\n",
")\n",
"output_dir = os.path.join(MODEL_BUCKET, job_name)\n",
"output_dir_gcsfuse = output_dir.replace(\"gs://\", \"/gcs/\")\n",
"\n",
"# Pass training arguments and launch job.\n",
"train_job.run(\n",
" args=[\n",
" \"--task=causal-language-modeling-lora\",\n",
" f\"--pretrained_model_id={base_model_id}\",\n",
" f\"--dataset_name={dataset_name}\",\n",
" f\"--output_dir={output_dir_gcsfuse}\",\n",
" \"--lora_rank=16\",\n",
" \"--lora_alpha=32\",\n",
" \"--lora_dropout=0.05\",\n",
" \"--warmup_steps=10\",\n",
" \"--max_steps=10\",\n",
" \"--learning_rate=2e-4\",\n",
" ],\n",
" replica_count=replica_count,\n",
" machine_type=machine_type,\n",
" accelerator_type=accelerator_type,\n",
" accelerator_count=accelerator_count,\n",
" boot_disk_size_gb=500,\n",
")\n",
"\n",
"print(\"Trained models were saved in: \", output_dir)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jqmCtkGnhDmp"
},
"source": [
"### Run inferences with serving images\n",
"This section uploads the model to Model Registry and deploys it on the Endpoint.\n",
"\n",
"The model deployment step will take ~15 minutes to complete.\n",
"\n",
"The peak GPU memory usages for [openlm-research/open_llama_3b](https://huggingface.co/openlm-research/open_llama_3b), [openlm-research/open_llama_7b](https://huggingface.co/openlm-research/open_llama_7b), and [openlm-research/open_llama_13b](https://huggingface.co/openlm-research/open_llama_13b) with LoRA weights are ~5.3G, ~8.7G and ~15.2G separately with the default settings. We use V100 in deployments for simplicity."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bf55e38815dc"
},
"outputs": [],
"source": [
"model, endpoint = deploy_model(\n",
" model_name=get_job_name_with_datetime(prefix=\"openllama-peft-serve\"),\n",
" base_model_id=base_model_id,\n",
" finetuned_lora_model_path=output_dir,\n",
" service_account=SERVICE_ACCOUNT,\n",
" task=\"causal-language-modeling-lora\",\n",
")\n",
"print(\"endpoint_name:\", endpoint.name)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint.\n",
"\n",
"Once deployment succeeds, you can send requests to the endpoint with text prompts."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4ab04da3ec9a"
},
"outputs": [],
"source": [
"# # Loads an existing endpoint as below.\n",
"# endpoint_name = endpoint.name\n",
"# aip_endpoint_name = (\n",
"# f\"projects/{PROJECT_ID}/locations/{REGION}/endpoints/{endpoint_name}\"\n",
"# )\n",
"# endpoint = aiplatform.Endpoint(aip_endpoint_name)\n",
"instances = [\n",
" {\"prompt\": \"Hi, Google.\"},\n",
"]\n",
"response = endpoint.predict(instances=instances)\n",
"\n",
"for prediction in response.predictions[0]:\n",
" print(prediction[\"generated_text\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "af21a3cff1e0"
},
"source": [
"### Clean up resources"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "911406c1561e"
},
"outputs": [],
"source": [
"# Delete custom train jobs.\n",
"train_job.delete()\n",
"\n",
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "W2USaHtQbE-l"
},
"source": [
"## Instruct + PEFT\n",
"\n",
"This section demonstrates how to finetune Falcon-instruct with PEFT LoRA, including [tiiuae/falcon-7b-instruct](https://huggingface.co/tiiuae/falcon-7b-instruct), and [tiiuae/falcon-40b-instruct](https://huggingface.co/tiiuae/falcon-40b-instruct)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PwluMqvYbLu9"
},
"source": [
"### Finetune with LoRA"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ap1pQd-ckAAb"
},
"source": [
"Set the base model id."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vVTfG2bpbR90"
},
"outputs": [],
"source": [
"base_model_id = \"tiiuae/falcon-7b-instruct\" # @param [\"tiiuae/falcon-7b-instruct\", \"tiiuae/falcon-40b-instruct\"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iJe_us8mkZEV"
},
"source": [
"Use the Vertex AI SDK to create and run the custom training jobs with Vertex AI Model Garden training images.\n",
"\n",
"This example uses the dataset [timdettmers/openassistant-guanaco](https://huggingface.co/datasets/timdettmers/openassistant-guanaco).\n",
"\n",
"The peak GPU memory usages are ~11G and ~34G for finetuning LoRA models for [tiiuae/falcon-7b-instruct](https://huggingface.co/tiiuae/falcon-7b-instruct), and [tiiuae/falcon-40b-instruct](https://huggingface.co/tiiuae/falcon-40b-instruct) separately with default training parameters and the example dataset. In theory, falcon-7b-instruct can be finetuned on 1 P100/V100, and falcon-40b-instruct can be finetuned on 1 A100 (40G). We choose to use 1 A100 (40G) by default to support all these models in this notebook for simplicity."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "-i4M7mWPbV8s"
},
"outputs": [],
"source": [
"dataset_name = \"timdettmers/openassistant-guanaco\" # @param {type:\"string\"}\n",
"\n",
"# Worker pool spec.\n",
"machine_type = \"a2-highgpu-1g\"\n",
"accelerator_type = \"NVIDIA_TESLA_A100\"\n",
"replica_count = 1\n",
"accelerator_count = 1\n",
"\n",
"# Setup training job.\n",
"job_name = get_job_name_with_datetime(\"falcon-instruct-lora-train\")\n",
"train_job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=job_name,\n",
" container_uri=TRAIN_DOCKER_URI,\n",
")\n",
"output_dir = os.path.join(MODEL_BUCKET, job_name)\n",
"output_dir_gcsfuse = output_dir.replace(\"gs://\", \"/gcs/\")\n",
"\n",
"# Pass training arguments and launch job.\n",
"max_steps = 10\n",
"train_job.run(\n",
" args=[\n",
" \"--task=instruct-lora\",\n",
" f\"--pretrained_model_id={base_model_id}\",\n",
" f\"--dataset_name={dataset_name}\",\n",
" f\"--output_dir={output_dir_gcsfuse}\",\n",
" \"--lora_rank=64\",\n",
" \"--lora_alpha=16\",\n",
" \"--lora_dropout=0.1\",\n",
" \"--warmup_ratio=0.03\",\n",
" f\"--max_steps={max_steps}\",\n",
" \"--max_seq_length=512\",\n",
" \"--learning_rate=2e-4\",\n",
" ],\n",
" replica_count=replica_count,\n",
" machine_type=machine_type,\n",
" accelerator_type=accelerator_type,\n",
" accelerator_count=accelerator_count,\n",
" boot_disk_size_gb=500,\n",
")\n",
"\n",
"print(\"Trained models were saved in: \", output_dir)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oCgivsdllZ1x"
},
"source": [
"### Run inferences with serving images"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_lNIFvielcyV"
},
"source": [
"This section uploads the model to Model Registry and deploys it on the Endpoint.\n",
"\n",
"The model deployment step will take ~15 minutes to complete.\n",
"\n",
"The peak GPU memory usages for [tiiuae/falcon-7b-instruct](https://huggingface.co/tiiuae/falcon-7b-instruct), and [tiiuae/falcon-40b-instruct](https://huggingface.co/tiiuae/falcon-40b-instruct) with LoRA weights are ~15.5G and ~38.2G separately with the default settings. We use V100 in deployments for simplicity."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "inrBXzoxk53t"
},
"outputs": [],
"source": [
"# # If deploy finetuned falcon-40b-instruct models, please set\n",
"# machine_type = \"a2-highgpu-1g\",\n",
"# accelerator_type = \"NVIDIA_TESLA_A100\"\n",
"machine_type = \"n1-standard-8\",\n",
"accelerator_type = \"NVIDIA_TESLA_V100\"\n",
"\n",
"accelerator_type =\n",
"model, endpoint = deploy_model(\n",
" model_name=get_job_name_with_datetime(prefix=\"falcon-peft-serve\"),\n",
" base_model_id=base_model_id,\n",
" finetuned_lora_model_path=os.path.join(output_dir, \"checkpoint-\"+str(max_steps)),\n",
" service_account=SERVICE_ACCOUNT,\n",
" task=\"instruct-lora\",\n",
" machine_type=machine_type,\n",
" accelerator_type=accelerator_type,\n",
")\n",
"print(\"endpoint_name: \", endpoint.name)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_dmO3XooliAs"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed after the above model deployment step succeeds and before you run the next step below. Otherwise you might see a ServiceUnavailable: 503 502:Bad Gateway error when you send requests to the endpoint.\n",
"\n",
"Once deployment succeeds, you can send requests to the endpoint with text prompts.\n",
"\n",
"Example:\n",
"\n",
"```\n",
"Human: What is a car?\n",
"Assistant: A car, or a motor car, is a road-connected human-transportation system used to move people or goods from one place to another. The term also encompasses a wide range of vehicles, including motorboats, trains, and aircrafts. Cars typically have four wheels, a cabin for passengers, and an engine or motor. They have been around since the early 19th century and are now one of the most popular forms of transportation, used for daily commuting, shopping, and other purposes.\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "JrKsrffGl14T"
},
"outputs": [],
"source": [
"# # Loads an existing endpoint as below.\n",
"# endpoint_name = endpoint.name\n",
"# aip_endpoint_name = (\n",
"# f\"projects/{PROJECT_ID}/locations/{REGION}/endpoints/{endpoint_name}\"\n",
"# )\n",
"# endpoint = aiplatform.Endpoint(aip_endpoint_name)\n",
"instances = [\n",
" {\"prompt\": \"What is a car?\"},\n",
"]\n",
"response = endpoint.predict(instances=instances)\n",
"\n",
"for prediction in response.predictions[0]:\n",
" print(prediction[\"generated_text\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uk-t69nFl9rr"
},
"source": [
"### Clean up resources"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CcIX2WAJmAI7"
},
"outputs": [],
"source": [
"# Delete custom train jobs.\n",
"train_job.delete()\n",
"\n",
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "og_s64QVmJDb"
},
"source": [
"## Sequence Classification + PEFT\n",
"\n",
"This section demonstrates how to finetune sequence classification models with PEFT LoRA, including [bert-base-uncased](https://huggingface.co/bert-base-uncased), [RoBERTa-large](https://huggingface.co/roberta-large), and [XLM-RoBERTa-large](https://huggingface.co/xlm-roberta-large)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QqJcvCb2mn8l"
},
"source": [
"### Finetune with PEFT"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c0E7dfqloeBB"
},
"source": [
"Set the base model id."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eru79ot6mtNG"
},
"outputs": [],
"source": [
"base_model_id = \"xlm-roberta-large\" # @param [\"bert-base-uncased\", \"roberta-large\", \"xlm-roberta-large\"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "y9n-qheaotS9"
},
"source": [
"Use the Vertex AI SDK to create and run the custom training jobs with Vertex AI Model Garden training images.\n",
"\n",
"This example uses the dataset [glue](https://huggingface.co/datasets/glue).\n",
"\n",
"The peak GPU memory usages are ~8.8G and ~15G for finetuning LoRA models for [RoBERTa-large](https://huggingface.co/roberta-large), and [XLM-RoBERTa-large](https://huggingface.co/xlm-roberta-large) separately with default training parameters and the example dataset. In theory, RoBERTa-large can be finetuned on 1 P100/V100, and XLM-RoBERTa-large can be finetuned on 1 A100 (40G). We choose to use 1 A100 (40G) by default to support all these models in this notebook for simplicity."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OHeSYEKinfP3"
},
"outputs": [],
"source": [
"dataset_name = \"glue\" # @param {type:\"string\"}\n",
"\n",
"# Worker pool spec.\n",
"# # Please switch to A100 or other powerful machines if you run out of memory.\n",
"# machine_type = \"a2-highgpu-1g\"\n",
"# accelerator_type = \"NVIDIA_TESLA_A100\"\n",
"machine_type = \"n1-standard-8\"\n",
"accelerator_type = \"NVIDIA_TESLA_V100\"\n",
"replica_count = 1\n",
"accelerator_count = 1\n",
"\n",
"# Setup training job.\n",
"job_name = get_job_name_with_datetime(os.path.basename(base_model_id) + \"-lora-train\")\n",
"train_job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=job_name,\n",
" container_uri=TRAIN_DOCKER_URI,\n",
")\n",
"output_dir = os.path.join(MODEL_BUCKET, job_name)\n",
"output_dir_gcsfuse = output_dir.replace(\"gs://\", \"/gcs/\")\n",
"\n",
"# Pass training arguments and launch job.\n",
"train_job.run(\n",
" args=[\n",
" \"--task=sequence-classification-lora\",\n",
" f\"--pretrained_model_id={base_model_id}\",\n",
" f\"--dataset_name={dataset_name}\",\n",
" f\"--output_dir={output_dir_gcsfuse}\",\n",
" \"--lora_rank=8\",\n",
" \"--lora_alpha=16\",\n",
" \"--lora_dropout=0.1\",\n",
" \"--num_epochs=20\",\n",
" \"--batch_size=32\",\n",
" \"--learning_rate=3e-4\",\n",
" ],\n",
" replica_count=replica_count,\n",
" machine_type=machine_type,\n",
" accelerator_type=accelerator_type,\n",
" accelerator_count=accelerator_count,\n",
" boot_disk_size_gb=500,\n",
")\n",
"\n",
"print(\"Trained models were saved in: \", output_dir)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kJuHaBCqoacg"
},
"source": [
"### Run inferences with serving images"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jw1GFXydoft0"
},
"source": [
"This section uploads the model to Model Registry and deploys it on the Endpoint.\n",
"\n",
"The model deployment step will take ~15 minutes to complete.\n",
"\n",
"The peak GPU memory usages for [RoBERTa-large](https://huggingface.co/roberta-large), and [XLM-RoBERTa-large](https://huggingface.co/xlm-roberta-large) with LoRA weights are ~2G and ~2.4G separately with the default settings. We use V100 in deployments for simplicity."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "A5j0a3AZoj3h"
},
"outputs": [],
"source": [
"model, endpoint = deploy_model(\n",
" model_name=get_job_name_with_datetime(prefix=\"sequence-classification-peft-serve\"),\n",
" base_model_id=base_model_id,\n",
" finetuned_lora_model_path=output_dir,\n",
" service_account=SERVICE_ACCOUNT,\n",
" task=\"sequence-classification-lora\",\n",
")\n",
"print(\"endpoint_name:\", endpoint.name)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6dR3-Hc7oqu-"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed after the above model deployment step succeeds and before you run the next step below. Otherwise you might see a ServiceUnavailable: 503 502:Bad Gateway error when you send requests to the endpoint.\n",
"\n",
"Once deployment succeeds, you can send requests to the endpoint with text prompts."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xAmULPegoyXl"
},
"outputs": [],
"source": [
"# # Loads an existing endpoint as below.\n",
"# endpoint_name = endpoint.name\n",
"# aip_endpoint_name = (\n",
"# f\"projects/{PROJECT_ID}/locations/{REGION}/endpoints/{endpoint_name}\"\n",
"# )\n",
"# endpoint = aiplatform.Endpoint(aip_endpoint_name)\n",
"instances = [\n",
" {\"prompt\": \"The cat sat on the mat.\"},\n",
"]\n",
"response = endpoint.predict(instances=instances)\n",
"labels = [int(item) for item in response.predictions]\n",
"print(labels)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1Vg_b46Jo6C1"
},
"source": [
"### Clean up resources"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vNiTDL_VpAlp"
},
"outputs": [],
"source": [
"# Delete custom train jobs.\n",
"train_job.delete()\n",
"\n",
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_pytorch_peft.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,450 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6ad30fe2-1fc1-47e3-8a9f-624170b5aae6"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cYYdTBQoKeCP"
},
"source": [
" # Vertex AI Model Garden - Segment Anything Model (SAM) Serving on Vertex AI\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_sam.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_sam.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_sam.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 CPU notebook is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JbmPgTp2LRCY"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates using the [huggingface/transformers](https://github.com/huggingface/transformers) framework to serve Segment Anything Model (SAM) models and deploy them for online prediction on Vertex AI.\n",
"\n",
"Following the notebook you will conduct experiments using the pre-built docker image on Vertex AI.\n",
"\n",
"- With the pre-built docker images, you can **deploy** models for the following tasks:\n",
" - Mask Generation\n",
"\n",
"### Objective\n",
"\n",
"- Upload the model to [Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model on [Endpoint](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for image captioning.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "78f72e0a-52e5-4de5-ac0f-2171b3493825"
},
"source": [
"## Setup environment\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "G__krby2Mqmh"
},
"source": [
"### Colab only"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RS5_6QVFMyc-"
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Li2aj1n9NDYl"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f6c1bc20-3495-448a-b242-01930ba8153c"
},
"source": [
"### Setup Google Cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5b1f2c08-c84e-4158-a976-e6b59d1055ca"
},
"source": [
"It's highly recommended to run this notebook on [Vertex AI workbench](https://cloud.google.com/vertex-ai-workbench)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4fc1fc14-2d77-4bf7-8f6d-c1afc10c848a"
},
"source": [
"If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk) and [gsutil](https://cloud.google.com/storage/docs/gsutil_install)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e02b9811-b730-4573-83fa-9d47f2ce0436"
},
"source": [
"####Fill following variables for experiments environment:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7c2ce2fa-5a9b-40f6-b99d-6c1325775b36"
},
"outputs": [],
"source": [
"# Cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"# The region you want to launch jobs in.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fwgeVkFXOS64"
},
"source": [
"*Initialize* Vertex AI API:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MxqnJMahPK8r"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tSjMVyG8PYS-"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "H05BzPO5Pcnh"
},
"outputs": [],
"source": [
"# The pre-built serving docker image.\n",
"# The model artifacts are embedded within the container, except for model weights which will be downloaded during deployment.\n",
"SERVE_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/sam-serve\"\n",
"\n",
"# The serving port.\n",
"SERVE_PORT = 7080\n",
"\n",
"# The serving route.\n",
"SERVE_ROUTE = \"/predictions/sam_serving\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "82058975-23b5-4b97-9e14-dd9a29c578ed"
},
"source": [
"### Define common utility functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a78f988d-e5e2-4a57-ba0f-569e970514c0"
},
"outputs": [],
"source": [
"import base64\n",
"from io import BytesIO\n",
"\n",
"import matplotlib.patches as patches\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pycocotools.mask as mask_util\n",
"import requests\n",
"from PIL import Image\n",
"\n",
"\n",
"def download_image(url):\n",
" response = requests.get(url)\n",
" return Image.open(BytesIO(response.content)).convert(\"RGB\")\n",
"\n",
"\n",
"def image_to_base64(image):\n",
" buffer = BytesIO()\n",
" image.save(buffer, format=\"JPEG\")\n",
" image_str = base64.b64encode(buffer.getvalue()).decode(\"utf-8\")\n",
" return image_str\n",
"\n",
"\n",
"def base64_to_image(image_str):\n",
" image = Image.open(BytesIO(base64.b64decode(image_str)))\n",
" return image\n",
"\n",
"\n",
"def image_grid(imgs, rows=2, cols=2):\n",
" w, h = imgs[0].size\n",
" grid = Image.new(\"RGB\", size=(cols * w, rows * h))\n",
" for i, img in enumerate(imgs):\n",
" grid.paste(img, box=(i % cols * w, i // cols * h))\n",
" return grid\n",
"\n",
"\n",
"def draw_image_with_boxes(image, boxes):\n",
" fig, ax = plt.subplots()\n",
" ax.imshow(image)\n",
" for box in boxes:\n",
" x, y = box[\"xmin\"], box[\"ymin\"]\n",
" width, height = box[\"xmax\"] - x, box[\"ymax\"] - y\n",
" rect = patches.Rectangle(\n",
" (x, y), width, height, linewidth=2, edgecolor=\"yellow\", facecolor=\"none\"\n",
" )\n",
" ax.add_patch(rect)\n",
" plt.axis(\"off\")\n",
" plt.show()\n",
"\n",
"\n",
"def decode_rle_masks(pred_masks_rle):\n",
" return np.stack([mask_util.decode(rle) for rle in pred_masks_rle])\n",
"\n",
"\n",
"def show_mask(mask, ax, random_color=False):\n",
" if random_color:\n",
" color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n",
" else:\n",
" color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])\n",
" h, w = mask.shape[-2:]\n",
" mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n",
" ax.imshow(mask_image)\n",
"\n",
"\n",
"def show_predictions(preds):\n",
" # create figure\n",
" fig = plt.figure(figsize=(10, 7))\n",
"\n",
" fig.add_subplot(1, 2, 1)\n",
" plt.imshow(np.array(image1))\n",
" ax = plt.gca()\n",
" masks = decode_rle_masks(preds[0][\"masks_rle\"])\n",
" for mask in masks:\n",
" show_mask(mask, ax=ax, random_color=True)\n",
" plt.axis(\"off\")\n",
"\n",
" fig.add_subplot(1, 2, 2)\n",
" plt.imshow(np.array(image2))\n",
" ax = plt.gca()\n",
" masks = decode_rle_masks(preds[1][\"masks_rle\"])\n",
" for mask in masks:\n",
" show_mask(mask, ax=ax, random_color=True)\n",
" plt.axis(\"off\")\n",
" plt.show()\n",
"\n",
"\n",
"def deploy_model(task, model_id):\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{task}-endpoint\")\n",
" serving_env = {\n",
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" model = aiplatform.Model.upload(\n",
" display_name=task,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
" serving_container_ports=[SERVE_PORT],\n",
" serving_container_predict_route=SERVE_ROUTE,\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=\"n1-standard-8\",\n",
" accelerator_type=\"NVIDIA_TESLA_T4\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" )\n",
" return endpoint, model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "242fc8cf-5a0e-483b-8c9d-77a474cedc4b"
},
"source": [
"## Mask Generation with Vertex AI Endpoint"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f3f9ed94d69c"
},
"outputs": [],
"source": [
"endpoint, model = deploy_model(\n",
" task=\"mask-generation\", model_id=\"facebook/sam-vit-large\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d6e51c57-b5e2-4ae7-888a-5391cceee5fb"
},
"outputs": [],
"source": [
"image1 = download_image(\"http://images.cocodataset.org/val2017/000000039769.jpg\")\n",
"image2 = download_image(\"http://images.cocodataset.org/val2017/000000000285.jpg\")\n",
"grid = image_grid([image1, image2], 1, 2)\n",
"display(grid)\n",
"\n",
"instances = [\n",
" {\"image\": image_to_base64(image1)},\n",
" {\"image\": image_to_base64(image2)},\n",
"]\n",
"preds = endpoint.predict(instances=instances).predictions\n",
"show_predictions(preds)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5UdquXMWR1E4"
},
"source": [
"## Clean up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "TGTWIJK8R136"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_pytorch_sam.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -24,6 +24,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "99c1c3fc2ca5"
@@ -48,12 +49,13 @@
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 CPU notebook is recommended)\n",
" (a Python-3 GPU notebook with preinstalled HuggingFace/transformer libraries is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "3de7470326a2"
@@ -61,13 +63,14 @@
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates finetuning [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5) with [Dreambooth](https://huggingface.co/docs/diffusers/training/dreambooth) and deploying it on Vertex AI for online prediction.\n",
"This notebook demonstrates running local inference for [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5) on either [Colab](https://colab.research.google.com) or [Vertex AI Workbench](https://cloud.google.com/vertex-ai-workbench). This notebook also demonstrates finetuning runwayml/stable-diffusion-v1-5 with [Dreambooth](https://huggingface.co/docs/diffusers/training/dreambooth) and deploying it on Vertex AI for online prediction.\n",
"\n",
"### Objective\n",
"\n",
"- Run local predictions for text-to-image and text-guided-image-to-image with serving dockers.\n",
"- Finetune the stable-diffusion-v1.5 model with [Dreambooth](https://huggingface.co/docs/diffusers/training/dreambooth).\n",
"- Upload the model to [Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model on [Endpoint](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Upload the model to [Vertex AI Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model to a [Vertex AI Endpoint resource](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for text-to-image and text-guided-image-to-image.\n",
"\n",
"### Costs\n",
@@ -81,23 +84,36 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "264c07757582"
},
"source": [
"## Setup environment\n",
"## Before you begin\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ioensNKM8ned"
},
"source": [
"### Setup notebook"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "d73ffa0c0b83"
},
"source": [
"### Colab only"
"#### Colab only\n",
"Run the following commands for Colab and skip this section if you are using Workbench."
]
},
{
@@ -108,69 +124,50 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
" ! pip3 install --upgrade pip\n",
" ! pip3 install torchvision==0.14.1\n",
" ! pip3 install transformers==4.27.1\n",
" ! pip3 install diffusers==0.15.1\n",
" ! pip3 install datasets==2.9.0\n",
" ! pip3 install accelerate==0.18.0\n",
" ! pip3 install triton==2.0.0.dev20221120\n",
" ! pip3 install xformers==0.0.16\n",
" # Install gdown for downloading example training images.\n",
" ! pip3 install gdown\n",
" # Remove wrong cublas version.\n",
" ! pip3 uninstall nvidia_cublas_cu11 --yes\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "fb671e75ca7b"
},
"source": [
"### Install dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dc8ee367fb42"
},
"outputs": [],
"source": [
"# Install gdown for downloading example training images.\n",
"!pip install gdown\n",
"# Install gsutil for downloading/uploading data from/to Cloud Storage buckets.\n",
"!pip install gsutil"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5244aac3d929"
},
"source": [
"Restart the notebook kernel after installs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "567212ff53a6"
},
"outputs": [],
"source": [
"import IPython\n",
"\n",
"app = IPython.Application.instance()\n",
"app.kernel.do_shutdown(True)"
"#### Workbench only\n",
"1. Follow [this link](https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_inpainting.ipynb) to deploy the notebook to a Vertex AI Workbench Instance.\n",
"2. Select `Create a new Notebook`.\n",
"3. Click `Advanced Options`.\n",
"4. In the **Environment** tab, select `Debian 10` for **Operating System** and select `Custom Container` for **Environment**.\n",
"5. Set `Docker container image` to `us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/transformers-notebook`.\n",
"6. Under **Machine configuration**, select 1 `T4` GPU and select `Install NVIDIA GPU driver automatically for me`.\n",
"7. Click `Create` to create the Vertex AI Workbench instance."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "bb7adab99e41"
@@ -184,10 +181,13 @@
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs."
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs.\n",
"\n",
"1. [Create a service account](https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console) with `Vertex AI User` and `Storage Object Admin` roles for deploying fine tuned model to Vertex AI endpoint."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "6c460088b873"
@@ -211,10 +211,14 @@
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
"GCS_BUCKET = \"\" # @param {type:\"string\"}\n",
"\n",
"# The service account for deploying fine tuned model.\n",
"SERVICE_ACCOUNT = \"\" # @param {type:\"string\"}"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "e828eb320337"
@@ -237,6 +241,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "2cc825514deb"
@@ -261,6 +266,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "0c250872074f"
@@ -278,12 +284,13 @@
"outputs": [],
"source": [
"import base64\n",
"import glob\n",
"import os\n",
"from datetime import datetime\n",
"from io import BytesIO\n",
"\n",
"import requests\n",
"from google.cloud import aiplatform\n",
"from google.cloud import aiplatform, storage\n",
"from PIL import Image\n",
"\n",
"\n",
@@ -326,8 +333,6 @@
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" # If the model_id is a GCS path, use artifact_uri to pass it to serving docker.\n",
" artifact_uri = model_id if model_id.startswith(\"gs://\") else None\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
@@ -335,7 +340,6 @@
" serving_container_predict_route=\"/predictions/diffusers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" artifact_uri=artifact_uri,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
@@ -343,11 +347,122 @@
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" service_account=SERVICE_ACCOUNT,\n",
" )\n",
" return model, endpoint"
" return model, endpoint\n",
"\n",
"\n",
"def get_bucket_and_blob_name(filepath):\n",
" # The gcs path is of the form gs://<bucket-name>/<blob-name>\n",
" gs_suffix = filepath.split(\"gs://\", 1)[1]\n",
" return tuple(gs_suffix.split(\"/\", 1))\n",
"\n",
"\n",
"def upload_local_dir_to_gcs(local_dir_path, gcs_dir_path):\n",
" \"\"\"Uploads files in a local directory to a GCS directory.\"\"\"\n",
" client = storage.Client()\n",
" bucket_name = gcs_dir_path.split(\"/\")[2]\n",
" bucket = client.get_bucket(bucket_name)\n",
" for local_file in glob.glob(local_dir_path + \"/**\"):\n",
" if not os.path.isfile(local_file):\n",
" continue\n",
" filename = local_file[1 + len(local_dir_path) :]\n",
" gcs_file_path = os.path.join(gcs_dir_path, filename)\n",
" _, blob_name = get_bucket_and_blob_name(gcs_file_path)\n",
" blob = bucket.blob(blob_name)\n",
" blob.upload_from_filename(local_file)\n",
" print(\"Copied {} to {}.\".format(local_file, gcs_file_path))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "e8a42fa49305"
},
"source": [
"## Run inferences locally"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "1d5ebc91c786"
},
"source": [
"### Text-to-image"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d39ed8c97cc5"
},
"outputs": [],
"source": [
"import torch\n",
"from diffusers import StableDiffusionPipeline\n",
"\n",
"model_id = \"runwayml/stable-diffusion-v1-5\"\n",
"pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)\n",
"pipe = pipe.to(\"cuda\")\n",
"\n",
"prompt = \"a photo of an astronaut riding a horse on mars\"\n",
"\n",
"results = pipe(prompt=prompt, guidance_scale=7.5)\n",
"images = results.images\n",
"nsfw_detects = results.nsfw_content_detected\n",
"display(images[0])\n",
"print(nsfw_detects[0])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "5aed5ed7b6f6"
},
"source": [
"### Text-guided image-to-image"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "faadabb7728f"
},
"outputs": [],
"source": [
"import torch\n",
"from diffusers import StableDiffusionImg2ImgPipeline\n",
"\n",
"device = \"cuda\"\n",
"model_id_or_path = \"runwayml/stable-diffusion-v1-5\"\n",
"pipe = StableDiffusionImg2ImgPipeline.from_pretrained(\n",
" model_id_or_path, torch_dtype=torch.float16\n",
")\n",
"pipe = pipe.to(device)\n",
"\n",
"url = \"https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg\"\n",
"\n",
"response = requests.get(url)\n",
"init_image = Image.open(BytesIO(response.content)).convert(\"RGB\")\n",
"init_image = init_image.resize((768, 512))\n",
"\n",
"prompt = \"A fantasy landscape, trending on artstation\"\n",
"\n",
"results = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5)\n",
"images = results.images\n",
"nsfw_detects = results.nsfw_content_detected\n",
"display(images[0])\n",
"print(nsfw_detects[0])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "e70e3519ff8b"
@@ -357,6 +472,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "0dc65d8f0689"
@@ -381,11 +497,12 @@
"!gdown --folder https://drive.google.com/drive/folders/1BO_dyz-p65qhBRRMRA4TbZ8qW4rB99JZ\n",
"\n",
"# Upload data to Cloud Storage bucket.\n",
"!gsutil -m cp -r dog/* gs://{GCS_BUCKET}/dreambooth/dog/\n",
"!gsutil -m cp -r dog/* gs://{GCS_BUCKET}/dreambooth/dog_class/"
"upload_local_dir_to_gcs(\"dog\", f\"gs://{GCS_BUCKET}/dreambooth/dog\")\n",
"upload_local_dir_to_gcs(\"dog\", f\"gs://{GCS_BUCKET}/dreambooth/dog_class\")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "969cfeb79317"
@@ -455,6 +572,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "bf7f82732e61"
@@ -464,6 +582,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "1cc26e68d7b0"
@@ -475,6 +594,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "cd7b56421392"
@@ -484,6 +604,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "6d331b1ea337"
@@ -504,12 +625,22 @@
},
"outputs": [],
"source": [
"# Set the model_id to a GCS path, like \"gs://GCS_BUCKET/dreambooth/output\", to load the dreambooth finetuned model above.\n",
"# Set the model_id to \"runwayml/stable-diffusion-v1-5\" to load the OSS pre-trained model.\n",
"model, endpoint = deploy_model(\n",
" model_id=\"runwayml/stable-diffusion-v1-5\", task=\"text-to-image\"\n",
" model_id=f\"gs://{GCS_BUCKET}/dreambooth/output\", task=\"text-to-image\"\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -530,6 +661,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "af21a3cff1e0"
@@ -554,6 +686,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "c1e51f764a60"
@@ -563,6 +696,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "fa686a54047c"
@@ -585,6 +719,16 @@
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "SsjYFLvNymc0"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -609,6 +753,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ed3795d474b9"
@@ -0,0 +1,770 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7d9bbf86da5e"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "99c1c3fc2ca5"
},
"source": [
"# Vertex AI Model Garden - Stable Diffusion V2.1\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_2_1.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_2_1.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_2_1.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 GPU notebook with preinstalled HuggingFace/transformer libraries is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3de7470326a2"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates running local inference for [stabilityai/stable-diffusion-2-1](https://huggingface.co/stabilityai/stable-diffusion-2-1) on either [Colab](https://colab.research.google.com) or [Vertex AI Workbench](https://cloud.google.com/vertex-ai-workbench). This notebook also demonstrates finetuning stabilityai/stable-diffusion-2-1 with [Dreambooth](https://huggingface.co/docs/diffusers/training/dreambooth) and deploying it on Vertex AI for online prediction.\n",
"\n",
"### Objective\n",
"\n",
"- Run local predictions for text-to-image and text-guided-image-to-image with serving dockers.\n",
"- Finetune the stabilityai/stable-diffusion-2-1 model with [Dreambooth](https://huggingface.co/docs/diffusers/training/dreambooth).\n",
"- Upload the model to [Vertex AI Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model to a [Vertex AI Endpoint resource](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for text-to-image and text-guided-image-to-image.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "264c07757582"
},
"source": [
"## Before you begin\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ioensNKM8ned"
},
"source": [
"### Setup notebook"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d73ffa0c0b83"
},
"source": [
"#### Colab only\n",
"Run the following commands for Colab and skip this section if you are using Workbench."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2707b02ef5df"
},
"outputs": [],
"source": [
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
" ! pip3 install --upgrade pip\n",
" ! pip3 install torchvision==0.14.1\n",
" ! pip3 install transformers==4.27.1\n",
" ! pip3 install diffusers==0.15.1\n",
" ! pip3 install datasets==2.9.0\n",
" ! pip3 install accelerate==0.18.0\n",
" ! pip3 install triton==2.0.0.dev20221120\n",
" ! pip3 install xformers==0.0.16\n",
" # Install gdown for downloading example training images.\n",
" ! pip3 install gdown\n",
" # Remove wrong cublas version.\n",
" ! pip3 uninstall nvidia_cublas_cu11 --yes\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fb671e75ca7b"
},
"source": [
"#### Workbench only\n",
"1. Follow [this link](https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_inpainting.ipynb) to deploy the notebook to a Vertex AI Workbench Instance.\n",
"2. Select `Create a new Notebook`.\n",
"3. Click `Advanced Options`.\n",
"4. In the **Environment** tab, select `Debian 10` for **Operating System** and select `Custom Container` for **Environment**.\n",
"5. Set `Docker container image` to `us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/transformers-notebook`.\n",
"6. Under **Machine configuration**, select 1 `T4` GPU and select `Install NVIDIA GPU driver automatically for me`.\n",
"7. Click `Create` to create the Vertex AI Workbench instance."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bb7adab99e41"
},
"source": [
"### Setup Google Cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs.\n",
"\n",
"1. [Create a service account](https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console) with `Vertex AI User` and `Storage Object Admin` roles for deploying fine tuned model to Vertex AI endpoint."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6c460088b873"
},
"source": [
"Fill following variables for experiments environment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "855d6b96f291"
},
"outputs": [],
"source": [
"# Cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"# The region you want to launch jobs in.\n",
"REGION = \"\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}\n",
"\n",
"# The service account for deploying fine tuned model.\n",
"SERVICE_ACCOUNT = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e828eb320337"
},
"source": [
"Initialize Vertex-AI API:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "12cd25839741"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2cc825514deb"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b42bd4fa2b2d"
},
"outputs": [],
"source": [
"# The pre-built training docker image. It contains training scripts and models.\n",
"TRAIN_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-diffusers-train:latest\"\n",
"\n",
"# The pre-built serving docker image. It contains serving scripts and models.\n",
"SERVE_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-diffusers-serve\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c250872074f"
},
"source": [
"### Define common functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "354da31189dc"
},
"outputs": [],
"source": [
"import base64\n",
"import glob\n",
"import os\n",
"from datetime import datetime\n",
"from io import BytesIO\n",
"\n",
"import requests\n",
"from google.cloud import aiplatform, storage\n",
"from PIL import Image\n",
"\n",
"\n",
"def create_job_name(prefix):\n",
" user = os.environ.get(\"USER\")\n",
" now = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
" job_name = f\"{prefix}-{user}-{now}\"\n",
" return job_name\n",
"\n",
"\n",
"def download_image(url):\n",
" response = requests.get(url)\n",
" return Image.open(BytesIO(response.content))\n",
"\n",
"\n",
"def image_to_base64(image, format=\"JPEG\"):\n",
" buffer = BytesIO()\n",
" image.save(buffer, format=format)\n",
" image_str = base64.b64encode(buffer.getvalue()).decode(\"utf-8\")\n",
" return image_str\n",
"\n",
"\n",
"def base64_to_image(image_str):\n",
" image = Image.open(BytesIO(base64.b64decode(image_str)))\n",
" return image\n",
"\n",
"\n",
"def image_grid(imgs, rows=2, cols=2):\n",
" w, h = imgs[0].size\n",
" grid = Image.new(\"RGB\", size=(cols * w, rows * h))\n",
" for i, img in enumerate(imgs):\n",
" grid.paste(img, box=(i % cols * w, i // cols * h))\n",
" return grid\n",
"\n",
"\n",
"def deploy_model(model_id, task):\n",
" model_name = \"stable-diffusion-v2\"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{model_name}-{task}-endpoint\")\n",
" serving_env = {\n",
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
" serving_container_ports=[7080],\n",
" serving_container_predict_route=\"/predictions/diffusers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=\"n1-standard-8\",\n",
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" service_account=SERVICE_ACCOUNT,\n",
" )\n",
" return model, endpoint\n",
"\n",
"\n",
"def get_bucket_and_blob_name(filepath):\n",
" # The gcs path is of the form gs://<bucket-name>/<blob-name>\n",
" gs_suffix = filepath.split(\"gs://\", 1)[1]\n",
" return tuple(gs_suffix.split(\"/\", 1))\n",
"\n",
"\n",
"def upload_local_dir_to_gcs(local_dir_path, gcs_dir_path):\n",
" \"\"\"Uploads files in a local directory to a GCS directory.\"\"\"\n",
" client = storage.Client()\n",
" bucket_name = gcs_dir_path.split(\"/\")[2]\n",
" bucket = client.get_bucket(bucket_name)\n",
" for local_file in glob.glob(local_dir_path + \"/**\"):\n",
" if not os.path.isfile(local_file):\n",
" continue\n",
" filename = local_file[1 + len(local_dir_path) :]\n",
" gcs_file_path = os.path.join(gcs_dir_path, filename)\n",
" _, blob_name = get_bucket_and_blob_name(gcs_file_path)\n",
" blob = bucket.blob(blob_name)\n",
" blob.upload_from_filename(local_file)\n",
" print(\"Copied {} to {}.\".format(local_file, gcs_file_path))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e8a42fa49305"
},
"source": [
"## Run inferences locally"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1d5ebc91c786"
},
"source": [
"### Text-to-image"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d39ed8c97cc5"
},
"outputs": [],
"source": [
"import torch\n",
"from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline\n",
"\n",
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"model_id = \"stabilityai/stable-diffusion-2-1\"\n",
"pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)\n",
"pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)\n",
"pipe = pipe.to(device)\n",
"pipe.enable_attention_slicing()\n",
"\n",
"prompt = \"\"\"\n",
" a picture of the universe, showing sea of stars, Nebula and Supernova\n",
" elegant, detailed digital painting\"\"\"\n",
"\n",
"results = pipe(prompt=prompt)\n",
"images = results.images\n",
"display(images[0])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5aed5ed7b6f6"
},
"source": [
"### Text-guided image-to-image"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "faadabb7728f"
},
"outputs": [],
"source": [
"import torch\n",
"from diffusers import (DPMSolverMultistepScheduler,\n",
" StableDiffusionImg2ImgPipeline)\n",
"\n",
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"model_id = \"stabilityai/stable-diffusion-2-1\"\n",
"pipe = StableDiffusionImg2ImgPipeline.from_pretrained(\n",
" model_id, torch_dtype=torch.float16\n",
")\n",
"pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)\n",
"pipe = pipe.to(device)\n",
"pipe.enable_attention_slicing()\n",
"\n",
"url = \"https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg\"\n",
"\n",
"response = requests.get(url)\n",
"init_image = Image.open(BytesIO(response.content)).convert(\"RGB\")\n",
"init_image = init_image.resize((768, 512))\n",
"\n",
"prompt = \"A fantasy landscape, trending on artstation\"\n",
"\n",
"results = pipe(prompt=prompt, image=init_image)\n",
"images = results.images\n",
"display(init_image)\n",
"display(images[0])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e70e3519ff8b"
},
"source": [
"## Finetune with Dreambooth"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0dc65d8f0689"
},
"source": [
"This section uses [dreambooth](https://dreambooth.github.io/) to finetune the [stable-diffusion-2-1](https://huggingface.co/stabilityai/stable-diffusion-2-1) model with [5 dog images](https://drive.google.com/drive/folders/1BO_dyz-p65qhBRRMRA4TbZ8qW4rB99JZ) to personalize the text-to-image model.\n",
"\n",
"It finetunes both text encoder and unet of the stable diffusion model up to 800 steps. The whole finetuning job takes 45 minutes to finish using 1 A100 GPU.\n",
"\n",
"The full model will be saved after the finetuning job finishs and it can be loaded by the [StableDiffusionPipeline](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/text2img) to run inference."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "34048707df5c"
},
"outputs": [],
"source": [
"# Download example training images.\n",
"!gdown --folder https://drive.google.com/drive/folders/1BO_dyz-p65qhBRRMRA4TbZ8qW4rB99JZ\n",
"\n",
"# Upload data to Cloud Storage bucket.\n",
"upload_local_dir_to_gcs(\"dog\", f\"gs://{GCS_BUCKET}/dreambooth/dog\")\n",
"upload_local_dir_to_gcs(\"dog\", f\"gs://{GCS_BUCKET}/dreambooth/dog_class\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "969cfeb79317"
},
"source": [
"**NOTE**: If the upload step fails due to lacking of permission, you need to [grant the Storage Object Admin role](https://cloud.google.com/storage/docs/access-control/using-iam-permissions) for the Cloud account of the notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "65467b361315"
},
"outputs": [],
"source": [
"# The pre-trained model to be loaded.\n",
"model_id = \"stabilityai/stable-diffusion-2-1\"\n",
"\n",
"# Input and output path.\n",
"instance_dir = f\"/gcs/{GCS_BUCKET}/dreambooth/dog\"\n",
"class_dir = f\"/gcs/{GCS_BUCKET}/dreambooth/dog_class\"\n",
"output_dir = f\"/gcs/{GCS_BUCKET}/dreambooth/output\"\n",
"\n",
"# Worker pool spec.\n",
"machine_type = \"a2-highgpu-1g\"\n",
"num_nodes = 1\n",
"gpu_type = \"NVIDIA_TESLA_A100\"\n",
"num_gpus = 1\n",
"\n",
"# Setup training job.\n",
"job_name = create_job_name(\"dreambooth-stable-diffusion\")\n",
"job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=job_name,\n",
" container_uri=TRAIN_DOCKER_URI,\n",
")\n",
"\n",
"# Pass training arguments and launch job.\n",
"# See https://github.com/huggingface/diffusers/blob/v0.14.0/examples/dreambooth/train_dreambooth.py#L75\n",
"# for a full list of training arguments.\n",
"model = job.run(\n",
" args=[\n",
" \"dreambooth/train_dreambooth.py\",\n",
" f\"--pretrained_model_name_or_path={model_id}\",\n",
" \"--train_text_encoder\",\n",
" f\"--instance_data_dir={instance_dir}\",\n",
" f\"--class_data_dir={class_dir}\",\n",
" f\"--output_dir={output_dir}\",\n",
" \"--with_prior_preservation\",\n",
" \"--prior_loss_weight=1.0\",\n",
" \"--instance_prompt='a photo of sks dog'\",\n",
" \"--class_prompt='a photo of dog'\",\n",
" \"--resolution=512\",\n",
" \"--train_batch_size=1\",\n",
" \"--gradient_checkpointing\",\n",
" \"--learning_rate=2e-6\",\n",
" \"--lr_scheduler=constant\",\n",
" \"--lr_warmup_steps=0\",\n",
" \"--num_class_images=200\",\n",
" \"--max_train_steps=800\",\n",
" ],\n",
" replica_count=num_nodes,\n",
" machine_type=machine_type,\n",
" accelerator_type=gpu_type,\n",
" accelerator_count=num_gpus,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bf7f82732e61"
},
"source": [
"## Upload and Deploy models"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1cc26e68d7b0"
},
"source": [
"This section uploads the model to Model Registry and deploys it on the Endpoint.\n",
"\n",
"The model deployment step will take ~15 minutes to complete."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cd7b56421392"
},
"source": [
"### Text-to-image"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6d331b1ea337"
},
"source": [
"Deploy the stable diffusion model for the text-to-image task.\n",
"\n",
"Once deployed, you can send a batch of text prompts to the endpoint to generated images.\n",
"\n",
"When deployed on one V100 GPU, the averaged inference time of a request is ~20 seconds."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bf55e38815dc"
},
"outputs": [],
"source": [
"# Set the model_id to \"stabilityai/stable-diffusion-2-1\" to load the OSS pre-trained model.\n",
"model, endpoint = deploy_model(\n",
" model_id=f\"gs://{GCS_BUCKET}/dreambooth/output\", task=\"text-to-image\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus upto 10 minutes of additional waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4ab04da3ec9a"
},
"outputs": [],
"source": [
"instances = [\n",
" {\"prompt\": \"a deer in Matisse style\"},\n",
" {\"prompt\": \"a sks dog in Van Gogh style\"},\n",
"]\n",
"response = endpoint.predict(instances=instances)\n",
"images = [base64_to_image(image) for image in response.predictions]\n",
"image_grid(images)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "af21a3cff1e0"
},
"source": [
"Clean up resources:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "911406c1561e"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c1e51f764a60"
},
"source": [
"### Text-guided image-to-image"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fa686a54047c"
},
"source": [
"Deploy the stable diffusion model for the text-guided image-to-image task."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "65e32356fbd1"
},
"outputs": [],
"source": [
"# Set the model_id to a GCS path, like \"gs://GCS_BUCKET/dreambooth/output\", to load the dreambooth finetuned model above.\n",
"model, endpoint = deploy_model(\n",
" model_id=\"stabilityai/stable-diffusion-2-1\", task=\"image-to-image\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SsjYFLvNymc0"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "83a50fd4a1ed"
},
"outputs": [],
"source": [
"init_image = download_image(\n",
" \"https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg\"\n",
")\n",
"display(init_image)\n",
"instances = [\n",
" {\n",
" \"prompt\": \"A fantasy landscape, trending on artstation\",\n",
" \"image\": image_to_base64(init_image),\n",
" },\n",
"]\n",
"response = endpoint.predict(instances=instances)\n",
"images = [base64_to_image(image) for image in response.predictions]\n",
"display(images[0])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ed3795d474b9"
},
"source": [
"Clean up resources:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b53b883257b4"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"name": "model_garden_pytorch_stable_diffusion_2_1.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -48,7 +48,7 @@
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 CPU notebook is recommended)\n",
" (a Python-3 GPU notebook with preinstalled HuggingFace/transformer libraries is recommended)\n",
" </td>\n",
"</table>"
]
@@ -61,13 +61,14 @@
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates finetuning [runwayml/stable-diffusion-inpainting](https://huggingface.co/runwayml/stable-diffusion-inpainting) with [Dreambooth](https://huggingface.co/docs/diffusers/training/dreambooth) and deploying it on Vertex-AI for online prediction.\n",
"This notebook demonstrates running local inference for [runwayml/stable-diffusion-inpainting](https://huggingface.co/runwayml/stable-diffusion-inpainting) on either [Colab](https://colab.research.google.com) or [Vertex AI Workbench](https://cloud.google.com/vertex-ai-workbench). This notebook also demonstrates finetuning runwayml/stable-diffusion-inpainting with [Dreambooth](https://huggingface.co/docs/diffusers/training/dreambooth) and deploying it on Vertex-AI for online prediction.\n",
"\n",
"### Objective\n",
"\n",
"- Run local predictions for image-inpainting with serving dockers.\n",
"- Finetune the stable-diffusion-inpainting model with [Dreambooth](https://huggingface.co/docs/diffusers/training/dreambooth).\n",
"- Upload the model to [Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model on [Endpoint](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Upload the model to [Vertex AI Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model to a [Vertex AI Endpoint resource](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for image-inpainting.\n",
"\n",
"### Costs\n",
@@ -83,10 +84,10 @@
{
"cell_type": "markdown",
"metadata": {
"id": "264c07757582"
"id": "Gl3bjJsV3k4J"
},
"source": [
"## Setup environment\n",
"## Before you begin\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
@@ -94,34 +95,10 @@
{
"cell_type": "markdown",
"metadata": {
"id": "d73ffa0c0b83"
"id": "CaCslNQE37P_"
},
"source": [
"### Colab only"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2707b02ef5df"
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
"### Setup notebook"
]
},
{
@@ -130,7 +107,8 @@
"id": "fb671e75ca7b"
},
"source": [
"### Install dependencies"
"#### Colab only\n",
"Run the following commands for Colab and skip this section if you are using Workbench."
]
},
{
@@ -141,33 +119,45 @@
},
"outputs": [],
"source": [
"# Install gdown for downloading example training images.\n",
"!pip install gdown\n",
"# Install gsutil for downloading/uploading data from/to Cloud Storage buckets.\n",
"!pip install gsutil"
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
" ! pip3 install --upgrade pip\n",
" ! pip3 install torchvision==0.14.1\n",
" ! pip3 install transformers==4.27.1\n",
" ! pip3 install diffusers==0.15.1\n",
" ! pip3 install datasets==2.9.0\n",
" ! pip3 install accelerate==0.18.0\n",
" ! pip3 install triton==2.0.0.dev20221120\n",
" ! pip3 install xformers==0.0.16\n",
" # Install gdown for downloading example training images.\n",
" ! pip3 install gdown\n",
" # Remove wrong cublas version.\n",
" ! pip3 uninstall nvidia_cublas_cu11 --yes\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5244aac3d929"
"id": "JaY__7zz3uWk"
},
"source": [
"Restart the notebook kernel after installs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "567212ff53a6"
},
"outputs": [],
"source": [
"import IPython\n",
"\n",
"app = IPython.Application.instance()\n",
"app.kernel.do_shutdown(True)"
"#### Workbench only\n",
"1. Follow [this link](https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_inpainting.ipynb) to deploy the notebook to a Vertex AI Workbench Instance.\n",
"2. Select `Create a new Notebook`.\n",
"3. Click `Advanced Options`.\n",
"4. Under **Environment**, select `Custom Container` for `Environment`. \n",
"5. Set `Docker container image` to `us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/transformers-notebook`.\n",
"6. Under **Machine configuration**, select 1 `T4` GPU and select `Install NVIDIA GPU driver automatically for me`.\n",
"7. Click `Create` to create the Vertex AI Workbench instance."
]
},
{
@@ -184,7 +174,9 @@
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs."
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs.\n",
"\n",
"1. [Create a service account](https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console) with `Vertex AI User` and `Storage Object Admin` roles for deploying fine tuned model to Vertex AI endpoint."
]
},
{
@@ -210,8 +202,14 @@
"# The region you want to launch jobs in.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
"# The Cloud Storage bucket for storing experiments output.\n",
"# Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}\n",
"\n",
"# The service account for deploying fine tuned model.\n",
"# The service account looks like:\n",
"# '<account_name>@<project>.iam.gserviceaccount.com'\n",
"SERVICE_ACCOUNT = \"\" # @param {type:\"string\"}"
]
},
{
@@ -271,19 +269,20 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": null,
"metadata": {
"id": "8759e624ebc0"
},
"outputs": [],
"source": [
"import base64\n",
"import glob\n",
"import os\n",
"from datetime import datetime\n",
"from io import BytesIO\n",
"\n",
"import requests\n",
"from google.cloud import aiplatform\n",
"from google.cloud import aiplatform, storage\n",
"from PIL import Image\n",
"\n",
"\n",
@@ -326,8 +325,6 @@
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" # If the model_id is a GCS path, use artifact_uri to pass it to serving docker.\n",
" artifact_uri = model_id if model_id.startswith(\"gs://\") else None\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
@@ -335,7 +332,6 @@
" serving_container_predict_route=\"/predictions/diffusers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" artifact_uri=artifact_uri,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
@@ -343,8 +339,81 @@
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" service_account=SERVICE_ACCOUNT,\n",
" )\n",
" return model, endpoint"
" return model, endpoint\n",
"\n",
"\n",
"def get_bucket_and_blob_name(filepath):\n",
" # The gcs path is of the form gs://<bucket-name>/<blob-name>\n",
" gs_suffix = filepath.split(\"gs://\", 1)[1]\n",
" return tuple(gs_suffix.split(\"/\", 1))\n",
"\n",
"\n",
"def upload_local_dir_to_gcs(local_dir_path, gcs_dir_path):\n",
" \"\"\"Uploads files in a local directory to a GCS directory.\"\"\"\n",
" client = storage.Client()\n",
" bucket_name = gcs_dir_path.split(\"/\")[2]\n",
" bucket = client.get_bucket(bucket_name)\n",
" for local_file in glob.glob(local_dir_path + \"/**\"):\n",
" if not os.path.isfile(local_file):\n",
" continue\n",
" filename = local_file[1 + len(local_dir_path) :]\n",
" gcs_file_path = os.path.join(gcs_dir_path, filename)\n",
" _, blob_name = get_bucket_and_blob_name(gcs_file_path)\n",
" blob = bucket.blob(blob_name)\n",
" blob.upload_from_filename(local_file)\n",
" print(\"Copied {} to {}.\".format(local_file, gcs_file_path))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Wx18bDXC2XPR"
},
"source": [
"## Run inferences locally"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OSYVyAvu2mfN"
},
"source": [
"### Image-inpainting"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CZ2RkKT32Zj2"
},
"outputs": [],
"source": [
"import torch\n",
"from diffusers import StableDiffusionInpaintPipeline\n",
"\n",
"image_url = \"https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png\"\n",
"image_response = requests.get(image_url)\n",
"init_image = Image.open(BytesIO(image_response.content)).convert(\"RGB\")\n",
"display(init_image)\n",
"\n",
"mask_url = \"https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png\"\n",
"mask_response = requests.get(mask_url)\n",
"mask_image = Image.open(BytesIO(mask_response.content)).convert(\"RGB\")\n",
"\n",
"pipe = StableDiffusionInpaintPipeline.from_pretrained(\n",
" \"runwayml/stable-diffusion-inpainting\",\n",
" revision=\"fp16\",\n",
" torch_dtype=torch.float16,\n",
")\n",
"pipe.to(\"cuda\")\n",
"\n",
"prompt = \"Face of a yellow cat, high resolution, sitting on a park bench\"\n",
"images = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images\n",
"display(images[0])"
]
},
{
@@ -381,17 +450,8 @@
"!gdown --folder https://drive.google.com/drive/folders/1BO_dyz-p65qhBRRMRA4TbZ8qW4rB99JZ\n",
"\n",
"# Upload data to Cloud Storage bucket.\n",
"!gsutil -m cp -r dog/* gs://{GCS_BUCKET}/dreambooth/dog/\n",
"!gsutil -m cp -r dog/* gs://{GCS_BUCKET}/dreambooth/dog_class/"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "969cfeb79317"
},
"source": [
"**NOTE**: If the upload step fails due to lacking of permission, you need to [grant the Storage Object Admin role](https://cloud.google.com/storage/docs/access-control/using-iam-permissions) for the Cloud account of the notebook."
"upload_local_dir_to_gcs(\"dog\", f\"gs://{GCS_BUCKET}/dreambooth/dog\")\n",
"upload_local_dir_to_gcs(\"dog\", f\"gs://{GCS_BUCKET}/dreambooth/dog_class\")"
]
},
{
@@ -504,12 +564,21 @@
},
"outputs": [],
"source": [
"# Set the model_id to a GCS path, like \"gs://GCS_BUCKET/dreambooth/output\", to load the dreambooth finetuned model above.\n",
"# Set the model_id to \"runwayml/stable-diffusion-inpainting\" to load the OSS pre-trained model.\n",
"model, endpoint = deploy_model(\n",
" model_id=\"runwayml/stable-diffusion-inpainting\", task=\"image-inpainting\"\n",
" model_id=f\"gs://{GCS_BUCKET}/dreambooth/output\", task=\"image-inpainting\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -0,0 +1,495 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7d9bbf86da5e"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "99c1c3fc2ca5"
},
"source": [
"# Vertex AI Model Garden - Stable Diffusion Upscaler\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_upscaler.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_upscaler.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_upscaler.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 GPU notebook with preinstalled HuggingFace/transformer libraries is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3de7470326a2"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates running local inference for [stabilityai/stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler) on either [Colab](https://colab.research.google.com) or [Vertex AI Workbench](https://cloud.google.com/vertex-ai-workbench). This notebook also demonstrates deploying the model on Vertex AI for online prediction.\n",
"\n",
"### Objective\n",
"\n",
"- Run local predictions for text-guided image super resolution.\n",
"- Upload the model to [Vertex AI Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model to a [Vertex AI Endpoint resource](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for text-guided image super resolution.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "264c07757582"
},
"source": [
"## Before you begin\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ioensNKM8ned"
},
"source": [
"### Setup notebook"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d73ffa0c0b83"
},
"source": [
"#### Colab only\n",
"Run the following commands for Colab and skip this section if you are using Workbench."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2707b02ef5df"
},
"outputs": [],
"source": [
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
" ! pip3 install --upgrade pip\n",
" ! pip3 install torchvision==0.14.1\n",
" ! pip3 install transformers==4.27.1\n",
" ! pip3 install diffusers==0.15.1\n",
" ! pip3 install datasets==2.9.0\n",
" ! pip3 install accelerate==0.18.0\n",
" ! pip3 install triton==2.0.0.dev20221120\n",
" ! pip3 install xformers==0.0.16\n",
" # Remove wrong cublas version.\n",
" ! pip3 uninstall nvidia_cublas_cu11 --yes\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fb671e75ca7b"
},
"source": [
"#### Workbench only\n",
"1. Follow [this link](https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_stable_diffusion_upscaler.ipynb) to deploy the notebook to a Vertex AI Workbench Instance.\n",
"2. Select `Create a new Notebook`.\n",
"3. Click `Advanced Options`, and select `Debian 10` for `Operating System`.\n",
"4. Under **Environment**, select `Custom Container` for `Environment`.\n",
"5. Set `Docker container image` to `us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/transformers-notebook`.\n",
"6. Under **Machine configuration**, select 1 `T4` GPU and select `Install NVIDIA GPU driver automatically for me`.\n",
"7. Click `Create` to create the Vertex AI Workbench instance."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bb7adab99e41"
},
"source": [
"### Setup Google Cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6c460088b873"
},
"source": [
"Fill following variables for experiments environment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "855d6b96f291"
},
"outputs": [],
"source": [
"# Cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"# The region you want to launch jobs in.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e828eb320337"
},
"source": [
"### Initialize Vertex-AI API\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project and corresponding bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "12cd25839741"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2cc825514deb"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b42bd4fa2b2d"
},
"outputs": [],
"source": [
"# The pre-built serving docker image. It contains serving scripts and models.\n",
"SERVE_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-diffusers-serve\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c250872074f"
},
"source": [
"### Define common functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "354da31189dc"
},
"outputs": [],
"source": [
"import base64\n",
"from io import BytesIO\n",
"\n",
"import requests\n",
"from PIL import Image\n",
"\n",
"\n",
"# Expand an image to a square image.\n",
"def expand2square(pil_img, background_color):\n",
" width, height = pil_img.size\n",
" if width == height:\n",
" return pil_img\n",
" elif width > height:\n",
" result = Image.new(pil_img.mode, (width, width), background_color)\n",
" result.paste(pil_img, (0, (width - height) // 2))\n",
" return result\n",
" else:\n",
" result = Image.new(pil_img.mode, (height, height), background_color)\n",
" result.paste(pil_img, ((height - width) // 2, 0))\n",
" return result\n",
"\n",
"\n",
"# Resize an image to a square image.\n",
"def resize2square(pil_img, target_size, background_color):\n",
" low_res_size = target_size\n",
" wpercent = low_res_size / float(pil_img.size[0])\n",
" hsize = int(float(pil_img.size[1]) * float(wpercent))\n",
" result_img = pil_img.resize((low_res_size, hsize), Image.ANTIALIAS)\n",
" return expand2square(result_img, background_color)\n",
"\n",
"\n",
"def download_image(url):\n",
" response = requests.get(url)\n",
" return Image.open(BytesIO(response.content))\n",
"\n",
"\n",
"def image_to_base64(image):\n",
" buffer = BytesIO()\n",
" image.save(buffer, format=\"JPEG\")\n",
" image_str = base64.b64encode(buffer.getvalue()).decode(\"utf-8\")\n",
" return image_str\n",
"\n",
"\n",
"def base64_to_image(image_str):\n",
" image = Image.open(BytesIO(base64.b64decode(image_str)))\n",
" return image\n",
"\n",
"\n",
"# Deploy a model to Vertex AI endpoint.\n",
"def deploy_model(model_id, task):\n",
" model_name = \"stable-diffusion-upscaler\"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{model_name}-{task}-endpoint\")\n",
" serving_env = {\n",
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
" serving_container_ports=[7080],\n",
" serving_container_predict_route=\"/predictions/diffusers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=\"n1-standard-8\",\n",
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" )\n",
" return model, endpoint"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e8a42fa49305"
},
"source": [
"## Run inferences locally\n",
"\n",
"The code below downloads the model and runs the model locally with a low resolution image."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "faadabb7728f"
},
"outputs": [],
"source": [
"import torch\n",
"from diffusers import StableDiffusionUpscalePipeline\n",
"from IPython import display\n",
"\n",
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"model_id = \"stabilityai/stable-diffusion-x4-upscaler\"\n",
"pipeline = StableDiffusionUpscalePipeline.from_pretrained(\n",
" model_id, torch_dtype=torch.float16\n",
")\n",
"pipeline = pipeline.to(device)\n",
"\n",
"prompt = \"Roaring tiger, close shot with dark circular pupils, DSLR\"\n",
"url = \"https://as2.ftcdn.net/v2/jpg/02/11/74/81/1000_F_211748113_fUCaGzZIdMk5JaehpyVttwVMWbPWUtBz.jpg\"\n",
"low_res_img = download_image(url)\n",
"low_res_img = resize2square(low_res_img, 256, (0, 0, 0))\n",
"print(\"Low resolution input image:\")\n",
"display.display(low_res_img)\n",
"\n",
"pipeline.enable_xformers_memory_efficient_attention()\n",
"upscaled_image = pipeline(\n",
" prompt=prompt, image=low_res_img, num_inference_steps=20\n",
").images[0]\n",
"print(\"Upscaled high resolution image:\")\n",
"display.display(upscaled_image)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bf7f82732e61"
},
"source": [
"## Upload and Deploy models"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1cc26e68d7b0"
},
"source": [
"This section uploads the stable diffusion upscaler model to Model Registry and deploys it on the Endpoint.\n",
"\n",
"The model deployment step will take ~15 minutes to complete."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "65e32356fbd1"
},
"outputs": [],
"source": [
"model, endpoint = deploy_model(\n",
" model_id=\"stabilityai/stable-diffusion-x4-upscaler\", task=\"conditioned-super-res\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SsjYFLvNymc0"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "83a50fd4a1ed"
},
"outputs": [],
"source": [
"from IPython import display\n",
"\n",
"prompt = \"Roaring tiger, close shot with dark circular pupils, DSLR\"\n",
"url = \"https://as2.ftcdn.net/v2/jpg/02/11/74/81/1000_F_211748113_fUCaGzZIdMk5JaehpyVttwVMWbPWUtBz.jpg\"\n",
"low_res_img = download_image(url)\n",
"low_res_size = 256\n",
"low_res_img = resize2square(low_res_img, low_res_size, (0, 0, 0))\n",
"print(\"Low resolution input image:\")\n",
"display.display(low_res_img)\n",
"\n",
"instances = [\n",
" {\n",
" \"prompt\": prompt,\n",
" \"image\": image_to_base64(low_res_img),\n",
" },\n",
"]\n",
"response = endpoint.predict(instances=instances)\n",
"images = [base64_to_image(image) for image in response.predictions]\n",
"print(\"Upscaled high resolution image:\")\n",
"display.display(upscaled_image)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ed3795d474b9"
},
"source": [
"## Clean up resources"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b53b883257b4"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"name": "model_garden_pytorch_stable_diffusion_upscaler.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,419 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ug_ZXeBdbFI4"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "Jr2jRuqabG1m"
},
"source": [
"# Vertex AI Model Garden - Text To Video\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_text_to_video.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_text_to_video.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_text_to_video.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 CPU notebook is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "wLLfRT_6bTZO"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates deploying the pre-trained [Text To Video](https://huggingface.co/docs/diffusers/main/en/api/pipelines/text_to_video) model on Vertex AI for online prediction.\n",
"\n",
"### Objective\n",
"\n",
"- Upload the model to [Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model on [Endpoint](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for text-to-video.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "J_fFK5ufbil8"
},
"source": [
"## Setup environment\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "dkbL0d3lbnI9"
},
"source": [
"### Colab only\n",
"\n",
"Run the following commands for colab and skip this section if you use workbench."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fsQlA1Yibroo"
},
"outputs": [],
"source": [
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
"\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)\n",
"\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "KsbbsTU5bwtJ"
},
"source": [
"### Setup Google Cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "izM_LAUwcHSa"
},
"source": [
"Fill following variables for experiments environment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "okVArp5bb3Wu"
},
"outputs": [],
"source": [
"# Cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"# The region you want to launch jobs in.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "92f16e22c20b"
},
"source": [
"Initialize Vertex AI API:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1680c257acfb"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "6ca48b699d17"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "de9882ea89ea"
},
"outputs": [],
"source": [
"# The pre-built serving docker image. It contains serving scripts and models.\n",
"SERVE_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-diffusers-serve\""
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "10188266a5cd"
},
"source": [
"### Define common functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cac4478ae098"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"\n",
"def deploy_model(model_id, task):\n",
" model_name = \"text-to-video\"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{model_name}-endpoint\")\n",
" serving_env = {\n",
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" # If the model_id is a GCS path, use artifact_uri to pass it to serving docker.\n",
" artifact_uri = model_id if model_id.startswith(\"gs://\") else None\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
" serving_container_ports=[7080],\n",
" serving_container_predict_route=\"/predictions/diffusers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" artifact_uri=artifact_uri,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=\"n1-standard-8\",\n",
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" )\n",
" return model, endpoint"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "d2d72ecdb8c9"
},
"source": [
"## Upload and deploy models"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "9448c5f545fa"
},
"source": [
"This section uploads the pre-trained model to Model Registry and deploys it on the Endpoint.\n",
"\n",
"The model deployment step will take ~15 minutes to complete."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "c277da31bde6"
},
"source": [
"### Text-guided image-to-image"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "a5a86996222c"
},
"source": [
"Deploy the model for the text-to-video task.\n",
"\n",
"Once deployed, you can send prompts to the endpoint to generated images.\n",
"\n",
"When deployed on one V100 GPU, the averaged inference time of a request is ~30 seconds."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b4b46c28d8b1"
},
"outputs": [],
"source": [
"model, endpoint = deploy_model(\n",
" model_id=\"damo-vilab/text-to-video-ms-1.7b\", task=\"text-to-video\"\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6be655247cb1"
},
"outputs": [],
"source": [
"instances = [\n",
" {\"prompt\": \"Spiderman is surfing\"},\n",
"]\n",
"response = endpoint.predict(instances=instances)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "0XeaCIfOjjOP"
},
"source": [
"You can view the generated video directly by executing the following cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nriQMwuOiS0k"
},
"outputs": [],
"source": [
"from IPython.display import HTML\n",
"\n",
"html = \"\"\n",
"for video in response.predictions:\n",
" html += \"<video controls>\"\n",
" html += f'<source src=\"data:video/mp4;base64,{video}\" type=\"video/mp4\">'\n",
" html += \"</video>\"\n",
"HTML(html)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "db7ffebdb4be"
},
"source": [
"### Clean up resources"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2ccf3714dbe9"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_pytorch_text_to_video.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,378 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7d9bbf86da5e"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "99c1c3fc2ca5"
},
"source": [
"# Vertex AI Model Garden - Zero-Shot Text-to-Video Generation\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_text_to_video_zero_shot.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_text_to_video_zero_shot.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_text_to_video_zero_shot.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 GPU notebook with preinstalled HuggingFace/transformer libraries is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3de7470326a2"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates deploying model on Vertex AI and running online inference for [Zero-Shot Text-to-Video Generation](https://huggingface.co/docs/diffusers/api/pipelines/text_to_video_zero).\n",
"\n",
"### Objective\n",
"\n",
"- Upload the model to [Vertex AI Model Registry](https://cloud.google.com/vertex-ai/docs/model-registry/introduction).\n",
"- Deploy the model to a [Vertex AI Endpoint resource](https://cloud.google.com/vertex-ai/docs/predictions/using-private-endpoints).\n",
"- Run online predictions for zero-shot text-to-video generation.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "264c07757582"
},
"source": [
"## Before you begin\n",
"\n",
"**NOTE**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ioensNKM8ned"
},
"source": [
"### Setup notebook"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d73ffa0c0b83"
},
"source": [
"#### Colab only\n",
"Run the following commands for Colab and skip this section if you are using Workbench."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2707b02ef5df"
},
"outputs": [],
"source": [
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bb7adab99e41"
},
"source": [
"### Setup Google Cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6c460088b873"
},
"source": [
"Fill following variables for experiments environment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "855d6b96f291"
},
"outputs": [],
"source": [
"# Cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"\n",
"# The region you want to launch jobs in.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket for storing experiments output. Fill it without the 'gs://' prefix.\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e828eb320337"
},
"source": [
"### Initialize Vertex-AI API\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project and corresponding bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "12cd25839741"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2cc825514deb"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b42bd4fa2b2d"
},
"outputs": [],
"source": [
"# The pre-built serving docker image. It contains serving scripts and models.\n",
"SERVE_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-diffusers-serve\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c250872074f"
},
"source": [
"### Define common functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "354da31189dc"
},
"outputs": [],
"source": [
"# Deploy a model to Vertex AI endpoint.\n",
"def deploy_model(model_id, task):\n",
" model_name = \"stable-diffusion-zero-shot-text-to-video\"\n",
" endpoint = aiplatform.Endpoint.create(display_name=f\"{model_name}-{task}-endpoint\")\n",
" serving_env = {\n",
" \"MODEL_ID\": model_id,\n",
" \"TASK\": task,\n",
" }\n",
" model = aiplatform.Model.upload(\n",
" display_name=model_name,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
" serving_container_ports=[7080],\n",
" serving_container_predict_route=\"/predictions/diffusers_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
" )\n",
" model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=\"n1-standard-8\",\n",
" accelerator_type=\"NVIDIA_TESLA_V100\",\n",
" accelerator_count=1,\n",
" deploy_request_timeout=1800,\n",
" )\n",
" return model, endpoint"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bf7f82732e61"
},
"source": [
"## Upload and Deploy models"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1cc26e68d7b0"
},
"source": [
"This section uploads the zero-shot text-to-video model to Model Registry and deploys it on the Endpoint.\n",
"\n",
"The model deployment step will take ~15 minutes to complete."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "65e32356fbd1"
},
"outputs": [],
"source": [
"model, endpoint = deploy_model(\n",
" model_id=\"runwayml/stable-diffusion-v1-5\", task=\"text-to-video-zero-shot\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SsjYFLvNymc0"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "83a50fd4a1ed"
},
"outputs": [],
"source": [
"from IPython.display import HTML\n",
"\n",
"instances = [\n",
" {\n",
" \"prompt\": \"a rainbow butterfly in a garden\",\n",
" },\n",
" {\n",
" \"prompt\": \"a spaceship flying through solar system\",\n",
" },\n",
"]\n",
"response = endpoint.predict(instances=instances)\n",
"html = \"\"\n",
"for i, video in enumerate(response.predictions):\n",
" html += (\n",
" '<iframe width=\"480\" height=\"480\" src=\"'\n",
" + \"data:video/mp4;base64,\"\n",
" + video\n",
" + '\" frameborder=\"2\" allowfullscreen></iframe>'\n",
" )\n",
"HTML(\n",
" html\n",
" + '<iframe width=\"0\" height=\"480\" src=\"\" frameborder=\"0\" allowfullscreen></iframe>'\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ed3795d474b9"
},
"source": [
"## Clean up resources"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b53b883257b4"
},
"outputs": [],
"source": [
"# Undeploy model and delete endpoint.\n",
"endpoint.delete(force=True)\n",
"\n",
"# Delete models.\n",
"model.delete()"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"name": "model_garden_pytorch_text_to_video_zero_shot.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,753 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ApNHZJmT2AMH"
},
"outputs": [],
"source": [
"# Copyright 2023 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YfxrFG052AMI"
},
"source": [
"# Vertex AI Model Garden - TIMM\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_timm.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_pytorch_timm.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/model_garden/model_garden_pytorch_timm.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
" (a Python-3 CPU notebook is recommended)\n",
" </td>\n",
"</table>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "76BCoQcm2AMJ"
},
"source": [
"## Overview\n",
"\n",
"This notebook demonstrates running local inference using the [timm](https://github.com/rwightman/pytorch-image-models) library, finetuning the PyTorch [timm models](https://github.com/huggingface/pytorch-image-models#models), and deploying the models on [Vertex AI](https://cloud.google.com/vertex-ai).\n",
"\n",
"### Objective\n",
"\n",
"- Setup environment.\n",
"- Run inference locally using the timm library.\n",
"- Create a custom training job on Vertex AI to train or finetune a model.\n",
"- Deploy the model on Vertex AI for online prediction.\n",
"\n",
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9iU1NKfh2AMJ"
},
"source": [
"## Setup environment"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7l3GN-QL2AMJ"
},
"source": [
"### Setup cloud project\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project). Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage.\n",
"\n",
"1. [Enable Artifact Registry](https://cloud.google.com/artifact-registry/docs/enable-service) and [create a repository](https://cloud.google.com/artifact-registry/docs/repositories/create-repos) for storing docker images.\n",
"\n",
"1. [Create a Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) for storing experiment outputs.\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. [Create a service account](https://cloud.google.com/iam/docs/service-accounts-create#iam-service-accounts-create-console) with `Vertex AI User` and `Storage Object Admin` roles for deploying fine tuned model to Vertex AI endpoint."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hyAQXmgf2AMK"
},
"source": [
"### Setup required libraries\n",
"\n",
"It's highly recommended to run this notebook on [Vertex AI workbench](https://cloud.google.com/vertex-ai-workbench), where you don't need to manually install any additional libraries.\n",
"\n",
"If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk) and [gsutil](https://cloud.google.com/storage/docs/gsutil_install)."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ad1f36f4b5c3"
},
"source": [
"### Install libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cb041d87f50a"
},
"outputs": [],
"source": [
"! pip3 install timm"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-uF7Kb112AMK"
},
"source": [
"### Colab Only\n",
"Run the following commands for colab and skip this section if you use workbench."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2lP6dnfy2AMK"
},
"outputs": [],
"source": [
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
"\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)\n",
"\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fo65Wg9Y2AMK"
},
"source": [
"### Setup environment variables\n",
"\n",
"This notebook supports models in https://huggingface.co/docs/timm/models.\n",
"\n",
"You can also run\n",
"`python -c \"from timm import list_models; print(list_models(pretrained=True))\"`\n",
"locally to see all pretrained models.\n",
"\n",
"The following models have been manually verified to work with this notebook:\n",
"\n",
"* vit_tiny_patch16_224\n",
"* beit_base_patch16_224\n",
"* deit3_small_patch16_224\n",
"* efficientnet_b2\n",
"* mobilenetv2_100\n",
"* resnet50\n",
"* resnest50d\n",
"* convnext_base\n",
"* cspdarknet53\n",
"* inception_v4"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3msH2i5V2AMK"
},
"outputs": [],
"source": [
"# The cloud project id.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"# The region for running jobs.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"\n",
"# The model you want to train and serve. Please select a model from the verified model list above.\n",
"# We use a ViT model as the example.\n",
"MODEL_NAME = \"vit_tiny_patch16_224\" # @param {type:\"string\"}\n",
"\n",
"# The Cloud Storage bucket name without gs:// prefix for training outputs.\n",
"# For example: test_bucket\n",
"GCS_BUCKET = \"\" # @param {type:\"string\"}\n",
"\n",
"# The service account for deploying fine tuned model. It looks like:\n",
"# '<account_name>@<project>.iam.gserviceaccount.com'\n",
"# Follow step 6 above to create this account.\n",
"SERVICE_ACCOUNT = \"\" # @param {type:\"string\"}"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "14a500024b7b"
},
"source": [
"## Run local inference\n",
"\n",
"This section runs local inference on an image using the model chosen in above section."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "54859170c1ad"
},
"source": [
"### Import libraries\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7505a2bf3897"
},
"outputs": [],
"source": [
"import timm\n",
"import torch\n",
"from PIL import Image\n",
"from timm.data import resolve_data_config\n",
"from timm.data.transforms_factory import create_transform"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "17e6d8a0dac3"
},
"source": [
"### Load a pretrained model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8b6bbe928998"
},
"outputs": [],
"source": [
"model = timm.create_model(MODEL_NAME, pretrained=True)\n",
"model.eval()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "0f2ce8fa5439"
},
"source": [
"### Load and preprocess the image"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6390302c9761"
},
"outputs": [],
"source": [
"config = resolve_data_config({}, model=model)\n",
"transform = create_transform(**config)\n",
"\n",
"# The example downloads a test image. You can upload and use your own images\n",
"# by changing IMAGE_FILENAME.\n",
"! wget https://github.com/pytorch/hub/raw/master/images/dog.jpg -O test.jpg\n",
"IMAGE_FILENAME = \"test.jpg\" # @param {type:\"string\"}\n",
"\n",
"# You can also copy over images stored in a GCS bucket with the line below.\n",
"# ! gsutil cp \"gs://path/to/image\" \"test.jpg\"\n",
"\n",
"img = Image.open(IMAGE_FILENAME).convert(\"RGB\")\n",
"tensor = transform(img).unsqueeze(0) # transform and add batch dimension\n",
"display(img)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "8a6e2ea460ad"
},
"source": [
"### Get the model predictions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0a7a666a0aef"
},
"outputs": [],
"source": [
"with torch.no_grad():\n",
" out = model(tensor)\n",
"probabilities = torch.nn.functional.softmax(out[0], dim=0)\n",
"print(probabilities.shape)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "691139fc5789"
},
"source": [
"### Get the top-5 predictions class names"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "147249af5dec"
},
"outputs": [],
"source": [
"# Get imagenet class mappings\n",
"url, filename = (\n",
" \"https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt\",\n",
" \"imagenet_classes.txt\",\n",
")\n",
"urllib.request.urlretrieve(url, filename)\n",
"with open(\"imagenet_classes.txt\") as f:\n",
" categories = [s.strip() for s in f.readlines()]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "a8740b668da6"
},
"source": [
"### Print top categories per image"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9f18bcd806f2"
},
"outputs": [],
"source": [
"top5_prob, top5_catid = torch.topk(probabilities, 5)\n",
"for i in range(top5_prob.size(0)):\n",
" print(categories[top5_catid[i]], top5_prob[i].item())\n",
"# prints class names and probabilities like:\n",
"# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "4120d1585355"
},
"source": [
"## Run training jobs\n",
"\n",
"This section runs a regular training job or a hyperparameter tuning job on Vertex AI.\n",
"\n",
"Before creating a training job, you need to prepare the dataset for training and evaluation.\n",
"\n",
"For example, you can use [ImageNet-1K](https://huggingface.co/datasets/imagenet-1k) held on a Cloud Storage bucket as the input dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qy4gKksX2AMK"
},
"outputs": [],
"source": [
"# The prebuilt training docker uri.\n",
"TRAIN_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-timm-train\"\n",
"\n",
"# The path to data directory on Cloud Storage without gs:// prefix.\n",
"# In the form of: <bucket-name>/path-to-data\n",
"GCS_DATA_DIR = \"\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0DnlJhO72AMK"
},
"source": [
"### Create a training job on Vertex AI\n",
"\n",
"This section creates a training job on Vertex AI. If you want to create a hyperparameter tuning job instead, you can skip to the next section."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1R5JWJGS2AML"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"# Init common setup.\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)\n",
"\n",
"# Input and output path.\n",
"data_dir = f\"/gcs/{GCS_DATA_DIR}\"\n",
"output_dir = f\"/gcs/{GCS_BUCKET}/timm\"\n",
"\n",
"# Worker pool spec.\n",
"# Single node with multiple GPUs.\n",
"machine_type = \"n1-highmem-32\"\n",
"num_nodes = 1\n",
"gpu_type = \"NVIDIA_TESLA_P100\" # @param {type:\"string\"}\n",
"num_gpus = 4 # @param {type:\"integer\"}\n",
"\n",
"# Model specific config.\n",
"job_name = f\"pytorch-{MODEL_NAME}\"\n",
"batch_size = 32\n",
"epochs = 2\n",
"\n",
"job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=job_name,\n",
" container_uri=TRAIN_DOCKER_URI,\n",
")\n",
"model = job.run(\n",
" args=[\n",
" \"--standalone\",\n",
" f\"--nnodes={num_nodes}\",\n",
" f\"--nproc_per_node={num_gpus}\",\n",
" \"train.py\",\n",
" data_dir,\n",
" f\"--model={MODEL_NAME}\",\n",
" \"--pretrained\",\n",
" f\"--output={output_dir}\",\n",
" f\"--batch-size={batch_size}\",\n",
" f\"--epochs={epochs}\",\n",
" ],\n",
" replica_count=num_nodes,\n",
" machine_type=machine_type,\n",
" accelerator_type=gpu_type,\n",
" accelerator_count=num_gpus,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Tf6P7ZI82AML"
},
"source": [
"### Create a hyperparameter tuning job on Vertex AI\n",
"\n",
"You can use a [hyperparameter tuning](https://cloud.google.com/vertex-ai/docs/training/hyperparameter-tuning-overview) job to find the best configuration of your hyperparameters.\n",
"\n",
"You can skip this section if you already trained a model in the previous section and do not want to tune the hyperparameters."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Hy_aCff_2AML"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"from google.cloud.aiplatform import hyperparameter_tuning as hpt\n",
"\n",
"# Init common setup.\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=GCS_BUCKET)\n",
"\n",
"# Input and output path.\n",
"data_dir = f\"/gcs/{GCS_DATA_DIR}\"\n",
"output_dir = f\"/gcs/{GCS_BUCKET}/timm\"\n",
"\n",
"# Model specific config.\n",
"job_name = f\"pytorch-hp-{MODEL_NAME}\"\n",
"batch_size = 32\n",
"epochs = 2\n",
"\n",
"# Worker pool spec.\n",
"machine_type = \"n1-highmem-16\"\n",
"num_nodes = 1\n",
"gpu_type = \"NVIDIA_TESLA_V100\" # @param {type:\"string\"}\n",
"num_gpus = 2 # @param {type:\"integer\"}\n",
"worker_pool_specs = [\n",
" {\n",
" \"machine_spec\": {\n",
" \"machine_type\": machine_type,\n",
" \"accelerator_type\": gpu_type,\n",
" \"accelerator_count\": num_gpus,\n",
" },\n",
" \"replica_count\": num_nodes,\n",
" \"container_spec\": {\n",
" \"image_uri\": TRAIN_DOCKER_URI,\n",
" \"args\": [\n",
" \"--standalone\",\n",
" f\"--nnodes={num_nodes}\",\n",
" f\"--nproc_per_node={num_gpus}\",\n",
" \"train.py\",\n",
" data_dir,\n",
" f\"--model={MODEL_NAME}\",\n",
" \"--pretrained\",\n",
" f\"--output={output_dir}\",\n",
" f\"--batch-size={batch_size}\",\n",
" f\"--epochs={epochs}\",\n",
" ],\n",
" },\n",
" }\n",
"]\n",
"\n",
"# Hyperparameter job specs.\n",
"metric_spec = {\"top1_accuracy\": \"maximize\"}\n",
"parameter_spec = {\n",
" \"lr\": hpt.DoubleParameterSpec(min=0.001, max=0.05, scale=\"log\"),\n",
"}\n",
"max_trial_count = 2\n",
"parallel_trial_count = 2\n",
"\n",
"# Launch jobs.\n",
"training_job = aiplatform.CustomJob(\n",
" display_name=job_name, worker_pool_specs=worker_pool_specs\n",
")\n",
"hp_job = aiplatform.HyperparameterTuningJob(\n",
" display_name=job_name,\n",
" custom_job=training_job,\n",
" metric_spec=metric_spec,\n",
" parameter_spec=parameter_spec,\n",
" max_trial_count=max_trial_count,\n",
" parallel_trial_count=parallel_trial_count,\n",
")\n",
"hp_job.run()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DAyRWwqW2AML"
},
"source": [
"## Deploy model for online prediction\n",
"\n",
"This section uploads the model to Model Registry and deploys it on an Endpoint resource.\n",
"\n",
"The model deployment step will take ~15 minutes to complete."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jbNbg0yR2AML"
},
"outputs": [],
"source": [
"# The prebuilt serving docker uri.\n",
"SERVE_DOCKER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/pytorch-timm-serve\"\n",
"# The port number used by torchserve traffic.\n",
"SERVE_PORT = 7080\n",
"# The path to model checkpoint file, including gs:// prefix.\n",
"MODEL_PT_PATH = \"gs://path_to_model_best.pth.tar\" # @param {type:\"string\"}\n",
"# [Optional] the path to index_to_name.json, including gs:// prefix.\n",
"INDEX_TO_NAME_FILE = \"gs://path_to_index_to_name.json\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "INPri3HQ2AML"
},
"source": [
"### Upload and deploy model on Vertex AI"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "WOvqoAaN2AML"
},
"outputs": [],
"source": [
"# Upload model.\n",
"serving_env = {\n",
" \"MODEL_NAME\": MODEL_NAME,\n",
" \"MODEL_PT_PATH\": MODEL_PT_PATH,\n",
" \"INDEX_TO_NAME_FILE\": INDEX_TO_NAME_FILE,\n",
"}\n",
"model = aiplatform.Model.upload(\n",
" display_name=MODEL_NAME,\n",
" serving_container_image_uri=SERVE_DOCKER_URI,\n",
" serving_container_ports=[SERVE_PORT],\n",
" serving_container_predict_route=\"/predictions/timm_serving\",\n",
" serving_container_health_route=\"/ping\",\n",
" serving_container_environment_variables=serving_env,\n",
")\n",
"# Or reuse a pre-uploaded model.\n",
"# model = aiplatform.Model('projects/123456789/locations/us-central1/models/123456789@1')\n",
"\n",
"# Create an endpoint.\n",
"endpoint = aiplatform.Endpoint.create(display_name=\"pytorch-timm-endpoint\")\n",
"# Or reuse a pre-created endpoint.\n",
"# endpoint = aiplatform.Endpoint('projects/123456789/locations/us-central1/endpoints/123456789')\n",
"\n",
"# Deploy model to endpoint.\n",
"model.deploy(\n",
" endpoint=endpoint,\n",
" machine_type=\"n1-standard-8\",\n",
" accelerator_type=\"NVIDIA_TESLA_T4\",\n",
" accelerator_count=1,\n",
" traffic_percentage=100,\n",
" service_account=SERVICE_ACCOUNT,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "s2gnYFEJ2AML"
},
"source": [
"You can mange your uploaded models in the [Model Registry](https://pantheon.corp.google.com/vertex-ai/models) and your endpoints in the [Endpoints](https://pantheon.corp.google.com/vertex-ai/endpoints)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5UP84Q5R2AMM"
},
"source": [
"### Test online prediction\n",
"\n",
"You will now test the deployed endpoint. Please prepare an image to predict."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "zL2Qbm2x2AMM"
},
"outputs": [],
"source": [
"import base64\n",
"\n",
"# You can get the deployed endpoint object by its resource name returned by Endpoint.create(). For example:\n",
"# endpoint = aiplatform.Endpoint('projects/816369962409/locations/us-central1/endpoints/8809168414485512192')\n",
"\n",
"# Please upload an image and enter its filename below.\n",
"IMAGE_FILENAME = \"test.jpg\" # @param {type:\"string\"}\n",
"\n",
"# Alternatively, uncomment the following line to download a cat image for demonstration.\n",
"# ! wget http://images.cocodataset.org/val2017/000000039769.jpg -O test.jpg\n",
"\n",
"with open(IMAGE_FILENAME, \"rb\") as f:\n",
" image_b64 = base64.b64encode(f.read()).decode(\"utf-8\")\n",
"instances = [{\"data\": {\"b64\": image_b64}}]\n",
"\n",
"prediction = endpoint.predict(instances=instances)\n",
"print(prediction)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KqSxSyT42AMM"
},
"source": [
"### Clean Up Resources"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tMwdxiH-2AMM"
},
"outputs": [],
"source": [
"endpoint.undeploy_all()\n",
"model.delete()"
]
}
],
"metadata": {
"colab": {
"name": "model_garden_pytorch_timm.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -332,6 +329,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -107,20 +107,17 @@
},
"outputs": [],
"source": [
"!pip3 install --upgrade google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b60a4d7100bf"
},
"outputs": [],
"source": [
"from google.colab import auth as google_auth\n",
"if \"google.colab\" in str(get_ipython()):\n",
" ! pip3 install --upgrade google-cloud-aiplatform\n",
" from google.colab import auth as google_auth\n",
"\n",
"google_auth.authenticate_user()"
" google_auth.authenticate_user()\n",
"\n",
" # Restart the notebook kernel after installs.\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
@@ -332,6 +329,15 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80b3fd2ace09"
},
"source": [
"NOTE: The model weights will be downloaded after the deployment succeeds. Thus additional 5 minutes of waiting time is needed **after** the above model deployment step succeeds and before you run the next step below. Otherwise you might see a `ServiceUnavailable: 503 502:Bad Gateway` error when you send requests to the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -118,7 +118,7 @@
},
"source": [
"### Colab Only\n",
"Run the following commands for colab and skip this section if you use workbench."
"Run the following commands for Colab and skip this section if you use Workbench."
]
},
{
@@ -181,7 +181,16 @@
"# The project and bucket are for experiments below.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"BUCKET_URI = \"\" # @param {type:\"string\"}\n",
"REGION = \"us-central1\"\n",
"\n",
"# You can choose a region from https://cloud.google.com/about/locations.\n",
"# Only regions prefixed by \"us\", \"asia\", or \"europe\" are supported.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"REGION_PREFIX = REGION.split(\"-\")[0]\n",
"assert REGION_PREFIX in (\n",
" \"us\",\n",
" \"europe\",\n",
" \"asia\",\n",
"), f'{REGION} is not supported. It must be prefixed by \"us\", \"asia\", or \"europe\".'\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
@@ -207,6 +216,9 @@
")\n",
"upload_config_to_gcs(\n",
" \"https://raw.githubusercontent.com/tensorflow/models/master/official/vision/configs/experiments/image_classification/imagenet_resnetrs50_i160_gpu.yaml\"\n",
")\n",
"upload_config_to_gcs(\n",
" \"https://raw.githubusercontent.com/tensorflow/models/master/official/projects/maxvit/configs/experiments/maxvit_base_imagenet_gpu.yaml\"\n",
")"
]
},
@@ -231,13 +243,13 @@
"\n",
"# Data converter constants.\n",
"DATA_CONVERTER_JOB_PREFIX = \"data_converter\"\n",
"DATA_CONVERTER_CONTAINER = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/data-converter:latest\"\n",
"DATA_CONVERTER_CONTAINER = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/data-converter\"\n",
"DATA_CONVERTER_MACHINE_TYPE = \"n1-highmem-8\"\n",
"\n",
"\n",
"# Training constants.\n",
"TRAINING_JOB_PREFIX = \"train\"\n",
"TRAIN_CONTAINER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-oss:latest\"\n",
"TRAIN_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-oss\"\n",
"TRAIN_MACHINE_TYPE = \"n1-highmem-16\"\n",
"TRAIN_ACCELERATOR_TYPE = \"NVIDIA_TESLA_P100\"\n",
"TRAIN_NUM_GPU = 1\n",
@@ -247,7 +259,7 @@
"\n",
"# Export constants.\n",
"EXPORT_JOB_PREFIX = \"export\"\n",
"EXPORT_CONTAINER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-serving:latest\"\n",
"EXPORT_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-serving\"\n",
"EXPORT_MACHINE_TYPE = \"n1-highmem-8\"\n",
"\n",
"# Prediction constants.\n",
@@ -256,9 +268,7 @@
"# and optimized tensorflow runtime dockers: https://cloud.google.com/vertex-ai/docs/predictions/optimized-tensorflow-runtime.\n",
"# The example in this notebook uses optimized tensorflow runtime dockers.\n",
"# You can adjust accelerator types and machine types to get faster predictions.\n",
"PREDICTION_CONTAINER_URI = (\n",
" \"us-docker.pkg.dev/vertex-ai-restricted/prediction/tf_opt-gpu.2-11:latest\"\n",
")\n",
"PREDICTION_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/prediction/tf_opt-gpu.2-11:latest\"\n",
"SERVING_CONTAINER_ARGS = [\"--allow_precompilation\", \"--allow_compression\"]\n",
"PREDICTION_ACCELERATOR_TYPE = \"NVIDIA_TESLA_T4\"\n",
"PREDICTION_MACHINE_TYPE = \"n1-standard-4\"\n",
@@ -307,10 +317,9 @@
" endpoint_id: str,\n",
" instances: Union[Dict, List[Dict]],\n",
" location: str = \"us-central1\",\n",
" api_endpoint: str = \"us-central1-aiplatform.googleapis.com\",\n",
"):\n",
" # The AI Platform services require regional API endpoints.\n",
" client_options = {\"api_endpoint\": api_endpoint}\n",
" client_options = {\"api_endpoint\": f\"{location}-aiplatform.googleapis.com\"}\n",
" # Initialize client that will be used to create and send requests.\n",
" # This client only needs to be created once, and can be reused for multiple requests.\n",
" client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)\n",
@@ -536,7 +545,7 @@
"# input_train_data_path = ''\n",
"# input_validation_data_path = ''\n",
"\n",
"experiment = \"ViT-s16\" # @param [\"ResNet-50\",\"ResNet-RS-50\",\"Efficientnetv2-m\",\"ViT-ti16\",\"ViT-s16\",\"ViT-b16\",\"ViT-l16\"]\n",
"experiment = \"ResNet-50\" # @param [\"ResNet-50\",\"ResNet-RS-50\",\"Efficientnetv2-m\",\"ViT-ti16\",\"ViT-s16\",\"ViT-b16\",\"ViT-l16\", \"MaxViT\"]\n",
"\n",
"train_job_name = get_job_name_with_datetime(TRAINING_JOB_PREFIX + \"_\" + OBJECTIVE)\n",
"model_dir = os.path.join(BUCKET_URI, train_job_name)\n",
@@ -562,6 +571,7 @@
" **{\n",
" \"experiment\": \"resnet_imagenet\",\n",
" \"config_file\": os.path.join(CONFIG_DIR, \"imagenet_resnet50_gpu.yaml\"),\n",
" \"init_checkpoint\": \"https://storage.googleapis.com/tf_model_garden/vision/resnet/resnet-50-i224.tar.gz\",\n",
" },\n",
" ),\n",
" \"ResNet-RS-50\": dict(\n",
@@ -617,6 +627,13 @@
" \"input_size\": \"224,224\",\n",
" },\n",
" ),\n",
" \"MaxViT\": dict(\n",
" common_args,\n",
" **{\n",
" \"experiment\": \"maxvit_imagenet\",\n",
" \"config_file\": os.path.join(CONFIG_DIR, \"maxvit_base_imagenet_gpu.yaml\"),\n",
" },\n",
" ),\n",
"}\n",
"experiment_container_args = experiment_container_args_dict[experiment]\n",
"\n",
@@ -627,6 +644,10 @@
" init_checkpoint\n",
" )\n",
"\n",
"# Use container that supports MaxViT\n",
"if experiment == \"MaxViT\":\n",
" TRAIN_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-oss-v2\"\n",
"\n",
"worker_pool_specs = [\n",
" {\n",
" \"machine_spec\": {\n",
@@ -24,6 +24,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "TirJ-SGQseby"
@@ -54,6 +55,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "dwGLvtIeECLK"
@@ -65,6 +67,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
@@ -103,6 +106,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "KEukV6uRk_S3"
@@ -112,13 +116,14 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "z__i0w0lCAsW"
},
"source": [
"### Colab Only\n",
"Run the following commands for colab and skip this section if you use workbench."
"Run the following commands for Colab and skip this section if you are using Workbench."
]
},
{
@@ -144,6 +149,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
@@ -181,30 +187,41 @@
"# The project and bucket are for experiments below.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"BUCKET_URI = \"\" # @param {type:\"string\"}\n",
"REGION = \"us-central1\"\n",
"\n",
"# You can choose a region from https://cloud.google.com/about/locations.\n",
"# Only regions prefixed by \"us\", \"asia\", or \"europe\" are supported.\n",
"REGION = \"us-central1\" # @param {type:\"string\"}\n",
"REGION_PREFIX = REGION.split(\"-\")[0]\n",
"assert REGION_PREFIX in (\n",
" \"us\",\n",
" \"europe\",\n",
" \"asia\",\n",
"), f'{REGION} is not supported. It must be prefixed by \"us\", \"asia\", or \"europe\".'\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
"STAGING_BUCKET = os.path.join(BUCKET_URI, \"temporal\")\n",
"CHECKPOINT_BUCKET = os.path.join(BUCKET_URI, \"ckpt\")\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=STAGING_BUCKET)\n",
"\n",
"# Download config files.\n",
"CONFIG_DIR = os.path.join(BUCKET_URI, \"config\")\n",
"! wget https://raw.githubusercontent.com/tensorflow/models/master/official/vision/configs/experiments/retinanet/coco_spinenet49_gpu_multiworker_mirrored.yaml\n",
"! gsutil cp coco_spinenet49_gpu_multiworker_mirrored.yaml $CONFIG_DIR\n",
"! gsutil cp coco_spinenet49_gpu_multiworker_mirrored.yaml $CONFIG_DIR/\n",
"\n",
"! wget https://raw.githubusercontent.com/tensorflow/models/master/official/vision/configs/experiments/retinanet/coco_spinenet96_gpu_multiworker_mirrored.yaml\n",
"! gsutil cp coco_spinenet96_gpu_multiworker_mirrored.yaml $CONFIG_DIR\n",
"! gsutil cp coco_spinenet96_gpu_multiworker_mirrored.yaml $CONFIG_DIR/\n",
"\n",
"! wget https://raw.githubusercontent.com/tensorflow/models/master/official/vision/configs/experiments/retinanet/coco_spinenet143_gpu_multiworker_mirrored.yaml\n",
"! gsutil cp coco_spinenet143_gpu_multiworker_mirrored.yaml $CONFIG_DIR\n",
"! gsutil cp coco_spinenet143_gpu_multiworker_mirrored.yaml $CONFIG_DIR/\n",
"\n",
"! wget https://raw.githubusercontent.com/tensorflow/models/master/official/projects/yolo/configs/experiments/yolov4/detection/scaled_yolov4_1280_gpu.yaml\n",
"! gsutil cp scaled_yolov4_1280_gpu.yaml $CONFIG_DIR"
"! gsutil cp scaled_yolov4_1280_gpu.yaml $CONFIG_DIR/"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "n6IFz75WGCam"
@@ -225,13 +242,13 @@
"\n",
"# Data converter constants.\n",
"DATA_CONVERTER_JOB_PREFIX = \"data_converter\"\n",
"DATA_CONVERTER_CONTAINER = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/data-converter:latest\"\n",
"DATA_CONVERTER_CONTAINER = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/data-converter\"\n",
"DATA_CONVERTER_MACHINE_TYPE = \"n1-highmem-8\"\n",
"\n",
"\n",
"# Training constants.\n",
"TRAINING_JOB_PREFIX = \"train\"\n",
"TRAIN_CONTAINER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-oss:latest\"\n",
"TRAIN_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-oss\"\n",
"TRAIN_MACHINE_TYPE = \"n1-highmem-16\"\n",
"TRAIN_ACCELERATOR_TYPE = \"NVIDIA_TESLA_V100\"\n",
"TRAIN_NUM_GPU = 2\n",
@@ -251,7 +268,7 @@
"\n",
"# Export constants.\n",
"EXPORT_JOB_PREFIX = \"export\"\n",
"EXPORT_CONTAINER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-serving:latest\"\n",
"EXPORT_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-serving\"\n",
"EXPORT_MACHINE_TYPE = \"n1-highmem-8\"\n",
"\n",
"# Prediction constants.\n",
@@ -260,10 +277,7 @@
"# and optimized tensorflow runtime dockers: https://cloud.google.com/vertex-ai/docs/predictions/optimized-tensorflow-runtime.\n",
"# The example in this notebook uses optimized tensorflow runtime dockers.\n",
"# You can adjust accelerator types and machine types to get faster predictions.\n",
"PREDICTION_CONTAINER_URI = (\n",
" \"us-docker.pkg.dev/vertex-ai-restricted/prediction/tf_opt-gpu.2-11:latest\"\n",
")\n",
"SERVING_CONTAINER_ARGS = [\"--allow_precompilation\", \"--allow_compression\"]\n",
"PREDICTION_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/prediction/tf_opt-gpu.2-11:latest\"\n",
"PREDICTION_ACCELERATOR_TYPE = \"NVIDIA_TESLA_T4\"\n",
"PREDICTION_MACHINE_TYPE = \"n1-standard-4\"\n",
"UPLOAD_JOB_PREFIX = \"upload\"\n",
@@ -271,6 +285,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ZZFPe_GezXg8"
@@ -313,10 +328,9 @@
" endpoint_id: str,\n",
" instances: Union[Dict, List[Dict]],\n",
" location: str = \"us-central1\",\n",
" api_endpoint: str = \"us-central1-aiplatform.googleapis.com\",\n",
"):\n",
" # The AI Platform services require regional API endpoints.\n",
" client_options = {\"api_endpoint\": api_endpoint}\n",
" client_options = {\"api_endpoint\": f\"{location}-aiplatform.googleapis.com\"}\n",
" # Initialize client that will be used to create and send requests.\n",
" # This client only needs to be created once, and can be reused for multiple requests.\n",
" client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)\n",
@@ -450,7 +464,7 @@
" font = ImageFont.truetype(\n",
" \"/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Regular.ttf\", 25\n",
" )\n",
" except IOError:\n",
" except OSError:\n",
" print(\"Font not found, using default font.\")\n",
" font = ImageFont.load_default()\n",
"\n",
@@ -469,10 +483,34 @@
" font,\n",
" display_str_list=[display_str],\n",
" )\n",
" return image"
" return image\n",
"\n",
"\n",
"def upload_checkpoint_to_gcs(checkpoint_url):\n",
" filename = os.path.basename(checkpoint_url)\n",
" checkpoint_name = filename.replace(\".tar.gz\", \"\")\n",
" print(\"Download checkpoint from\", checkpoint_url, \"and store to\", CHECKPOINT_BUCKET)\n",
" ! wget $checkpoint_url -O $filename\n",
" ! mkdir -p $checkpoint_name\n",
" ! tar -xvzf $filename -C $checkpoint_name\n",
"\n",
" # Search for relative path to the checkpoint.\n",
" checkpoint_path = None\n",
" for root, dirs, files in os.walk(checkpoint_name):\n",
" for file in files:\n",
" if file.endswith(\".index\"):\n",
" checkpoint_path = os.path.join(root, os.path.splitext(file)[0])\n",
" checkpoint_path = os.path.relpath(checkpoint_path, checkpoint_name)\n",
" break\n",
"\n",
" ! gsutil cp -r $checkpoint_name $CHECKPOINT_BUCKET/\n",
" checkpoint_uri = os.path.join(CHECKPOINT_BUCKET, checkpoint_name, checkpoint_path)\n",
" print(\"Checkpoint uploaded to\", checkpoint_uri)\n",
" return checkpoint_uri"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "RB_xY9ipr7ZU"
@@ -488,6 +526,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "zgPO1eR3CYjk"
@@ -564,6 +603,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "SA8DVTn7j69v"
@@ -575,6 +615,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "aaff6f5be7f6"
@@ -621,8 +662,8 @@
" \"objective\": OBJECTIVE,\n",
" \"model_dir\": model_dir,\n",
" \"num_classes\": num_classes,\n",
" \"global_batch_size\": 4,\n",
" \"prefetch_buffer_size\": 12,\n",
" \"global_batch_size\": 2,\n",
" \"prefetch_buffer_size\": 6,\n",
" \"train_steps\": 2000,\n",
" \"input_size\": \"1024,1024\",\n",
"}\n",
@@ -661,9 +702,19 @@
" **{\n",
" \"experiment\": \"scaled_yolo\",\n",
" \"config_file\": TRAIN_YOLOV4_CONFIG,\n",
" \"init_checkpoint\": \"https://storage.googleapis.com/tf_model_garden/vision/yolo/scaled-yolov4/scaled-yolov4-l-p6-i1280.tar.gz\",\n",
" \"input_size\": \"1280,1280\",\n",
" },\n",
" ),\n",
"}\n",
"experiment_container_args = experiment_container_args_dict[experiment]\n",
"\n",
"# Copy checkpoint to GCS bucket if specified.\n",
"init_checkpoint = experiment_container_args.get(\"init_checkpoint\")\n",
"if init_checkpoint:\n",
" experiment_container_args[\"init_checkpoint\"] = upload_checkpoint_to_gcs(\n",
" init_checkpoint\n",
" )\n",
"\n",
"params_override = \"runtime.num_gpus=%s\" % TRAIN_NUM_GPU\n",
"eval_params_override = \"runtime.num_gpus=1,runtime.distribution_strategy=mirrored\"\n",
@@ -681,10 +732,7 @@
" \"--mode=train\",\n",
" \"--params_override=%s\" % params_override,\n",
" ]\n",
" + [\n",
" \"--{}={}\".format(k, v)\n",
" for k, v in experiment_container_args_dict[experiment].items()\n",
" ],\n",
" + [\"--{}={}\".format(k, v) for k, v in experiment_container_args.items()],\n",
" },\n",
" },\n",
" {},\n",
@@ -702,10 +750,7 @@
" \"--mode=continuous_eval\",\n",
" \"--params_override=%s\" % eval_params_override,\n",
" ]\n",
" + [\n",
" \"--{}={}\".format(k, v)\n",
" for k, v in experiment_container_args_dict[experiment].items()\n",
" ],\n",
" + [\"--{}={}\".format(k, v) for k, v in experiment_container_args.items()],\n",
" },\n",
" },\n",
"]\n",
@@ -723,6 +768,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "HwcCjwlBTQIz"
@@ -771,6 +817,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "mV-Djz-frBni"
@@ -807,8 +854,7 @@
" \"args\": [\n",
" \"--objective=%s\" % OBJECTIVE,\n",
" \"--input_image_size=1024,1024\",\n",
" \"--experiment=%s\"\n",
" % experiment_container_args_dict[experiment][\"experiment\"],\n",
" \"--experiment=%s\" % experiment_container_args[\"experiment\"],\n",
" \"--config_file=%s/params.yaml\" % best_trial_dir,\n",
" \"--checkpoint_path=%s/best_ckpt\" % best_trial_dir,\n",
" \"--export_dir=%s/best_model\" % model_dir,\n",
@@ -832,6 +878,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "g0BGaofgsMsy"
@@ -857,6 +904,11 @@
"\n",
"upload_job_name = get_job_name_with_datetime(UPLOAD_JOB_PREFIX + \"_\" + OBJECTIVE)\n",
"\n",
"if 'yolo' in experiment:\n",
" SERVING_CONTAINER_ARGS = [\"--allow_precompilation\"]\n",
"else:\n",
" SERVING_CONTAINER_ARGS = [\"--allow_precompilation\", \"--allow_compression\"]\n",
"\n",
"model = aiplatform.Model.upload(\n",
" display_name=upload_job_name,\n",
" artifact_uri=trained_model_dir,\n",
@@ -930,6 +982,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "kkH2nrpdp4sp"
@@ -119,7 +119,7 @@
"source": [
"### Colab Only\n",
"\n",
"Run the following commands for colab and skip this section if you use workbench."
"Run the following commands for Colab and skip this section if you use Workbench."
]
},
{
@@ -182,18 +182,28 @@
"# The project and bucket are for experiments below.\n",
"PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"BUCKET_URI = \"\" # @param {type:\"string\"}\n",
"REGION = \"us-central1\"\n",
"\n",
"# You can choose a region from https://cloud.google.com/about/locations.\n",
"# Only regions prefixed by \"us\", \"asia\", or \"europe\" are supported.\n",
"REGION = \"europe-west4\" # @param {type:\"string\"}\n",
"REGION_PREFIX = REGION.split(\"-\")[0]\n",
"assert REGION_PREFIX in (\n",
" \"us\",\n",
" \"europe\",\n",
" \"asia\",\n",
"), f'{REGION} is not supported. It must be prefixed by \"us\", \"asia\", or \"europe\".'\n",
"\n",
"! gcloud config set project $PROJECT_ID\n",
"\n",
"STAGING_BUCKET = os.path.join(BUCKET_URI, \"temporal\")\n",
"CHECKPOINT_BUCKET = os.path.join(BUCKET_URI, \"ckpt\")\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=STAGING_BUCKET)\n",
"\n",
"# Download config files.\n",
"CONFIG_DIR = os.path.join(BUCKET_URI, \"config\")\n",
"! wget https://raw.githubusercontent.com/tensorflow/models/master/official/vision/configs/experiments/semantic_segmentation/deeplabv3plus_resnet101_cityscapes_gpu_multiworker_mirrored.yaml\n",
"! gsutil cp deeplabv3plus_resnet101_cityscapes_gpu_multiworker_mirrored.yaml $CONFIG_DIR"
"! gsutil cp deeplabv3plus_resnet101_cityscapes_gpu_multiworker_mirrored.yaml $CONFIG_DIR/"
]
},
{
@@ -217,13 +227,13 @@
"\n",
"# Data converter constants.\n",
"DATA_CONVERTER_JOB_PREFIX = \"data_converter\"\n",
"DATA_CONVERTER_CONTAINER = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/data-converter:latest\"\n",
"DATA_CONVERTER_CONTAINER = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/data-converter\"\n",
"DATA_CONVERTER_MACHINE_TYPE = \"n1-highmem-8\"\n",
"\n",
"\n",
"# Training constants.\n",
"TRAINING_JOB_PREFIX = \"train\"\n",
"TRAIN_CONTAINER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-oss:latest\"\n",
"TRAIN_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-oss\"\n",
"TRAIN_MACHINE_TYPE = \"n1-highmem-16\"\n",
"TRAIN_ACCELERATOR_TYPE = \"NVIDIA_TESLA_V100\"\n",
"TRAIN_NUM_GPU = 2\n",
@@ -236,7 +246,7 @@
"\n",
"# Export constants.\n",
"EXPORT_JOB_PREFIX = \"export\"\n",
"EXPORT_CONTAINER_URI = \"us-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-serving:latest\"\n",
"EXPORT_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/vertex-vision-model-garden-dockers/tfvision-serving\"\n",
"EXPORT_MACHINE_TYPE = \"n1-highmem-8\"\n",
"\n",
"# Prediction constants.\n",
@@ -245,9 +255,7 @@
"# and optimized tensorflow runtime dockers: https://cloud.google.com/vertex-ai/docs/predictions/optimized-tensorflow-runtime.\n",
"# The example in this notebook uses optimized tensorflow runtime dockers.\n",
"# You can adjust accelerator types and machine types to get faster predictions.\n",
"PREDICTION_CONTAINER_URI = (\n",
" \"us-docker.pkg.dev/vertex-ai-restricted/prediction/tf_opt-gpu.2-11:latest\"\n",
")\n",
"PREDICTION_CONTAINER_URI = f\"{REGION_PREFIX}-docker.pkg.dev/vertex-ai-restricted/prediction/tf_opt-gpu.2-11:latest\"\n",
"SERVING_CONTAINER_ARGS = [\"--allow_precompilation\", \"--allow_compression\"]\n",
"PREDICTION_ACCELERATOR_TYPE = \"NVIDIA_TESLA_T4\"\n",
"PREDICTION_MACHINE_TYPE = \"n1-standard-4\"\n",
@@ -298,10 +306,9 @@
" endpoint_id: str,\n",
" instances: Union[Dict, List[Dict]],\n",
" location: str = \"us-central1\",\n",
" api_endpoint: str = \"us-central1-aiplatform.googleapis.com\",\n",
"):\n",
" # The AI Platform services require regional API endpoints.\n",
" client_options = {\"api_endpoint\": api_endpoint}\n",
" client_options = {\"api_endpoint\": f\"{location}-aiplatform.googleapis.com\"}\n",
" # Initialize client that will be used to create and send requests.\n",
" # This client only needs to be created once, and can be reused for multiple requests.\n",
" client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)\n",
@@ -508,7 +515,30 @@
" ]\n",
" category_image_color = Image.fromarray(category_image_color_np)\n",
"\n",
" return score_image_grayscale, category_image_color"
" return score_image_grayscale, category_image_color\n",
"\n",
"\n",
"def upload_checkpoint_to_gcs(checkpoint_url):\n",
" filename = os.path.basename(checkpoint_url)\n",
" checkpoint_name = filename.replace(\".tar.gz\", \"\")\n",
" print(\"Download checkpoint from\", checkpoint_url, \"and store to\", CHECKPOINT_BUCKET)\n",
" ! wget $checkpoint_url -O $filename\n",
" ! mkdir -p $checkpoint_name\n",
" ! tar -xvzf $filename -C $checkpoint_name\n",
"\n",
" # Search for relative path to the checkpoint.\n",
" checkpoint_path = None\n",
" for root, dirs, files in os.walk(checkpoint_name):\n",
" for file in files:\n",
" if file.endswith(\".index\"):\n",
" checkpoint_path = os.path.join(root, os.path.splitext(file)[0])\n",
" checkpoint_path = os.path.relpath(checkpoint_path, checkpoint_name)\n",
" break\n",
"\n",
" ! gsutil cp -r $checkpoint_name $CHECKPOINT_BUCKET/\n",
" checkpoint_uri = os.path.join(CHECKPOINT_BUCKET, checkpoint_name, checkpoint_path)\n",
" print(\"Checkpoint uploaded to\", checkpoint_uri)\n",
" return checkpoint_uri"
]
},
{
@@ -665,8 +695,17 @@
" \"prefetch_buffer_size\": 12,\n",
" \"train_steps\": 500,\n",
" \"output_size\": \"1024,2048\",\n",
" \"init_checkpoint\": \"https://storage.googleapis.com/tf_model_garden/vision/deeplabv3plus/dilated-resnet-101-deeplabv3plus.tar.gz\",\n",
" }\n",
"}\n",
"experiment_container_args = experiment_container_args_dict[experiment]\n",
"\n",
"# Copy checkpoint to GCS bucket if specified.\n",
"init_checkpoint = experiment_container_args.get(\"init_checkpoint\")\n",
"if init_checkpoint:\n",
" experiment_container_args[\"init_checkpoint\"] = upload_checkpoint_to_gcs(\n",
" init_checkpoint\n",
" )\n",
"\n",
"worker_pool_specs = [\n",
" {\n",
@@ -681,10 +720,7 @@
" \"args\": [\n",
" \"--mode=train_and_eval\",\n",
" ]\n",
" + [\n",
" \"--{}={}\".format(k, v)\n",
" for k, v in experiment_container_args_dict[experiment].items()\n",
" ],\n",
" + [\"--{}={}\".format(k, v) for k, v in experiment_container_args.items()],\n",
" },\n",
" },\n",
"]\n",
@@ -787,13 +823,11 @@
" \"command\": [],\n",
" \"args\": [\n",
" \"--objective=%s\" % OBJECTIVE,\n",
" \"--experiment=%s\"\n",
" % experiment_container_args_dict[experiment][\"experiment\"],\n",
" \"--experiment=%s\" % experiment_container_args[\"experiment\"],\n",
" \"--config_file=%s/params.yaml\" % best_trial_dir,\n",
" \"--checkpoint_path=%s/best_ckpt\" % best_trial_dir,\n",
" \"--export_dir=%s/best_model\" % model_dir,\n",
" \"--input_image_size=%s\"\n",
" % experiment_container_args_dict[experiment][\"output_size\"],\n",
" \"--input_image_size=%s\" % experiment_container_args[\"output_size\"],\n",
" ],\n",
" },\n",
" }\n",
@@ -1479,7 +1479,7 @@
"source": [
"For more information about VPC peering in Vertex AI, see https://cloud.google.com/vertex-ai/docs/general/vpc-peering.\n",
"\n",
"**IMPORTANT: you can only setup one VPC peering to servicenetworking.googleapis.com per project.**"
"**IMPORTANT: you can only setup one VPC peering to servicenetworking.googleapis.com per VPC network.**"
]
},
{
-34
View File
@@ -1,34 +0,0 @@
tag,notebook,doc
"AutoML, Text data",official/automl/automl-text-classification.ipynb,vertex-ai/docs/text-data/classification/train-model
"AutoML, Tabular data",official/automl/sdk_automl_tabular_forecasting_batch.ipynb,vertex-ai/docs/tabular-data/forecasting/tutorials-samples
"BigQuery, Vertex AI Workbench",official/workbench/exploratory_data_analysis/explore_data_in_bigquery_with_workbench.ipynb,
"BigQuery ML, Vertex AI Model Registry, Batch prediction",official/model-registry/bqml-vertexai-model-registry.ipynb,
"BigQuery ML, Vertex AI Model Registry, Online prediction",official/bigquery_ml/bqml-online-prediction.ipynb,
Custom Training,official/custom/sdk-custom-image-classification-batch.ipynb,
Custom Training,official/custom/sdk-custom-image-classification-online.ipynb,
Tabular Data,official/automl/automl_forecasting_bqml_arima_plus_comparison.ipynb,vertex-ai/docs/tabular-data/forecasting-arima/overview
"AutoML, Tabular Data",official/automl/automl_tabular_on_vertex_pipelines.ipynb,vertex-ai/docs/tabular-data/tabular-workflows/e2e-automl
Vertex AI Experiments,official/experiments/comparing_pipeline_runs.ipynb,
Vertex AI Experiments,official/experiments/build_model_experimentation_lineage_with_prebuild_code.ipynb,
Vertex AI Experiments,official/experiments/comparing_local_trained_models.ipynb,
Vertex AI Feature Store,official/feature_store/sdk-feature-store.ipynb,
Matching Engine,official/matching_engine/sdk_matching_engine_for_indexing.ipynb,
Model Monitoring,official/model_monitoring/model_monitoring.ipynb,
Vertex AI Pipelines,official/pipelines/lightweight_functions_component_io_kfp.ipynb,
"Vertex AI Pipelines Image data",official/pipelines/google_cloud_pipeline_components_automl_images.ipynb,
"Vertex AI Pipelines, Tabular data",official/pipelines/automl_tabular_classification_beans.ipynb,
"Vertex AI Pipelines, Tabular data",official/pipelines/google_cloud_pipeline_components_automl_tabular.ipynb,
"Vertex AI Pipelines, Text data",official/pipelines/google_cloud_pipeline_components_automl_text.ipynb,
Vertex AI Pipelines,official/pipelines/custom_model_training_and_batch_prediction.ipynb,
Vertex AI Pipelines,official/pipelines/google_cloud_pipeline_components_model_train_upload_deploy.ipynb,
Vertex AI Pipelines,official/pipelines/control_flow_kfp.ipynb,
Vertex AI Pipelines,official/pipelines/metrics_viz_run_compare_kfp.ipynb,
Vertex AI Pipelines,official/pipelines/pipelines_intro_kfp.ipynb,
Vertex AI Vizier,official/vizier/gapic-vizier-multi-objective-optimization.ipynb,vertex-ai/docs/vizier/using-vizier
"Vertex Explainable AI, Tabular data",official/explainable_ai/sdk_automl_tabular_binary_classification_batch_explain.ipynb,vertex-ai/docs/explainable-ai/overview
"Vertex Explainable AI, Tabular data",official/explainable_ai/sdk_automl_tabular_classification_online_explain.ipynb,vertex-ai/docs/explainable-ai/overview
"Vertex Explainable AI, Image data",official/explainable_ai/sdk_custom_image_classification_batch_explain.ipynb,vertex-ai/docs/explainable-ai/overview
"Vertex Explainable AI, Image data",official/explainable_ai/sdk_custom_image_classification_online_explain.ipynb,vertex-ai/docs/explainable-ai/overview
"Vertex Explainable AI, Tabular data",official/explainable_ai/sdk_custom_tabular_regression_batch_explain.ipynb,vertex-ai/docs/explainable-ai/overview
"Vertex Explainable AI, Tabular data",official/explainable_ai/sdk_custom_tabular_regression_online_explain.ipynb,vertex-ai/docs/explainable-ai/overview
Vertex ML Metadata,official/ml_metadata/sdk-metric-parameter-tracking-for-custom-jobs.ipynb,
1 tag notebook doc
2 AutoML, Text data official/automl/automl-text-classification.ipynb vertex-ai/docs/text-data/classification/train-model
3 AutoML, Tabular data official/automl/sdk_automl_tabular_forecasting_batch.ipynb vertex-ai/docs/tabular-data/forecasting/tutorials-samples
4 BigQuery, Vertex AI Workbench official/workbench/exploratory_data_analysis/explore_data_in_bigquery_with_workbench.ipynb
5 BigQuery ML, Vertex AI Model Registry, Batch prediction official/model-registry/bqml-vertexai-model-registry.ipynb
6 BigQuery ML, Vertex AI Model Registry, Online prediction official/bigquery_ml/bqml-online-prediction.ipynb
7 Custom Training official/custom/sdk-custom-image-classification-batch.ipynb
8 Custom Training official/custom/sdk-custom-image-classification-online.ipynb
9 Tabular Data official/automl/automl_forecasting_bqml_arima_plus_comparison.ipynb vertex-ai/docs/tabular-data/forecasting-arima/overview
10 AutoML, Tabular Data official/automl/automl_tabular_on_vertex_pipelines.ipynb vertex-ai/docs/tabular-data/tabular-workflows/e2e-automl
11 Vertex AI Experiments official/experiments/comparing_pipeline_runs.ipynb
12 Vertex AI Experiments official/experiments/build_model_experimentation_lineage_with_prebuild_code.ipynb
13 Vertex AI Experiments official/experiments/comparing_local_trained_models.ipynb
14 Vertex AI Feature Store official/feature_store/sdk-feature-store.ipynb
15 Matching Engine official/matching_engine/sdk_matching_engine_for_indexing.ipynb
16 Model Monitoring official/model_monitoring/model_monitoring.ipynb
17 Vertex AI Pipelines official/pipelines/lightweight_functions_component_io_kfp.ipynb
18 Vertex AI Pipelines Image data official/pipelines/google_cloud_pipeline_components_automl_images.ipynb
19 Vertex AI Pipelines, Tabular data official/pipelines/automl_tabular_classification_beans.ipynb
20 Vertex AI Pipelines, Tabular data official/pipelines/google_cloud_pipeline_components_automl_tabular.ipynb
21 Vertex AI Pipelines, Text data official/pipelines/google_cloud_pipeline_components_automl_text.ipynb
22 Vertex AI Pipelines official/pipelines/custom_model_training_and_batch_prediction.ipynb
23 Vertex AI Pipelines official/pipelines/google_cloud_pipeline_components_model_train_upload_deploy.ipynb
24 Vertex AI Pipelines official/pipelines/control_flow_kfp.ipynb
25 Vertex AI Pipelines official/pipelines/metrics_viz_run_compare_kfp.ipynb
26 Vertex AI Pipelines official/pipelines/pipelines_intro_kfp.ipynb
27 Vertex AI Vizier official/vizier/gapic-vizier-multi-objective-optimization.ipynb vertex-ai/docs/vizier/using-vizier
28 Vertex Explainable AI, Tabular data official/explainable_ai/sdk_automl_tabular_binary_classification_batch_explain.ipynb vertex-ai/docs/explainable-ai/overview
29 Vertex Explainable AI, Tabular data official/explainable_ai/sdk_automl_tabular_classification_online_explain.ipynb vertex-ai/docs/explainable-ai/overview
30 Vertex Explainable AI, Image data official/explainable_ai/sdk_custom_image_classification_batch_explain.ipynb vertex-ai/docs/explainable-ai/overview
31 Vertex Explainable AI, Image data official/explainable_ai/sdk_custom_image_classification_online_explain.ipynb vertex-ai/docs/explainable-ai/overview
32 Vertex Explainable AI, Tabular data official/explainable_ai/sdk_custom_tabular_regression_batch_explain.ipynb vertex-ai/docs/explainable-ai/overview
33 Vertex Explainable AI, Tabular data official/explainable_ai/sdk_custom_tabular_regression_online_explain.ipynb vertex-ai/docs/explainable-ai/overview
34 Vertex ML Metadata official/ml_metadata/sdk-metric-parameter-tracking-for-custom-jobs.ipynb
+1 -1
View File
@@ -373,7 +373,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
"! gsutil mb -l {REGION} -p {PROJECT_ID} {BUCKET_URI}"
]
},
{
+2 -1
View File
@@ -41,4 +41,5 @@
/sdk/SDK_FBProphet_Forecasting_Online.ipynb @brianchunkang
/pipelines/Train_tabular_models_with_many_frameworks_and_import_to_Vertex_AI_using_Pipelines @Ark-kun
/experiments/get_started_with_vertex_experiments_autologging.ipynb @inardini
/experiments/delete_outdated_tensorboard_experiments.ipynb @inardini
/experiments/delete_outdated_tensorboard_experiments.ipynb @inardini
/experiments/get_started_with_custom_training_autologging_local_script.ipynb @inardini
+104 -3
View File
@@ -57,6 +57,77 @@ The steps performed are:
&nbsp;&nbsp;&nbsp;Learn more about [BQML ARIMA+ forecasting for tabular data](https://cloud.google.com/vertex-ai/docs/tabular-data/forecasting-arima/overview).
[AutoML training image classification model for batch prediction](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/automl_image_classification_batch_prediction.ipynb)
```
In this tutorial, you create an AutoML image classification model from a Python script, and then do a batch prediction using the Vertex SDK.
The steps performed include:
- Create a Vertex `Dataset` resource.
- Train the model.
- View the model evaluation.
- Make a batch prediction.
```
&nbsp;&nbsp;&nbsp;Learn more about [Get predictions from an image classification model](https://cloud.google.com/vertex-ai/docs/image-data/classification/get-predictions).
[AutoML training image classification model for online prediction](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/automl_image_classification_online_prediction.ipynb)
```
In this tutorial, you create an AutoML image classification model and deploy for online prediction from a Python script using the Vertex SDK.
The steps performed include:
- Create a Vertex `Dataset` resource.
- Train the model.
- View the model evaluation.
- Deploy the `Model` resource to a serving `Endpoint` resource.
- Make a prediction.
- Undeploy the `Model`.
```
&nbsp;&nbsp;&nbsp;Learn more about [Get predictions from an image classification model](https://cloud.google.com/vertex-ai/docs/image-data/classification/get-predictions).
[AutoML training image object detection model for export to edge](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/automl_image_object_detection_export_edge.ipynb)
```
In this tutorial, you create an AutoML image object detection model from a Python script using the Vertex SDK, and then export the model as an Edge model in TFLite format.
The steps performed include:
- Create a Vertex `Dataset` resource.
- Train the model.
- Export the `Edge` model from the `Model` resource to Cloud Storage.
- Download the model locally.
- Make a local prediction.
```
[AutoML training image object detection model for online prediction](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/automl_image_object_detection_online_prediction.ipynb)
```
In this tutorial, you create an AutoML image object detection model and deploy for online prediction from a Python script using the Vertex AI SDK.
The steps performed include:
- Create a Vertex `Dataset` resource.
- Train the model.
- View the model evaluation.
- Deploy the `Model` resource to a serving `Endpoint` resource.
- Make a prediction.
- Undeploy the `Model`.
```
&nbsp;&nbsp;&nbsp;Learn more about [Object detection for image data](https://cloud.google.com/vertex-ai/docs/training-overview#object_detection_for_images).
[AutoML Tabular Workflow pipelines](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/automl_tabular_on_vertex_pipelines.ipynb)
```
@@ -72,6 +143,38 @@ The steps performed are:
&nbsp;&nbsp;&nbsp;Learn more about [Tabular Workflow for E2E AutoML](https://cloud.google.com/vertex-ai/docs/tabular-data/tabular-workflows/e2e-automl).
[AutoML training text entity extraction model for batch prediction](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/automl_text_entity_extraction_batch_prediction.ipynb)
```
In this tutorial, you create an AutoML text entity extraction model from a Python script, and then do a batch prediction using the Vertex AI SDK.
The steps performed include:
- Create a Vertex `Dataset` resource.
- Train the model.
- View the model evaluation.
- Make a batch prediction.
```
&nbsp;&nbsp;&nbsp;Learn more about [Entity extraction for text data](https://cloud.google.com/vertex-ai/docs/training-overview#entity_extraction_for_text).
[AutoML training text sentiment analysis model for batch prediction](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/automl_text_sentiment_analysis_batch_prediction.ipynb)
```
In this tutorial, you create an AutoML text sentiment analysis model from a Python script, and then do a batch prediction using the Vertex SDK.
The steps performed include:
- Create a Vertex `Dataset` resource.
- Train the model.
- View the model evaluation.
- Make a batch prediction.
```
[Get started with AutoML Training](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/get_started_automl_training.ipynb)
```
@@ -101,9 +204,7 @@ The steps performed include:
- Create a Vertex AI `TimeSeriesDataset` resource.
- Train the model.
- View the model evaluation.
- Deploy the `Model` resource to a serving `Endpoint` resource.
- Make a prediction.
- Undeploy the `Model`.
- Make a batch prediction.
```
@@ -142,284 +142,171 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\") and not os.getenv(\"VIRTUAL_ENV\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"# Install the packagesimport os\n",
"! pip3 install {USER_FLAG} -q --upgrade google-cloud-aiplatform \\\n",
" google-cloud-storage"
"# Install the packages\n",
"! pip3 install --quiet --upgrade google-cloud-aiplatform \\\n",
" google-cloud-storage"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d3a26cb9b19d"
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EzrelQZ22IZj"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0e3cab0cc491"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"## Before you begin\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"\"\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Get your Google Cloud project ID from gcloud\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID: \", PROJECT_ID)"
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qJYoRfYng0XZ"
"id": "region"
},
"source": [
"Otherwise, set your project ID here."
"#### Region\n",
"\n",
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
"id": "region"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "06571eb4063b"
},
"source": [
"### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "697568e92bd6"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dr--iN2kAylZ"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Notebooks**, your environment is already\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sBCra4QMA2wR"
},
"source": [
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "535223fa4b84"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"# The Google Cloud Notebook product has specific requirements\n",
"IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
"\n",
"# If on Google Cloud Notebooks, then don't execute this code\n",
"if not IS_GOOGLE_CLOUD_NOTEBOOK:\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zgPO1eR3CYjk"
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"This notebook demonstrates how to use Vertex AI SDK for Python to create an AutoML model based on a tabular dataset. You will need to provide a Cloud Storage bucket where the dataset will be stored.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all of your \n",
"Cloud Storage buckets.\n",
"\n",
"You may also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Make sure to [choose a region where Vertex AI services are\n",
"available](https://cloud.google.com/vertex-ai/docs/general/locations). You may\n",
"not use a Multi-Regional Storage bucket for training with Vertex AI."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MzGDU7TWdts_"
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"gs://[your-bucket-name]\" # @param {type:\"string\"}\n",
"REGION = \"[your-region]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cf221059d072"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n",
" BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-EcIXiGsCePi"
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
@@ -429,31 +316,11 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NIq7R4HZCfIc"
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ucvCsknMCims"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vhOb7YnwClBb"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_NAME"
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
@@ -474,9 +341,9 @@
"outputs": [],
"source": [
"IMPORT_FILE = \"petfinder-tabular-classification.csv\"\n",
"! gsutil cp gs://cloud-samples-data/ai-platform-unified/datasets/tabular/{IMPORT_FILE} {BUCKET_NAME}/data/\n",
"! gsutil cp gs://cloud-samples-data/ai-platform-unified/datasets/tabular/{IMPORT_FILE} {BUCKET_URI}/data/\n",
"\n",
"gcs_source = f\"{BUCKET_NAME}/data/{IMPORT_FILE}\""
"gcs_source = f\"{BUCKET_URI}/data/{IMPORT_FILE}\""
]
},
{
@@ -485,9 +352,9 @@
"id": "Y9Uo3tifg1kx"
},
"source": [
"### Import Vertex SDK for Python\n",
"### Import Vertex AI SDK for Python\n",
"\n",
"Import the Vertex SDK into your Python environment and initialize it."
"Import the Vertex AI SDK into your Python environment and initialize it."
]
},
{
@@ -549,7 +416,7 @@
"id": "ba5011d50ac7"
},
"source": [
"### Launch a Training Job to Create a Model\n",
"### Launch a training job to create a Model\n",
"\n",
"Once we have defined your training script, we will create a model. The `run` function creates a training pipeline that trains and creates a `Model` object. After the training pipeline completes, the `run` function returns the `Model` object."
]
@@ -726,10 +593,6 @@
},
"outputs": [],
"source": [
"delete_training_job = True\n",
"delete_model = True\n",
"delete_endpoint = True\n",
"\n",
"# Warning: Setting this to true will delete everything in your bucket\n",
"delete_bucket = False\n",
"\n",
@@ -742,8 +605,8 @@
"# Delete the endpoint\n",
"endpoint.delete()\n",
"\n",
"if delete_bucket and \"BUCKET_NAME\" in globals():\n",
" ! gsutil -m rm -r $BUCKET_NAME"
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil -m rm -r $BUCKET_URI"
]
}
],
@@ -309,7 +309,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"your-bucket-name-unique\" # @param {type:\"string\"}\n",
"BUCKET_NAME = f\"your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
@@ -330,7 +330,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
"! gsutil mb -l {REGION} {BUCKET_URI}"
]
},
{
@@ -88,8 +88,8 @@
"- Make a batch prediction with the BigQuery ML model.\n",
"- Create a Vertex AI `Dataset` resource.\n",
"- Train the Vertex AI Forecasting model.\n",
"- View the Model evaluation.\n",
"- Make a batch prediction with the Model.\n"
"- View the Vertex AI Model Evaluation results.\n",
"- Make a batch prediction with the Vertex AI Forecasting model.\n"
]
},
{
@@ -124,38 +124,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_local"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements. You need the following:\n",
"\n",
"- The Cloud Storage SDK\n",
"- Python 3\n",
"- virtualenv\n",
"- Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Cloud Storage guide to [Setting up a Python development environment](https://cloud.google.com/python/setup) and the [Jupyter installation guide](https://jupyter.org/install) provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions:\n",
"\n",
"1. [Install and initialize the SDK](https://cloud.google.com/sdk/docs/).\n",
"\n",
"2. [Install Python 3](https://cloud.google.com/python/setup#installing_python).\n",
"\n",
"3. [Install virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv) and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"4. To install Jupyter, run `pip3 install jupyter` on the command-line in a terminal shell.\n",
"\n",
"5. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"6. Open this notebook in the Jupyter Notebook Dashboard.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -175,21 +143,7 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"else:\n",
" USER_FLAG = \"\"\n",
"\n",
"! (pip3 install --upgrade $USER_FLAG \\\n",
"! (pip3 install --upgrade --quiet \\\n",
" google-cloud-bigquery[pandas]==2.34.4 \\\n",
" google-cloud-aiplatform==1.16.1 \\\n",
" google-cloud-pipeline-components==1.0.23)"
@@ -201,29 +155,22 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages.\n",
"\n",
"**Note: You may get a message saying \"Your session crashed for an unknown reason.\", this is expected. Once this cell has finished running, continue on. You do not need to re-run any of the cells above.**"
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PMiYln_IQEH5"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
@@ -234,39 +181,12 @@
"source": [
"## Before you begin\n",
"\n",
"### GPU runtime\n",
"\n",
"This tutorial does not require a GPU runtime.\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"6. (optional) You may also specify a service account to use to run Vertex AI Pipelines in the project.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JDzPOakHF1d2"
},
"source": [
"### Set your project ID\n",
"\n",
"Set your project ID below. If you know know your project ID, leave the field blank and the following cells may be able to find it. Optionally, you may also set a service account in the cell below."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -277,33 +197,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -313,18 +210,8 @@
},
"source": [
"#### Region\n",
"All BigQuery operations (`DATA_REGION`) are set to run in the `US` multi-region. This is required by the ARIMA pipeline because the data you use is stored in this region. All destination tables will also be stored in this region.\n",
"\n",
"You may change the `REGION` variable, which is used for Vertex AI Forecasting operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)"
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -335,42 +222,8 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"DATA_REGION = \"US\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "84Vdv7R-QEH6"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"REGION = \"us-central1\"\n",
"DATA_REGION = \"US\""
]
},
{
@@ -381,56 +234,54 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"- In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"- **Click Create service account**.\n",
"\n",
"- In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"- In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"- Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"- Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ssKjl9KrQEH6"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS '[your-service-account-key-path]'"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -441,11 +292,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex AI SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -456,21 +303,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4FxNxXwW3inJ"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -490,27 +323,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9axiWxVBQEH7"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
"! gsutil mb -l {REGION} -p {PROJECT_ID} {BUCKET_URI}"
]
},
{
@@ -543,6 +356,9 @@
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if (\n",
" SERVICE_ACCOUNT == \"\"\n",
" or SERVICE_ACCOUNT is None\n",
@@ -603,7 +419,9 @@
"outputs": [],
"source": [
"import json\n",
"import os\n",
"import urllib\n",
"import uuid\n",
"\n",
"import pandas as pd\n",
"from google.cloud import aiplatform, bigquery\n",
@@ -661,23 +479,29 @@
},
"outputs": [],
"source": [
"arima_dataset_name = f\"forecasting_demo_arima_{UUID}\"\n",
"vertex_dataset_name = f\"forecasting_demo_vertex_{UUID}\"\n",
"arima_dataset_name = \"forecasting_demo_arima\"\n",
"vertex_dataset_name = \"forecasting_demo_vertex\"\n",
"\n",
"arima_dataset_path = \".\".join([PROJECT_ID, arima_dataset_name])\n",
"vertex_dataset_path = \".\".join([PROJECT_ID, vertex_dataset_name])\n",
"\n",
"# Must be same region as TRAINING_DATASET_BQ_PATH.\n",
"client = bigquery.Client(project=PROJECT_ID)\n",
"bq_dataset = bigquery.Dataset(arima_dataset_path)\n",
"bq_dataset.location = DATA_REGION\n",
"bq_dataset = client.create_dataset(bq_dataset)\n",
"bq_dataset_pre = bigquery.Dataset(arima_dataset_path)\n",
"bq_dataset_pre.location = DATA_REGION\n",
"try:\n",
" bq_dataset = client.create_dataset(bq_dataset_pre)\n",
"except:\n",
" bq_dataset = client.get_dataset(bq_dataset_pre)\n",
"print(f\"Created bigquery dataset {arima_dataset_path} in {DATA_REGION}\")\n",
"\n",
"# Make this the same region as the other dataset for easier comparisons.\n",
"bq_dataset = bigquery.Dataset(vertex_dataset_path)\n",
"bq_dataset.location = DATA_REGION\n",
"bq_dataset = client.create_dataset(bq_dataset)\n",
"bq_dataset_pre = bigquery.Dataset(vertex_dataset_path)\n",
"bq_dataset_pre.location = DATA_REGION\n",
"try:\n",
" bq_dataset = client.create_dataset(bq_dataset_pre)\n",
"except:\n",
" bq_dataset = client.get_dataset(bq_dataset_pre)\n",
"print(f\"Created bigquery dataset {vertex_dataset_path} in {DATA_REGION}\")"
]
},
@@ -1007,7 +831,7 @@
"outputs": [],
"source": [
"# The display name should be unique even if this cell is rerun.\n",
"DISPLAY_NAME = f\"forecasting-demo-train-{generate_uuid()}\"\n",
"DISPLAY_NAME = f\"forecasting-demo-train-{str(uuid.uuid1())}\"\n",
"\n",
"job = aiplatform.PipelineJob(\n",
" job_id=DISPLAY_NAME,\n",
@@ -1141,7 +965,7 @@
"outputs": [],
"source": [
"# The display name should be unique even if this cell is rerun.\n",
"DISPLAY_NAME = f\"forecasting-demo-predict-{generate_uuid()}\"\n",
"DISPLAY_NAME = \"forecasting-demo-predict\"\n",
"\n",
"job = aiplatform.PipelineJob(\n",
" job_id=DISPLAY_NAME,\n",
@@ -1327,7 +1151,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.TimeSeriesDataset.create(\n",
" display_name=\"forecasting_demo_train\" + \"_\" + UUID,\n",
" display_name=\"forecasting_demo_train\",\n",
" bq_source=[TRAINING_DATASET_BQ_PATH],\n",
")\n",
"print(dataset.resource_name)"
@@ -1394,7 +1218,7 @@
},
"outputs": [],
"source": [
"MODEL_DISPLAY_NAME = f\"forecasting-demo-model_{UUID}\"\n",
"MODEL_DISPLAY_NAME = \"forecasting-demo-model\"\n",
"\n",
"training_job = aiplatform.AutoMLForecastingTrainingJob(\n",
" display_name=MODEL_DISPLAY_NAME,\n",
@@ -1568,7 +1392,7 @@
"outputs": [],
"source": [
"batch_prediction_job = model.batch_predict(\n",
" job_display_name=f\"forecasting_demo_predictions_{UUID}\",\n",
" job_display_name=\"forecasting_demo_predictions\",\n",
" bigquery_source=PREDICTION_DATASET_BQ_PATH,\n",
" instances_format=\"bigquery\",\n",
" bigquery_destination_prefix=f\"bq://{vertex_dataset_path}\",\n",
@@ -143,12 +143,10 @@
"source": [
"import os\n",
"\n",
"USER_FLAG = \"\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG\n",
"! pip3 install --upgrade --quiet google-cloud-aiplatform\n",
"\n",
"if os.environ[\"IS_TESTING\"]:\n",
" ! pip3 install --upgrade tensorflow $USER_FLAG"
" ! pip3 install --upgrade --quiet tensorflow"
]
},
{
@@ -137,12 +137,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"USER_FLAG = \"\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform \\\n",
" tensorflow $USER_FLAG"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" tensorflow"
]
},
{
@@ -362,6 +358,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"import google.cloud.aiplatform as aiplatform"
]
},
@@ -141,13 +141,7 @@
"source": [
"import os\n",
"\n",
"# Google Cloud Notebook\n",
"if os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
" USER_FLAG = \"--user\"\n",
"else:\n",
" USER_FLAG = \"\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG\n",
"! pip3 install --upgrade --quiet google-cloud-aiplatform\n",
"\n",
"if os.environ[\"IS_TESTING\"]:\n",
" ! pip3 install --upgrade tensorflow $USER_FLAG"
@@ -370,6 +364,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"import google.cloud.aiplatform as aiplatform"
]
},
@@ -146,10 +146,8 @@
"source": [
"import os\n",
"\n",
"USER_FLAG = \"\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform \\\n",
" tensorflow $USER_FLAG\n",
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" tensorflow\n",
"\n",
"if os.environ[\"IS_TESTING\"]:\n",
" ! pip3 install --upgrade tensorflow $USER_FLAG"
@@ -122,44 +122,12 @@
{
"cell_type": "markdown",
"metadata": {
"id": "tuOonx6suOb7"
"id": "install_aip:mbsdk"
},
"source": [
"### Set up your local development environment\n",
"## Installation\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements. You need the following:\n",
"\n",
"- The Cloud Storage SDK\n",
"- Python 3\n",
"- virtualenv\n",
"- Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Cloud Storage guide to [Setting up a Python development environment](https://cloud.google.com/python/setup) and the [Jupyter installation guide](https://jupyter.org/install) provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions:\n",
"\n",
"1. [Install and initialize the SDK](https://cloud.google.com/sdk/docs/).\n",
"\n",
"2. [Install Python 3](https://cloud.google.com/python/setup#installing_python).\n",
"\n",
"3. [Install virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv) and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"4. To install Jupyter, run `pip3 install jupyter` on the command-line in a terminal shell.\n",
"\n",
"5. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"6. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e85f0288a6df"
},
"source": [
"## Install additional packages\n",
"\n",
"Install the latest version of the Google Cloud Pipeline Components (GCPC) SDK."
"Install the latest version of Vertex AI SDK for Python."
]
},
{
@@ -170,38 +138,32 @@
},
"outputs": [],
"source": [
"!pip install -U google-cloud-pipeline-components==1.0.25 -q"
"!pip3 install --upgrade --quiet google-cloud-pipeline-components==1.0.25 \\\n",
" google-cloud-aiplatform"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Bj5O0S5RTxzY"
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages.\n",
"\n",
"\n",
"**Note: Once this cell has finished running, continue on. You do not need to re-run any of the cells above.**\n"
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "023DMKUaTypt"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
@@ -212,26 +174,26 @@
"source": [
"## Before you begin\n",
"\n",
"### GPU runtime\n",
"### Set your project ID\n",
"\n",
"This tutorial does not require a GPU runtime.\n",
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Dataflow APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,dataflow.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$`."
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -248,224 +210,123 @@
{
"cell_type": "markdown",
"metadata": {
"id": "95cb7ffd6895"
"id": "region"
},
"source": [
"### Set your project ID\n",
"#### Region\n",
"\n",
"Set your project ID below. If you know know your project ID, leave the field blank and the following cells may be able to find it. Optionally, you may also set a service account in the cell below."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cd85f5c794e5"
"id": "region"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5a604eeffc32"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "30e64c0eda41"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b12f508d97c6"
},
"source": [
"### Region\n",
"You may change the `REGION` variable, which is used for Vertex Forecasting operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8e8b7997de7a"
},
"outputs": [],
"source": [
"REGION = \"us-central1\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eu0e2TRVxjHb"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Google Cloud Notebooks**, your environment is already authenticated. Skip this step.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"- In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"- **Click Create service account**.\n",
"\n",
"- In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"- In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"- Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"- Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_nJ1VqdTxosw"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS '[your-service-account-key-path]'"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OUfwWir9yPNV"
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"All training related files (TF model checkpoint, TensorBoard file, etc) will be saved to the GCS bucket. The pipeline will not clean up the files since some of them might be useful for you, **please make sure to clean up the files**. For easy cleanup, you can set [GCS bucket level TTL](https://cloud.google.com/storage/docs/lifecycle).\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization.\n"
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5325f437b46a"
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_URI = \"gs://[your-bucket-name]\" # @param {type:\"string\"}\n",
"GENERATE_BUCKET_URI = True # @param {type:\"boolean\"}"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a30ea8551126"
"id": "create_bucket"
},
"source": [
"Create the bucket if it doesn't already exist."
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0217c63ed87f"
"id": "create_bucket"
},
"outputs": [],
"source": [
"import uuid\n",
"\n",
"if GENERATE_BUCKET_URI:\n",
" bucket_name = \"gs://test-{}\".format(uuid.uuid4())\n",
" !gsutil mb -p {PROJECT_ID} -l {REGION} {bucket_name}\n",
"\n",
" # set GCS bucket object TTL to 7 days\n",
" !echo '{\"rule\":[{\"action\": {\"type\": \"Delete\"},\"condition\": {\"age\": 7}}]}' > gcs_lifecycle.tmp\n",
" !gsutil lifecycle set gcs_lifecycle.tmp {bucket_name}\n",
" !rm gcs_lifecycle.tmp\n",
"\n",
" BUCKET_URI = bucket_name\n",
" print(f\"changed BUCKET_URI to {BUCKET_URI} due to GENERATE_BUCKET_URI is True\")\n",
"\n",
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_URI = \"gs://\" + PROJECT_ID + \"aip-\" + uuid.uuid4()\n",
"\n",
"! gsutil ls -b $BUCKET_URI || gsutil mb -l $DATA_REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c4cf2cdebb50"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "96ad3d416327"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
@@ -556,8 +417,10 @@
},
"outputs": [],
"source": [
"# Import required modules\n",
"import json\n",
"# Import required modules\n",
"import os\n",
"import uuid\n",
"from typing import Any, Dict, List\n",
"\n",
"from google.cloud import aiplatform, storage\n",
@@ -571,9 +434,9 @@
"id": "c0423f260423"
},
"source": [
"## Initialize Vertex SDK for Python\n",
"## Initialize Vertex AI SDK for Python\n",
"\n",
"Initialize the Vertex SDK for Python for your project."
"Initialize the Vertex AI SDK for Python for your project."
]
},
{
@@ -168,21 +168,10 @@
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\") and not os.getenv(\"VIRTUAL_ENV\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"# Install the packages\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install --upgrade google-cloud-storage $USER_FLAG -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage "
]
},
{
@@ -191,64 +180,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "project_id"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"### Set your project ID\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI, Compute Engine and Cloud Storage APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage_component).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5aee4379e8e5"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -259,33 +222,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -296,16 +236,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -316,95 +247,65 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3ffa6b6c7cdb"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"1. **Click Create service account**.\n",
"\n",
"2. In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"3. In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex AI\" into the filter box, and select **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"4. Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"5. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2b72272258fc"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -415,11 +316,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -430,21 +327,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = \"gs://\" + BUCKET_NAME"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -467,26 +350,6 @@
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -501,12 +364,14 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": null,
"metadata": {
"id": "import_aip:mbsdk"
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"import google.cloud.aiplatform as aiplatform"
]
},
@@ -791,7 +656,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.ImageDataset.create(\n",
" display_name=\"flowers_\" + TIMESTAMP,\n",
" display_name=\"flowers\",\n",
" gcs_source=[IMPORT_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.image.single_label_classification,\n",
")\n",
@@ -839,7 +704,7 @@
"outputs": [],
"source": [
"dag = aiplatform.AutoMLImageTrainingJob(\n",
" display_name=\"flowers_\" + TIMESTAMP,\n",
" display_name=\"flowers\",\n",
" prediction_type=\"classification\",\n",
" multi_label=False,\n",
" model_type=\"MOBILE_TF_LOW_LATENCY_1\",\n",
@@ -894,7 +759,7 @@
"source": [
"model = dag.run(\n",
" dataset=dataset,\n",
" model_display_name=\"flowers_\" + TIMESTAMP,\n",
" model_display_name=\"flowers\",\n",
" training_fraction_split=0.8,\n",
" validation_fraction_split=0.1,\n",
" test_fraction_split=0.1,\n",
@@ -1037,7 +902,7 @@
"\n",
"# Download the test image in bytes format\n",
"storage_client = storage.Client(project=PROJECT_ID)\n",
"bucket = storage_client.bucket(bucket_name=BUCKET_NAME)\n",
"bucket = storage_client.bucket(bucket_name=BUCKET_URI[5:])\n",
"test_content = bucket.get_blob(\"test.jpg\").download_as_bytes()\n",
"\n",
"# The format of each instance should conform to the deployed model's prediction input schema.\n",
@@ -1306,9 +1171,9 @@
"outputs": [],
"source": [
"dataset = aiplatform.TabularDataset.create(\n",
" display_name=\"gsod_\" + TIMESTAMP,\n",
" display_name=\"gsod\",\n",
" bq_source=[IMPORT_FILE],\n",
" labels={\"user_metadata\": BUCKET_NAME},\n",
" labels={\"user_metadata\": BUCKET_URI[5:]},\n",
")\n",
"\n",
"label_column = \"mean_temp\"\n",
@@ -1376,7 +1241,7 @@
"outputs": [],
"source": [
"dag = aiplatform.AutoMLTabularTrainingJob(\n",
" display_name=\"gsod_\" + TIMESTAMP,\n",
" display_name=\"gsod\",\n",
" optimization_prediction_type=\"regression\",\n",
" optimization_objective=\"minimize-rmse\",\n",
" column_transformations=TRANSFORMATIONS,\n",
@@ -1419,7 +1284,7 @@
"source": [
"model = dag.run(\n",
" dataset=dataset,\n",
" model_display_name=\"gsod_\" + TIMESTAMP,\n",
" model_display_name=\"gsod\",\n",
" training_fraction_split=0.8,\n",
" validation_fraction_split=0.1,\n",
" test_fraction_split=0.1,\n",
@@ -1845,7 +1710,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.TextDataset.create(\n",
" display_name=\"happydb_\" + TIMESTAMP,\n",
" display_name=\"happydb\",\n",
" gcs_source=[IMPORT_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.text.single_label_classification,\n",
")\n",
@@ -1885,7 +1750,7 @@
"outputs": [],
"source": [
"dag = aiplatform.AutoMLTextTrainingJob(\n",
" display_name=\"happydb_\" + TIMESTAMP,\n",
" display_name=\"happydb\",\n",
" prediction_type=\"classification\",\n",
" multi_label=False,\n",
")\n",
@@ -1924,7 +1789,7 @@
"source": [
"model = dag.run(\n",
" dataset=dataset,\n",
" model_display_name=\"happydb_\" + TIMESTAMP,\n",
" model_display_name=\"happydb\",\n",
" training_fraction_split=0.8,\n",
" validation_fraction_split=0.1,\n",
" test_fraction_split=0.1,\n",
@@ -2304,7 +2169,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.VideoDataset.create(\n",
" display_name=\"human_motion_\" + TIMESTAMP,\n",
" display_name=\"human_motion\",\n",
" gcs_source=[IMPORT_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.video.classification,\n",
")\n",
@@ -2342,7 +2207,7 @@
"outputs": [],
"source": [
"dag = aiplatform.AutoMLVideoTrainingJob(\n",
" display_name=\"human_motion_\" + TIMESTAMP,\n",
" display_name=\"human_motion\",\n",
" prediction_type=\"classification\",\n",
")\n",
"\n",
@@ -2379,7 +2244,7 @@
"source": [
"model = dag.run(\n",
" dataset=dataset,\n",
" model_display_name=\"human_motion_\" + TIMESTAMP,\n",
" model_display_name=\"human_motion\",\n",
" training_fraction_split=0.8,\n",
" test_fraction_split=0.2,\n",
")"
@@ -122,48 +122,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_local"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* The Google Cloud SDK\n",
"* Git\n",
"* Python 3\n",
"* virtualenv\n",
"* Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Google Cloud guide to [Setting up a Python development\n",
"environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
"installation guide](https://jupyter.org/install) provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
"\n",
"1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
"\n",
"1. [Install\n",
" virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip3 install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -185,18 +143,7 @@
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform"
]
},
{
@@ -205,72 +152,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0e3cab0cc491"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin:nogpu"
},
"source": [
"### Set up your Google Cloud project\n",
"## Before you begin\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"### Set your project ID\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1460fd744366"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -281,33 +194,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -318,16 +208,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. It is recommended that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -338,41 +219,7 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
@@ -383,64 +230,54 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. Skip this step.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell.\n"
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gcp_authenticate"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -451,11 +288,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -466,21 +299,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -503,26 +322,6 @@
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -629,7 +428,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.TimeSeriesDataset.create(\n",
" display_name=\"iowa_liquor_sales_train\" + \"_\" + UUID,\n",
" display_name=\"iowa_liquor_sales_train\",\n",
" bq_source=[TRAINING_DATASET_BQ_PATH],\n",
")\n",
"\n",
@@ -689,7 +488,7 @@
},
"outputs": [],
"source": [
"MODEL_DISPLAY_NAME = f\"iowa-liquor-sales-forecast-model_{UUID}\"\n",
"MODEL_DISPLAY_NAME = \"iowa-liquor-sales-forecast-model\"\n",
"\n",
"training_job = aiplatform.AutoMLForecastingTrainingJob(\n",
" display_name=MODEL_DISPLAY_NAME,\n",
@@ -812,7 +611,7 @@
},
"outputs": [],
"source": [
"batch_predict_bq_output_dataset_name = f\"iowa_liquor_sales_predictions_{UUID}\"\n",
"batch_predict_bq_output_dataset_name = \"iowa_liquor_sales_predictions\"\n",
"batch_predict_bq_output_dataset_path = \"{}.{}\".format(\n",
" PROJECT_ID, batch_predict_bq_output_dataset_name\n",
")\n",
@@ -833,7 +632,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "99b7a9287ba6"
@@ -857,7 +655,7 @@
")\n",
"\n",
"batch_prediction_job = model.batch_predict(\n",
" job_display_name=f\"iowa_liquor_sales_forecasting_predictions_{UUID}\",\n",
" job_display_name=\"iowa_liquor_sales_forecasting_predictions\",\n",
" bigquery_source=PREDICTION_DATASET_BQ_PATH,\n",
" instances_format=\"bigquery\",\n",
" bigquery_destination_prefix=batch_predict_bq_output_uri_prefix,\n",
@@ -123,39 +123,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_local"
},
"source": [
"### Set up your local development environment\n",
"\n",
"If you are using Colab or Google Cloud Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step.\n",
"\n",
"Otherwise, make sure your environment meets this notebook's requirements. You need the following:\n",
"\n",
"- The Cloud Storage SDK\n",
"- Git\n",
"- Python 3\n",
"- virtualenv\n",
"- Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Cloud Storage guide to [Setting up a Python development environment](https://cloud.google.com/python/setup) and the [Jupyter installation guide](https://jupyter.org/install) provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions:\n",
"\n",
"1. [Install and initialize the SDK](https://cloud.google.com/sdk/docs/).\n",
"\n",
"2. [Install Python 3](https://cloud.google.com/python/setup#installing_python).\n",
"\n",
"3. [Install virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv) and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"4. To install Jupyter, run `pip3 install jupyter` on the command-line in a terminal shell.\n",
"\n",
"5. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"6. Open this notebook in the Jupyter Notebook Dashboard.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -164,7 +131,7 @@
"source": [
"## Installation\n",
"\n",
"Install the latest version of Vertex SDK for Python."
"Install the latest version of Vertex AI SDK for Python."
]
},
{
@@ -177,33 +144,8 @@
"source": [
"import os\n",
"\n",
"# Google Cloud Notebook\n",
"if os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
" USER_FLAG = \"--user\"\n",
"else:\n",
" USER_FLAG = \"\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "install_storage"
},
"source": [
"Install the latest GA version of *google-cloud-storage* library as well."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_storage"
},
"outputs": [],
"source": [
"! pip3 install -U google-cloud-storage $USER_FLAG"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage"
]
},
{
@@ -212,57 +154,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin:nogpu"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### GPU runtime\n",
"### Set your project ID\n",
"\n",
"This tutorial does not require a GPU runtime.\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -273,33 +196,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -310,16 +210,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)"
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -330,33 +221,7 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
@@ -367,53 +232,54 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Google Cloud Notebooks**, your environment is already authenticated. Skip this step.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"**Click Create service account**.\n",
"\n",
"In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gcp_authenticate"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Google Cloud Notebook, then don't execute this code\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -424,11 +290,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -439,19 +301,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"gs://[your-bucket-name]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n",
" BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -471,27 +321,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_NAME"
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
]
},
{
@@ -538,7 +368,7 @@
},
"outputs": [],
"source": [
"aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME)"
"aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)"
]
},
{
@@ -630,7 +460,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.TextDataset.create(\n",
" display_name=\"NCBI Biomedical\" + \"_\" + TIMESTAMP,\n",
" display_name=\"NCBI Biomedical\",\n",
" gcs_source=[IMPORT_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.text.extraction,\n",
")\n",
@@ -670,7 +500,7 @@
"outputs": [],
"source": [
"job = aiplatform.AutoMLTextTrainingJob(\n",
" display_name=\"biomedical_\" + TIMESTAMP, prediction_type=\"extraction\"\n",
" display_name=\"biomedical\", prediction_type=\"extraction\"\n",
")\n",
"\n",
"print(job)"
@@ -707,7 +537,7 @@
"source": [
"model = job.run(\n",
" dataset=dataset,\n",
" model_display_name=\"biomedical_\" + TIMESTAMP,\n",
" model_display_name=\"biomedical\",\n",
" training_fraction_split=0.8,\n",
" validation_fraction_split=0.1,\n",
" test_fraction_split=0.1,\n",
@@ -735,7 +565,7 @@
"outputs": [],
"source": [
"# Get model resource ID\n",
"models = aiplatform.Model.list(filter=\"display_name=biomedical_\" + TIMESTAMP)\n",
"models = aiplatform.Model.list(filter=\"display_name=biomedical\")\n",
"\n",
"# Get a reference to the Model Service client\n",
"client_options = {\"api_endpoint\": f\"{REGION}-aiplatform.googleapis.com\"}\n",
@@ -916,7 +746,7 @@
"job.delete()\n",
"\n",
"if os.getenv(\"IS_TESTING\"):\n",
" ! gsutil -m rm -r $BUCKET_NAME"
" ! gsutil -m rm -r $BUCKET_URI"
]
}
],
@@ -124,44 +124,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_local"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* The Google Cloud SDK\n",
"\n",
"The Google Cloud guide to [Setting up a Python development\n",
"environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
"installation guide](https://jupyter.org/install) provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
"\n",
"1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
"\n",
"1. [Install\n",
" virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip3 install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -183,19 +145,8 @@
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install -U google-cloud-storage $USER_FLAG -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage"
]
},
{
@@ -204,65 +155,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin:nogpu"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"### Set your project ID\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI, Compute Engine, and Cloud Storage APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "af794e75b7e3"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -273,33 +197,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -310,16 +211,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)"
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -330,41 +222,7 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
@@ -375,64 +233,54 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. \n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gcp_authenticate"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS '[your-service-account-key-path]'"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -443,11 +291,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize your Vertex AI SDK, you provide a Cloud Storage bucket to the SDK to serve as a staging bucket for the session. \n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -458,21 +302,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -495,26 +325,6 @@
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -638,7 +448,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.TextDataset.create(\n",
" display_name=\"Crowdflower Claritin-Twitter\" + \"_\" + UUID,\n",
" display_name=\"Crowdflower Claritin-Twitter\",\n",
" gcs_source=[IMPORT_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.text.sentiment,\n",
")\n",
@@ -681,7 +491,7 @@
"outputs": [],
"source": [
"job = aiplatform.AutoMLTextTrainingJob(\n",
" display_name=\"claritin_\" + UUID,\n",
" display_name=\"claritin\",\n",
" prediction_type=\"sentiment\",\n",
" sentiment_max=SENTIMENT_MAX,\n",
")\n",
@@ -720,7 +530,7 @@
"source": [
"model = job.run(\n",
" dataset=dataset,\n",
" model_display_name=\"claritin_\" + UUID,\n",
" model_display_name=\"claritin\",\n",
" training_fraction_split=0.8,\n",
" validation_fraction_split=0.1,\n",
" test_fraction_split=0.1,\n",
@@ -749,7 +559,7 @@
"outputs": [],
"source": [
"# Get model resource ID\n",
"models = aiplatform.Model.list(filter=\"display_name=claritin_\" + UUID)\n",
"models = aiplatform.Model.list(filter=\"display_name=claritin\")\n",
"\n",
"# Get a reference to the Model Service client\n",
"client_options = {\"api_endpoint\": f\"{REGION}-aiplatform.googleapis.com\"}\n",
@@ -130,48 +130,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_local"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* The Google Cloud SDK\n",
"* Git\n",
"* Python 3\n",
"* virtualenv\n",
"* Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Google Cloud guide to [Setting up a Python development\n",
"environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
"installation guide](https://jupyter.org/install) provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
"\n",
"1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
"\n",
"1. [Install\n",
" virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip3 install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -193,17 +151,8 @@
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --upgrade --quiet {USER_FLAG} google-cloud-aiplatform google-cloud-storage"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage"
]
},
{
@@ -212,65 +161,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin:nogpu"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"### Set your project ID\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5aee4379e8e5"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -281,33 +203,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -318,16 +217,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. It is recommended that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -338,41 +228,7 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
@@ -383,64 +239,54 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. \n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gcp_authenticate"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -451,11 +297,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you run a Vertex AI pipeline job using the Cloud SDK, your job stores the pipeline artifacts to a Cloud Storage bucket. In this tutorial, you create a Vertex AI Pipeline job that saves the artifacts like evaluation metrics and feature attributes to a Cloud Storage bucket.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -466,27 +308,13 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_bucket"
"id": "autoset_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
@@ -496,33 +324,13 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "create_bucket"
"id": "91c46850b49b"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -653,7 +461,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.VideoDataset.create(\n",
" display_name=\"Golf Swings\" + \"_\" + UUID,\n",
" display_name=\"Golf Swings\",\n",
" gcs_source=IMPORT_FILES,\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.video.action_recognition,\n",
")\n",
@@ -693,7 +501,7 @@
"outputs": [],
"source": [
"job = aiplatform.AutoMLVideoTrainingJob(\n",
" display_name=\"golf_\" + UUID,\n",
" display_name=\"golf\",\n",
" prediction_type=\"action_recognition\",\n",
")\n",
"\n",
@@ -730,7 +538,7 @@
"source": [
"model = job.run(\n",
" dataset=dataset,\n",
" model_display_name=\"golf_\" + UUID,\n",
" model_display_name=\"golf\",\n",
" training_fraction_split=0.8,\n",
" test_fraction_split=0.2,\n",
")"
@@ -876,7 +684,7 @@
"outputs": [],
"source": [
"batch_predict_job = model.batch_predict(\n",
" job_display_name=\"golf_\" + UUID,\n",
" job_display_name=\"golf\",\n",
" gcs_source=gcs_input_uri,\n",
" gcs_destination_prefix=BUCKET_URI,\n",
" sync=False,\n",
@@ -128,55 +128,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "384b53dfdb54"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_local"
},
"source": [
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* The Google Cloud SDK\n",
"* Git\n",
"* Python 3\n",
"* virtualenv\n",
"* Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Google Cloud guide to [Setting up a Python development\n",
"environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
"installation guide](https://jupyter.org/install) provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
"\n",
"1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
"\n",
"1. [Install\n",
" virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip3 install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -198,19 +149,8 @@
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform {USER_FLAG} -q\n",
"! pip3 install -U google-cloud-storage {USER_FLAG} -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage"
]
},
{
@@ -219,79 +159,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin:nogpu"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### GPU runtime\n",
"### Set your project ID\n",
"\n",
"This tutorial does not require a GPU runtime.\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these conmmands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1460fd744366"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cd85f5c794e5"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -302,22 +201,10 @@
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -328,16 +215,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)"
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -348,116 +226,65 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "79055ac4078d"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gcp_authenticate"
},
"source": [
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gcp_authenticate"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -468,12 +295,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you create a model in Vertex AI using the Cloud SDK, you give a Cloud Storage path where the trained model is saved. In this tutorial, you create a batch prediction job using the Vertex AI model. For this purpose, you need to save your test instances to a Cloud Storage bucket and give a destination Cloud Storage path to write the batch predictions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all\n",
"Cloud Storage buckets."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -484,21 +306,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -521,26 +329,6 @@
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -669,7 +457,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.VideoDataset.create(\n",
" display_name=\"MIT Human Motion\" + \"_\" + UUID,\n",
" display_name=\"MIT Human Motion\",\n",
" gcs_source=[IMPORT_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.video.classification,\n",
")\n",
@@ -707,7 +495,7 @@
"outputs": [],
"source": [
"job = aiplatform.AutoMLVideoTrainingJob(\n",
" display_name=\"hmdb_\" + UUID,\n",
" display_name=\"hmdb\",\n",
" prediction_type=\"classification\",\n",
")\n",
"\n",
@@ -744,7 +532,7 @@
"source": [
"model = job.run(\n",
" dataset=dataset,\n",
" model_display_name=\"hmdb_\" + UUID,\n",
" model_display_name=\"hmdb\",\n",
" training_fraction_split=0.8,\n",
" test_fraction_split=0.2,\n",
")"
@@ -773,7 +561,7 @@
"outputs": [],
"source": [
"# Get model resource ID using the display_name\n",
"models = aiplatform.Model.list(filter=\"display_name=hmdb_\" + UUID)\n",
"models = aiplatform.Model.list(filter=\"display_name=hmdb\")\n",
"\n",
"if len(models) != 0:\n",
"\n",
@@ -876,7 +664,7 @@
"}\n",
"\n",
"\n",
"bucket = storage.Client(project=PROJECT_ID).bucket(BUCKET_NAME)\n",
"bucket = storage.Client(project=PROJECT_ID).bucket(BUCKET_URI[5:])\n",
"blob = bucket.blob(blob_name=test_filename)\n",
"data = json.dumps(data_1) + \"\\n\" + json.dumps(data_2) + \"\\n\"\n",
"blob.upload_from_string(data)\n",
@@ -929,7 +717,7 @@
"outputs": [],
"source": [
"batch_predict_job = model.batch_predict(\n",
" job_display_name=\"hmdb_\" + UUID,\n",
" job_display_name=\"hmdb\",\n",
" gcs_source=gcs_input_uri,\n",
" gcs_destination_prefix=BUCKET_URI,\n",
" sync=False,\n",
@@ -126,38 +126,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_local"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements. You need the following:\n",
"\n",
"- The Cloud Storage SDK\n",
"- Python 3\n",
"- virtualenv\n",
"- Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Cloud Storage guide to [Setting up a Python development environment](https://cloud.google.com/python/setup) and the [Jupyter installation guide](https://jupyter.org/install) provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions:\n",
"\n",
"1. [Install and initialize the SDK](https://cloud.google.com/sdk/docs/).\n",
"\n",
"2. [Install Python 3](https://cloud.google.com/python/setup#installing_python).\n",
"\n",
"3. [Install virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv) and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"4. To install Jupyter, run `pip3 install jupyter` on the command-line in a terminal shell.\n",
"\n",
"5. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"6. Open this notebook in the Jupyter Notebook Dashboard.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -179,19 +147,8 @@
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"else:\n",
" USER_FLAG = \"\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform google-cloud-storage $USER_FLAG -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage"
]
},
{
@@ -200,109 +157,52 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages.\n",
"\n",
"**Note: You may get a message saying \"Your session crashed for an unknown reason.\", this is expected. Once this cell has finished running, continue on. You do not need to re-run any of the cells above.**"
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin:nogpu"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### GPU runtime\n",
"### Set your project ID\n",
"\n",
"This tutorial does not require a GPU runtime.\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"6. (optional) You may also specify a service account to use to run Vertex AI Pipelines in the project.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5aee4379e8e5"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dcdfccf50581"
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5bf9979b96ff"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "09021c90b34c"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -313,16 +213,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)"
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -333,40 +224,7 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
@@ -377,56 +235,54 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"- In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"- **Click Create service account**.\n",
"\n",
"- In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"- In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"- Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"- Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gcp_authenticate"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS '[your-service-account-key-path]'"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -437,42 +293,24 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex AI SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f78cf4290843"
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "219a24ea078b"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a8a62bec0259"
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
@@ -489,26 +327,6 @@
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4e69d430073b"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "835eaacd691f"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -642,7 +460,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.VideoDataset.create(\n",
" display_name=\"Traffic\" + \"_\" + UUID,\n",
" display_name=\"Traffic\",\n",
" gcs_source=[IMPORT_FILE],\n",
" import_schema_uri=aiplatform.schema.dataset.ioformat.video.object_tracking,\n",
")\n",
@@ -680,7 +498,7 @@
"outputs": [],
"source": [
"job = aiplatform.AutoMLVideoTrainingJob(\n",
" display_name=\"traffic_\" + UUID,\n",
" display_name=\"traffic\",\n",
" prediction_type=\"object_tracking\",\n",
")\n",
"\n",
@@ -717,7 +535,7 @@
"source": [
"model = job.run(\n",
" dataset=dataset,\n",
" model_display_name=\"traffic_\" + UUID,\n",
" model_display_name=\"traffic\",\n",
" training_fraction_split=0.8,\n",
" test_fraction_split=0.2,\n",
")"
@@ -895,7 +713,7 @@
"outputs": [],
"source": [
"batch_predict_job = model.batch_predict(\n",
" job_display_name=\"traffic_\" + UUID,\n",
" job_display_name=\"traffic\",\n",
" gcs_source=gcs_input_uri,\n",
" gcs_destination_prefix=BUCKET_URI,\n",
" sync=False,\n",
@@ -126,55 +126,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ze4-nDLfK4pw"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gCuSR8GkAgzl"
},
"source": [
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* The Google Cloud SDK\n",
"* Git\n",
"* Python 3\n",
"* virtualenv\n",
"* Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Google Cloud guide to <a href=\"https://cloud.google.com/python/setup\" target=\"_blank\">Setting up a Python development\n",
"environment</a> and the <a href=\"https://jupyter.org/install\" target=\"_blank\">Jupyter\n",
"installation guide</a> provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. <a href=\"https://cloud.google.com/sdk/docs/\" target=\"_blank\">Install and initialize the Cloud SDK.</a>\n",
"\n",
"1. <a href=\"https://cloud.google.com/python/setup#installing_python\" target=\"_blank\">Install Python 3.</a>\n",
"\n",
"1. <a href=\"https://cloud.google.com/python/setup#installing_and_using_virtualenv\" target=\"_blank\">Install\n",
" virtualenv</a>\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip3 install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -194,140 +145,63 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform {USER_FLAG} -q google-cloud-bigquery db-dtypes"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-bigquery \\\n",
" db-dtypes"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hhq5zEbGg0XX"
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EzrelQZ22IZj"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lWEdiXsJg0XY"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"## Before you begin\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"### Set your project ID\n",
"\n",
"1. <a href=\"https://console.cloud.google.com/cloud-resource-manager\" target=\"_blank\">Select or create a Google Cloud project</a>. When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. <a href=\"https://cloud.google.com/billing/docs/how-to/modify-project\" target=\"_blank\">Make sure that billing is enabled for your project</a>.\n",
"\n",
"1. <a href=\"https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com\" target=\"_blank\">Enable the Vertex AI API</a>.\n",
"\n",
"1. If you are running this notebook locally, you will need to install the <a href=\"https://cloud.google.com/sdk\" target=\"_blank\">Cloud SDK</a>.\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3c8049930470"
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qJYoRfYng0XZ"
},
"source": [
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -338,16 +212,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You might not be able to use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about <a href=\"https://cloud.google.com/vertex-ai/docs/general/locations\" target=\"_blank\">Vertex AI regions</a>."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -358,115 +223,118 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "06571eb4063b"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "697568e92bd6"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dr--iN2kAylZ"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sBCra4QMA2wR"
},
"source": [
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"1. In the Cloud Console, go to the <a href=\"https://console.cloud.google.com/apis/credentials/serviceaccountkey\" target=\"_blank\">**Create service account key** page</a>.\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PyQmSRbKA8r-"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"import os\n",
"import sys\n",
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "44accda192d5"
},
"source": [
"#### Service Account\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"You use a service account to create Vertex AI Pipeline jobs. If you do not want to use your project's Compute Engine service account, set `SERVICE_ACCOUNT` to another service account ID."
]
},
{
@@ -569,7 +437,7 @@
},
"outputs": [],
"source": [
"bq_client = bigquery.Client(project=PROJECT_ID)"
"bq_client = bigquery.Client(project=PROJECT_ID, location=REGION)"
]
},
{
@@ -633,7 +501,7 @@
},
"outputs": [],
"source": [
"BQ_DATASET_NAME = f\"ga4_churnprediction_{UUID}\"\n",
"BQ_DATASET_NAME = \"ga4_churnprediction\"\n",
"\n",
"sql_create_dataset = f\"\"\"CREATE SCHEMA IF NOT EXISTS {BQ_DATASET_NAME}\"\"\"\n",
"\n",
@@ -714,7 +582,7 @@
"source": [
"# this cell may take ~1 min to run\n",
"\n",
"BQML_MODEL_NAME = f\"bqml_model_churn_{UUID}\"\n",
"BQML_MODEL_NAME = \"bqml_model_churn\"\n",
"\n",
"sql_train_model_bqml = f\"\"\"\n",
"CREATE OR REPLACE MODEL {BQ_DATASET_NAME}.{BQML_MODEL_NAME} \n",
@@ -139,23 +139,12 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\") and not os.getenv(\"VIRTUAL_ENV\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"# Install the packages\n",
"! pip3 install --upgrade pyarrow \\\n",
" google-cloud-aiplatform \\\n",
" google-cloud-bigquery \\\n",
" google-cloud-bigquery-storage \\\n",
" db-dtypes $USER_FLAG -q"
"! pip3 install --upgrade --quiet pyarrow \\\n",
" google-cloud-aiplatform \\\n",
" google-cloud-bigquery \\\n",
" google-cloud-bigquery-storage \\\n",
" db-dtypes "
]
},
{
@@ -164,64 +153,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "project_id"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"### Set your project ID\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI, BigQuery, Compute Engine and Cloud Storage APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,bigquery,compute_component,storage_component).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "56d591439df1"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -232,33 +195,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -269,16 +209,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -289,95 +220,65 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f3bd8c0d0469"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"1. **Click Create service account**.\n",
"\n",
"2. In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"3. In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex AI\" into the filter box, and select **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"4. Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"5. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e0953a00668e"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -388,11 +289,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -403,21 +300,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -440,26 +323,6 @@
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -791,9 +654,12 @@
" print(\"Running ...\")\n",
"print(job.errors, job.state)\n",
"\n",
"tblname = job.ddl_target_table\n",
"tblname = \"{}.{}\".format(tblname.dataset_id, tblname.table_id)\n",
"print(\"{} created in {}\".format(tblname, job.ended - job.started))"
"try:\n",
" tblname = job.ddl_target_table\n",
" tblname = \"{}.{}\".format(tblname.dataset_id, tblname.table_id)\n",
" print(\"{} created in {}\".format(tblname, job.ended - job.started))\n",
"except Exception as e:\n",
" print(e)"
]
},
{
@@ -891,7 +757,7 @@
"outputs": [],
"source": [
"model = aiplatform.Model.upload(\n",
" display_name=\"penguins_\" + TIMESTAMP,\n",
" display_name=\"penguins\",\n",
" artifact_uri=MODEL_DIR,\n",
" serving_container_image_uri=DEPLOY_IMAGE,\n",
" sync=True,\n",
@@ -927,7 +793,7 @@
},
"outputs": [],
"source": [
"DEPLOYED_NAME = \"penguins-\" + TIMESTAMP\n",
"DEPLOYED_NAME = \"penguins\"\n",
"\n",
"TRAFFIC_SPLIT = {\"0\": 100}\n",
"\n",
@@ -1074,9 +940,12 @@
" print(\"Running ...\")\n",
"print(job.errors, job.state)\n",
"\n",
"tblname = job.ddl_target_table\n",
"tblname = \"{}.{}\".format(tblname.dataset_id, tblname.table_id)\n",
"print(\"{} created in {}\".format(tblname, job.ended - job.started))"
"try:\n",
" tblname = job.ddl_target_table\n",
" tblname = \"{}.{}\".format(tblname.dataset_id, tblname.table_id)\n",
" print(\"{} created in {}\".format(tblname, job.ended - job.started))\n",
"except Exception as e:\n",
" print(e)"
]
},
{
@@ -1182,9 +1051,12 @@
" print(\"Running ...\")\n",
"print(job.errors, job.state)\n",
"\n",
"tblname = job.ddl_target_table\n",
"tblname = \"{}.{}\".format(tblname.dataset_id, tblname.table_id)\n",
"print(\"{} created in {}\".format(tblname, job.ended - job.started))"
"try:\n",
" tblname = job.ddl_target_table\n",
" tblname = \"{}.{}\".format(tblname.dataset_id, tblname.table_id)\n",
" print(\"{} created in {}\".format(tblname, job.ended - job.started))\n",
"except Exception as e:\n",
" print(e)"
]
},
{
@@ -1272,7 +1144,7 @@
" model_type='DNN_CLASSIFIER',\n",
" labels = ['species'],\n",
" model_registry=\"vertex_ai\",\n",
" vertex_ai_model_id=\"bqml_model_{TIMESTAMP}\", \n",
" vertex_ai_model_id=\"bqml_model\", \n",
" vertex_ai_model_version_aliases=[\"1\"]\n",
" )\n",
"AS\n",
@@ -1290,9 +1162,12 @@
" print(\"Running ...\")\n",
"print(job.errors, job.state)\n",
"\n",
"tblname = job.ddl_target_table\n",
"tblname = \"{}.{}\".format(tblname.dataset_id, tblname.table_id)\n",
"print(\"{} created in {}\".format(tblname, job.ended - job.started))"
"try:\n",
" tblname = job.ddl_target_table\n",
" tblname = \"{}.{}\".format(tblname.dataset_id, tblname.table_id)\n",
" print(\"{} created in {}\".format(tblname, job.ended - job.started))\n",
"except Exception as e:\n",
" print(e)"
]
},
{
@@ -1314,7 +1189,7 @@
},
"outputs": [],
"source": [
"models = aiplatform.Model.list(filter=\"display_name=bqml_model_\" + TIMESTAMP)\n",
"models = aiplatform.Model.list(filter=\"display_name=bqml_model\")\n",
"model = models[0]\n",
"\n",
"print(model.gca_resource)"
+55
View File
@@ -60,6 +60,22 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Vertex AI Training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Custom training with custom training container and automatic registering of the model](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/custom/custom_training_container_and_model_registry.ipynb)
```
In this tutorial, you create a custom model from a Python script in a custom Docker container using the Vertex AI SDK, and automatically register the model in the Vertex AI Model Registry.
The steps performed include:
- Create a Vertex AI custom job for training a model.
- Train and register a TensorFlow model using a custom container,
- List the registered model from the Vertex AI Model Registry.
```
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Profile model training performance using Profiler](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/custom/custom_training_tensorboard_profiler.ipynb)
```
@@ -77,6 +93,45 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Vertex AI TensorBoard Profiler](https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-profiler).
[Get started with Vertex AI Training for XGBoost](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/custom/get_started_vertex_training.ipynb)
```
Learn how to use `Vertex AI Training` for training a XGBoost custom model.
The steps performed include:
- Training using a Python package.
- Report accuracy when hyperparameter tuning.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Create a `Vertex AI Model` resource.
```
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Get started with Endpoint and shared VM](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/custom/get_started_with_vertex_endpoint_and_shared_vm.ipynb)
```
Learn how to use deployment resource pools for deploying models.
The steps performed include:
- Upload a pre-trained image classification model as a `Model` resource (model A).
- Upload a pre-trained text sentence encoder model as a `Model` resource (model B).
- Create a shared VM deployment resource pool.
- List shared VM deployment resource pools.
- Create two `Endpoint` resources.
- Deploy first model (model A) to first `Endpoint` resource using deployment resource pool.
- Deploy second model (model B) to second `Endpoint` resource using deployment resource pool.
- Make a prediction request with first deployed model (model A).
- Make a prediction request with second deployed model (model B).
```
&nbsp;&nbsp;&nbsp;Learn more about [Shared resources across deployments](https://cloud.google.com/vertex-ai/docs/predictions/model-co-hosting).
[Custom training and batch prediction](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/custom/sdk-custom-image-classification-batch.ipynb)
```
@@ -125,58 +125,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ze4-nDLfK4pw"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench notebooks**, your environment already meets\n",
"all the requirements to run this notebook.\n",
"\n",
"**If you are using Colab**, docker related steps are skipped as Colab doesn't fully support docker yet."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gCuSR8GkAgzl"
},
"source": [
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* Docker\n",
"* Git\n",
"* Google Cloud SDK (gcloud)\n",
"* Python 3\n",
"* virtualenv\n",
"* Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Google Cloud guide to [Setting up a Python development\n",
"environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
"installation guide](https://jupyter.org/install) provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
"\n",
"1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
"\n",
"1. [Install\n",
" virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -211,319 +159,176 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"# Required in Docker serving container\n",
"! pip3 install -U {USER_FLAG} -r requirements.txt -q\n",
"! pip3 install -U -r requirements.txt -q\n",
"\n",
"# For local FastAPI development and running\n",
"! pip3 install -U {USER_FLAG} \"uvicorn[standard]>=0.12.0,<0.14.0\" fastapi~=0.63 -q\n",
"! pip3 install -U \"uvicorn[standard]>=0.12.0,<0.14.0\" fastapi~=0.63 -q\n",
"\n",
"# Vertex SDK for Python\n",
"! pip3 install -U {USER_FLAG} google-cloud-aiplatform -q"
"! pip3 install -U google-cloud-aiplatform -q"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hhq5zEbGg0XX"
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EzrelQZ22IZj"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lWEdiXsJg0XY"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"## Before you begin\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"### Set your project ID\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the APIs for Vertex AI, Compute Engine and Artifact Registry](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute.googleapis.com,artifactregistry.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cde8e0876d62"
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "becb6514d26a"
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. It is recommended that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "959545da671a"
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e663bd062c6f"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "953fa6e5ddda"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "40206eb20b53"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench notebooks**, your environment is already\n",
"authenticated.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4dd67f16eff2"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "62f861b68b50"
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"To update your model artifacts without re-building the container, you upload your model\n",
"artifacts and any custom code to Cloud Storage bucket.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all\n",
"Cloud Storage buckets. "
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9724b00aeead"
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "db3de5b7b0a4"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "58cb4f5895f0"
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
@@ -533,31 +338,11 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2d2208676cee"
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c664a5abc11a"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2c1b1c29f5f6"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
"! gsutil mb -l {REGION} {BUCKET_URI}"
]
},
{
@@ -577,6 +362,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"from google.cloud import aiplatform"
]
},
@@ -946,6 +733,9 @@
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not IS_COLAB and not os.getenv(\"IS_TESTING\"):\n",
" ! sudo docker build \\\n",
" --tag=\"{REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}\" \\\n",
@@ -1053,26 +843,66 @@
{
"cell_type": "markdown",
"metadata": {
"id": "212b2935ea12"
"id": "93002a20a2a6"
},
"source": [
"### Push the container to artifact registry\n",
"### Build Custom Container\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2d242773d707"
},
"source": [
"#### Enable Artifact Registry API\n",
"You must enable the Artifact Registry API service for your project.\n",
"\n",
"Create your repository in the Artifact registry and push your container image to the repository.\n",
"Run this below cell once to create the artifact repository."
"<a href=\"https://cloud.google.com/artifact-registry/docs/enable-service\">Learn more about Enabling service</a>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5f98a42332e5"
"id": "9d72f89cabd5"
},
"outputs": [],
"source": [
"!gcloud artifacts repositories create {REPOSITORY} \\\n",
" --repository-format=docker \\\n",
" --location=$REGION"
"! gcloud services enable artifactregistry.googleapis.com\n",
"\n",
"if os.getenv(\"IS_TESTING\"):\n",
" ! sudo apt-get update --yes && sudo apt-get --only-upgrade --yes install google-cloud-sdk-cloud-run-proxy google-cloud-sdk-harbourbridge google-cloud-sdk-cbt google-cloud-sdk-gke-gcloud-auth-plugin google-cloud-sdk-kpt google-cloud-sdk-local-extract google-cloud-sdk-minikube google-cloud-sdk-app-engine-java google-cloud-sdk-app-engine-go google-cloud-sdk-app-engine-python google-cloud-sdk-spanner-emulator google-cloud-sdk-bigtable-emulator google-cloud-sdk-nomos google-cloud-sdk-package-go-module google-cloud-sdk-firestore-emulator kubectl google-cloud-sdk-datastore-emulator google-cloud-sdk-app-engine-python-extras google-cloud-sdk-cloud-build-local google-cloud-sdk-kubectl-oidc google-cloud-sdk-anthos-auth google-cloud-sdk-app-engine-grpc google-cloud-sdk-pubsub-emulator google-cloud-sdk-datalab google-cloud-sdk-skaffold google-cloud-sdk google-cloud-sdk-terraform-tools google-cloud-sdk-config-connector\n",
" ! gcloud components update --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "23f3ba8346f4"
},
"source": [
"### Create a private Docker repository\n",
"Your first step is to create your own Docker repository in Google Artifact Registry.\n",
"\n",
"1 - Run the gcloud artifacts repositories create command to create a new Docker repository with your region with the description \"docker repository\".\n",
"\n",
"2 - Run the gcloud artifacts repositories list command to verify that your repository was created."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "64fee26c2dff"
},
"outputs": [],
"source": [
"REPOSITORY = \"my-docker-repo-unique\"\n",
"\n",
"! gcloud artifacts repositories create {REPOSITORY} --repository-format=docker --location={REGION} --description=\"Docker repository\"\n",
"\n",
"! gcloud artifacts repositories list"
]
},
{
@@ -129,51 +129,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ze4-nDLfK4pw"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**If you are using Colab**, docker related steps are skipped as Colab doesn't fully support docker yet. \n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* Docker\n",
"* Git\n",
"* Google Cloud SDK (gcloud)\n",
"* Python 3\n",
"* virtualenv\n",
"* Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Google Cloud guide to [Setting up a Python development\n",
"environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
"installation guide](https://jupyter.org/install) provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
"\n",
"1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
"\n",
"1. [Install\n",
" virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip3 install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -204,7 +159,7 @@
"pyarrow==8.0.0\n",
"fastapi~=0.63\n",
"pystan\n",
"prophet==1.1"
"prophet==1.1.4"
]
},
{
@@ -215,313 +170,170 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"# install dependencies from requirements.txt\n",
"! pip3 install {USER_FLAG} -r requirements.txt -q"
"! pip3 install -r requirements.txt -q"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hhq5zEbGg0XX"
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EzrelQZ22IZj"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lWEdiXsJg0XY"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"## Before you begin\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"### Set your project ID\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the APIs for Vertex AI, Compute Engine and Artifact Registry](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute.googleapis.com,artifactregistry.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4dbb3cd4c564"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "563c444fb946"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "233cd87467c7"
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)"
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eb356bd4d5e9"
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2a598c7e52fb"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1aec5e7288ab"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dr--iN2kAylZ"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench notebooks**, your environment is already\n",
"authenticated.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PyQmSRbKA8r-"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS '[your-service-account-key-path]'"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "62f861b68b50"
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"To update your model artifacts without re-building the container, you upload your model\n",
"artifacts and any custom code to a Cloud Storage bucket. You also provide a Cloud Storage bucket to serve as a default staging location for your Vertex AI SDK.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all\n",
"Cloud Storage buckets. "
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2232344edb11"
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6749c55b3f6f"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "58cb4f5895f0"
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
@@ -531,31 +343,11 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2d2208676cee"
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c664a5abc11a"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2c1b1c29f5f6"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
"! gsutil mb -l {REGION} {BUCKET_URI}"
]
},
{
@@ -1318,10 +1110,14 @@
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"\n",
"def build_image():\n",
" ! sudo docker build --tag=\"{REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}\" . > logs.txt\n",
"\n",
"\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not IS_COLAB and not os.getenv(\"IS_TESTING\"):\n",
" print(\"Building the image...\")\n",
" build_image()\n",
@@ -1469,26 +1265,55 @@
{
"cell_type": "markdown",
"metadata": {
"id": "212b2935ea12"
"id": "2d242773d707"
},
"source": [
"### Push the container to artifact registry\n",
"#### Enable Artifact Registry API\n",
"You must enable the Artifact Registry API service for your project.\n",
"\n",
"Create your repository in the Artifact registry and push your container image to the repository.\n",
"Run this below cell once to create the artifact repository."
"<a href=\"https://cloud.google.com/artifact-registry/docs/enable-service\">Learn more about Enabling service</a>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8b2c683d1e2d"
"id": "9d72f89cabd5"
},
"outputs": [],
"source": [
"!gcloud artifacts repositories create {REPOSITORY} \\\n",
" --repository-format=docker \\\n",
" --location=$REGION"
"! gcloud services enable artifactregistry.googleapis.com\n",
"\n",
"if os.getenv(\"IS_TESTING\"):\n",
" ! sudo apt-get update --yes && sudo apt-get --only-upgrade --yes install google-cloud-sdk-cloud-run-proxy google-cloud-sdk-harbourbridge google-cloud-sdk-cbt google-cloud-sdk-gke-gcloud-auth-plugin google-cloud-sdk-kpt google-cloud-sdk-local-extract google-cloud-sdk-minikube google-cloud-sdk-app-engine-java google-cloud-sdk-app-engine-go google-cloud-sdk-app-engine-python google-cloud-sdk-spanner-emulator google-cloud-sdk-bigtable-emulator google-cloud-sdk-nomos google-cloud-sdk-package-go-module google-cloud-sdk-firestore-emulator kubectl google-cloud-sdk-datastore-emulator google-cloud-sdk-app-engine-python-extras google-cloud-sdk-cloud-build-local google-cloud-sdk-kubectl-oidc google-cloud-sdk-anthos-auth google-cloud-sdk-app-engine-grpc google-cloud-sdk-pubsub-emulator google-cloud-sdk-datalab google-cloud-sdk-skaffold google-cloud-sdk google-cloud-sdk-terraform-tools google-cloud-sdk-config-connector\n",
" ! gcloud components update --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "23f3ba8346f4"
},
"source": [
"### Create a private Docker repository\n",
"Your first step is to create your own Docker repository in Google Artifact Registry.\n",
"\n",
"1 - Run the gcloud artifacts repositories create command to create a new Docker repository with your region with the description \"docker repository\".\n",
"\n",
"2 - Run the gcloud artifacts repositories list command to verify that your repository was created."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "64fee26c2dff"
},
"outputs": [],
"source": [
"! gcloud artifacts repositories create {REPOSITORY} --repository-format=docker --location={REGION} --description=\"Docker repository\"\n",
"\n",
"! gcloud artifacts repositories list"
]
},
{
@@ -24,6 +24,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "l2mMvIUG9meX"
@@ -54,6 +55,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
@@ -67,6 +69,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "dmfmQL6w84pS"
@@ -90,6 +93,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "zfXf0r-K81Y-"
@@ -101,6 +105,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "I3KFLvpq87rs"
@@ -121,6 +126,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ze4-nDLfK4pw"
@@ -139,10 +145,11 @@
},
"outputs": [],
"source": [
"! pip3 install --user --upgrade google-cloud-aiplatform --quiet"
"! pip3 install --upgrade google-cloud-aiplatform --quiet"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "aUw6ibN-n5Za"
@@ -167,6 +174,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "LgFWLeJfoGQu"
@@ -188,6 +196,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "8ckyxpX_oSzD"
@@ -216,6 +225,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "mSQjVQmMosMl"
@@ -238,6 +248,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "IfJRIMBpo5Pg"
@@ -249,6 +260,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "acFN0s3So9-Y"
@@ -259,6 +271,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "dQ_mNwuapE5T"
@@ -279,6 +292,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "h-MuVI_ypJfw"
@@ -300,6 +314,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "3ivZkPUjpaFz"
@@ -352,6 +367,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "OKtKGmr9pfr6"
@@ -374,6 +390,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "GOaOsIjxp0oB"
@@ -394,6 +411,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ankcS-vtp7Wv"
@@ -414,6 +432,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "OMrAJ8RGqBQu"
@@ -436,6 +455,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "MYzX9ZgjsyyY"
@@ -460,6 +480,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "-ayTbNdi62_t"
@@ -471,6 +492,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "9c3QrDTZdaxk"
@@ -491,6 +513,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "vJrWKK0mY7H7"
@@ -519,6 +542,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "yoR29gW2S24w"
@@ -536,6 +560,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "OrpUIkAIs_uQ"
@@ -554,8 +579,16 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"DOCKER_REPOSITORY = f\"{PROJECT_ID}-repo-unique\"\n",
"\n",
"! gcloud services enable artifactregistry.googleapis.com\n",
"\n",
"if os.getenv(\"IS_TESTING\"):\n",
" ! sudo apt-get update --yes && sudo apt-get --only-upgrade --yes install google-cloud-sdk-cloud-run-proxy google-cloud-sdk-harbourbridge google-cloud-sdk-cbt google-cloud-sdk-gke-gcloud-auth-plugin google-cloud-sdk-kpt google-cloud-sdk-local-extract google-cloud-sdk-minikube google-cloud-sdk-app-engine-java google-cloud-sdk-app-engine-go google-cloud-sdk-app-engine-python google-cloud-sdk-spanner-emulator google-cloud-sdk-bigtable-emulator google-cloud-sdk-nomos google-cloud-sdk-package-go-module google-cloud-sdk-firestore-emulator kubectl google-cloud-sdk-datastore-emulator google-cloud-sdk-app-engine-python-extras google-cloud-sdk-cloud-build-local google-cloud-sdk-kubectl-oidc google-cloud-sdk-anthos-auth google-cloud-sdk-app-engine-grpc google-cloud-sdk-pubsub-emulator google-cloud-sdk-datalab google-cloud-sdk-skaffold google-cloud-sdk google-cloud-sdk-terraform-tools google-cloud-sdk-config-connector\n",
" ! gcloud components update --quiet\n",
"\n",
"! gcloud artifacts repositories create {DOCKER_REPOSITORY} \\\n",
" --repository-format=docker \\\n",
" --location={REGION} \\\n",
@@ -566,6 +599,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "MPqbvhO6tK_e"
@@ -593,6 +627,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "pSXrzCWi-bTD"
@@ -619,6 +654,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "hyAwgsoQmaYI"
@@ -748,6 +784,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "LiOEvgkA_90f"
@@ -771,6 +808,7 @@
"\n",
"# Installs additional packages as you need.\n",
"RUN pip3 install google-cloud-aiplatform[cloud_profiler]\n",
"RUN pip3 install protobuf==3.20.2\n",
"\n",
"# Copies the trainer code to the docker image.\n",
"RUN mkdir /root/trainer\n",
@@ -781,6 +819,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ihYFahRAr6sj"
@@ -804,6 +843,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "k4e6OYmimqTR"
@@ -830,6 +870,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "51hKGTbU32Eg"
@@ -874,6 +915,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "JkEe2Nb_85UD"
@@ -887,6 +929,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "TpV-iwP9qw9c"
@@ -142,28 +142,15 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_mlops"
"id": "3357af6a0f34"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\") and not os.getenv(\"VIRTUAL_ENV\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"# Install the packages\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install --upgrade tensorflow $USER_FLAG -q\n",
"! pip3 install --upgrade tensorflow-hub $USER_FLAG -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" tensorflow \\\n",
" tensorflow-hub"
]
},
{
@@ -172,55 +159,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "project_id"
"id": "yfEglUHQk9S3"
},
"source": [
"### Set up your Google Cloud project\n",
"## Before you begin\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"### Set your project ID\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI, Compute Engine and Cloud Storage APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage_component).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n",
"\n",
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -231,33 +201,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -268,16 +215,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -288,94 +226,65 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3ffa6b6c7cdb"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"1. **Click Create service account**.\n",
"\n",
"2. In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"3. In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex AI\" into the filter box, and select **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"4. Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"5. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2b72272258fc"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
@@ -386,11 +295,7 @@
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -401,21 +306,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = \"gs://\" + BUCKET_NAME"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -438,26 +329,6 @@
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -478,6 +349,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"import google.cloud.aiplatform as aiplatform\n",
"import google.cloud.aiplatform_v1beta1 as aip_beta\n",
"import tensorflow as tf\n",
@@ -895,7 +768,7 @@
"outputs": [],
"source": [
"model_icn = aiplatform.Model.upload(\n",
" display_name=\"icn_\" + TIMESTAMP,\n",
" display_name=\"icn\",\n",
" artifact_uri=MODEL_ICN_DIR,\n",
" serving_container_image_uri=DEPLOY_IMAGE,\n",
")\n",
@@ -1006,7 +879,7 @@
"outputs": [],
"source": [
"model_use = aiplatform.Model.upload(\n",
" display_name=\"icn_\" + TIMESTAMP,\n",
" display_name=\"icn\",\n",
" artifact_uri=MODEL_USE_DIR,\n",
" serving_container_image_uri=DEPLOY_IMAGE,\n",
")\n",
@@ -1163,11 +1036,11 @@
},
"outputs": [],
"source": [
"endpoint_icn = aiplatform.Endpoint.create(display_name=\"icn_\" + TIMESTAMP)\n",
"endpoint_icn = aiplatform.Endpoint.create(display_name=\"icn\")\n",
"\n",
"print(endpoint_icn)\n",
"\n",
"endpoint_use = aiplatform.Endpoint.create(display_name=\"use_\" + TIMESTAMP)\n",
"endpoint_use = aiplatform.Endpoint.create(display_name=\"use\")\n",
"\n",
"print(endpoint_use)"
]
@@ -144,7 +144,10 @@
},
"outputs": [],
"source": [
"! pip3 install --upgrade --quiet google-cloud-aiplatform google-cloud-storage pillow numpy\n"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage \\\n",
" pillow \\\n",
" numpy"
]
},
{
@@ -307,7 +310,7 @@
},
"outputs": [],
"source": [
"BUCKET_URI = \"gs://your-bucket-name-unique\" # @param {type:\"string\"}"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
+2
View File
@@ -18,6 +18,8 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [BigQuery Datasets](https://cloud.google.com/bigquery/docs/datasets-intro).
&nbsp;&nbsp;&nbsp;Learn more about [Vertex AI for BigQuery users](https://cloud.google.com/vertex-ai/docs/beginner/bqml).
[Get started with Vertex AI Data Labeling](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/datasets/get_started_with_data_labeling.ipynb)
@@ -180,27 +180,14 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\") and not os.getenv(\"VIRTUAL_ENV\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --upgrade --quiet {USER_FLAG} google-cloud-aiplatform \\\n",
" google-cloud-bigquery \\\n",
" tensorflow \\\n",
" tensorflow-io==0.18 \\\n",
" xgboost \\\n",
" numpy \\\n",
" pandas \\\n",
" pyarrow"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-bigquery \\\n",
" tensorflow \\\n",
" tensorflow-io==0.18 \\\n",
" xgboost \\\n",
" numpy \\\n",
" pandas \\\n",
" pyarrow"
]
},
{
@@ -209,108 +196,52 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "restart"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import sys\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
"id": "yfEglUHQk9S3"
},
"source": [
"### Set up your Google Cloud project\n",
"## Before you begin\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"### Set your project ID\n",
"\n",
"1. <a href=\"https://console.cloud.google.com/cloud-resource-manager\" target=\"_blank\">Select or create a Google Cloud project</a>. When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. <a href=\"https://cloud.google.com/billing/docs/how-to/modify-project\" target=\"_blank\">Make sure that billing is enabled for your project</a>.\n",
"\n",
"1. <a href=\"https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com\" target=\"_blank\">Enable the Vertex AI API</a>.\n",
"\n",
"1. If you are running this notebook locally, you will need to install the <a href=\"https://cloud.google.com/sdk\" target=\"_blank\">Cloud SDK</a>.\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3c8049930470"
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qJYoRfYng0XZ"
},
"source": [
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -321,16 +252,7 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You might not be able to use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about <a href=\"https://cloud.google.com/vertex-ai/docs/general/locations\" target=\"_blank\">Vertex AI regions</a>."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
@@ -341,156 +263,93 @@
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "06571eb4063b"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "697568e92bd6"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dr--iN2kAylZ"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. \n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the <a href=\"https://console.cloud.google.com/apis/credentials/serviceaccountkey\" target=\"_blank\">**Create service account key** page</a>.\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PyQmSRbKA8r-"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "62f861b68b50"
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"To update your model artifacts without re-building the container, you upload your model\n",
"artifacts and any custom code to a Cloud Storage bucket. You also provide a Cloud Storage bucket to serve as a default staging location for your Vertex AI SDK.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all\n",
"Cloud Storage buckets. "
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2232344edb11"
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6749c55b3f6f"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "58cb4f5895f0"
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
@@ -500,33 +359,13 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2d2208676cee"
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c664a5abc11a"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2c1b1c29f5f6"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -645,7 +484,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.TabularDataset.create(\n",
" display_name=\"NOAA historical weather data\" + \"_\" + UUID,\n",
" display_name=\"NOAA historical weather data\",\n",
" bq_source=[IMPORT_FILE],\n",
" labels={\"user_metadata\": BUCKET_URI[5:]},\n",
")\n",
@@ -720,7 +559,7 @@
"gcs_source = IMPORT_FILES\n",
"\n",
"dataset = aiplatform.TabularDataset.create(\n",
" display_name=\"NOAA historical weather data\" + \"_\" + UUID,\n",
" display_name=\"NOAA historical weather data\",\n",
" gcs_source=gcs_source,\n",
" labels={\"user_metadata\": BUCKET_URI[5:]},\n",
")\n",
@@ -762,10 +601,10 @@
" or BQ_MY_DATASET is None\n",
" or BQ_MY_DATASET == \"[your-dataset-name]\"\n",
"):\n",
" BQ_MY_DATASET = \"mlops_dataset_\" + UUID\n",
" BQ_MY_DATASET = \"mlops_dataset\"\n",
"\n",
"if BQ_MY_TABLE == \"\" or BQ_MY_TABLE is None or BQ_MY_TABLE == \"[your-view-name]\":\n",
" BQ_MY_TABLE = \"mlops_view_\" + UUID"
" BQ_MY_TABLE = \"mlops_view\""
]
},
{
@@ -147,23 +147,12 @@
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\") and not os.getenv(\"VIRTUAL_ENV\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"# Install the packages\n",
"! pip3 install --upgrade google-cloud-aiplatform \\\n",
" google-cloud-storage $USER_FLAG -q\n",
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage \n",
"\n",
"if os.getenv(\"IS_TESTING\"):\n",
" ! pip3 install --upgrade google-api-core==2.10 $USER_FLAG -q"
" ! pip3 install --upgrade --quiet google-api-core==2.10 "
]
},
{
@@ -172,68 +161,38 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the Vertex AI SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.\n"
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GIwKc4pk_i_t"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### GPU run-time\n",
"### Set your project ID\n",
"\n",
"*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\n",
"\n",
"### Set up your GCP project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a GCP project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
"\n",
"3. [Enable the Vertex AI APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component)\n",
"\n",
"4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Vertex AI Workbench Notebooks.\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
@@ -244,33 +203,10 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -281,54 +217,18 @@
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6Xtp5tvK_i_y"
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d70An-Mg_i_2"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
@@ -381,80 +281,65 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. \n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "chybg3Ap_i_2"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:batch_prediction"
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.\n"
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -465,21 +350,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = \"gs://\" + BUCKET_NAME"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -488,40 +359,20 @@
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.\n"
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qPPrwWpO_i_6"
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fn744B7x_i_7"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -554,7 +405,6 @@
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"import time\n",
"\n",
"import google.cloud.aiplatform as aip\n",
@@ -745,7 +595,7 @@
},
"outputs": [],
"source": [
"dataset = aip.ImageDataset.create(\"labeling_\" + TIMESTAMP)\n",
"dataset = aip.ImageDataset.create(\"labeling\")\n",
"print(dataset)"
]
},
@@ -802,8 +652,8 @@
"outputs": [],
"source": [
"specialist_pool = {\n",
" \"name\": \"labeling_\" + TIMESTAMP,\n",
" \"display_name\": \"labeling_\" + TIMESTAMP,\n",
" \"name\": \"labeling\",\n",
" \"display_name\": \"labeling\",\n",
" \"specialist_manager_emails\": [EMAIL],\n",
"}\n",
"\n",
@@ -863,7 +713,7 @@
"inputs = ParseDict({\"annotation_specs\": [\"rose\"]}, Value())\n",
"\n",
"data_labeling_job = {\n",
" \"display_name\": \"labeling_\" + TIMESTAMP,\n",
" \"display_name\": \"labeling\",\n",
" \"datasets\": [dataset.resource_name],\n",
" \"labeler_count\": 1,\n",
" \"instruction_uri\": INSTRUCTION_FILE,\n",
+33
View File
@@ -56,6 +56,24 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Vertex AI Pipelines](https://cloud.google.com/vertex-ai/docs/pipelines/introduction).
[Delete Outdated Experiments in Vertex AI TensorBoard](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/experiments/delete_outdated_tensorboard_experiments.ipynb)
```
Learn how to delete outdated TensorBoard Experiments to avoid unnecessary storage costs.
The steps performed include:
- How to delete the TB Experiment with a predefined key-value label pair `<label_key, label_value>`
- How to delete the TB Experiments created before the `create_time`
- How to delete the TB Experiments created before the `update_time`
```
&nbsp;&nbsp;&nbsp;Learn more about [Vertex AI TensorBoard](https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-overview).
[Get started with Vertex AI Experiments](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/experiments/get_started_with_vertex_experiments.ipynb)
```
@@ -88,3 +106,18 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Autologging](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/experiments/autologging.ipynb)
```
Learn how to use `Vertex AI Autologging`.
The steps performed include:
- Enable autologging in the Vertex AI SDK.
- Train scikit-learn model and see the resulting experiment run with metrics and parameters autologged to Vertex AI Experiments without setting an experiment run.
- Train Tensorflow model, check autologged metrics and parameters to Vertex AI Experiments by manually setting an experiment run with `aiplatform.start_run()` and `aiplatform.end_run()`.
- Disable autologging in the Vertex AI SDK, train a PyTorch model and check that none of the parameters or metrics are logged.
```
@@ -50,7 +50,7 @@
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td> \n",
"</table>"
"</table>\n"
]
},
{
@@ -132,55 +132,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ze4-nDLfK4pw"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gCuSR8GkAgzl"
},
"source": [
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* The Google Cloud SDK\n",
"* Git\n",
"* Python 3\n",
"* virtualenv\n",
"* Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Google Cloud guide to [Setting up a Python development\n",
"environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
"installation guide](https://jupyter.org/install) provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
"\n",
"1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
"\n",
"1. [Install\n",
" virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip3 install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -189,7 +140,7 @@
"source": [
"### Install additional packages\n",
"\n",
"Install additional package dependencies not installed in your notebook environment,TensorFlow or Vertex AI SDK. Use the latest major GA version of each package."
"Install additional package dependencies not installed in your notebook environment."
]
},
{
@@ -200,337 +151,170 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install {USER_FLAG} --upgrade joblib fsspec gcsfs scikit-learn -q\n",
"! pip install {USER_FLAG} --upgrade google-cloud-aiplatform -q"
"! pip3 install --upgrade --quiet joblib fsspec gcsfs scikit-learn \n",
"! pip3 install --upgrade --quiet google-cloud-aiplatform "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hhq5zEbGg0XX"
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
"### Colab only: Uncomment the following cell to restart the kernel"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EzrelQZ22IZj"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"# Automatically restart kernel after installs so that your environment can access the new packages\n",
"# import IPython\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
"# app = IPython.Application.instance()\n",
"# app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
"id": "yfEglUHQk9S3"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"### Set your project ID\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudresourcemanager.googleapis.com,aiplatform.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
"**If you don't know your project ID**, try the following:\n",
"* Run `gcloud config list`.\n",
"* Run `gcloud projects list`.\n",
"* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
"id": "set_project_id"
},
"outputs": [],
"source": [
"import os\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"PROJECT_ID = \"\"\n",
"\n",
"# Get your Google Cloud project ID from gcloud\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID: \", PROJECT_ID)"
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qJYoRfYng0XZ"
},
"source": [
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wJyyYlKGYqaa"
},
"outputs": [],
"source": [
"!gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "88dd74c4c84e"
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"You can also change the `REGION` variable used by Vertex AI. Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5c615e53149f"
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "06571eb4063b"
},
"source": [
"#### UUID\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "697568e92bd6"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dr--iN2kAylZ"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sBCra4QMA2wR"
},
"source": [
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"Depending on your Jupyter environment, you may have to manually authenticate. Follow the relevant instructions below.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"**1. Vertex AI Workbench**\n",
"* Do nothing as you are already authenticated.\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type and select\n",
"the following role into the filter box:\n",
"\n",
" * Storage Admin\n",
" * Storage Object Admin\n",
" * Service Account User\n",
" * Vertex AI Administrator\n",
"\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PyQmSRbKA8r-"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"\n",
"IS_COLAB = False\n",
"\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
"\n",
" IS_COLAB = True\n",
"\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
"\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
"\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zgPO1eR3CYjk"
"id": "0367eac06a10"
},
"source": [
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c13224697bfb"
},
"source": [
"**4. Service account or other**\n",
"* See how to grant Cloud Storage permissions to your service account at https://cloud.google.com/storage/docs/gsutil/commands/iam#ch-examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:mbsdk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MzGDU7TWdts_"
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cf221059d072"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-EcIXiGsCePi"
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
@@ -540,31 +324,11 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NIq7R4HZCfIc"
"id": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ucvCsknMCims"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vhOb7YnwClBb"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
"! gsutil mb -l {REGION} {BUCKET_URI}"
]
},
{
@@ -573,7 +337,7 @@
"id": "0ljjTziu90rZ"
},
"source": [
"### Set project folder"
"### Set data folder"
]
},
{
@@ -585,7 +349,7 @@
"outputs": [],
"source": [
"DATA_PATH = \"data\"\n",
"!mkdir -m 777 -p {DATA_PATH}"
"! mkdir -m 777 -p {DATA_PATH}"
]
},
{
@@ -606,21 +370,12 @@
"outputs": [],
"source": [
"DATASET_URL = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00359/NewsAggregatorDataset.zip\"\n",
"!wget --no-parent {DATASET_URL} --directory-prefix={DATA_PATH}\n",
"!mkdir -m 777 -p {DATA_PATH}/temp {DATA_PATH}/raw\n",
"!unzip {DATA_PATH}/*.zip -d {DATA_PATH}/temp\n",
"!mv {DATA_PATH}/temp/*.csv {DATA_PATH}/raw && rm -Rf {DATA_PATH}/temp && rm -f {DATA_PATH}/*.zip"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "N-chqqLJAOpM"
},
"outputs": [],
"source": [
"!gsutil -m cp -R {DATA_PATH}/raw $BUCKET_URI/{DATA_PATH}/raw"
"! wget --no-parent {DATASET_URL} --directory-prefix={DATA_PATH}\n",
"! mkdir -m 777 -p {DATA_PATH}/temp {DATA_PATH}/raw\n",
"! unzip {DATA_PATH}/*.zip -d {DATA_PATH}/temp\n",
"! mv {DATA_PATH}/temp/*.csv {DATA_PATH}/raw && rm -Rf {DATA_PATH}/temp && rm -f {DATA_PATH}/*.zip\n",
"\n",
"! gsutil -m cp -R {DATA_PATH}/raw $BUCKET_URI/{DATA_PATH}/raw"
]
},
{
@@ -649,6 +404,7 @@
"import collections\n",
"import tempfile\n",
"import time\n",
"import uuid\n",
"from json import dumps\n",
"\n",
"collections.Iterable = collections.abc.Iterable\n",
@@ -674,6 +430,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Base\n",
"DATASET_NAME = \"news_corpora\"\n",
"DATASET_URI = f\"{BUCKET_URI}/{DATA_PATH}/raw/newsCorpora.csv\"\n",
@@ -681,7 +439,7 @@
"# Experiments\n",
"TASK = \"classification\"\n",
"MODEL_TYPE = \"naivebayes\"\n",
"EXPERIMENT_NAME = f\"{TASK}-{MODEL_TYPE}-{UUID}\"\n",
"EXPERIMENT_NAME = f\"{TASK}-{MODEL_TYPE}-{uuid.uuid1()}\"\n",
"EXPERIMENT_RUN_NAME = \"run-1\"\n",
"\n",
"# Preprocessing\n",
@@ -710,7 +468,7 @@
"FEATURES = \"title\"\n",
"TEST_SIZE = 0.2\n",
"SEED = 8\n",
"TRAINED_MODEL_URI = f\"{BUCKET_URI}/deliverables/{UUID}\"\n",
"TRAINED_MODEL_URI = f\"{BUCKET_URI}/deliverables/{uuid.uuid1()}\"\n",
"MODEL_NAME = f\"{EXPERIMENT_NAME}-model\""
]
},
@@ -860,6 +618,8 @@
"\"\"\"\n",
"\n",
"\n",
"import string\n",
"\n",
"import pandas as pd\n",
"\n",
"\n",
@@ -1283,17 +1043,6 @@
"\n",
"!rm -Rf {DATA_PATH}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3f00c455b930"
},
"outputs": [],
"source": [
"!rm -Rf {DATA_PATH}"
]
}
],
"metadata": {

Some files were not shown because too many files have changed in this diff Show More