Compare commits

...
158 Commits
Author SHA1 Message Date
Andrew Ferlitsch 6953f43736 fix: pause 2023-06-21 17:04:36 +00:00
Andrew Ferlitsch c46d35f6be fix: longer pause 2023-06-21 16:35:43 +00:00
Andrew Ferlitsch efc7e5e29c fix: delete AR 2023-06-20 17:22:58 +00:00
Andrew Ferlitsch 2b765cb993 Merge branch 'reduction_82' of https://github.com/GoogleCloudPlatform/vertex-ai-samples into reduction_82 2023-06-08 16:24:03 +00:00
Andrew Ferlitsch 3c5ddea432 fix: enable api 2023-06-08 16:23:37 +00:00
Andrew FerlitschandGitHub 2117abbfd3 fix: import os 2023-06-07 16:39:13 -07:00
Andrew FerlitschandGitHub 9f7a694702 fix: indent 2023-06-07 16:10:35 -07:00
Andrew Ferlitsch 447308606f fix: AR repo 2023-06-07 22:11:16 +00:00
Andrew Ferlitsch 22c2cc951f fix: IS_COLAB 2023-06-07 21:53:47 +00:00
Andrew Ferlitsch fef19a7b7a fix: boilerplate reduction 82 2023-06-07 21:35:11 +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
132 changed files with 17526 additions and 12691 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
+55 -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,52 @@ parser.add_argument(
default=True,
help="Should run notebooks in parallel.",
)
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
)
@@ -21,11 +21,15 @@ 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
@@ -40,6 +44,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 +72,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 +90,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,
@@ -191,7 +269,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 +281,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 +326,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 +348,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 +416,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,
@@ -369,6 +481,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):
@@ -471,7 +585,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 +603,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}
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")
+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.4.0
isort==5.12.0
flake8==6.0.0
nbqa==1.5.3
nbqa==1.7.0
+6
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,6 +42,7 @@
/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_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
@@ -56,3 +58,7 @@
/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/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
+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,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\": 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,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
}
@@ -271,7 +271,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 +345,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 +409,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."
]
},
{
@@ -332,6 +332,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,
@@ -332,6 +332,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,
@@ -314,9 +314,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 +339,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 +369,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
@@ -352,6 +352,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,
@@ -332,6 +332,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,
@@ -351,6 +351,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,
@@ -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-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",
@@ -86,18 +87,28 @@
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ioensNKM8ned"
},
"source": [
"### Setup notebook"
]
},
{
"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,66 +119,46 @@
},
"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."
]
},
{
@@ -184,7 +175,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 +204,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 for deploying fine tuned model.\n",
"SERVICE_ACCOUNT = \"\" # @param {type:\"string\"}"
]
},
{
@@ -278,12 +274,14 @@
"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",
"import torch\n",
"from google.cloud import aiplatform, storage\n",
"from PIL import Image\n",
"\n",
"\n",
@@ -326,8 +324,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 +331,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 +338,107 @@
" 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": "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": [
"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)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5aed5ed7b6f6"
},
"source": [
"### Text-guided image-to-image"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "faadabb7728f"
},
"outputs": [],
"source": [
"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",
"images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images\n",
"display(images[0])"
]
},
{
@@ -381,8 +475,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/"
"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 +598,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-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",
")"
]
},
{
"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,
@@ -585,6 +688,15 @@
")"
]
},
{
"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,
@@ -24,6 +24,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "1e9c07efb6ac"
@@ -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": "cd8433ec804a"
@@ -61,13 +63,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",
@@ -81,56 +84,36 @@
]
},
{
"attachments": {},
"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."
]
},
{
"attachments": {},
"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"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "fb671e75ca7b"
},
"source": [
"### Install dependencies"
"#### Colab only\n",
"Run the following commands for Colab and skip this section if you are using Workbench."
]
},
{
@@ -141,36 +124,50 @@
},
"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)"
]
},
{
"attachments": {},
"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. **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"
@@ -210,11 +210,18 @@
"# 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\"}"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "e828eb320337"
@@ -237,6 +244,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "2cc825514deb"
@@ -261,6 +269,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "0c250872074f"
@@ -271,19 +280,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 +336,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 +343,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 +350,87 @@
" 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": "Wx18bDXC2XPR"
},
"source": [
"## Run inferences locally"
]
},
{
"attachments": {},
"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])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "e70e3519ff8b"
@@ -357,6 +440,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "f560edbf96c6"
@@ -381,17 +465,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\")"
]
},
{
@@ -455,6 +530,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "90d3c379090e"
@@ -464,6 +540,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "1cc26e68d7b0"
@@ -475,6 +552,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "b8bb7d198315"
@@ -484,6 +562,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "79b66382f849"
@@ -504,12 +583,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-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",
")"
]
},
{
"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,
@@ -538,6 +627,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "f12f8d9c2786"
@@ -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
}
@@ -332,6 +332,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,
@@ -332,6 +332,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",
@@ -231,13 +240,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 +256,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 +265,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 +314,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 +542,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\"]\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 +568,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",
@@ -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 are using Workbench."
]
},
{
@@ -181,27 +181,37 @@
"# 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/"
]
},
{
@@ -225,13 +235,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 +261,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,9 +270,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",
@@ -313,10 +321,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",
@@ -469,7 +476,30 @@
" 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"
]
},
{
@@ -621,8 +651,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 +691,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 +721,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 +739,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",
@@ -807,8 +841,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",
@@ -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"
]
}
],
@@ -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\"}"
]
},
{
@@ -493,26 +326,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": "9axiWxVBQEH7"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -603,7 +416,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,8 +476,8 @@
},
"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",
@@ -1007,7 +822,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 +956,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 +1142,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 +1209,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 +1383,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)
```
@@ -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)"
]
+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.
```
@@ -120,48 +120,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gCuSR8GkAgzl"
},
"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": {
@@ -170,7 +128,7 @@
"source": [
"### Install additional packages\n",
"\n",
"Install additional package dependencies not installed in your notebook environment, such as TensorFlow and Vertex AI SDK. Use the latest major GA version of each package."
"Install additional package dependencies not installed in your notebook environment."
]
},
{
@@ -181,132 +139,62 @@
},
"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 {USER_FLAG} tensorflow==2.8 google-cloud-aiplatform -q --no-warn-conflicts\n",
"! pip3 install {USER_FLAG} protobuf==3.20.3"
"! pip3 install tensorflow==2.8 google-cloud-aiplatform -q --no-warn-conflicts\n",
"! pip3 install protobuf==3.20.3"
]
},
{
"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 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 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": "cd85f5c794e5"
"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": "30e64c0eda41"
},
"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}"
]
},
{
@@ -315,7 +203,7 @@
"id": "717d548a9e90"
},
"source": [
"#### Get your project number {TODO: Include these cells if the notebook uses a project number}\n",
"#### Get your project number\n",
"Now that the project ID is set, you get your corresponding project number."
]
},
@@ -340,16 +228,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)."
]
},
{
@@ -360,160 +239,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": "05030c0446bc"
"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.\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 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": "201e8e760d22"
"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": "818dcc274793"
"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": "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": "0a407d8b11f6"
},
"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."
@@ -523,91 +335,11 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "91c46850b49b"
"id": "create_bucket"
},
"outputs": [],
"source": [
"! 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": {
"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",
"\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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PyQmSRbKA8r-"
},
"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",
"# If on Google Cloud Notebooks, 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 ''"
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
@@ -627,7 +359,10 @@
},
"outputs": [],
"source": [
"import uuid\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pandas as pd\n",
"from google.cloud import aiplatform as vertex_ai\n",
"from tensorflow.python.keras import Sequential, layers\n",
@@ -672,7 +407,7 @@
"outputs": [],
"source": [
"if EXPERIMENT_NAME == \"[your-experiment-name]\" or EXPERIMENT_NAME is None:\n",
" EXPERIMENT_NAME = \"my-experiment-\" + UUID"
" EXPERIMENT_NAME = f\"my-experiment-{uuid.uuid1()}\""
]
},
{
@@ -967,6 +702,12 @@
"\n",
" # Log final metrics\n",
" loss, mae, mse = model.evaluate(normed_test_data, test_labels, verbose=2)\n",
" if np.isnan(loss):\n",
" loss = 0\n",
" if np.isnan(mae):\n",
" mae = 0\n",
" if np.isnan(mse):\n",
" mse = 0\n",
" vertex_ai.log_metrics({\"eval_loss\": loss, \"eval_mae\": mae, \"eval_mse\": mse})\n",
"\n",
" vertex_ai.end_run()"
@@ -1080,6 +821,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Delete experiment\n",
"exp = vertex_ai.Experiment(EXPERIMENT_NAME)\n",
"exp.delete(delete_backing_tensorboard_runs=True)\n",
@@ -120,48 +120,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gCuSR8GkAgzl"
},
"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": {
@@ -170,7 +128,7 @@
"source": [
"### Install additional packages\n",
"\n",
"Install additional package dependencies not installed in your notebook environment, such as Vertex AI SDK and KFP SDK. Use the latest major GA version of each package."
"Install additional package dependencies not installed in your notebook environment."
]
},
{
@@ -181,339 +139,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} --force-reinstall 'google-cloud-aiplatform>=1.15' -q --no-warn-conflicts\n",
"!pip3 install {USER_FLAG} kfp -q --no-warn-conflicts"
"! pip3 install --force-reinstall 'google-cloud-aiplatform>=1.15' -q --no-warn-conflicts\n",
"! pip3 install kfp -q --no-warn-conflicts"
]
},
{
"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 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 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": "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": [
"import os\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"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": "f2e3c0f2cbfb"
},
"outputs": [],
"source": [
"! gcloud config set project $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 = \"python-docs-samples-tests\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2aa333eca058"
"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": "d8b34ef9a3d0"
"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": "126548a06aa1"
},
"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": "e660b8504e63"
},
"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": "sBCra4QMA2wR"
"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.\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 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",
"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": "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."
@@ -523,31 +312,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"
]
},
{
@@ -669,6 +438,7 @@
"# General\n",
"import os\n",
"import time\n",
"import uuid\n",
"\n",
"logger = logging.getLogger(\"logger\")\n",
"logging.basicConfig(level=logging.INFO)\n",
@@ -693,7 +463,7 @@
"# Experiments\n",
"TASK = \"classification\"\n",
"MODEL_TYPE = \"xgboost\"\n",
"EXPERIMENT_NAME = f\"{PROJECT_ID}-{TASK}-{MODEL_TYPE}-{UUID}\"\n",
"EXPERIMENT_NAME = f\"{PROJECT_ID}-{TASK}-{MODEL_TYPE}-{uuid.uuid1()}\"\n",
"\n",
"# Pipeline\n",
"PIPELINE_TEMPLATE_FILE = \"pipeline.json\"\n",
@@ -0,0 +1,893 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ur8xi4C7S06n"
},
"outputs": [],
"source": [
"# Copyright 2022 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": "JAPoU8Sm5E6e"
},
"source": [
"# Vertex AI Experiments: Custom training autologging - Local script\n",
"\n",
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/experiments/get_started_with_custom_training_autologging_local_script.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/official/experiments/get_started_with_custom_training_autologging_local_script.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/official/experiments/get_started_with_custom_training_autologging_local_script.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",
"As a Data Scientist experimenting with large models, you need a way to run experiments on a scalable training service to log parameters and metrics. This guarantees reproducibility.\n",
"\n",
"With Vertex AI Training and Experiments autologging integration, you can run your ML experiments at scale and autolog their parameters and metrics by `enable_autolog` argument.\n",
"\n",
"Learn more about [Vertex AI Experiments](https://cloud.google.com/vertex-ai/docs/experiments/intro-vertex-ai-experiments)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d975e698c9a4"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to autolog paramenters and metrics of an ML experiment running on Vertex AI training by leveraging the integration with Vertex AI Experiments.\n",
"\n",
"This tutorial uses the following Google Cloud ML services and resources:\n",
"\n",
"- Vertex AI Experiments\n",
"- Vertex AI Training\n",
"\n",
"The steps performed include:\n",
"\n",
"- Formalize model experiment in a script\n",
"- Run model traning using local script on Vertex AI Training\n",
"- Check out ML experiment parameters and metrics in Vertex AI Experiments"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "08d289fa873f"
},
"source": [
"### Dataset\n",
"\n",
"The [Glass Identification dataset](https://archive-beta.ics.uci.edu/dataset/42/glass+identification) is a dataset from USA Forensic Science Service with 6 types of glass defined in terms of their oxide content (i.e. Na, Fe, K, etc). The goal is classifying the types of glass based on oxide features."
]
},
{
"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),\n",
"and [Cloud Storage pricing](https://cloud.google.com/storage/pricing),\n",
"and use the [Pricing Calculator](https://cloud.google.com/products/calculator/)\n",
"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",
"USER = \"\"\n",
"! pip3 install {USER} --upgrade google-cloud-aiplatform --quiet --no-warn-conflicts"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "58707a750154"
},
"source": [
"### Colab only: Uncomment the following cell to restart the kernel."
]
},
{
"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",
"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 API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk)."
]
},
{
"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": "1s_lfsWxhctH"
},
"outputs": [],
"source": [
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-_8nZXd7NqIj"
},
"source": [
"### UUID\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": "dY-WpyyzNtS0"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of length 8\n",
"def generate_uuid():\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=8))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"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.\n"
]
},
{
"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": "set_service_account"
},
"source": [
"### Set 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.\n",
"\n",
"*Note:* The code for automatically finding your service account works on a user-managed Workbench AI noteboook. If you are using a fully-managed notebook, you will need to manually enter your service account."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "M4WZi4CDJ39n"
},
"outputs": [],
"source": [
"SERVICE_ACCOUNT = \"[your-service-account]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_service_account"
},
"outputs": [],
"source": [
"IS_COLAB = False\n",
"\n",
"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 Training\n",
"\n",
"Run the following commands to grant your service account access to read and update metadata in Vertex AI ML Metadata while the custom training job is running -- you only need to run these once per service account. Check out the [documentation](https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-training#create_a_service_account_with_required_permissions) to get more information."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mI3IJONMJ39n"
},
"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": "UlICvTdOtyLN"
},
"source": [
"### Set up project template\n",
"Set the folder you use in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rxRaeiQIt6kn"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"TUTORIAL_DIR = os.path.join(\n",
" os.getcwd(), \"custom_training_autologging_local_script_tutorial\"\n",
")\n",
"os.makedirs(TUTORIAL_DIR, exist_ok=True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-flLpWUeOX_n"
},
"source": [
"### Get dataset\n",
"Get the glass classification dataset from the public Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eRBPBlj1PBUK"
},
"outputs": [],
"source": [
"SOURCE_DATA_URL = \"gs://cloud-samples-data/vertex-ai/dataset-management/datasets/uci_glass_preprocessed/glass.csv\"\n",
"DESTINATION_DATA_URL = f\"{BUCKET_URI}/data/glass.csv\"\n",
"\n",
"! gsutil cp $SOURCE_DATA_URL $DESTINATION_DATA_URL"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "960505627ddf"
},
"source": [
"### Import libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PyQmSRbKA8r-"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"from google.cloud import aiplatform as vertex_ai"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rLzhLCJVKIHO"
},
"source": [
"### Define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "sWa5mNJEKKEx"
},
"outputs": [],
"source": [
"# Training\n",
"EXPERIMENT_NAME = f\"glass-classification-{UUID}\"\n",
"TRAIN_SCRIPT_PATH = os.path.join(TUTORIAL_DIR, \"task.py\")\n",
"JOB_DISPLAY_NAME = f\"sklearn-autologged-custom-job-{UUID}\"\n",
"PRE_BUILT_TRAINING_CONTAINER_IMAGE_URI = (\n",
" f\"{REGION.split('-')[0]}-docker.pkg.dev/vertex-ai/training/tf-cpu.2-11:latest\"\n",
")\n",
"MODEL_FILE_URI = f\"{BUCKET_URI}/models/model.joblib\"\n",
"DESTINATION_DATA_PATH = DESTINATION_DATA_URL.replace(\"gs://\", \"/gcs/\")\n",
"MODEL_FILE_PATH = MODEL_FILE_URI.replace(\"gs://\", \"/gcs/\")\n",
"REPLICA_COUNT = 1\n",
"TRAIN_MACHINE_TYPE = \"n1-standard-4\"\n",
"TRAINING_JOBS_URI = f\"{BUCKET_URI}/jobs\""
]
},
{
"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": "kyr59QdyhctK"
},
"outputs": [],
"source": [
"vertex_ai.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wJoFEV5VNWb3"
},
"source": [
"### Create an experiment for tracking training parameters and metrics\n",
"\n",
"To start, initiate an experiment using the `init()` method."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8ZEB_90wNc2J"
},
"outputs": [],
"source": [
"vertex_ai.init(\n",
" project=PROJECT_ID,\n",
" location=REGION,\n",
" staging_bucket=BUCKET_URI,\n",
" experiment=EXPERIMENT_NAME,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ig4h3BP_EuqF"
},
"source": [
"### Train a scikit-learn model with a prebuilt container\n",
"\n",
"Then, you train a custom model using a prebuilt container for scikit-learn models.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yeKHxs4TK0Es"
},
"source": [
"#### Create scikit-learn training script"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "zOKUe_J3JWBs"
},
"outputs": [],
"source": [
"task_script = f\"\"\"\n",
"#!/usr/bin/env python3\n",
"\n",
"'''\n",
"A simple module to train a classifier on the glass dataset.\n",
"'''\n",
"\n",
"# Libraries\n",
"import argparse\n",
"from pathlib import Path\n",
"import pandas as pd\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.ensemble import RandomForestClassifier\n",
"from sklearn.metrics import accuracy_score\n",
"import joblib\n",
"\n",
"\n",
"# Variables\n",
"DATA_PATH = '{DESTINATION_DATA_PATH}'\n",
"MODEL_PATH = '{MODEL_FILE_PATH}'\n",
"TEST_SIZE = 0.2\n",
"SEED = 8\n",
"\n",
"# Helpers\n",
"def read_data(path):\n",
" df = pd.read_csv(path)\n",
" return df\n",
"\n",
"\n",
"def split_data(df):\n",
" y = df.pop('glass_type')\n",
" X = df\n",
" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TEST_SIZE, random_state=SEED)\n",
" return X_train, X_test, y_train, y_test\n",
"\n",
"\n",
"def train_model(X_train, y_train):\n",
" model = RandomForestClassifier(n_estimators=5)\n",
" model.fit(X_train, y_train)\n",
" return model\n",
"\n",
"\n",
"def evaluate_model(model, X_test, y_test):\n",
" y_pred = model.predict(X_test)\n",
" accuracy = accuracy_score(y_test, y_pred)\n",
" return accuracy\n",
"\n",
"\n",
"def save_model(model, path):\n",
" p = Path(path)\n",
" if not p.parent.exists():\n",
" p.parent.mkdir(parents=True)\n",
" joblib.dump(model, path)\n",
"\n",
"\n",
"def main():\n",
"\n",
" # Read data\n",
" df = read_data(DATA_PATH)\n",
"\n",
" # Split data\n",
" X_train, X_test, y_train, y_test = split_data(df)\n",
"\n",
" # Train model\n",
" model = train_model(X_train, y_train)\n",
"\n",
" # Evaluate model\n",
" accuracy = evaluate_model(model, X_test, y_test)\n",
" print('Model accuracy:', accuracy)\n",
"\n",
" # Save model\n",
" save_model(model, MODEL_PATH)\n",
"\n",
"\n",
"\n",
"if __name__ == '__main__':\n",
"\n",
" # Run main\n",
" main()\n",
"\"\"\"\n",
"\n",
"with open(TRAIN_SCRIPT_PATH, \"w\") as train_file:\n",
" train_file.write(task_script)\n",
"train_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7tXILrH3Kr4p"
},
"source": [
"#### Define custom training job\n",
"\n",
"Define a custom job with the prebuilt container image for training code packaged as Python script. In this case, you set `enable_autolog=True` to automatically track parameters and metrics after the training job completes. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jACJpf78LFoy"
},
"outputs": [],
"source": [
"job = vertex_ai.CustomJob.from_local_script(\n",
" project=PROJECT_ID,\n",
" staging_bucket=TRAINING_JOBS_URI,\n",
" display_name=JOB_DISPLAY_NAME,\n",
" script_path=TRAIN_SCRIPT_PATH,\n",
" container_uri=PRE_BUILT_TRAINING_CONTAINER_IMAGE_URI,\n",
" requirements=[\"pandas\", \"scikit-learn\"],\n",
" replica_count=REPLICA_COUNT,\n",
" machine_type=TRAIN_MACHINE_TYPE,\n",
" enable_autolog=True,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xfaE5rK-MYxO"
},
"source": [
"### Run custom training job\n",
"Next, you run the training job using the method `run`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4-Jn9rJeMUZa"
},
"outputs": [],
"source": [
"job.run(experiment=EXPERIMENT_NAME, service_account=SERVICE_ACCOUNT)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SYwi0B3cd515"
},
"source": [
"### Get your autologged experiment\n",
"\n",
"After you train your model, you can get parameters and metrics of the autologged experiment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IQCXPih6d9nA"
},
"outputs": [],
"source": [
"experiment_df = vertex_ai.get_experiment_df(experiment=EXPERIMENT_NAME)\n",
"experiment_df.T"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ffcedb5809e4"
},
"source": [
"Also you can get custom training job metadata associated with the experiment you run. You resume the logged experiments and use `get_logged_custom_jobs()` to get all `CustomJobs` resources associated to this experiment run. Then you use `job_spec` to print custom job metadata such as the training python package, training resources and more. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fI2xd4DbJvHC"
},
"outputs": [],
"source": [
"experiment_run = experiment_df.run_name.iloc[0]\n",
"\n",
"with vertex_ai.start_run(experiment_run, resume=True) as run:\n",
" # get the latest logged custom job\n",
" logged_job = run.get_logged_custom_jobs()[-1]\n",
"\n",
"print(logged_job.job_spec)"
]
},
{
"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": [
"import os\n",
"\n",
"# delete flags\n",
"delete_experiment = False\n",
"delete_bucket = False\n",
"\n",
"# Delete experiment\n",
"if delete_experiment or os.getenv(\"IS_TESTING\"):\n",
" experiment = vertex_ai.Experiment.get(experiment_name=EXPERIMENT_NAME)\n",
" experiment.delete(delete_backing_tensorboard_runs=True)\n",
"\n",
"# Delete Cloud Storage objects that were created\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil -m rm -r $BUCKET_URI"
]
}
],
"metadata": {
"colab": {
"name": "get_started_with_custom_training_autologging_local_script.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -179,20 +179,8 @@
},
"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 google-cloud-aiplatform {USER_FLAG} -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" pandas"
]
},
{
@@ -201,64 +189,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, Cloud Storage and Cloud Logging APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage_component,logging).\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)"
]
},
{
@@ -269,33 +231,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}"
]
},
{
@@ -306,16 +245,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)."
]
},
{
@@ -326,101 +256,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": "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": "4e166d927e36"
},
"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": "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 = \"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."
]
},
{
@@ -431,11 +325,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."
]
},
{
@@ -446,21 +336,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\"}"
]
},
{
@@ -476,33 +352,13 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aO4sKJfFox9R"
"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": "yWnghzKFox9S"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -572,6 +428,9 @@
},
"outputs": [],
"source": [
"import os\n",
"import uuid\n",
"\n",
"import google.cloud.aiplatform as aiplatform"
]
},
@@ -794,7 +653,7 @@
"EXPERIMENT_NAME = \"[your-experiment-name]\"\n",
"\n",
"if EXPERIMENT_NAME == \"[your-experiment-name]\":\n",
" EXPERIMENT_NAME = \"example-\" + UUID"
" EXPERIMENT_NAME = f\"example-{uuid.uuid1()}\""
]
},
{
@@ -994,7 +853,10 @@
"outputs": [],
"source": [
"exp = aiplatform.Experiment(EXPERIMENT_NAME)\n",
"exp.delete()"
"try:\n",
" exp.delete()\n",
"except Exception as e:\n",
" print(e)"
]
},
{
@@ -1017,6 +879,7 @@
"outputs": [],
"source": [
"# Create experiment\n",
"EXPERIMENT_NAME = f\"example-{uuid.uuid1()}\"\n",
"aiplatform.init(experiment=EXPERIMENT_NAME)\n",
"aiplatform.start_run(\"run-1\")"
]
@@ -1191,7 +1054,10 @@
},
"outputs": [],
"source": [
"exp.delete()"
"try:\n",
" exp.delete()\n",
"except Exception as e:\n",
" print(e)"
]
},
{
@@ -1440,7 +1306,7 @@
},
"outputs": [],
"source": [
"DISPLAY_NAME = \"example_\" + UUID\n",
"DISPLAY_NAME = \"example\"\n",
"\n",
"job = aiplatform.CustomPythonPackageTrainingJob(\n",
" display_name=DISPLAY_NAME,\n",
@@ -1478,6 +1344,8 @@
},
"outputs": [],
"source": [
"EXPERIMENT_NAME = f\"example-{uuid.uuid1()}\"\n",
"\n",
"CMDARGS = [\n",
" \"--model-dir=\" + BUCKET_URI,\n",
" \"--dataset-uri=gs://example/foo.csv\",\n",
@@ -1540,7 +1408,10 @@
},
"outputs": [],
"source": [
"print(\"Open the following link\", experiment_df[\"metric.lineage\"][0])"
"try:\n",
" print(\"Open the following link\", experiment_df[\"metric.lineage\"][0])\n",
"except Exception as e:\n",
" print(e)"
]
},
{
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/experiments/autologging.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/experiments/get_started_with_vertex_experiments_autologging.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/official/experiments/autologging.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/experiments/get_started_with_vertex_experiments_autologging.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/official/experiments/autologging.ipynb\">\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/official/experiments/get_started_with_vertex_experiments_autologging.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",
+1 -1
View File
@@ -60,7 +60,7 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Vertex AI Batch Prediction](https://cloud.google.com/vertex-ai/docs/tabular-data/classification-regression/get-batch-predictions).
[Custom training image classification model for online prediction with explainabilty](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/explainable_ai/sdk_custom_image_classification_online_explain.ipynb)
[Custom training image classification model for online prediction with explainability](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/explainable_ai/sdk_custom_image_classification_online_explain.ipynb)
```
Learn how to use `Vertex AI Training and Explainable AI` to create a custom image classification model with explanations, and then you learn to use `Vertex AI Prediction` to make an online prediction request with explanations.
@@ -130,39 +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 Notebook, 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.\n",
"\n",
"4. Activate that environment and run `pip3 install Jupyter` in a terminal shell to install Jupyter.\n",
"\n",
"5. Run `jupyter notebook` on the command line in a terminal shell to launch Jupyter.\n",
"\n",
"6. Open this notebook in the Jupyter Notebook Dashboard.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -184,20 +151,9 @@
"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 google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install {USER_FLAG} --upgrade google-cloud-storage -q\n",
"! pip3 install --upgrade tensorflow $USER_FLAG"
"! pip3 install --upgrade --quiet google-cloud-aiplatform\n",
"! pip3 install --upgrade --quiet google-cloud-storage\n",
"! pip3 install --upgrade --quiet tensorflow"
]
},
{
@@ -206,57 +162,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. [The Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebook.\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)"
]
},
{
@@ -267,33 +204,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}"
]
},
{
@@ -304,16 +218,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)."
]
},
{
@@ -324,40 +229,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",
"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 the uuid 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 length 8\n",
"def generate_uuid():\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=8))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
@@ -368,64 +240,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."
"**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."
]
},
{
@@ -436,11 +298,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."
]
},
{
@@ -451,21 +309,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 = \"gs://\" + BUCKET_NAME"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -488,26 +332,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": {
@@ -648,7 +472,7 @@
"outputs": [],
"source": [
"dataset = aip.TabularDataset.create(\n",
" display_name=\"Bank Marketing\" + \"_\" + UUID, gcs_source=[IMPORT_FILE]\n",
" display_name=\"Bank Marketing\", gcs_source=[IMPORT_FILE]\n",
")\n",
"\n",
"print(dataset.resource_name)"
@@ -699,7 +523,7 @@
"outputs": [],
"source": [
"dag = aip.AutoMLTabularTrainingJob(\n",
" display_name=\"bank_\" + UUID,\n",
" display_name=\"bank\",\n",
" optimization_prediction_type=\"classification\",\n",
" optimization_objective=\"minimize-log-loss\",\n",
")\n",
@@ -741,7 +565,7 @@
"source": [
"model = dag.run(\n",
" dataset=dataset,\n",
" model_display_name=\"bank_\" + UUID,\n",
" model_display_name=\"bank\",\n",
" training_fraction_split=0.6,\n",
" validation_fraction_split=0.2,\n",
" test_fraction_split=0.2,\n",
@@ -863,7 +687,7 @@
"outputs": [],
"source": [
"batch_predict_job = model.batch_predict(\n",
" job_display_name=\"bank_\" + UUID,\n",
" job_display_name=\"bank\",\n",
" gcs_source=gcs_input_uri,\n",
" gcs_destination_prefix=BUCKET_URI,\n",
" instances_format=\"csv\",\n",
@@ -125,39 +125,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 Notebook, 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.\n",
"\n",
"4. Activate that environment and run `pip3 install Jupyter` in a terminal shell to install Jupyter.\n",
"\n",
"5. Run `jupyter notebook` on the command line in a terminal shell to launch Jupyter.\n",
"\n",
"6. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -177,22 +144,9 @@
},
"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-storage \\\n",
" tensorflow==2.5"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage \\\n",
" tensorflow==2.5"
]
},
{
@@ -201,57 +155,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. [The Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebook.\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)"
]
},
{
@@ -262,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}"
]
},
{
@@ -299,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)."
]
},
{
@@ -319,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 length 8\n",
"def generate_uuid():\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=8))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
@@ -364,64 +233,54 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Workbench AI 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."
]
},
{
@@ -432,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 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."
]
},
{
@@ -447,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 = \"gs://\" + BUCKET_NAME"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -484,26 +325,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": {
@@ -524,6 +345,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"import google.cloud.aiplatform as aip"
]
},
@@ -960,7 +783,7 @@
"outputs": [],
"source": [
"job = aip.CustomTrainingJob(\n",
" display_name=\"boston_\" + UUID,\n",
" display_name=\"boston\",\n",
" script_path=\"custom/trainer/task.py\",\n",
" container_uri=TRAIN_IMAGE,\n",
" requirements=[\"gcsfs==0.7.1\", \"tensorflow-datasets==4.4\"],\n",
@@ -995,7 +818,7 @@
},
"outputs": [],
"source": [
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, UUID)\n",
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, \"model\")\n",
"\n",
"EPOCHS = 20\n",
"STEPS = 100\n",
@@ -1416,7 +1239,7 @@
"outputs": [],
"source": [
"model = aip.Model.upload(\n",
" display_name=\"boston_\" + UUID,\n",
" display_name=\"boston\",\n",
" artifact_uri=MODEL_DIR,\n",
" serving_container_image_uri=DEPLOY_IMAGE,\n",
" explanation_parameters=parameters,\n",
@@ -1519,7 +1342,7 @@
"MAX_NODES = 1\n",
"\n",
"batch_predict_job = model.batch_predict(\n",
" job_display_name=\"boston_\" + UUID,\n",
" job_display_name=\"boston\",\n",
" gcs_source=gcs_input_uri,\n",
" gcs_destination_prefix=BUCKET_URI,\n",
" instances_format=\"csv\",\n",
@@ -128,39 +128,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 Notebook, 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.\n",
"\n",
"4. Activate that environment and run `pip3 install Jupyter` in a terminal shell to install Jupyter.\n",
"\n",
"5. Run `jupyter notebook` on the command line in a terminal shell to launch Jupyter.\n",
"\n",
"6. Open this notebook in the Jupyter Notebook Dashboard.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -180,22 +147,9 @@
},
"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 google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install {USER_FLAG} --upgrade google-cloud-storage -q\n",
"! pip3 install --upgrade tensorflow $USER_FLAG -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage \\\n",
" tensorflow "
]
},
{
@@ -204,57 +158,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. [The Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebook.\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)"
]
},
{
@@ -265,33 +200,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}"
]
},
{
@@ -302,16 +214,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)."
]
},
{
@@ -325,30 +228,6 @@
"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": {
@@ -357,64 +236,54 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Workbench AI 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."
"**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."
]
},
{
@@ -425,11 +294,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."
]
},
{
@@ -440,21 +305,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 = \"gs://\" + BUCKET_NAME"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
@@ -477,26 +328,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": {
@@ -517,6 +348,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"import google.cloud.aiplatform as aip"
]
},
@@ -957,7 +790,7 @@
"outputs": [],
"source": [
"job = aip.CustomTrainingJob(\n",
" display_name=\"boston_\" + TIMESTAMP,\n",
" display_name=\"boston\",\n",
" script_path=\"custom/trainer/task.py\",\n",
" container_uri=TRAIN_IMAGE,\n",
" requirements=[\"gcsfs==0.7.1\", \"tensorflow-datasets==4.4\"],\n",
@@ -993,7 +826,7 @@
},
"outputs": [],
"source": [
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, TIMESTAMP)\n",
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, \"model\")\n",
"\n",
"EPOCHS = 20\n",
"STEPS = 100\n",
@@ -1414,7 +1247,7 @@
"outputs": [],
"source": [
"model = aip.Model.upload(\n",
" display_name=\"boston_\" + TIMESTAMP,\n",
" display_name=\"boston\",\n",
" artifact_uri=MODEL_DIR,\n",
" serving_container_image_uri=DEPLOY_IMAGE,\n",
" explanation_parameters=parameters,\n",
@@ -1454,7 +1287,7 @@
},
"outputs": [],
"source": [
"DEPLOYED_NAME = \"boston-\" + TIMESTAMP\n",
"DEPLOYED_NAME = \"boston\"\n",
"\n",
"TRAFFIC_SPLIT = {\"0\": 100}\n",
"\n",
@@ -130,39 +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 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": {
@@ -184,45 +151,11 @@
"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",
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage\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"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_tensorflow"
},
"outputs": [],
"source": [
"if os.getenv(\"IS_TESTING\"):\n",
" ! pip3 install --upgrade tensorflow $USER_FLAG"
" ! pip3 install --upgrade --quiet tensorflow "
]
},
{
@@ -231,57 +164,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)"
]
},
{
@@ -292,33 +206,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}"
]
},
{
@@ -329,16 +220,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)."
]
},
{
@@ -352,30 +234,6 @@
"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": {
@@ -384,53 +242,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."
]
},
{
@@ -441,11 +300,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."
]
},
{
@@ -456,19 +311,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\"}"
]
},
{
@@ -488,27 +331,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $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 $BUCKET_URI"
]
},
{
@@ -553,7 +376,7 @@
},
"outputs": [],
"source": [
"aip.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME)"
"aip.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)"
]
},
{
@@ -934,7 +757,7 @@
"! rm -f custom.tar custom.tar.gz\n",
"! tar cvf custom.tar custom\n",
"! gzip custom.tar\n",
"! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_boston.tar.gz"
"! gsutil cp custom.tar.gz $BUCKET_URI/trainer_boston.tar.gz"
]
},
{
@@ -967,7 +790,7 @@
"outputs": [],
"source": [
"job = aip.CustomTrainingJob(\n",
" display_name=\"boston_\" + TIMESTAMP,\n",
" display_name=\"boston\",\n",
" script_path=\"custom/trainer/task.py\",\n",
" container_uri=TRAIN_IMAGE,\n",
" requirements=[\"gcsfs==0.7.1\", \"tensorflow-datasets==4.4\"],\n",
@@ -1002,7 +825,7 @@
},
"outputs": [],
"source": [
"MODEL_DIR = \"{}/{}\".format(BUCKET_NAME, TIMESTAMP)\n",
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, \"model\")\n",
"\n",
"EPOCHS = 20\n",
"STEPS = 100\n",
@@ -1353,7 +1176,7 @@
"outputs": [],
"source": [
"model = aip.Model.upload(\n",
" display_name=\"boston_\" + TIMESTAMP,\n",
" display_name=\"boston\",\n",
" artifact_uri=MODEL_DIR,\n",
" serving_container_image_uri=DEPLOY_IMAGE,\n",
" explanation_parameters=parameters,\n",
@@ -1393,7 +1216,7 @@
},
"outputs": [],
"source": [
"DEPLOYED_NAME = \"boston-\" + TIMESTAMP\n",
"DEPLOYED_NAME = \"boston\"\n",
"\n",
"TRAFFIC_SPLIT = {\"0\": 100}\n",
"\n",
@@ -1677,17 +1500,7 @@
"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",
"- Pipeline\n",
"- Model\n",
"- Endpoint\n",
"- AutoML Training Job\n",
"- Batch Job\n",
"- Custom Job\n",
"- Hyperparameter Tuning Job\n",
"- Cloud Storage Bucket"
"Otherwise, you can delete the individual resources you created in this tutorial."
]
},
{
@@ -1698,60 +1511,13 @@
},
"outputs": [],
"source": [
"delete_all = True\n",
"delete_bucket = False\n",
"\n",
"if delete_all:\n",
" # Delete the dataset using the Vertex dataset object\n",
" try:\n",
" if \"dataset\" in globals():\n",
" dataset.delete()\n",
" except Exception as e:\n",
" print(e)\n",
"endpoint.delete()\n",
"model.delete()\n",
"\n",
" # Delete the model using the Vertex model object\n",
" try:\n",
" if \"model\" in globals():\n",
" model.delete()\n",
" except Exception as e:\n",
" print(e)\n",
"\n",
" # Delete the endpoint using the Vertex endpoint object\n",
" try:\n",
" if \"endpoint\" in globals():\n",
" endpoint.delete()\n",
" except Exception as e:\n",
" print(e)\n",
"\n",
" # Delete the AutoML or Pipeline trainig job\n",
" try:\n",
" if \"dag\" in globals():\n",
" dag.delete()\n",
" except Exception as e:\n",
" print(e)\n",
"\n",
" # Delete the custom trainig job\n",
" try:\n",
" if \"job\" in globals():\n",
" job.delete()\n",
" except Exception as e:\n",
" print(e)\n",
"\n",
" # Delete the batch prediction job using the Vertex batch prediction object\n",
" try:\n",
" if \"batch_predict_job\" in globals():\n",
" batch_predict_job.delete()\n",
" except Exception as e:\n",
" print(e)\n",
"\n",
" # Delete the hyperparameter tuning job using the Vertex hyperparameter tuning object\n",
" try:\n",
" if \"hpt_job\" in globals():\n",
" hpt_job.delete()\n",
" except Exception as e:\n",
" print(e)\n",
"\n",
" if \"BUCKET_NAME\" in globals():\n",
" ! gsutil rm -r $BUCKET_NAME"
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil rm -r $BUCKET_URI"
]
}
],
File diff suppressed because one or more lines are too long
+110 -110
View File
@@ -1,5 +1,5 @@
[AutoML Image Classification](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb)
[AutoML Image Classification](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-image-classification-batch-online.ipynb)
```
Learn to use `AutoML` to train an image model and use `Vertex AI Prediction` and `Vertex AI Batch Prediction` to do online and batch predictions.
@@ -18,15 +18,14 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Classification for image data](https://cloud.google.com/vertex-ai/docs/training-overview#classification_for_images).
[Custom Scikit-Learn model with pre-built training container](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb)
[AutoML image object detection](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-image-object-detection-batch-online.ipynb)
```
Learn to use `Vertex AI Training` to create a custom trained model and use `Vertex AI Batch Prediction` to do a batch prediction on the trained model.
Learn to use `AutoML` to train an image model and use `Vertex AI Prediction` and `Vertex AI Batch Prediction` to do online and batch predictions.
The steps performed include:
- Create a `Vertex AI` custom job for training a scikit-learn model.
- Upload the trained model artifacts as a `Model` resource.
- Train an AutoML object detection model.
- Make a batch prediction.
- Deploy model to a endpoint
- Make a online prediction
@@ -35,40 +34,7 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Hyperparameter Tuning](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ11 Vertex SDK Hyperparameter Tuning.ipynb)
```
Learn to use `Vertex AI Hyperparameter` to create and tune a custom trained model.
The steps performed include:
- Create a `Vertex AI` hyperparameter tuning job for training a TensorFlow model.
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/training/hyperparameter-tuning-overview).
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[AutoML Video Classification](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ14 Vertex SDK AutoML Video Classification.ipynb)
```
Learn to use `AutoML` to train a video model and use `Vertex AI Batch Prediction` to do batch predictions.
The steps performed include:
- Train an AutoML video classification model.
- Make a batch prediction.
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [Classification for video data](https://cloud.google.com/vertex-ai/docs/training-overview#classification_for_videos).
&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 Video Object Tracking](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ15 Vertex SDK AutoML Object Tracking.ipynb)
@@ -88,55 +54,7 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Object tracking for video data](https://cloud.google.com/vertex-ai/docs/training-overview#object_tracking_for_videos).
[Custom Image Classification w/pre-built training container](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ2,12 Vertex SDK Custom Image Classification with pre-built training container.ipynb)
```
Learn how to train a tensorflow image classification model using a prebuilt container and Vertex AI training.
The steps performed include:
- *Package the training code into a python application.*
- *Containerize the training application using Cloud Build and Artifact Registry.*
- *Create a custom container training job in Vertex AI and run it.*
- *Evaluate the model generated from the training job.*
- *Create a model resource for the trained model in Vertex AI Model Registry.*
- *Run a Vertex AI batch prediction job.*
- *Deploy the model resource to a Vertex AI Endpoint.*
- *Run a online prediction job on the model resource.*
- *Clean up the resources created.*
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Custom Image Classification w/custom training container](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ3 Vertex SDK Custom Image Classification with custom training container.ipynb)
```
Learn how to train a tensorflow image classification model using a custom container and Vertex AI training.
The steps performed include:
- *Package the training code into a python application.*
- *Containerize the training application using Cloud Build and Artifact Registry.*
- *Create a custom container training job in Vertex AI and run it.*
- *Evaluate the model generated from the training job.*
- *Create a model resource for the trained model in Vertex AI Model Registry.*
- *Run a Vertex AI batch prediction job.*
- *Deploy the model resource to a Vertex AI Endpoint.*
- *Run a online prediction job on the model resource.*
- *Clean up the resources created.*
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[AutoML Tabular Binary Classification](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ4 Vertex SDK AutoML Tabular Binary Classification.ipynb)
[AutoML tabular binary classification](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-tabular-binary-classification-online-prediction.ipynb)
```
In this tutorial, you create an AutoML tabular binary classification model and deploy for online prediction from a Python script using the Vertex AI SDK.
@@ -157,26 +75,7 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Classification for tabular data](https://cloud.google.com/vertex-ai/docs/tabular-data/classification-regression/overview).
[AutoML Image Object Detection](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ5 Vertex SDK AutoML Image Object Detection.ipynb)
```
Learn to use `AutoML` to train an image model and use `Vertex AI Prediction` and `Vertex AI Batch Prediction` to do online and batch predictions.
The steps performed include:
- Train an AutoML object detection model.
- Make a batch prediction.
- Deploy model to a endpoint
- Make a online prediction
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&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 Text Classification](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ6 Vertex SDK AutoML Text Classification.ipynb)
[AutoML Text Classification](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-text-classification-batch-prediction.ipynb)
```
The objective of this notebook is to build a AutoML Text Classification Model.
@@ -198,7 +97,7 @@ The steps performed include the following:
&nbsp;&nbsp;&nbsp;Learn more about [Classification for text data](https://cloud.google.com/vertex-ai/docs/training-overview#classification_for_text).
[AutoML Text Entity Extraction](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ7 Vertex SDK AutoML Text Entity Extraction.ipynb)
[AutoML Text Entity Extraction](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-text-classification-batch-prediction.ipynb)
```
The objective of this notebook is to build a AutoML Text Entity Extraction model.
@@ -241,7 +140,72 @@ The steps performed include the following:
&nbsp;&nbsp;&nbsp;Learn more about [Sentiment analysis for text data](https://cloud.google.com/vertex-ai/docs/training-overview#sentiment_analysis_for_text).
[Custom XGBoost model with pre-built training container](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ9 Vertex SDK Custom XGBoost with pre-built training container.ipynb)
[AutoML Video Classification](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ14 Vertex SDK AutoML Video Classification.ipynb)
```
Learn to use `AutoML` to train a video model and use `Vertex AI Batch Prediction` to do batch predictions.
The steps performed include:
- Train an AutoML video classification model.
- Make a batch prediction.
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [Classification for video data](https://cloud.google.com/vertex-ai/docs/training-overview#classification_for_videos).
[Custom image classification with a custom training container](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-image-classification-custom-container.ipynb)
```
Learn how to train a tensorflow image classification model using a custom container and Vertex AI training.
The steps performed include:
- *Package the training code into a python application.*
- *Containerize the training application using Cloud Build and Artifact Registry.*
- *Create a custom container training job in Vertex AI and run it.*
- *Evaluate the model generated from the training job.*
- *Create a model resource for the trained model in Vertex AI Model Registry.*
- *Run a Vertex AI batch prediction job.*
- *Deploy the model resource to a Vertex AI Endpoint.*
- *Run a online prediction job on the model resource.*
- *Clean up the resources created.*
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Custom image classification with a pre-built training container](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-image-classification-prebuilt-container.ipynb)
```
Learn how to train a tensorflow image classification model using a prebuilt container and Vertex AI training.
The steps performed include:
- *Package the training code into a python application.*
- *Containerize the training application using Cloud Build and Artifact Registry.*
- *Create a custom container training job in Vertex AI and run it.*
- *Evaluate the model generated from the training job.*
- *Create a model resource for the trained model in Vertex AI Model Registry.*
- *Run a Vertex AI batch prediction job.*
- *Deploy the model resource to a Vertex AI Endpoint.*
- *Run a online prediction job on the model resource.*
- *Clean up the resources created.*
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Custom Scikit-Learn model with pre-built training container](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-scikit-learn-prebuilt-container.ipynb)
```
Learn to use `Vertex AI Training` to create a custom trained model and use `Vertex AI Batch Prediction` to do a batch prediction on the trained model.
@@ -260,3 +224,39 @@ The steps performed include:
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Custom XGBoost model with pre-built training container](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-xgboost-prebuilt-container.ipynb)
```
Learn to use `Vertex AI Training` to create a custom trained model and use `Vertex AI Batch Prediction` to do a batch prediction on the trained model.
The steps performed include:
- Create a `Vertex AI` custom job for training a scikit-learn model.
- Upload the trained model artifacts as a `Model` resource.
- Make a batch prediction.
- Deploy model to a endpoint
- Make a online prediction
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/start/migrating-to-vertex-ai).
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
[Hyperparameter Tuning](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-hyperparameter-tuning.ipynb)
```
Learn to use `Vertex AI Hyperparameter` to create and tune a custom trained model.
The steps performed include:
- Create a `Vertex AI` hyperparameter tuning job for training a TensorFlow model.
```
&nbsp;&nbsp;&nbsp;Learn more about [Migrate to Vertex AI](https://cloud.google.com/vertex-ai/docs/training/hyperparameter-tuning-overview).
&nbsp;&nbsp;&nbsp;Learn more about [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training).
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-image-classification-batch-online.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/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-image-classification-batch-online.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/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb\" target='_blank'>\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/official/migration/sdk-automl-image-classification-batch-online.ipynb\" target='_blank'>\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",
@@ -1458,7 +1458,7 @@
],
"metadata": {
"colab": {
"name": "UJ1 Vertex SDK AutoML Image Classification.ipynb",
"name": "sdk-automl-image-classification-batch-online.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ5 Vertex SDK AutoML Image Object Detection.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-image-object-detection-batch-online.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/official/migration/UJ5 Vertex SDK AutoML Image Object Detection.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-image-object-detection-batch-online.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/official/migration/UJ5 Vertex SDK AutoML Image Object Detection.ipynb\" target='_blank'>\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/official/migration/sdk-automl-image-object-detection-batch-online.ipynb\" target='_blank'>\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",
@@ -1454,7 +1454,7 @@
],
"metadata": {
"colab": {
"name": "UJ5 Vertex SDK AutoML Image Object Detection.ipynb",
"name": "sdk-automl-image-object-detection-batch-online.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ15 Vertex SDK AutoML Object Tracking.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-object-tracking-batch-prediction.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/official/migration/UJ15 Vertex SDK AutoML Object Tracking.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-object-tracking-batch-prediction.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/official/migration/UJ15 Vertex SDK AutoML Object Tracking.ipynb\" target='_blank'>\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/official/migration/sdk-automl-object-tracking-batch-prediction.ipynb\" target='_blank'>\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",
@@ -633,8 +633,9 @@
" gcs_source=[IMPORT_FILE],\n",
" import_schema_uri=aip.schema.dataset.ioformat.video.object_tracking,\n",
")\n",
"if os.getenv('IS_TESTING'):\n",
"if os.getenv(\"IS_TESTING\"):\n",
" import time\n",
"\n",
" time.sleep(30)\n",
"\n",
"print(dataset.resource_name)"
@@ -1251,7 +1252,7 @@
],
"metadata": {
"colab": {
"name": "UJ15 Vertex SDK AutoML Object Tracking.ipynb",
"name": "sdk-automl-object-tracking-batch-prediction.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ4 Vertex SDK AutoML Tabular Binary Classification.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-tabular-binary-classification-online-prediction.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/official/migration/UJ4 Vertex SDK AutoML Tabular Binary Classification.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-tabular-binary-classification-online-prediction.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/official/migration/UJ4 Vertex SDK AutoML Tabular Binary Classification.ipynb\">\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/official/migration/sdk-automl-tabular-binary-classification-online-prediction.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",
@@ -1410,7 +1410,7 @@
],
"metadata": {
"colab": {
"name": "UJ4 Vertex SDK AutoML Tabular Binary Classification.ipynb",
"name": "sdk-automl-tabular-binary-classification-online-prediction.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -33,18 +33,18 @@
"\n",
"<table align=\"left\">\n",
" <td>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ6 Vertex SDK AutoML Text Classification.ipynb\" target='_blank'>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-text-classification-batch-prediction.ipynb\" target='_blank'>\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/official/migration/UJ6 Vertex SDK AutoML Text Classification.ipynb\" target='_blank'>\n",
"<a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-text-classification-batch-prediction.ipynb\" target='_blank'>\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/official/migration/UJ6 Vertex SDK AutoML Text Classification.ipynb\" target='_blank'>\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/official/migration/sdk-automl-text-classification-batch-prediction.ipynb\" target='_blank'>\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",
@@ -1337,7 +1337,7 @@
],
"metadata": {
"colab": {
"name": "UJ6 Vertex SDK AutoML Text Classification.ipynb",
"name": "sdk-automl-text-classification-batch-prediction.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -33,18 +33,18 @@
"\n",
"<table align=\"left\">\n",
" <td>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ7 Vertex SDK AutoML Text Entity Extraction.ipynb\" target='_blank'>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-text-classification-batch-prediction.ipynb\" target='_blank'>\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/official/migration/UJ7 Vertex SDK AutoML Text Entity Extraction.ipynb\" target='_blank'>\n",
"<a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-text-classification-batch-prediction.ipynb\" target='_blank'>\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/official/migration/UJ7 Vertex SDK AutoML Text Entity Extraction.ipynb\" target='_blank'>\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/official/migration/sdk-automl-text-classification-batch-prediction.ipynb\" target='_blank'>\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",
@@ -1428,7 +1428,7 @@
],
"metadata": {
"colab": {
"name": "UJ7 Vertex SDK AutoML Text Entity Extraction.ipynb",
"name": "sdk-automl-text-entity-extraction-batch-prediction.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ8 Vertex SDK AutoML Text Sentiment Analysis.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-text-sentiment-analysis-batch-prediction.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/official/migration/UJ8 Vertex SDK AutoML Text Sentiment Analysis.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-automl-text-sentiment-analysis-batch-prediction.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/official/migration/UJ8 Vertex SDK AutoML Text Sentiment Analysis.ipynb\" target='_blank'>\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/official/migration/sdk-automl-text-sentiment-analysis-batch-prediction.ipynb\" target='_blank'>\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",
@@ -1413,7 +1413,7 @@
],
"metadata": {
"colab": {
"name": "UJ8 Vertex SDK AutoML Text Sentiment Analysis.ipynb",
"name": "sdk-automl-text-sentiment-analysis-batch-prediction.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -1297,7 +1297,7 @@
],
"metadata": {
"colab": {
"name": "UJ14 Vertex SDK AutoML Video Classification.ipynb",
"name": "sdk-automl-video-classification-batch-prediction.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ3 Vertex SDK Custom Image Classification with custom training container.ipynb\" target='_blank'>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-image-classification-custom-container.ipynb\" target='_blank'>\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/official/migration/UJ3 Vertex SDK Custom Image Classification with custom training container.ipynb\" target='_blank'>\n",
"<a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-image-classification-custom-container.ipynb\" target='_blank'>\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/official/migration/UJ3 Vertex SDK Custom Image Classification with custom training container.ipynb\" target='_blank'>\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/official/migration/sdk-custom-image-classification-custom-container.ipynb\" target='_blank'>\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",
@@ -1899,7 +1899,7 @@
],
"metadata": {
"colab": {
"name": "UJ3 Vertex SDK Custom Image Classification with custom training container.ipynb",
"name": "sdk-custom-image-classification-custom-container.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ2,12 Vertex SDK Custom Image Classification with pre-built training container.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-image-classification-prebuilt-container.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/official/migration/UJ2,12 Vertex SDK Custom Image Classification with pre-built training container.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-image-classification-prebuilt-container.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/official/migration/UJ2,12 Vertex SDK Custom Image Classification with pre-built training container.ipynb\" target='_blank'>\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/official/migration/sdk-custom-image-classification-prebuilt-container.ipynb\" target='_blank'>\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",
@@ -2005,7 +2005,7 @@
],
"metadata": {
"colab": {
"name": "UJ2,12 Vertex SDK Custom Image Classification with pre-built training container.ipynb",
"name": "sdk-custom-image-classification-prebuilt-container.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -33,18 +33,18 @@
"\n",
"<table align=\"left\">\n",
" <td>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb\" target='_blank'>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-scikit-learn-prebuilt-container.ipynb\" target='_blank'>\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/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb\" target='_blank'>\n",
"<a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-scikit-learn-prebuilt-container.ipynb\" target='_blank'>\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/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb\" target='_blank'>\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/official/migration/sdk-custom-scikit-learn-prebuilt-container.ipynb\" target='_blank'>\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",
@@ -1577,7 +1577,7 @@
],
"metadata": {
"colab": {
"name": "UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb",
"name": "sdk-custom-scikit-learn-prebuilt-container.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -33,18 +33,18 @@
"\n",
"<table align=\"left\">\n",
" <td>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ9 Vertex SDK Custom XGBoost with pre-built training container.ipynb\" target='_blank'>\n",
"<a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-xgboost-prebuilt-container.ipynb\" target='_blank'>\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/official/migration/UJ9 Vertex SDK Custom XGBoost with pre-built training container.ipynb\" target='_blank'>\n",
"<a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-custom-xgboost-prebuilt-container.ipynb\" target='_blank'>\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/official/migration/UJ9 Vertex SDK Custom XGBoost with pre-built training container.ipynb\" target='_blank'>\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/official/migration/sdk-custom-xgboost-prebuilt-container.ipynb\" target='_blank'>\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",
@@ -1459,7 +1459,7 @@
],
"metadata": {
"colab": {
"name": "UJ9 Vertex SDK Custom XGBoost with pre-built training container.ipynb",
"name": "sdk-custom-xgboost-prebuilt-container.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -34,18 +34,18 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/UJ11 Vertex SDK Hyperparameter Tuning.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-hyperparameter-tuning.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/official/migration/UJ11 Vertex SDK Hyperparameter Tuning.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/migration/sdk-hyperparameter-tuning.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/official/migration/UJ11 Vertex SDK Hyperparameter Tuning.ipynb\" target='_blank'>\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/official/migration/sdk-hyperparameter-tuning.ipynb\" target='_blank'>\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",
@@ -1414,7 +1414,7 @@
],
"metadata": {
"colab": {
"name": "UJ11 Vertex SDK Hyperparameter Tuning.ipynb",
"name": "sdk-hyperparameter-tuning.ipynb",
"toc_visible": true
},
"kernelspec": {
@@ -63,7 +63,7 @@
"\n",
"This notebook demonstrates how to track metrics and parameters for Vertex AI custom training jobs, and how to perform detailed analysis using this data.\n",
"\n",
"Learn more about [Vertex ML Metadata](https://cloud.google.com/vertex-ai/docs/ml-metadata) and [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training)."
"Learn more about [Vertex ML Metadata](https://cloud.google.com/vertex-ai/docs/ml-metadata), [Custom training](https://cloud.google.com/vertex-ai/docs/training/custom-training), and [Vertex AI Experiments](https://cloud.google.com/vertex-ai/docs/experiments/intro-vertex-ai-experiments)."
]
},
{
@@ -81,6 +81,7 @@
"- Vertex AI Model\n",
"- Vertex AI Endpoint\n",
"- Vertex AI Custom Training Job\n",
"- Vertex AI Experiments\n",
"\n",
"The steps performed include:\n",
"- Track training parameters and prediction metrics for a custom training job.\n",
@@ -124,55 +124,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 AI Platform 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 `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": {
@@ -184,34 +135,6 @@
"Run the following commands to install the Vertex AI SDK and packages used in this notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IaYsrh0Tc17L"
},
"outputs": [],
"source": [
"import os\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",
"# Google Cloud Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_GOOGLE_CLOUD_NOTEBOOK:\n",
" USER_FLAG = \"--user\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MCQDRsnE3uzz"
},
"source": [
"Install Vertex AI and Kubeflow Pipelines SDKs."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -220,196 +143,142 @@
},
"outputs": [],
"source": [
"!pip3 install {USER_FLAG} google-cloud-aiplatform==1.7.0\n",
"!pip3 install {USER_FLAG} kfp==1.8.9"
"! pip3 install --upgrade --quiet google-cloud-aiplatform==1.7.0 \\\n",
" kfp==1.8.9"
]
},
{
"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"
"## Before you begin\n",
"\n",
"### 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": "BF1j6f9HApxa"
"id": "region"
},
"source": [
"### Set up your Google Cloud project\n",
"#### Region\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 services we'll be using throughout this notebook by running the cell below.\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 project ID 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."
"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": "e86205a30eb4"
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using AI Platform Notebooks**, your environment is already\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "28f75ab2b551"
},
"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 \"AI Platform\"\n",
"into the filter box, and select\n",
" **AI Platform 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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d2b00dc291f7"
},
"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`."
"**2. Local JupyterLab instance, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a6a066dd8d6a"
"id": "ce6043da7b33"
},
"outputs": [],
"source": [
"import os\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)"
"# ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dbeae85aef1d"
"id": "0367eac06a10"
},
"source": [
"Otherwise, set your project ID here."
"**3. Colab, uncomment and run:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f90e4cbfb7af"
"id": "21ad4dbb4a61"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
"# from google.colab import auth\n",
"# auth.authenticate_user()"
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {
"id": "fdb343d2ae3c"
"id": "c13224697bfb"
},
"outputs": [],
"source": [
"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",
"# If on Google Cloud Notebooks, then don't execute this code\n",
"IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
"\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",
" !gcloud config set project $PROJECT_ID\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 ''"
"**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."
]
},
{
@@ -439,64 +308,117 @@
{
"cell_type": "markdown",
"metadata": {
"id": "06571eb4063b"
"id": "bucket:mbsdk"
},
"source": [
"#### Timestamp\n",
"### Create a Cloud Storage bucket\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."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "697568e92bd6"
"id": "bucket"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "641c8b2873c0"
"id": "create_bucket"
},
"source": [
"### Create a Cloud Storage Bucket"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "68e74d218ea9"
},
"source": [
"To run our Vertex Pipeline, we'll need a storage bucket to store artifacts generated by our pipeline. This bucket needs to be regional. We're using the `us-central1` region here, but you are welcome to use another region (just replace it throughout this lab). If you already have a bucket you can replace the `BUCKET_NAME` variable with the name of your bucket and skip the `gsutil mb` step."
"**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": "953a1399e79f"
"id": "create_bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"gs://{}-bucket\".format(PROJECT_ID)\n",
"!gsutil mb -l us-central1 $BUCKET_NAME # You only need to run this once"
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b75e9153c699"
"id": "set_service_account"
},
"source": [
"Next, make sure your compute service account has `store.objectAdmin` access to this bucket. Your compute service account will look something like `YOUR_PROJECT_NUMBER-compute@developer.gserviceaccount.com`."
"### Service Account\n",
"\n",
"You use a service account to create Vertex AI Pipeline jobs.\n",
"\n",
"If you do not want to use your project's Compute Engine service account, set `SERVICE_ACCOUNT` to another service account ID."
]
},
{
"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",
" else: # 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"
]
},
{
@@ -556,7 +478,7 @@
"%env PATH={PATH}:/home/jupyter/.local/bin\n",
"REGION = \"us-central1\"\n",
"\n",
"PIPELINE_ROOT = f\"{BUCKET_NAME}/pipeline_root/\"\n",
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/\"\n",
"PIPELINE_ROOT"
]
},
@@ -50,7 +50,7 @@ Learn how to use `Vertex AI Pipelines` and `Google Cloud Pipeline Components` to
The steps performed include:
- Create a Vertex AI `Dataset`.
- Train a Automl Tabular Classification model on the `Dataset` resource.
- Train a Automl Text Classification model on the `Dataset` resource.
- Import the trained `AutoML model resource` into the pipeline.
- Run a `Batch Prediction` job.
- Evaulate the AutoML model using the `Classification Evaluation Component`.
@@ -152,3 +152,5 @@ The steps performed include:
```
&nbsp;&nbsp;&nbsp;Learn more about [Model evaluation in Vertex AI](https://cloud.google.com/vertex-ai/docs/evaluation/introduction).
@@ -143,48 +143,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gCuSR8GkAgzl"
},
"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": {
@@ -204,126 +162,64 @@
},
"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 \\\n",
" google-cloud-pipeline-components==1.0.26 \\\n",
" kfp \\\n",
" matplotlib {USER_FLAG} -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-pipeline-components==1.0.26 \\\n",
" kfp \\\n",
" matplotlib"
]
},
{
"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",
"### Set up your Google Cloud project\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 Dataflow APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,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": "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": "riG_qUokg0XZ"
},
"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}"
]
},
{
@@ -334,175 +230,128 @@
"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": "sduDOFQVF6kv"
"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": "sBCra4QMA2wR"
"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 ''"
"# ! 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": "aab852d94fc7"
},
"source": [
"#### Enable Cloud services used throughout this notebook.\n",
"\n",
"Run the cell below to the enable Compute Engine, Container Registry, and Vertex AI services."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "18396d3d7fe4"
},
"outputs": [],
"source": [
"!gcloud services enable compute.googleapis.com \\\n",
" containerregistry.googleapis.com \\\n",
" aiplatform.googleapis.com"
]
},
{
"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 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."
]
},
{
"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."
@@ -512,31 +361,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"
]
},
{
@@ -693,7 +522,7 @@
"source": [
"# Create the Vertex AI Dataset resource\n",
"dataset = aiplatform.TabularDataset.create(\n",
" display_name=\"petfinder-tabular-dataset_\" + UUID,\n",
" display_name=\"petfinder-tabular-dataset\",\n",
" gcs_source=DATA_SOURCE,\n",
")\n",
"\n",
@@ -738,7 +567,7 @@
" or TRAINING_JOB_DISPLAY_NAME is None\n",
" or TRAINING_JOB_DISPLAY_NAME == \"[your-train-job-display-name]\"\n",
"):\n",
" TRAINING_JOB_DISPLAY_NAME = \"train-petfinder-automl_\" + UUID"
" TRAINING_JOB_DISPLAY_NAME = \"train-petfinder-automl\""
]
},
{
@@ -823,7 +652,7 @@
" or MODEL_DISPLAY_NAME is None\n",
" or MODEL_DISPLAY_NAME == \"[your-model-display-name]\"\n",
"):\n",
" MODEL_DISPLAY_NAME = \"pet-adoption-prediction-model_\" + UUID"
" MODEL_DISPLAY_NAME = \"pet-adoption-prediction-model\""
]
},
{
@@ -1096,7 +925,7 @@
" or PIPELINE_DISPLAY_NAME == \"\"\n",
" or PIPELINE_DISPLAY_NAME is None\n",
"):\n",
" PIPELINE_DISPLAY_NAME = \"pet_adoption_\" + UUID"
" PIPELINE_DISPLAY_NAME = \"pet_adoption\""
]
},
{
@@ -1126,7 +955,7 @@
},
"outputs": [],
"source": [
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/pet_adoption_{UUID}\"\n",
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/pet_adoption\"\n",
"parameters = {\n",
" \"project\": PROJECT_ID,\n",
" \"location\": REGION,\n",
@@ -1368,6 +1197,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Delete model resource\n",
"model.delete()\n",
"\n",
@@ -143,48 +143,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",
"**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": {
@@ -204,126 +162,64 @@
},
"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",
"# 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-pipeline-components==1.0.26 \\\n",
" kfp \\\n",
" matplotlib "
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-pipeline-components==1.0.26 \\\n",
" kfp \\\n",
" matplotlib "
]
},
{
"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": "before_you_begin:nogpu"
},
"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."
]
},
{
"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": "riG_qUokg0XZ"
},
"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}"
]
},
{
@@ -334,175 +230,105 @@
"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": "sduDOFQVF6kv"
"id": "2dw8q9fdQEH5"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"REGION = \"us-central1\"\n",
"DATA_REGION = \"US\""
]
},
{
"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.\n"
]
},
{
"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 [**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 ''"
"# ! 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 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."
]
},
{
"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": "autoset_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
@@ -512,33 +338,13 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NIq7R4HZCfIc"
"id": "91c46850b49b"
},
"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"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -736,7 +542,7 @@
" or TRAINING_JOB_DISPLAY_NAME is None\n",
" or TRAINING_JOB_DISPLAY_NAME == \"[your-train-job-display-name]\"\n",
"):\n",
" TRAINING_JOB_DISPLAY_NAME = \"train-pet-agefinder-automl_\" + UUID"
" TRAINING_JOB_DISPLAY_NAME = \"train-pet-agefinder-automl\""
]
},
{
@@ -826,7 +632,7 @@
" or MODEL_DISPLAY_NAME is None\n",
" or MODEL_DISPLAY_NAME == \"[your-model-display-name]\"\n",
"):\n",
" MODEL_DISPLAY_NAME = \"pet-agefinder-prediction-model_\" + UUID"
" MODEL_DISPLAY_NAME = \"pet-agefinder-prediction-model\""
]
},
{
@@ -952,7 +758,7 @@
" or PIPELINE_DISPLAY_NAME is None\n",
"):\n",
" PIPELINE_DISPLAY_NAME = (\n",
" f\"vertex-evaluation-automl-tabular-regression-feature-attribution-{UUID}\"\n",
" \"vertex-evaluation-automl-tabular-regression-feature-attribution\"\n",
" )"
]
},
@@ -1125,7 +931,7 @@
},
"outputs": [],
"source": [
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/pet_agefinder_{UUID}\"\n",
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/pet_agefinder\"\n",
"batch_predict_sample_size = 10000\n",
"parameters = {\n",
" \"project\": PROJECT_ID,\n",
@@ -1395,6 +1201,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Delete model resource\n",
"model.delete()\n",
"\n",
@@ -127,48 +127,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.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -188,24 +146,10 @@
},
"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",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform \\\n",
" kfp \\\n",
" google-cloud-pipeline-components==1.0.26 \\\n",
" google-cloud-storage {USER_FLAG} -q"
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" kfp \\\n",
" google-cloud-pipeline-components==1.0.26 \\\n",
" google-cloud-storage"
]
},
{
@@ -214,27 +158,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."
"### 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)"
]
},
{
@@ -245,48 +184,12 @@
"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)"
]
},
{
@@ -297,22 +200,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}"
]
},
{
@@ -323,61 +214,19 @@
"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": "region"
"id": "2dw8q9fdQEH5"
},
"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\"\n",
"DATA_REGION = \"US\""
]
},
{
@@ -388,64 +237,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."
]
},
{
@@ -456,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 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\n",
"Cloud Storage buckets."
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
@@ -472,27 +306,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."
@@ -502,33 +322,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": {
@@ -725,7 +525,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",
@@ -768,7 +568,7 @@
"outputs": [],
"source": [
"training_job = aiplatform.AutoMLVideoTrainingJob(\n",
" display_name=\"hmdb_\" + UUID,\n",
" display_name=\"hmdb\",\n",
" prediction_type=\"classification\",\n",
")\n",
"\n",
@@ -803,6 +603,9 @@
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"if os.getenv(\"IS_TESTING\"):\n",
" sys.exit(0)"
]
@@ -817,7 +620,7 @@
"source": [
"model = training_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",
")\n",
@@ -848,7 +651,7 @@
"outputs": [],
"source": [
"# Get Vertex AI 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",
@@ -971,7 +774,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",
@@ -1181,7 +984,7 @@
"outputs": [],
"source": [
"LABEL_COLUMN = \"outputLabel\"\n",
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/pen{UUID}\"\n",
"PIPELINE_ROOT = \"{BUCKET_URI}/pipeline_root/pen\"\n",
"SAMPLE_SIZE = 2\n",
"CLASS_LABELS = [\"brush_hair\", \"cartwheel\"]\n",
"parameters = {\n",
@@ -1227,7 +1030,7 @@
"source": [
"import google.cloud.aiplatform as aip\n",
"\n",
"DISPLAY_NAME = \"video_classification\" + UUID\n",
"DISPLAY_NAME = \"video_classification\"\n",
"job = aip.PipelineJob(\n",
" display_name=DISPLAY_NAME,\n",
" template_path=\"video_classification_pipeline.json\",\n",
@@ -128,40 +128,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. \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 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 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 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",
"1. To install Jupyter, run `pip3 install jupyter` on the 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": {
@@ -181,20 +147,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",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
" \n",
"! pip3 install --upgrade --quiet {USER_FLAG} google-cloud-aiplatform \\\n",
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" tensorflow \\\n",
" google-cloud-pipeline-components==1.0.26 \\\n",
" kfp \\\n",
@@ -208,27 +161,22 @@
"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": "zV1CWUyBw0aF"
"id": "D-ZBOjErv5mM"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\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)"
]
},
{
@@ -239,70 +187,26 @@
"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 [Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com), [Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=compute.googleapis.com) and [DataFlow API](https://console.cloud.google.com/flows/enableapi?apiid=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."
"**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": "markdown",
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_project_id"
},
"outputs": [],
"source": [
"#### Set your project ID\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\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": "autoset_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "M62-VQzzbsd3"
},
"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 project --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"
"# Set the project id\n",
"! gcloud config set project {PROJECT_ID}"
]
},
{
@@ -313,61 +217,19 @@
"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": "WAWQWrHsw0aH"
"id": "2dw8q9fdQEH5"
},
"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": "vt9hPftRw0aH"
},
"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\""
]
},
{
@@ -378,64 +240,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": "svZvVnvdw0aI"
"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."
]
},
{
@@ -446,11 +298,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."
]
},
{
@@ -461,27 +309,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."
@@ -491,33 +325,13 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CSJEpo1aw0aJ"
"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": "RhEu0QxRw0aJ"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -1063,7 +877,7 @@
"outputs": [],
"source": [
"train_job = aip.CustomTrainingJob(\n",
" display_name=\"boston_\" + UUID,\n",
" display_name=\"boston\",\n",
" script_path=\"custom/trainer/task.py\",\n",
" container_uri=TRAIN_IMAGE,\n",
" requirements=[\"gcsfs==0.7.1\", \"tensorflow-datasets==4.4\"],\n",
@@ -1098,7 +912,7 @@
},
"outputs": [],
"source": [
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, UUID)\n",
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, \"model\")\n",
"\n",
"EPOCHS = 20\n",
"STEPS = 100\n",
@@ -1450,7 +1264,7 @@
"outputs": [],
"source": [
"model = aip.Model.upload(\n",
" display_name=\"boston_\" + UUID + \"new_model\",\n",
" display_name=\"boston_new_model\",\n",
" artifact_uri=MODEL_DIR,\n",
" serving_container_image_uri=DEPLOY_IMAGE,\n",
" instance_schema_uri=f\"{BUCKET_URI}/instance_schema.yaml\",\n",
@@ -1584,7 +1398,7 @@
" or PIPELINE_DISPLAY_NAME is None\n",
"):\n",
" PIPELINE_DISPLAY_NAME = (\n",
" f\"vertex-evaluation-custom-tabular-regression-feature-attribution-{UUID}\"\n",
" \"vertex-evaluation-custom-tabular-regression-feature-attribution\"\n",
" )"
]
},
@@ -1789,7 +1603,7 @@
},
"outputs": [],
"source": [
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/boston_{UUID}\"\n",
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/boston\"\n",
"batch_predict_sample_size = 5\n",
"parameters = {\n",
" \"project\": PROJECT_ID,\n",
@@ -2053,6 +1867,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Delete model resource\n",
"model.delete()\n",
"\n",

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