Compare commits

...
Author SHA1 Message Date
Andrew Ferlitsch ade4556a99 debug: force use of newest cloud-build 2022-12-17 19:58:02 +00:00
Axel PerezandGitHub 1448645ba4 Updating PyTorch Torchrun notebook in community folder (#1366)
* updating custom container with PyTorch v1.13

* moved etcd install to custom container build
2022-12-17 09:46:40 -08:00
Andrew FerlitschandGitHub 3d19ffb131 fix: timeout issue for notebook test (#1365) 2022-12-16 18:27:09 -08:00
Xiang XuandGitHub b6018551a5 add fsdp training (#1317) 2022-12-16 09:53:26 -08:00
Phuong NguyenandGitHub 65fbf0ee0b Use sample dataset from regional bucket (#1355)
* Use sample dataset from regional bucket

* retrigger checks
2022-12-16 09:48:05 -08:00
Andrew FerlitschandGitHub 427bd3d5ea upgrade: replace CURL with GAPIC (#1357) 2022-12-15 11:47:33 -08:00
Andrew FerlitschandGitHub 5f41599745 Autoindex 1 (#1354)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance

* fix: autogen README index for workbench folder

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective
2022-12-14 14:11:12 -08:00
Andrew FerlitschandGitHub 67fbd84832 Autoindex 1 (#1353)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance

* fix: autogen README index for workbench folder

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective
2022-12-14 12:53:09 -08:00
Andrew FerlitschandGitHub 9b427b6a1f Autoindex 1 (#1352)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance

* fix: autogen README index for workbench folder

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective
2022-12-14 12:45:39 -08:00
Andrew FerlitschandGitHub 37d5d5b992 Autoindex 1 (#1351)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance

* fix: autogen README index for workbench folder

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective
2022-12-14 11:26:16 -08:00
Andrew FerlitschandGitHub 287911b681 Autoindex 1 (#1350)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance

* fix: autogen README index for workbench folder

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective
2022-12-14 11:20:14 -08:00
Andrew FerlitschandGitHub c83387181a Autoindex 1 (#1349)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance

* fix: autogen README index for workbench folder

* fix: branding and objective

* fix: branding and objective

* fix: branding and objective
2022-12-14 11:13:18 -08:00
Andrew FerlitschandGitHub 236d45b87e Autoindex 1 (#1348)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance

* fix: autogen README index for workbench folder

* fix: branding and objective
2022-12-14 10:50:01 -08:00
Soheila ZangenehandGitHub 4eb7b3ce39 Feature Store ingestion streaming notebook (#1321)
* Add featurestore ingestion streaming nb

* Add notebook to CODEOWNERS

* Run linter

* Add pyarrow installation

* Run linter

* Resolve PR comments

* Run linter
2022-12-14 10:47:46 -08:00
Rajesh ThallamandGitHub d74554f641 Torchrun notebook (#1344)
* PyTorch efficient training - refcator code

* Revert "PyTorch efficient training - refcator code"

This reverts commit 90b563a7697b15b4154ac76236b894253dd58f3c.

* Refactor torchrun notebook

* Refactor torchrun notebook

* Refactor torchrun notebook

* Torchrun notebook - Linting fixes

* Torchrun notebook - Linting fixes
2022-12-13 10:23:58 -08:00
Andrew FerlitschandGitHub 3e70c63899 Autoindex 1 (#1343)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance

* fix: autogen README index for workbench folder
2022-12-13 09:44:58 -08:00
Andrew FerlitschandGitHub 4c79ab91e2 Autoindex 1 (#1342)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder

* fix: template conformance
2022-12-13 09:24:15 -08:00
Andrew FerlitschandGitHub dd8a7ad325 Autoindex 1 (#1341)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes

* fix: bad links in workbench folder
2022-12-13 09:12:30 -08:00
Andrew FerlitschandGitHub a3bb273e78 Autoindex 1 (#1340)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes

* fix: update official indexes
2022-12-12 19:04:27 -08:00
Andrew FerlitschandGitHub 1ff0872546 Autoindex 1 (#1339)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official

* fix: update indexes
2022-12-12 18:56:26 -08:00
Andrew FerlitschandGitHub 91144b8476 Autoindex 1 (#1338)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices

* fix: update autogen index in official
2022-12-12 18:40:26 -08:00
Andrew FerlitschandGitHub 9822bd64a1 Autoindex 1 (#1337)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices

* fix: update official indices
2022-12-12 16:47:05 -08:00
Andrew FerlitschandGitHub f14ff50d2b Autoindex 1 (#1336)
* feat: autogen index

* feat: autogen index

* feat: autogen index

* feat: update indices
2022-12-12 16:27:49 -08:00
Andrew FerlitschandGitHub fdc30dab67 Autoindex 1 (#1335)
* feat: autogen index

* feat: autogen index

* feat: autogen index
2022-12-12 16:12:05 -08:00
Andrew FerlitschandGitHub 93229f62c9 fix: next round of restructuring. (#1163)
* fix: working on abstract class

* fix: working on abstract class

* fix: restructuring

* fix: changes per TW needs

* fix: request changes

* fix: before you begin

* feat: task: making cell navigation independent of rules

* fix: review comments

* fix: review comments

* fix: review comments

* fix: review comments

* feat: writeback fixed notebook

* fix: target=_blank detection

* fix: autofixing bad link
2022-12-12 14:55:10 -08:00
Peter PingandGitHub b37f474255 Update stream_update_for_matching_engine.ipynb (#1324)
* Update stream_update_for_matching_engine.ipynb

change "allow_list" to "allow" for index creation as allow_list is not supported but allow is supported for index creation.

* Update stream_update_for_matching_engine.ipynb

Updated to resolve the comments.

* Updated Google Cloud Notebooks to Workbench AI Notebooks
2022-12-12 09:29:38 -08:00
Ivan NardiniandGitHub 344b0dd6d7 update vertex_ai_model_registry_bqml_custom_model_versioning.ipynb (#1331)
* fix dataproc version issue

* linter test passed
2022-12-12 09:12:35 -08:00
Andrew FerlitschandGitHub 48b7cdb21d Ci admin howto 2 (#1333)
* feat: howto admin

* fix: review comments
2022-12-12 08:40:45 -08:00
Andrew FerlitschandGitHub cefdc32d5f feat: howto admin (#1330) 2022-12-09 14:52:36 -08:00
Andrew FerlitschandGitHub 7558411fbc feat: migrate batch model monitoring notebook to official (#1322)
* feat: migrate notebook to official

* fix: set links to official

* fix package issue when testing

* Update batch_prediction_model_monitoring.ipynb

* Update batch_prediction_model_monitoring.ipynb

* Update batch_prediction_model_monitoring.ipynb

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: install/import issues

* fix: dependencies

* fix: missing import
2022-12-09 14:38:33 -08:00
Andrew FerlitschandGitHub 1c0487c459 fix: rm line about load mean/stddev (#1327) 2022-12-08 15:04:56 -08:00
Edgar BermudezandGitHub 6b7bb867ab Fixed links to notebooks (#1302)
* Update README.md

* Fixed links to notebooks

* Fixed links to notebooks
2022-12-07 16:58:42 -08:00
Alexey VolkovandGitHub 8c7363c2b0 Updated the tabular training pipelines to load the components from the vertex-ai-samples repo (#1326) 2022-12-07 16:54:34 -08:00
Brian KangandGitHub 2ea22da2bf Briankang pytorch torchrun (#1323)
* Adding PyTorch Torchrun example

* Revert 'Adding PyTorch Torchrun example'

This reverts commit 239b9fe3b7

* Adding PyTorch torchrun ImageNet training example

* Updated CODEOWNERS for PyTorch torchrun example

* Ran Linter

* Updated based on review feedback
2022-12-07 09:52:49 -08:00
Soheila ZangenehandGitHub 1d96584421 Notebook to demonstrate feature filtering in BatchPredictionJob (#1309)
* Add feature filter notebook

* Clean code

* Run linter

* Add the notebook to CODEOWNERS

* Remove user flag

* Run linter

* Fix bucket URI

* Run linter

* Simplify the notebook
2022-12-07 09:49:29 -08:00
Ivan NardiniandGitHub 06d57da90c inardini -- anomaly detection with BigQuery ML and Vertex AI (#1319)
* adding anomalydetection pipeline

* reviewed notebook

* add code owner

* remove to do

* linter test

* reviewed based on feeback from andy

* linter test passed

* fix links

* linter test passed
2022-12-07 09:42:34 -08:00
Alexey VolkovandGitHub 355105218d Added pipeline components used in the "Train_tabular_models_with_many_frameworks_and_import_to_Vertex_AI_using_Pipelines" samples (#1294)
* Added pipeline components used in the "Train_tabular_models_with_many_frameworks_and_import_to_Vertex_AI_using_Pipelines" samples.

* Removed Pandas type conversion

* Removed Pandas type conversion
2022-12-06 16:42:06 -08:00
Andrew FerlitschandGitHub 3090a312c0 fix: autofix bad links (#1318)
* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links

* fix: autofix bad links
2022-12-06 14:17:41 -08:00
8c265ee1ef Added matching engine resource managers (#1314)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-12-01 13:41:23 -08:00
fdbfecda04 Updates notebooks/official/model_evaluation/custom_tabular_regression_model_evaluation.ipynb (#1264)
* remove key_columns variable

* ran linter

* remove key_columns in text

* notebooks/official/model_evaluation/custom_tabular_regression_model_evaluation.ipynb

* modified text

* ran linter

* andrew comments resolved

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-12-01 09:30:42 -08:00
7050730b6a sdk_automl_tabular_regression_online_bq (#1246)
* bioler plate changes

* linter test

* made review changes

* linter test

* bioler plate changes

* linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-12-01 05:04:26 -08:00
Ivan CheungandGitHub 4ec962d277 custom-tabular-bq-managed-dataset.ipynb: Addressed comments regarding evaluation, normalization and dataset creation (#1313)
* Address comments

* Added back BQ dataset creation
2022-11-30 16:09:39 -05:00
Ivan CheungandGitHub 3185ca7d48 Hierarchical forecasting notebook (#664)
This is a hierarchical forecasting notebook demonstrating the use of the new hierarchical forecasting parameters for AutoML Forecasting.

If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [x] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [x] Follow the style and grammar rules outlined in the above notebook template.
- [ ] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [x] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [x] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [x] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.
2022-11-30 20:02:13 +00:00
sudarshan-SpringMLandGitHub 32ac97982c Updates sdk_automl_video_action_recognition_batch.ipynb (#1233)
File came in regression log. Unable to download executed notebook. When ran in local, file executed successfully.
**Changes made**:

Update notebook according to template

- [X] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [X] Follow the style and grammar rules outlined in the above notebook template.
- [X] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [X] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [X] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [X] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.

<br>
2022-11-30 00:04:13 +00:00
uday kumarandGitHub 1aa94377f5 automl-text-classification (#1244)
**REQUIRED:** Add a summary of your PR here, typically including why the change is needed and what was changed. Include any design alternatives for discussion purposes.

<br>
Changed according to boilerplate requirement.
<br><br><br>

**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [X] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [X] Follow the style and grammar rules outlined in the above notebook template.
- [X] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [X] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [X] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [X] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.
2022-11-29 06:20:13 +00:00
sarahcduganandGitHub 7271fde2d7 Adding a link to documentation (#1305)
Currently the notebook references docs but doesn't link to them.

**REQUIRED:** Add a summary of your PR here, typically including why the change is needed and what was changed. Include any design alternatives for discussion purposes.

<br>
--- YOUR PR SUMMARY GOES HERE ---
<br><br><br>

**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [ ] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [ ] Follow the style and grammar rules outlined in the above notebook template.
- [ ] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [ ] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [ ] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [ ] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.

<br>

2. If you are opening a PR for `Community Notebooks` under the [notebooks/community](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community) folder:
- [ ] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/CODEOWNERS) file under the `Community Notebooks` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).

<br>

3. If you are opening a PR for `Community Content` under the [community-content](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/community-content) folder:
- [ ] Make sure your main `Content Directory Name` is descriptive, informative, and includes some of the key products and attributes of your content, so that it is differentiable from other content
- [ ] The main content directory has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/community-content/CODEOWNERS) file under the `Community Content` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
2022-11-28 23:24:13 +00:00
Ivan CheungandGitHub 71431d5520 pipelines_intro_kfp.ipynb: Reduced boilerplate (#1307)
Reduced boilerplate in pipelines_intro_kfp.ipynb
2022-11-28 19:44:13 +00:00
Andrew FerlitschandGitHub 0f58771ecd fix: bad link (#1303) 2022-11-27 10:16:58 -05:00
05c5b68db1 pytorch efficient training (#1257)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-26 16:48:11 -08:00
ee2744a7de Updates file google_cloud_pipeline_components_automl_images.ipynb (#1238)
* modified notebook

* ran linter

* ivan comments addressed

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-26 16:38:29 -08:00
a32db129ea Update notebook to use v1 components (#1260)
Co-authored-by: Win Woo <wwoo@google.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-25 22:21:18 -08:00
c9aff9a5d9 training-multi-class-classification-model-for-ads-targeting-usecase (#1161)
* Made changes in accordance with notebook template

* Ran Linter test

* Changed protobuf version

* Ran linter test

* made sklearn to scikit learn

* ran linter

* andrew comments addressed

* ran linter

* ivan comments addressed

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: sudarshan-SpringML <82567512+sudarshan-SpringML@users.noreply.github.com>
Co-authored-by: sudarshan-SpringML <sudarshan.c@springml.com>
2022-11-25 21:35:40 -08:00
bhupana @ springmlGitHubIvan Cheunggcf-merge-on-green[bot] <60162190+gcf-merge-on-green[bot]@users.noreply.github.com>Andrew Ferlitsch
7324b084ee Made minor changes to Google cloud pipeline components automl tabular notebook (#1253)
* made some minor changes

* Ran linter test

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: gcf-merge-on-green[bot] <60162190+gcf-merge-on-green[bot]@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-25 21:08:27 -08:00
095b0bd628 sdk_matching_engine_for_indexing.ipynb: Adds filtering example to matching engine notebook. (#1249)
* Added matching engine filtering notebook

* Added filter

* Fixed typos in other notebooks and linted

* Fixed lint issues

* Added PROJECT_NUMBER retrieval

* Removed unneeded RANDOM_ID

* Linted

* Reverted changes

* Fixed review comments

Co-authored-by: gericdong <itseric@google.com>
2022-11-25 18:04:08 -08:00
Ivan CheungandGitHub 7a1b262154 Regression notebook: Remove unneeded cells (#1297)
Removed unneeded cells.
2022-11-23 21:38:13 +00:00
gericdongandGitHub ad1a827824 feat: Reorganize all TensorBoard notebooks together under directory 'tensorboard" (#1296)
**REQUIRED:** Add a summary of your PR here, typically including why the change is needed and what was changed. Include any design alternatives for discussion purposes.

<br>
This is the first step of two to move the TensorBoard profiler to tensorboard directory.
<br><br><br>

**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [ ] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [ ] Follow the style and grammar rules outlined in the above notebook template.
- [ ] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [ ] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [ ] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [ ] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.

<br>

2. If you are opening a PR for `Community Notebooks` under the [notebooks/community](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community) folder:
- [ ] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/CODEOWNERS) file under the `Community Notebooks` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).

<br>

3. If you are opening a PR for `Community Content` under the [community-content](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/community-content) folder:
- [ ] Make sure your main `Content Directory Name` is descriptive, informative, and includes some of the key products and attributes of your content, so that it is differentiable from other content
- [ ] The main content directory has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/community-content/CODEOWNERS) file under the `Community Content` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
2022-11-23 16:48:15 +00:00
Ivan CheungandGitHub 1ff7fc70ed custom-tabular-bq-managed-dataset.ipynb: Remove preprocessing (#1278)
- [x] Removed pre-processing (normalization)

This simplifies the code but reduces accuracy.
2022-11-23 16:16:42 +00:00
Ivan CheungandGitHub b45e17efc0 sdk_automl_tabular_regression_batch_bq.ipynb: Fixed unneeded concatenation (#1265)
- [x] Fixed unneeded concatenation
- [x] Fixed incorrect service account info.
2022-11-23 03:02:15 +00:00
gericdongandGitHub 98ad1655a7 fix: updated TensorBoard profiler notebook 2 (#1284)
* fix: updated TensorBoard profiler notebook 2

* Address linter check errors

* Addressed review comments 2

* Added prints for debug

* Added --quiet for another gcloud command
2022-11-22 19:24:36 -05:00
uday kumarGitHubgcf-merge-on-green[bot] <60162190+gcf-merge-on-green[bot]@users.noreply.github.com>
19d56c0fa0 sdk_automl_image_object_detection_batch (#1240)
* changed according to boiler plate requirements

* ran linter test

* changed according to boilerplate requirements

* linter test

* changed file based on boilerplate requirements

* linter test

* biolerplate requirements

* linter test

* changes based on boilerplate

* linter test

* added os library

* linter test

* textual corrections

* linter test

* biolerplate chnages

* linter test

* bioler plate changes

* linter test

Co-authored-by: gcf-merge-on-green[bot] <60162190+gcf-merge-on-green[bot]@users.noreply.github.com>
2022-11-22 14:44:15 -05:00
Soheila ZangenehandGitHub a3ee3687da Fix: Hardcode gcpc version in model eval automl regression notebook (#1267)
**REQUIRED:** Add a summary of your PR here, typically including why the change is needed and what was changed. Include any design alternatives for discussion purposes.

Hardcoded gcpc version because it fails in newer versions. And this is a request from model eval swe team to hardcode the version.

**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [x] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [x] Follow the style and grammar rules outlined in the above notebook template.
- [x] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [x] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [x] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [x] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [x] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.
2022-11-22 01:44:13 +00:00
Soheila ZangenehandGitHub ff1b9ad8ef Fix: Hardcode gcpc version in model eval automl classification notebook (#1268)
* Hardcode gcpc and use better variable name

* Run linter
2022-11-21 15:33:51 -05:00
sudarshan-SpringMLandGitHub 64b4f5103c Updates notebooks/official/pipelines/google_cloud_pipeline_components_model_train_upload_deploy.ipynb (#1250)
**Error from regression test**:RuntimeError: Job failed with:
code: 9
message: "The DAG failed because some tasks failed. The failed tasks are: [model-deploy].; Job (project_id = python-docs-samples-tests, job_id = 2073372166241386496) is failed due to the above error.; Failed to handle the job: {project_number = 1012616486416, job_id = 2073372166241386496}"

Changes made:
Just ran notebook in local. It ran fine. Updated notebook according to template


- [X] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [X] Follow the style and grammar rules outlined in the above notebook template.
- [X] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [X] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [X] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [X] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.

<br>
2022-11-18 20:16:14 +00:00
bhupana @ springmlandGitHub a2e8f933dc Sdk custom image classification batch (#1252)
boilerplate for sdk-custom-image-classification-batch notebook

**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [ ] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [ ] Follow the style and grammar rules outlined in the above notebook template.
- [x] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [x] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [x] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [x] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.
2022-11-18 18:28:14 +00:00
sudarshan-SpringMLandGitHub 5cb368585c Updates notebooks/official/custom/sdk-custom-image-classification-online.ipynb (#1247)
Reduce boilerplate for sdk-custom-image-classification-online.ipynb notebook

- [X] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [X] Follow the style and grammar rules outlined in the above notebook template.
- [X] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [X] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [X] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [X] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.

<br>
2022-11-18 17:24:15 +00:00
uday kumarandGitHub db96de8266 sdk-metric-parameter-tracking-for-custom-jobs (#1242)
**REQUIRED:** Add a summary of your PR here, typically including why the change is needed and what was changed. Include any design alternatives for discussion purposes.

<br>

1. Boilerplate changes.
2. Added code for deleting experiment otherwise its throwing experiment name already exist.
<br><br><br>

**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [X] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [X] Follow the style and grammar rules outlined in the above notebook template.
- [X] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [X] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [X] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [X] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.

<br>
2022-11-18 17:04:13 +00:00
uday kumarandGitHub 18440f5c0c sdk-metric-parameter-tracking-for-locally-trained-models (#1248)
**REQUIRED:** Add a summary of your PR here, typically including why the change is needed and what was changed. Include any design alternatives for discussion purposes.

<br>
Boilerplate changes.
<br><br><br>

**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [X] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [X] Follow the style and grammar rules outlined in the above notebook template.
- [X] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [X] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [X] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [X] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.

<br>
2022-11-18 16:34:15 +00:00
Mend RenovateandGitHub 95d44d0cf5 chore(deps): update dependency nbqa to v1.5.3 (#1259) 2022-11-18 10:42:11 -05:00
Mend RenovateGitHubIvan Cheunggcf-merge-on-green[bot] <60162190+gcf-merge-on-green[bot]@users.noreply.github.com>
fc2e91d050 chore(deps): update dependency nbqa to v1.5.2 (#967)
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: gcf-merge-on-green[bot] <60162190+gcf-merge-on-green[bot]@users.noreply.github.com>
2022-11-17 15:47:43 -05:00
Mend RenovateandGitHub b8872c1e03 chore(deps): update dependency black to v22.10.0 (#918) 2022-11-17 15:45:52 -05:00
b21ec83ba3 chore(deps): update dependency pyupgrade to v2.38.4 (#1042)
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-11-17 15:41:39 -05:00
Jonathan SimonandGitHub d42cc4fbc9 Update notebooks/official/matching_engine/README.md (#1258)
* Update notebooks/official/matching_engine/README.md

* Update region tag formatting

* Update README.md format for single notebook

* Remove horizontal-rules for single notebook
2022-11-17 12:04:17 -08:00
Kacper KulczakandGitHub 28ceb8085e bugfix: custom region for training (#722)
If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [x] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [x] Follow the style and grammar rules outlined in the above notebook template.
- [x] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [x] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [x] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [x] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.


If you are opening a PR for `Community Notebooks` under the [notebooks/community](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community) folder:
- [ ] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/CODEOWNERS) file under the `Community Notebooks` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).

If you are opening a PR for `Community Content` under the [community-content](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/community-content) folder:
- [ ] Make sure your main `Content Directory Name` is descriptive, informative, and includes some of the key products and attributes of your content, so that it is differentiable from other content
- [ ] The main content directory has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/community-content/CODEOWNERS) file under the `Community Content` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
2022-11-17 19:08:14 +00:00
Juan AcevedoandGitHub a460dcbdd8 f/find_ideal_machine_type_endpoints (#1256)
* initial commit

* add CODEOWNERS
2022-11-16 14:58:01 -08:00
Krishna Chaitanya MovvaandGitHub a76ffe0103 moves the owners line from community file to the official file for SDK_FBProphet_forecasting_online.ipynb notebook (#1254) 2022-11-16 16:06:01 -05:00
168c5c2f15 Add custom tabular classification model evaluation notebook (#1219)
* adds the custom tabular classification evaluation notebook

* removes json import

* ran linter test

* fixes the model serving code and adds image

* ran linter test

* adds notebook to the codeowners file

* addresses the review comments: updates text, adds headings

* ran linter test

* boiler-plate reduction, addresses the review comments, adds a constant for table id

* ran linter test

* updates the installation step

* ran linter test

* removes the --user flag while installation

* ran linter test

Co-authored-by: Soheila Zangeneh <49654056+soheilazangeneh@users.noreply.github.com>
2022-11-16 10:12:14 -05:00
Krishna Chaitanya MovvaandGitHub d45bbb36df Adding the official version for SDK-FB-prophet-online-forecasting-notebook (#317)
Checklist for moving the notebook to the main repo: 
- [x] Use the [notebook template](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [x] Follow the style and grammar rules outlined in the above notebook template.
- [x] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
- [x] Passes all the required automated checks. You can locally test for formatting and linting with these [instructions](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/docs/contributing.md#code-quality-checks).
- [ ] You have consulted with a tech writer to see if tech writer review is necessary. If so, the notebook has been reviewed by a tech writer, and they have approved it.
- [x] This notebook has been added to the [CODEOWNERS](https://togithub.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/docs/CODEOWNERS) file under `# Official Notebooks` section, pointing to the author or the author's team.
- [x] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.
2022-11-16 00:26:14 +00:00
a83ee780f1 Update file automl_tabular_regression_model_evaluation (#1179)
* text correction made

* ran linter

* modified file

* ran linter

* updated file

* ran linter

* addressed comments

* ran linte

* changing component and parameter names as per new gcpc 1.0.26

* ran linter

* updated notebook as per new package changes

* modified notebook

* ran linter

Co-authored-by: Soheila Zangeneh <49654056+soheilazangeneh@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-15 10:01:36 -05:00
6011ca5127 Tabnet on Vertex pipelines (#1171)
* Cloud Storage bucket permission issues resolved

* Cloud Storage bucket permission issues resolved

* ran linter test

* DAG issues

* linter test

* textual corrections

* ran linter test

* added service account for pipeline job

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-12 07:30:45 -08:00
haomengchaoandGitHub d53ebed734 fix vertex ai pipelines name issue and rename the colab (#1239)
* fix vertex ai pipelines name issue and rename the colab

* lint
2022-11-11 15:01:43 -05:00
38f29064a0 Updated file notebooks/official/automl/sdk_automl_tabular_regression_batch_bq.ipynb (#1217)
* notebooks/official/automl/sdk_automl_tabular_regression_batch_bq.ipynb

* updated text

* ran linter

* removed --user

* ran linter

* modified notebook, updated installs section

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-11-11 08:15:04 -08:00
Ivan CheungandGitHub 6ccad69a18 Reduce boilerplate for custom tabular bq notebook (#1207)
* Reduced boilerplate

Ran linter and fixed install

Added pyarrow

Fixed pip install

Reverted unneeded changes

Fixed pip install

Linted code and added missing preprocessor call

Fixed preprocessor

Default to us-central1

* Ran linter

* Simplified service account section
2022-11-10 17:47:13 -05:00
Andrew FerlitschandGitHub 0ca86220f8 feat: log model size (#1234) 2022-11-10 13:44:08 -05:00
Andrew FerlitschandGitHub 25e004b60e feat: DIY autlogging for XGBoost (#1229)
* feat: DIY autlogging for XGBoost

* feat: add more heap injection

* feat: lint issues

* fix: review comments
2022-11-10 12:25:27 -05:00
871288ac1a feat: add TFModel example (#1232)
Co-authored-by: gericdong <itseric@google.com>
2022-11-10 12:01:26 -05:00
753bb0e120 Update file automl_video_classification_model_evaluation (#1201)
* added model evaluation component

* linter test cases

* linter test cases

* model_name param issues resolved

* linter test case

* import issues resloved

* linter test cases

* made review changes

* made review changes

* ran linter test

* made review changes

* made review changes

* made review changes

* linter test

* ran linter test

* made review changes

* ran linter test

* made review changes

* ran linter test

* linter test

* review changes

* ran linter test

* added The links for Colab, Github and Workbench

* added The links for Colab, Github and Workbench

* ran linter test

* added The links for Colab, Github and Workbench

* ran linter test

* added The links for Colab, Github and Workbench

* ran linter test

* notebook title changed

* ran linter test

* text changes and made review changes

* ran linter test

* made review changes

* linter test

* made review changes

* linter test

* content changes

* ran linter test

* textual corrections and links

* ran linter test

* changed function names bases on latest gcpc version

* ran linter test

* changed function names bases on latest gcpc version

* linter test

* ran linter test

* updated arguments in ModelEvaluationClassificationOp based on new version

* ran linter test

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Soheila Zangeneh <49654056+soheilazangeneh@users.noreply.github.com>
2022-11-09 23:16:46 -08:00
3893b76486 Modified notebook notebooks/official/workbench/demand_forecasting/forecasting-retail-demand.ipynb (#1200)
* modified notebook

* ran linter

* removed unused libraries

* ran linter

* comments resolved

* ran linter

* updated library

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-09 17:55:40 -08:00
ee805e7846 Creates a notebook for batch-prediction pipeline with BQ I/O on a custom-tabular model (#992)
* adds the custom-model-bq-io-batch-prediction-pipeline notebook to the official folder

* removes the unused libraries and variables

* ran linter test

* adds a raise exception statement to prevent auto-test check as this notebook is just to serve as a template

* resolves review comments: fixes names, removes trailing comma, fixes link format

* removes the raise excpetion step

* ran linter test

* cleans up code, explains sections and renames the notebook

* removes unused variable batch_predict_task

* removes unnecessary imports

* ran linter test

* updates the dependencies

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-09 16:16:48 -08:00
Ivan CheungandGitHub eb605b7943 Linted file (#1231) 2022-11-09 15:30:41 -05:00
Andrew FerlitschandGitHub 6f0cab7bbb fix: bad links in auto logging notebook (#1225)
* feat: DIY autologging

* feat: DIY autologging

* fix: bad links
2022-11-09 09:41:16 -05:00
eb9b6552d8 feat: DIY autologging (#1224)
* feat: DIY autologging

* feat: DIY autologging

Co-authored-by: gericdong <itseric@google.com>
2022-11-08 17:04:19 -05:00
Ivan CheungandGitHub 35d71b410e Boilerplate reduction: Notebook template (#1204)
* Reduced notebook boilerplate

* Fixed lint issues

* Added unique suffix note

* Added unique string processor and moved tests to own folder

* Fixed broken link

* Added message about updating links

* Fixed typo

* Added missing import

* Added back useful instructions

* Addressed comments

* Removed matching engine

* Fixed comments
2022-11-08 14:10:50 -05:00
b7d98d6f9a Vertex SDK AutoML Text Sentiment Analysis (#1157)
* bucket issues

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-07 20:12:51 -08:00
a421dc1354 Modified file sdk_automl_video_object_tracking_batch.ipynb (#1151)
* file modified

* ran linter

* model evaluation metrics are printed

* ran linter

* notebook modified

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-07 12:50:17 -08:00
a4a72c8b22 Modified file notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb (#1165)
* modified file

* ran linter

* unused library removed

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-07 09:18:25 -08:00
5c403dde3d Minor updates for automl-tabular-classification-model evaluation notebook (#1184)
* upgrades gcpc to latest, adds minor textual corrections

* ran linter test

* minor textual corrections

* ran linter test

* fixes sentence cases, unnecessary capitalizations, article corrections and sentence corrections

* ran linter test

* renames the ground_truth_column argument in classificationeval component to target_field_name as per version 1.0.26 and updates the reference link

* ran linter test

* upgrades gcpc to latest, adds minor textual corrections

* ran linter test

* minor textual corrections

* ran linter test

* fixes sentence cases, unnecessary capitalizations, article corrections and sentence corrections

* ran linter test

* renames the ground_truth_column argument in classificationeval component to target_field_name as per version 1.0.26 and updates the reference link

* ran linter test

* fixes the prediction_score_column unsupported error, adds class_labels field, adds the targetfieldremover component, minor structural/textual updates

* ran linter test & updates the image

* removes unnecessary newline

* ran linter test

Co-authored-by: Soheila Zangeneh <49654056+soheilazangeneh@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-07 08:15:33 -08:00
a85753e1b7 Adds Pytorch text sentiment classification notebook to official folder: (#1166)
* Custom pytorch text sentiment classification

* Ran linter test

* Added creating predictor directory

* ran linter test

* Creating python package files from the notebook

* Ran linter test

* cleans up the pytorch-text-classification notebook, renames the directory and removes unnecessary files

* ran linter test

* rectifies the python test version

* ran linter test

* removes the python version line

* ran linter test

* restores the README.md file for official folder

* minor textual edits

* ran linter test

* updates notebook structure, removes unnecessary print statements, moves import statements to one cell, textual updates

* ran linter test

* corrects the Colab link

* ran linter test

* addresses review comments: grammatical/textual corrections

* ran linter test

Co-authored-by: krishr2d2 <krishna.movva@springml.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-04 22:09:00 -07:00
2f54cf23cc Made some Minor changes to Uj7 vertex sdk auto ml text entity extraction notebook (#1057)
* Made Minor changes

* Ran Linter test

* Made minor changes

* ran linter test

* Madesome Minor changes

* Ran linter test

* Made some minor changes

* Ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-04 19:51:05 -07:00
ffc7427265 Bqml online prediction v1 (#1160)
* Made changes in accordance with the notebook_template

* Ran Linter Test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-04 14:17:36 -07:00
0e738b506f Made minor changes to Tensorboard custom training with custom container (#1051)
* UID changes added

* Ran lintertest

* removed pip install

* modified custom code

* ran linter test

* Made Minor changes

* Ran linter test

* Ran linter test

Co-authored-by: sudarshan-SpringML <sudarshan.c@springml.com>
Co-authored-by: sudarshan-SpringML <82567512+sudarshan-SpringML@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-04 12:24:06 -07:00
fdeaaa37fb Update file sdk_automl_text_sentiment_analysis_online (#1208)
* added uuid and textual correction

* ran linter test

* made one cell for pip installations

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-04 08:51:36 -07:00
fed7df10ac Use correct display name for Vertex AI Matching Engine brute force index (#1189)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-03 19:11:41 -07:00
725b2fdd32 Updated file custom_tabular_regression_model_evaluation (#1198)
* made text corrections

* ran linter

* modified notebook

* modified notebook

* ran linter

* modified installation step

* ran linter

* updated component name and parameters

* ran linter

* ran linter

Co-authored-by: Soheila Zangeneh <49654056+soheilazangeneh@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-03 13:57:47 -07:00
a70f93fe0a Resolves name collisions in featurestore-pandas notebook + elaborates descriptions (#1199)
* updates featurestore name with uuid to avoid name collisions, elaboration, textual corrections

* ran linter test

* addresses review comments: adds headings + textual corrections

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-03 12:43:25 -07:00
d03697cf73 Vertex AI Experiments - All-in-one notebook (#1216)
* add notebook. update codeowners

* linter fixes

* linter test passed

* fix issues

* linter passed

* implement andy's comments

* linter passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-11-03 11:56:08 -07:00
haomengchaoandGitHub 191f2a11bc add doc about using tensorboard in vertex pipeline (#1190)
* add doc about using tensorboard in vertex pipeline

* format the doc

* fix format

* set default value to params

* fix format

* fix import

* fix format again

* update colab, github and workbench link

* update according to latest offical notebook template

* update according to comments
2022-11-03 11:38:36 -07:00
1b692bc330 feat: notebook request from UX community meeting (#1215)
Co-authored-by: gericdong <itseric@google.com>
2022-11-03 10:28:00 -07:00
Andrew FerlitschandGitHub edfd7727d3 feat: monitor non-TF model (#1211)
* feat: monitor non-TF model

* fix: review comments
2022-11-03 07:06:03 -07:00
Andrew FerlitschandGitHub 5d32bd8835 fix: error in text cell (#1214) 2022-11-02 19:26:55 -04:00
Nikita NamjoshiandGitHub 8b188a11b2 fix broken links in hptune example (#1210)
* fix broken links

* fix linter
2022-11-02 10:31:38 -05:00
Andrew FerlitschandGitHub 83546a8e7b feat: TF Serving with TF tabular model (#1209)
* feat: TF Serving with TF tabular model

* fix: typo
2022-11-01 15:22:01 -04:00
c9aa6df17b fix: bad links for HPT notebook (#1205)
* Added notebook demonstrating hyperparameter tuning

* fix lint errors

* fix failing test

* ran linter

* ran linter

* resolved editorial comments

* small editorial edits

* fix failing test

* fix linter

* update colab and workbench links

Co-authored-by: nikitamaia <namjoshi.nikita@gmail.com>
2022-11-01 13:23:28 -05:00
b4955b28a2 Train tabular models with many frameworks and import to Vertex AI using Pipelines (#1174)
These pipelines are:

* Working out of the box (run with zero modifications)
* End-to-end (from nothing to a Vertex Model)
* Feature multiple ML frameworks (TensorFlow, PyTorch, XGBoost, Scikit-learn)
* Feature multiple training objectives: tabular classification and tabular regression

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-11-01 11:00:04 -04:00
Andrew FerlitschandGitHub f33d9eb6d1 feat: add example of instance schema (#1203) 2022-10-31 14:21:56 -07:00
Andrew FerlitschandGitHub 1bdbb7921a fix: reduce visibility of proto code (#1202) 2022-10-31 16:00:27 -04:00
7154a722ba Update Experiments notebook for log_classification_metrics (#1182)
* Update build_model_experimentation_lineage_with_prebuild_code.ipynb

* Update build_model_experimentation_lineage_with_prebuild_code.ipynb

* Update build_model_experimentation_lineage_with_prebuild_code.ipynb

* Update build_model_experimentation_lineage_with_prebuild_code.ipynb

* Update build_model_experimentation_lineage_with_prebuild_code.ipynb

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-31 12:27:27 -07:00
halio-gandGitHub 99d4a8c31a Adding Open Source Vizier converstion sample[Updated] (#1187)
* Add a colab to show how to integrate the training job with Dask.

* Reformat the notebook xgboost_data_parallel_training_on_cpu_using_dask

* Add the code owner of the sample training/xgboost_data_parallel_training_on_cpu_using_dask.ipynb

* Changed the project id to [your-project-id].

* Fixed the issue for Non colab.

* Adding the sample of converting the Vertex Vizier SDK with Open source Vizier.

* Add the owner for conversions_vertex_vizier_and_open_source_vizier.ipynb

* Addressed the comments in the xgboost_data_parallel_training_on_cpu_using_dask

* Fixed the format of xgboost_data_parallel_training_on_cpu_using_dask

* Addressed the comments in the training/xgboost_data_parallel_training_on_cpu_using_dask.ipynb

* Add explanation that Docker is not available on Colab.

* Add  before docker command.

* add timeout in the worker to wait for the scheduler.

* Addressed the comments in the pr.

* Addressed the comments in the pr.
2022-10-28 15:26:14 -07:00
f9cedf2850 Added notebook demonstrating hyperparameter tuning (#1168)
* Added notebook demonstrating hyperparameter tuning

* fix lint errors

* fix failing test

* ran linter

* ran linter

* resolved editorial comments

* small editorial edits

* fix failing test

* fix linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-28 09:53:22 -07:00
f4f0112a6a Pipelines xgboost (#1196)
* feat: add notebook

* feat: add notebook

* fix: typos in text

Co-authored-by: gericdong <itseric@google.com>
2022-10-27 20:18:20 -04:00
Kevin NaughtonandGitHub e441568c38 Quick typo update in model_monitoring.ipynb (#1197)
The Monitoring Interval is in hours, not seconds.
2022-10-27 17:10:42 -07:00
Andrew FerlitschandGitHub fee8c969e4 feat: add xgboost pipeline notebook (#1194)
* feat: add notebook

* feat: add notebook
2022-10-27 15:20:10 -04:00
Andrew FerlitschandGitHub bdac091e3f feat: add sklearn pipeline notebook (#1193)
* feat: add notebook

* feat: add notebook

* fix: typo in text for dataset-url
2022-10-27 13:32:09 -04:00
kthytangandGitHub ff9338ed3c chore: remove preview note from CPR notebooks (#1192) 2022-10-26 11:31:42 -07:00
Andrew FerlitschandGitHub 1a538fd249 fix: multi-class vs binary classifier (#1191) 2022-10-26 08:28:35 -07:00
4f09c94b5f fix: textual corrections and Upgrade the gcpc version for automl_video_classification_model_evaluation notebook. (#1169)
* added model evaluation component

* linter test cases

* linter test cases

* model_name param issues resolved

* linter test case

* import issues resloved

* linter test cases

* made review changes

* made review changes

* ran linter test

* made review changes

* made review changes

* made review changes

* linter test

* ran linter test

* made review changes

* ran linter test

* made review changes

* ran linter test

* linter test

* review changes

* ran linter test

* added The links for Colab, Github and Workbench

* added The links for Colab, Github and Workbench

* ran linter test

* added The links for Colab, Github and Workbench

* ran linter test

* added The links for Colab, Github and Workbench

* ran linter test

* notebook title changed

* ran linter test

* text changes and made review changes

* ran linter test

* made review changes

* linter test

* made review changes

* linter test

* content changes

* ran linter test

* textual corrections and links

* ran linter test

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Soheila Zangeneh <49654056+soheilazangeneh@users.noreply.github.com>
2022-10-25 17:32:44 -04:00
bcf3e6b0f5 Updated file custom_tabular_regression_model_evaluation (#1180)
* made text corrections

* ran linter

* modified notebook

* modified notebook

* ran linter

* modified installation step

* ran linter

Co-authored-by: Soheila Zangeneh <49654056+soheilazangeneh@users.noreply.github.com>
2022-10-25 12:42:48 -04:00
Bo zhengandGitHub fbcf783064 feat: change E2E AutoML dataset to use bank marketing data
* Change E2E AutoML dataset to use bank marketing data

* Remove vs code config
2022-10-24 22:15:43 -07:00
halio-gandGitHub 2f5fe80f34 Adding the official version for Dask parallel training on cpu (#1153)
* Add a colab to show how to integrate the training job with Dask.

* Reformat the notebook xgboost_data_parallel_training_on_cpu_using_dask

* Add the code owner of the sample training/xgboost_data_parallel_training_on_cpu_using_dask.ipynb

* Changed the project id to [your-project-id].

* Fixed the issue for Non colab.

* Addressed the comments in the xgboost_data_parallel_training_on_cpu_using_dask

* Fixed the format of xgboost_data_parallel_training_on_cpu_using_dask

* Addressed the comments in the training/xgboost_data_parallel_training_on_cpu_using_dask.ipynb

* Add explanation that Docker is not available on Colab.

* Add  before docker command.

* add timeout in the worker to wait for the scheduler.
2022-10-24 10:37:13 -07:00
a850f3a88a fix: missed bad links (#1183)
* fix: missed bad links

* fix: missed bad links

Co-authored-by: gericdong <itseric@google.com>
2022-10-21 11:09:11 -04:00
Andrew FerlitschandGitHub de91feaca1 Update README.md (#1181)
added missing link
2022-10-21 07:15:38 -07:00
Andrew FerlitschandGitHub a7fd0734dc feat: XGBoost online serving (#1175)
* feat: xgboost online serving

* fix: review comments and added pipeline example

* fix: review comments
2022-10-19 08:49:31 -07:00
Soheila ZangenehandGitHub ce1b167f08 Edit folder and file name for model registry (#1178)
* Update folder and file name

* Update file name

* Update CODEOWNERS

* Update notebook links

* Update README

* Run linter
2022-10-18 14:40:52 -07:00
Soheila ZangenehandGitHub 65ff3cab60 Revert "Update folder and file names (#1176)" (#1177)
This reverts commit c7ef72f1d3.
2022-10-18 16:59:39 -04:00
Soheila ZangenehandGitHub c7ef72f1d3 Update folder and file names (#1176)
* Rename folder

* Rename file

* Update the links

* Update CODOWNERS

* Run linter
2022-10-18 16:42:36 -04:00
Andrew FerlitschandGitHub bd58428857 fix: issue 1122 (#1173) 2022-10-18 15:09:35 -04:00
Andrew FerlitschandGitHub a4a6ed848b fix: working on abstract class (#1156)
* fix: working on abstract class

* fix: working on abstract class
2022-10-13 10:56:17 -04:00
Andrew FerlitschandGitHub b753bc58d3 fix: enum and cell index naming (#1152) 2022-10-12 14:54:57 -04:00
6279e12eea Bug fixes and automation improvements for google_cloud_pipeline_components_dataproc_tabular.ipynb (#1139)
* Bug fixes and improved automation

* Clean up notebook

* Add --quiet flag to gcloud call

* Add Python prediction and subnetwork parameter

Co-authored-by: Win Woo <wwoo@google.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-12 08:19:25 -07:00
Andrew FerlitschandGitHub fc0c34c905 Boilerplate 2 (#1148)
* fix: merge corruption

* fix: still fix post corruption

* tuning: boiler plate script

* tuning: boiler plate

* tuning: boiler plate

* tuning: boiler plate
2022-10-11 14:01:41 -07:00
Andrew FerlitschandGitHub ef388ecf30 Boilerplate 2 (#1147)
* fix: merge corruption

* fix: still fix post corruption

* tuning: boiler plate script

* tuning: boiler plate

* tuning: boiler plate
2022-10-11 13:57:40 -07:00
Andrew FerlitschandGitHub bafb2c6f59 Boilerplate 2 (#1146)
* fix: merge corruption

* fix: still fix post corruption

* tuning: boiler plate script

* tuning: boiler plate
2022-10-11 13:43:27 -07:00
Andrew FerlitschandGitHub f2d431c182 tuning: boiler plate (#1145)
* fix: merge corruption

* fix: still fix post corruption

* tuning: boiler plate script
2022-10-11 13:31:55 -07:00
Andrew FerlitschandGitHub 2e4b6a1b1b fix: structure (#1138) 2022-10-11 13:29:11 -07:00
95cebcbf8f Update google_cloud_pipeline_components_dataproc_tabular.ipynb (#1136)
Removed extraneous `$` from CWD variable causing scala-sbt build to fail

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-11 13:04:28 -07:00
Andrew FerlitschandGitHub 08f1b659c5 Boilerplate 1 (#1144)
* feat: boiler plate reduction

* feat: boiler plate reduction
2022-10-11 11:30:08 -07:00
Andrew FerlitschandGitHub 86ba71931d fix: merge corruption (#1143) 2022-10-11 11:19:05 -07:00
d811306fb9 minor fixes (#1140)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-11 11:09:24 -07:00
Andrew FerlitschandGitHub 4173e6d561 Boilerplate 1 (#1142)
* feat: boiler plate reduction

* feat: boiler plate reduction
2022-10-11 10:27:04 -07:00
Andrew FerlitschandGitHub 499d25055a feat: boiler plate reduction (#1141) 2022-10-11 09:32:30 -07:00
Andrew FerlitschandGitHub 60776de953 fix: bad links and branding (#1137) 2022-10-10 15:57:22 -07:00
Andrew FerlitschandGitHub 182ebcf285 fix: script format (#1134)
* fix: script format

* fix: script format

* fix: script format

* fix: script format
2022-10-10 15:56:31 -07:00
MarcandGitHub 39359a5b21 switch mm ownership to Andy (#1133) 2022-10-10 09:48:12 -07:00
0d72cfe070 Modified file automl_forecasting_bqml_arima_plus_comparison (#1124)
* modified notebook

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-10 08:51:51 -07:00
64fef140a2 Vertex SDK AutoML Image Classification (#1123)
* tf library issues solved

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-07 15:14:53 -07:00
015809b948 Cleans up official/migration/UJ3 notebook and fixes the issue from regression logs (#1063)
* cleans up the notebook,replaces docker with cloud build, textual edits still in progress

* cleans up the notebook

* ran linter test

* changes tf train/serve version to 2.9

* ran linter test

* adds '=' to fix a typo

* ran linter test

* updates the opencv installation package

* ran linter test

* updates the opencv installation dependencies

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-07 09:37:12 -07:00
gericdongandGitHub faccdd081f fix: improved notebook comments and readme (#1131)
* fix: improved notebook comments

* fix: improved notebook comments and formatting
2022-10-07 08:00:02 -07:00
3e8a3cf28e updates: autoreview (#1126)
Co-authored-by: gericdong <itseric@google.com>
2022-10-06 16:11:13 -04:00
Andrew FerlitschandGitHub 821bba2776 fix: loose ends on objective conformance (#1125) 2022-10-06 15:46:31 -04:00
c82bdee299 fix: incorrect linking (#1119)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* fix: incorrect linking for index

* fix: incorrect linking

Co-authored-by: gericdong <itseric@google.com>
2022-10-06 10:11:45 -04:00
Andrew FerlitschandGitHub c27381139b fix: incorrect linking (#1121) 2022-10-05 18:28:32 -07:00
Andrew FerlitschandGitHub 01236836f2 fix: incorrect linking (#1120) 2022-10-05 18:12:30 -07:00
Andrew FerlitschandGitHub b8380650bd fix: incorrect linking (#1118)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* fix: incorrect linking for index
2022-10-05 17:52:45 -07:00
Andrew FerlitschandGitHub 69d266cb90 add: autogen index for official/vizier (#1117)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 17:25:04 -07:00
Andrew FerlitschandGitHub 530524ac6e feat: add autogen index for official/training (#1116)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 17:22:17 -07:00
Andrew FerlitschandGitHub ba66961fce feat: add autoindex for official/tensorboard (#1115)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 17:20:06 -07:00
Andrew FerlitschandGitHub aca7035482 add: add autogen index for official/tabular_workflows (#1114)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 17:17:15 -07:00
Andrew FerlitschandGitHub 3d270cde69 feat: add autoindex for official/tabnet (#1113)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 17:14:48 -07:00
Andrew FerlitschandGitHub 9754c265ff feat: add autoindex for official/structured_data (#1112)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 17:09:35 -07:00
Andrew FerlitschandGitHub f5d730c9f1 feat: add autoindex for official/sdk (#1111)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 17:02:06 -07:00
Andrew FerlitschandGitHub acd42a3a1b feat: add autogen index for official/reduction_server (#1110)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 16:58:46 -07:00
Andrew FerlitschandGitHub eb7cf4b6bc feat: add autoindex for official/pipelines (#1109)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 16:54:26 -07:00
Andrew FerlitschandGitHub 34b1011ac9 feat: add autoindex for official/model-registry (#1108)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 16:46:04 -07:00
Andrew FerlitschandGitHub 239d664990 feat: add autogen index for official/model_monitoring (#1107)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 16:43:16 -07:00
Andrew FerlitschandGitHub 920c771238 feat: add autogen index for official/model_evaluation (#1106)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 16:41:01 -07:00
Andrew FerlitschandGitHub e7c68ecb78 fix: autogen index for official/ml_metadata (#1105)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 16:37:29 -07:00
Andrew FerlitschandGitHub cfeb118d8b feat: add autogen index for official/matching_engine (#1104)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index

* feat: add autogen index
2022-10-05 16:30:00 -07:00
Andrew FerlitschandGitHub 2c9c8db15c feat: add autogen index for official/feature_store (#1103)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index

* feat: add autogen index
2022-10-05 16:24:10 -07:00
Andrew FerlitschandGitHub 6778a2cfbf fix: update autogen index for official/automl (#1102)
* feat: add autogen index

* fix: missed the REAME

* fix: update autogen index
2022-10-05 16:14:24 -07:00
Andrew FerlitschandGitHub 26c5d56e6d feat: update autogen index for official/explainable_ai (#1101)
* feat: add autogen index

* fix: missed the REAME
2022-10-05 16:08:41 -07:00
Andrew FerlitschandGitHub 527fe79f15 feat: add autogen index (#1100) 2022-10-05 16:06:38 -07:00
Andrew FerlitschandGitHub 2a003fa9c3 add: autogen index (#1085) 2022-10-05 15:55:29 -07:00
Andrew FerlitschandGitHub 03b9b6026f feat: add index (#1084) 2022-10-05 15:55:09 -07:00
Andrew FerlitschandGitHub ff8d6a9d56 feat: add autogen index (#1083) 2022-10-05 13:21:55 -07:00
Andrew FerlitschandGitHub 874c881ad6 feat: add autogen index (#1080) 2022-10-05 13:21:24 -07:00
Andrew FerlitschandGitHub f484429a89 fix: auto regen index for curated (#1076)
* fix: auto regen index for curated

* fix: bad links
2022-10-05 13:20:22 -07:00
Andrew FerlitschandGitHub 7fa2502c09 PR: bad links and objective (#1099)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective
2022-10-05 11:13:12 -07:00
Andrew FerlitschandGitHub 056791fadd fix: bad links and objective (#1098)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective
2022-10-05 11:10:35 -07:00
Andrew FerlitschandGitHub 154be75dce fix: bad links and objective (#1097)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective
2022-10-05 11:07:09 -07:00
Andrew FerlitschandGitHub ed7e900a02 fix: bad links and objective (#1096)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective
2022-10-05 11:01:19 -07:00
Andrew FerlitschandGitHub f109fefbfa fix: bad links (#1095)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective
2022-10-05 10:54:19 -07:00
Andrew FerlitschandGitHub 6f9c99d1df fix: bad links and objective (#1094)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective

* fix: bad links and objective
2022-10-05 10:49:41 -07:00
Andrew FerlitschandGitHub ed39d78005 fix: bad links and objective conformance (#1093)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: bad links and objective

* fix: bad links and objective
2022-10-05 10:25:02 -07:00
Andrew FerlitschandGitHub d6466ab1a6 fix: bad links and objective (#1092)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: bad links and objective
2022-10-05 10:15:36 -07:00
Andrew FerlitschandGitHub 65e310e4e6 fix: bad links and objective (#1091)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance
2022-10-05 10:08:39 -07:00
Andrew FerlitschandGitHub 0e773ba90f fix: bad links and objective (#1090)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance

* fix: objective conformance
2022-10-05 10:07:35 -07:00
Andrew FerlitschandGitHub 0747f9efb8 fix: objective (#1089)
* fix: objective conformance

* fix: objective conformance

* fix: objective conformance
2022-10-05 09:38:50 -07:00
Andrew FerlitschandGitHub 53785fb812 fix: objective section (#1088)
* fix: objective conformance

* fix: objective conformance
2022-10-05 09:33:13 -07:00
Andrew FerlitschandGitHub b85c24dca5 fix: objective conformance (#1087) 2022-10-05 09:21:49 -07:00
Andrew FerlitschandGitHub ea5c12c22a Autoreview 17 (#1082)
* fix: bad link

* fix: objective
2022-10-04 17:32:04 -07:00
Andrew FerlitschandGitHub 392c1b7361 fix: bad link (#1081) 2022-10-04 17:26:30 -07:00
Andrew FerlitschandGitHub c5980e636e Autoreview 15 (#1079)
* fix: tag handling

* fix: objective

* fix: bad links
2022-10-04 17:08:46 -07:00
Andrew FerlitschandGitHub 8859e9426d fix: tag handling (#1078) 2022-10-04 16:57:34 -07:00
Andrew FerlitschandGitHub db7cc9000a fix: bad links (#1077)
* fix: bad links

* fix: bad links and branding
2022-10-04 16:44:03 -07:00
Andrew FerlitschandGitHub d1fe50a1d9 fix: last tag handling (#1075) 2022-10-04 14:18:22 -07:00
Andrew FerlitschandGitHub 9e3597692f Autoreview text fixes (#1074)
* fix: bad links

* fix: bad links

* fix: objective intro

* fix: objective

* fix: objective statement

* fix: objective statement
2022-10-04 14:07:17 -07:00
Andrew FerlitschandGitHub 45c8deebe5 Autoreview text fixes (#1073)
* fix: bad links

* fix: bad links

* fix: objective intro

* fix: objective

* fix: objective statement
2022-10-04 14:03:10 -07:00
Andrew FerlitschandGitHub 6705c4e4ee Autoreview text fixes (#1072)
* fix: bad links

* fix: bad links

* fix: objective intro

* fix: objective
2022-10-04 13:54:50 -07:00
Andrew FerlitschandGitHub b7f06d948a Autoreview text fixes (#1071)
* fix: bad links

* fix: bad links

* fix: objective intro
2022-10-04 13:20:29 -07:00
Andrew FerlitschandGitHub 7f3c1a9a36 fix: bad links (#1070)
* fix: bad links

* fix: bad links
2022-10-04 13:12:54 -07:00
2e991c5b9d New notebook for PyTorch distributed training on reduction server (#1064)
* feat: added new notebook for PyTorch distributed training on reduction server

* Fixed linter errors

* Addressed review comments

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-04 13:07:43 -07:00
Andrew FerlitschandGitHub f8ac68ec10 Autoreview 10 (#1069)
* fix: handling of linkback for web output

* fix: tune markdown output
2022-10-04 13:06:38 -07:00
Andrew FerlitschandGitHub a591c39367 fix: handling of linkback for web output (#1068) 2022-10-04 12:08:46 -07:00
Andrew FerlitschandGitHub d938982aae feat: calculate links for new notebooks (#1065) 2022-10-04 12:08:18 -07:00
1397c9a64a Fixed line break (#1067)
* Added tags, links to corresponding documentation pages

* Fixed line break issue

Co-authored-by: Max Reznitskii <reznitskii@google.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-04 11:31:32 -07:00
da97ec2244 Added tags, links to corresponding documentation pages (#1066)
Co-authored-by: Max Reznitskii <reznitskii@google.com>
2022-10-04 11:20:08 -07:00
c3f1f8239b UJ15 Vertex SDK AutoML Object Tracking (#1055)
* resloved tf library issues

* ran linter test

* made review changes

* ran linter test

* made review changes

* ran linter

* made review changes

* linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-04 08:51:17 -07:00
Andrew FerlitschandGitHub 73878dcc01 update: support for multi-tags and desc for web output (#1061) 2022-10-04 09:32:20 -04:00
Andrew FerlitschandGitHub 13bad2e6a3 Autoreview readme (#1060)
* fix: re autogen index

* fix: descriptions

* fix: descriptions
2022-10-03 13:24:59 -07:00
Andrew FerlitschandGitHub 0172f2b11b fix: re autogen index (#1059) 2022-10-03 12:39:50 -07:00
Andrew FerlitschandGitHub 1ba0c17555 fix: tuning README output (#1058) 2022-10-03 15:14:32 -04:00
399c961074 Modified notebook chicago_taxi_fare_prediction according to notebook template (#1043)
* error resolved

* ran linter

* andrew comments resolved

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-03 08:35:59 -07:00
d44836db9d Modified notebook inventory_prediction (#1041)
* resolved error

* resolved error

* ran linter

* andrew comments resolved

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-03 08:34:47 -07:00
4e236fd553 Text classification evaluation (#959)
* Model evaluation for text classification using Automl

* Removed unused library

* Ran Linter Test

* Commented text

* Commented Text

* Ran Linter test

* Made changes suggested in review

* Removed unused import

* Ran Linter Test

* Removed dataflow parameters as mentioned in the review

* Ran Linter Test

* Made review changes and changed notebook links in the beginning of the notebook

* Ran Linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-10-02 13:49:06 -07:00
Andrew FerlitschandGitHub 352b1e2710 fix: error handling improvements (#1053) 2022-09-30 15:40:30 -04:00
13cc94d3b7 feat: Add notebook for Wide & Deep on Vertex Pipelines (#984)
* Add notebook for Wide & Deep on Vertex Pipelines

* Address comments

* Clear output

* Fix deletion logic

* Run linter

* Rename custom_job and hpt_job to pipeline_job

* Use Vertex SDK for deletion instead of gcloud

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-30 09:46:23 -07:00
632362ed80 Modified notebook fraud-detection-model notebook (#1052)
* resolved error

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-30 09:44:45 -07:00
90b5575b0c feat: Add notebook for TabNet on Vertex Pipelines (#726)
* Added notebook for TabNet on Vertex Pipelines

* Added notebook for TabNet on Vertex Pipelines

* Added notebook for TabNet on Vertex Pipelines

* Run linter

* Ran linter

* Ran linter again

* Addressed comments

* Addressed more comments

* Remove parameter definitions, reference documentation, add details under CustomJob/HPT job sections

* Address more comments

* Fix tests

* Bug fix

* Rework TabNet HPT job section

* Addressed more comments

* Update documentation links

* Fix tests

* Fix tests

* Linter and some changes

* Address more comments

* Update CustomJob description to align with documentation

* Use bank-marketing dataset instead of safedriver

* Rename variables

* Rename variables

* Update gcs location to official one

* Changes to make notebook run with updated SDK

* Bug fix

* Rewording

* Fix workbench link

* Update notebook format to align with template

* Fix deletion logic

* Run linter

* Rename custom_job and hpt_job to pipeline_job

* Use Vertex SDK for deletion instead of gcloud

Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-29 16:58:53 -07:00
2d96cc0af1 Rapid prototyping bqml automl (#877)
* Made changes in accordance with Notebook template

* Ran Linter Test

* Attached UUID to BQ_DATSET and use bq to delete dataset

* Removed unused imports

* Ran Linter Test

* Fixed BQ_DATASET

* Fixed BQ_DATASET

* Ran linter test

* Made review changes

* Removed unused library

* Ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-29 13:17:14 -07:00
aadc80752b UJ6 Vertex SDK AutoML Text Classification (#1039)
* add The links for Colab, Github and Workbench

* added The links for Colab, Github and Workbench

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-29 13:15:10 -07:00
e8745a750b Modified notebook telecom-subscriber-churn-prediction (#874)
* modified notebook telecom-subscriber-churn-prediction.ipynb

* ran linter

* changes suggested by andrew are done

* ran linter

* changes suggested by andrew done

* ran linter

* resolved error

* ran linter

* fixed a monor bug

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-29 13:13:40 -07:00
Andrew FerlitschandGitHub 67b54685be fix: bad link (#1050)
* fix: bad link

* fix: bad link
2022-09-29 12:07:27 -07:00
Andrew FerlitschandGitHub 738dc1e01c fix: bad links (#1049)
* fix: bad link

* fix: bad link
2022-09-29 12:02:54 -07:00
Andrew FerlitschandGitHub 3b481a43a9 fix: bad links (#1048)
* fix: bad links

* fix: bad links
2022-09-29 12:02:08 -07:00
Andrew FerlitschandGitHub 35d0dee5a0 fix: bad link (#1047)
* fix: bad link

* fix: bad link
2022-09-29 11:47:25 -07:00
Andrew FerlitschandGitHub 90a0bb9b4c fix: bad link (#1046)
* fix: bad link

* fix: bad link
2022-09-29 11:47:01 -07:00
Andrew FerlitschandGitHub e59d5462b4 fix: improve args and add webdoc generation (#1045) 2022-09-29 14:15:52 -04:00
Andrew FerlitschandGitHub f94bf3c7e1 fix: bad link (#1044)
* fix: bad links

* fix: bad links
2022-09-29 09:36:59 -07:00
Andrew FerlitschandGitHub dd215b8cf0 corrections to official notebook (#978)
* fix: corrections

* fix: corrections

* fix: missing bq client

* fix: missing bq client

* fix: installs

* fix: installs

* fix: add missing imports

* fix: add missing imports
2022-09-29 09:10:44 -07:00
Andrew FerlitschandGitHub 784c94a72f fix: bad link, title (#1023)
* fix: bad link, title

* fix: bad link, title
2022-09-29 09:10:08 -07:00
Andrew FerlitschandGitHub dccfed9743 fix: broken link (#1033)
* fix: bad link

* fix: bad link
2022-09-29 09:05:29 -07:00
8346855cfe automl_video_classification_model_evaluation (#1035)
* added model evaluation component

* linter test cases

* linter test cases

* model_name param issues resolved

* linter test case

* import issues resloved

* linter test cases

* made review changes

* made review changes

* ran linter test

* made review changes

* made review changes

* made review changes

* linter test

* ran linter test

* made review changes

* ran linter test

* made review changes

* ran linter test

* linter test

* review changes

* ran linter test

* added The links for Colab, Github and Workbench

* added The links for Colab, Github and Workbench

* ran linter test

* added The links for Colab, Github and Workbench

* ran linter test

* added The links for Colab, Github and Workbench

* ran linter test

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-29 09:13:24 -04:00
Andrew FerlitschandGitHub 64ad5123d0 fix: bad link (#1008)
* fix: bad link

* fix: bad link
2022-09-28 19:26:37 -07:00
Andrew Ferlitsch 0025e56323 fix: Objective 2022-09-29 02:23:03 +00:00
Andrew Ferlitsch 8fd9f35aca fix: Objective 2022-09-29 02:22:33 +00:00
Andrew FerlitschandGitHub 658abd6d5b fix: title in link (#1029)
* fix: bad links

* fix: bad links
2022-09-28 18:52:04 -07:00
Andrew FerlitschandGitHub 1243f736e2 fix: bad link (#1007)
* fix: bad link

* fix: bad link
2022-09-28 17:01:53 -07:00
Andrew FerlitschandGitHub dd0b07163f fix: bad links (#1031)
* fix: bad links

* fix: bad links
2022-09-28 16:54:38 -07:00
Andrew FerlitschandGitHub c6b268ba89 fix: bad links (#1028)
* fix: bad links

* fix: bad links
2022-09-28 15:53:01 -07:00
Andrew FerlitschandGitHub fd4f7d2641 fix: bad links (#1030)
* fix: bad links

* fix: bad links
2022-09-28 15:52:39 -07:00
Andrew FerlitschandGitHub 5c513e20c9 fix: parsing links (#1032) 2022-09-28 15:45:15 -07:00
Andrew FerlitschandGitHub d78dba7941 fix: bad links (#1025)
* fix: bad links

* fix: bad links
2022-09-28 15:37:55 -07:00
Andrew FerlitschandGitHub 42fa88547b fix: bad links (#1027)
* fix: bad links

* fix: bad links
2022-09-28 15:33:47 -07:00
Andrew FerlitschandGitHub c4cda29095 fix: bad links (#1026)
* fix: bad links

* fix: bad links
2022-09-28 15:33:25 -07:00
Andrew FerlitschandGitHub 47725449b5 fix: bad link (#1005)
* fix: bad link

* fix: bad link
2022-09-28 15:01:44 -07:00
Andrew FerlitschandGitHub 2eba462437 fix: bad link (#1010)
* fix: bad link

* fix: bad link
2022-09-28 14:31:37 -07:00
Andrew FerlitschandGitHub 97a3f4d3dd fix: add abbr (#1024) 2022-09-28 14:28:34 -07:00
Andrew FerlitschandGitHub 531e567358 fix: bad links (#1009)
* fix: bad link

* fix: bad link
2022-09-28 14:12:58 -07:00
Andrew FerlitschandGitHub 1f7c7105bb fix: link, title, format (#1018)
* fix: link, title, format

* fix: link, title, format
2022-09-28 14:12:29 -07:00
Andrew FerlitschandGitHub b109183d52 fix: bad links (#1011)
* fix: bad link

* fix: bad link
2022-09-28 13:53:45 -07:00
Andrew FerlitschandGitHub 72ed00fe0f fix: bad links (#1012)
* fix: bad link

* fix: bad link
2022-09-28 13:53:27 -07:00
Andrew FerlitschandGitHub e8d9137a50 fix: bad links (#1013)
* fix: bad link

* fix: bad link
2022-09-28 13:52:51 -07:00
Andrew FerlitschandGitHub 872e98c544 fix: bad links (#1014)
* fix: bad link

* fix: bad link
2022-09-28 13:52:17 -07:00
Andrew FerlitschandGitHub 0966fc56a4 fix: bad links, missing title (#1015)
* fix: bad link, missing title

* fix: bad link, missing title
2022-09-28 13:51:56 -07:00
Andrew FerlitschandGitHub e8d1e58fc6 fix: bad link, title (#1016)
* fix: bad link, correct title

* fix: bad link, correct title
2022-09-28 13:50:44 -07:00
Andrew FerlitschandGitHub f73ff8a44f fix: bad link, title (#1017)
* fix: bad link, correct title

* fix: bad link, correct title
2022-09-28 13:49:53 -07:00
Andrew FerlitschandGitHub 48c5810bd7 fix: bad link, title (#1019)
* fix: bad link, title

* fix: bad link, title
2022-09-28 13:49:25 -07:00
Andrew FerlitschandGitHub 9821d8986c fix: bad link, title (#1020)
* fix: bad link, title

* fix: bad link, title
2022-09-28 13:48:57 -07:00
Andrew FerlitschandGitHub 207d5db3e9 fix: bad link, title (#1021)
* fix: bad link, title

* fix: bad link, title
2022-09-28 13:48:29 -07:00
Andrew FerlitschandGitHub 9deb05e3e7 fix: bad link (#1022)
* fix: bad links

* fix: bad links
2022-09-28 13:47:59 -07:00
Andrew FerlitschandGitHub 8dafc25aab fix: bad link (#1006)
* fix: bad link

* fix: bad link
2022-09-28 13:47:25 -07:00
ef10e7db53 Vertex AI Model Registry - AutoML model management notebook (#995)
* new notebook

* linter test passed

* linter test passed

* andy review

* linter test passed

* add codeowner

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-28 09:41:50 -07:00
Andrew FerlitschandGitHub cba907ddf8 fix: tuning the script (#1004) 2022-09-28 12:21:47 -04:00
16c3d7fe25 automl_video_classification_model_evaluation (#960)
* added model evaluation component

* linter test cases

* linter test cases

* model_name param issues resolved

* linter test case

* import issues resloved

* linter test cases

* made review changes

* made review changes

* ran linter test

* made review changes

* made review changes

* made review changes

* linter test

* ran linter test

* made review changes

* ran linter test

* made review changes

* ran linter test

* linter test

* review changes

* ran linter test

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-28 07:33:08 -07:00
60e1f92ef4 Vertex AI Model Registry - BQML and custom model management notebook (#991)
* add new notebook

* linter test passed

* clean text

* linter test passed

* add code owner new model registry notebook

* add more description

* linter test passed

* align with new template

* linter test passed

* andy reviews

* linter test passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-28 00:05:41 -07:00
Andrew FerlitschandGitHub fb392c6375 Issue 937 (#998)
* fix: issue 937

* fix: issue 937

* fix: wrong method for service account

* fix: wrong method for service account
2022-09-27 21:33:12 -07:00
b4d10bc5aa Modified SDK_Custom_Training_Python_Package_Managed_Text_Dataset_Tensorflow_Serving_Container.ipynb (#996)
* modified notebook, resolved error and modified notebook according to template

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-27 19:51:55 -07:00
4049250bad chore: Fix Workbench links. (#983)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-27 15:24:51 -07:00
923db816e1 Added changes such as timestamp, removed colab references, added markup text mentioning usage of flag -q in a command for the file SDK_Custom_Container_Prediction (#503)
* Added changes in notebook

* Ran linter test

* Replaced Timestamp with UUID; Added 'delete-bucket' in cleanup; Added condition for repo creation and few other minor changes

* Ran Linter Test

* Made some minor changes to install packages

* Made minor changes to fix linter failed tests

* ran linter test

* Made some minor changes

* ran linter test

* addresses the review comments: fixes container build steps, license year, updates according to the template

* ran linter test

* removes beta from gcloud to avoid timeouts

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: SamyuktaDR <samyukta.dontireddy@springml.com>
Co-authored-by: SamyuktaDR <45586340+SamyuktaDR@users.noreply.github.com>
Co-authored-by: Krishna Chaitanya Movva <krishr2d2@gmail.com>
Co-authored-by: krishr2d2 <krishna.movva@springml.com>
2022-09-27 15:13:29 -07:00
Andrew FerlitschandGitHub 872f1561cd fix: argument handling improvements (#999) 2022-09-27 16:51:41 -04:00
8d7832de6e fix: issue 241479124 (#997)
* fix: issue 241479124

* fix: issue 241479124

Co-authored-by: gericdong <itseric@google.com>
2022-09-27 15:08:10 -04:00
Michael HuandGitHub f840017cda fix: bump gcpc version for bqml arima notebook (#985)
* fix: bump gcpc version for bqml arima notebook

* pr fixes
2022-09-27 11:02:38 -07:00
de3f35b8a6 Modified notebook sdk_automl_tabular_forecasting_batch.ipynb (#896)
* modified notebook

* ran linter

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-26 20:17:58 -07:00
b746bc80d4 Resolves shell-output issue in google_cloud_pipeline_components_model_upload_predict_evaluate.ipynb notebook (#878)
* resolves the shell-output issue + updates the structure based on the template

* ran linter test

* fixes issues from review: textual updates, delete_bucket=False

* ran linter test

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-26 16:27:29 -07:00
2001604d37 Modified pricing-optimization.ipynb (#867)
* modified notebook according to notebook_template.

* ran linter

* Added create dataset step

* ran linter

* replaced hardcoded dataset name with a variable

* ran linter

* changes suggested by nadrew done

* ran linter

* followed prolong lin comments, data cleaning now done in bigquery

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-09-26 15:37:48 -07:00
faa148f66e Bqml vertex model registry (#993)
* Add bqml-vertexai-model-registry notebook

* Run linter

* Add notebook to CODEOWNERS file

* Update the links

* Ran linter again

* Rename bigquey-ml folder to model-registry

* Add bigquery-ml folder

* Moved the notebook

* Deleted folder

* Resolve comments

* Use UUID

* Remove using existing endpoint

* Remove try statement

* Get model sample based on model's name

* Use job.result to check query job status

* Run linter

* Fix dataset not found error by adding region in bq client creation

* Revert changes

* Fix bq bugs

* Run linter

* Resolve comments

* Display dataframe

* Updated the codeowner file

* Updated the links and editted text

* Run linter

* Remove repeated resources

* Run linter

* Resolve comments

* Run linter

* Install pyarrow

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-26 18:22:57 -04:00
f184411666 Create a function to get notebook python version for execution (#828)
* Create a function to get notebook python version for execution

* Inject python version to yaml file

* Fix python version references

* Add python string to python version variable

* add python version extraction script (untested)

* Create a function to get notebook python version for execution

* Inject python version to yaml file

* Fix python version references

* Add python string to python version variable

* Remove one notebook condition

* Remove extra check and use python 3 as default version

* Use python3.9 as default version

* Update python version notebook parser

* Add python version to the notebook template

* Fix bug

* Update python version parser function

* Add python version to a notebook for testing

* Run linter

* Use regex in python version parser function

* Add new notebook for testing

* Use better variable name

* fix typo

* Use f string instead +

* Use python from env instead of using _PYTHON_VERSION

* Use simpler regex

* Add python version test notebook

* Fixed a mistake

* Updated notebook template with python version

* Fixed python version format

* Print log contents to stdout

* Remove failing notebook

* Run linter

* Remove extra steps in the printed log

* Edit comments

* Run linter

* Run linter

* Revert test changes

Co-authored-by: AG Sol <aarongabriel@google.com>
2022-09-26 14:32:53 -07:00
bdad774100 Vertex SDK AutoML Text Sentiment Analysis (#824)
* new changes for sentiment analysis notebook

* new changes for sentiment analysis notebook

* changed back to year 2021 text

* changed back to year 2021 text

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-25 08:37:58 -07:00
9abe9a643b Added Custom tabular regression model evaluation file (#942)
* added file

* removed unnecessary imports

* ran linter

* removed extra batch prediction component

* ran linter

* moved file to official

* changed links to point to official

* ran linter

* Jason comments addressed

* ran linter

* comments addressed

* ran linter

* comments addresed

* ran linter

* added predictionschema instance schema files

* ran linter

* Followed Karen Lin's comments

* ran linter

* replaced old prebuilt containers with latest ones

* ran linter

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-24 11:12:06 -07:00
ab230ca06f add fixes to sdk-feature-store.ipynb (formatting, link edits) (#913)
* fix sdk-feature-store.ipynb Workbench link

* adding changes

* fixing links

* lint issues:

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-24 09:37:06 -07:00
dcbd3702d2 Made uuid changes and cleaned Uj6 vertex sdk auto ml text classification notebook (#904)
* Made some minor changes to notebook

* Ran linter test

* Ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-24 09:03:11 -07:00
0505d0c04c Vizier sdk (#981)
* update: replace GAPIC with SDK

* update: replace GAPIC with SDK

Co-authored-by: gericdong <itseric@google.com>
2022-09-23 16:27:36 -04:00
a47e0aacbb Model monitor batch (#980)
* fix: batch monitoring notebook

* fix: batch monitoring notebook

Co-authored-by: gericdong <itseric@google.com>
2022-09-23 15:10:54 -04:00
15912adeaf Update the vizier sample to replace the gapic library with new Vertex Vizier SDK. (#979)
* Update the vizier codelab to replace the gapic library with new Vertex Vizier SDK.

* Added the [project_id] and [region] in the parameter field.

* Fixed the lint errors for vizier sample.

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-23 11:12:28 -07:00
Ivan NardiniandGitHub 35fdba7e1c Vertex AI Experiments - Title fix (#982)
* title fix

* linter test passed
2022-09-23 07:17:58 -07:00
f403fa9051 Made UUID changes for Sdk automl tabular regression batch bq (#976)
* Made UUID changes

* Ran lintertest

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-22 14:45:45 -07:00
0d346b136e Vertex AI Experiments - Comparing local trained models notebook - update (#971)
* clean and update comparing_local_trained_models based on feedback

* linter test passed

* fix libraries

* linter test passed

* andy review fixes

* linter test passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-22 12:21:22 -07:00
Andrew FerlitschandGitHub 60d71d29cc update: add explain example (#974) 2022-09-22 09:35:13 -07:00
28c872f4b6 chore(deps): update python docker tag to v3.10 (#977)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-21 17:09:31 -07:00
Andrew FerlitschandGitHub c637d693b7 tune: pricing, branding, combining text cells (#966)
* tune: pricing, branding, combining text cells

* fix: lint
2022-09-21 13:20:01 -07:00
Andrew FerlitschandGitHub 5c3a216eb7 feat: Add notebook for automl text model online predict (#973) 2022-09-21 14:34:10 -04:00
Ivan CheungandGitHub 0b7831b0f4 Added Dockerfile for linter (#975)
Updated Dockerfile
2022-09-21 09:26:42 -07:00
Andrew FerlitschandGitHub 6a6f077ae4 update: add explain (#972) 2022-09-20 18:40:49 -04:00
Andrew FerlitschandGitHub 27f0a4bb63 feat: notebook for automl tabular online serving (#961)
* feat: notebook for automl tabular online serving

* feat: notebook for AutoML tabular model online prediction

* updates: add explain
2022-09-20 12:54:46 -07:00
1476453603 Moves Sentiment-Analysis notebook from community to official folder (#868)
* moves the sentiment_analysis notebook from community to official folder after making the updates

* removes unused modules

* ran linter test

* updates the dataset's GCS links and notebook links in the heading

* ran linter test

* fixes the typo(=)

* ran linter test

* removes wait() calls and IS_TESTING condition

* ran linter test

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-20 07:35:15 -07:00
dbafcb47ea Modified notebook UJ4 Vertex SDK AutoML Tabular Binary Classification (#891)
* modified notebook

* ran linter

* tensorflow was used only for file reading.So replaced tensorflow with pandas

* ran linter

* made text changes

* ran linter

* latest andrew domments addressed

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-19 14:46:22 -07:00
f20700f25a Model monitoring (#964)
* Changed protobuf version

* ran linter test

* Cleared execution outputs

* Ran Linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-19 11:31:01 -07:00
Andrew FerlitschandGitHub d1ca1cd7f8 fix: reported issues (#968) 2022-09-19 14:11:56 -04:00
Andrew FerlitschandGitHub 9b03fb7f8e fix: install issues (#969) 2022-09-19 09:43:07 -07:00
aac271eacc Sdk metric parameter tracking for custom jobs (#844)
* Replaced timestamp with UUID

* Ran Linter test

* Removed local kernel from metadata

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-09-16 11:43:45 -07:00
68b53e0d32 UJ11 Vertex SDK Hyperparameter Tuning (#957)
* library issues resolved

* library issues resolved

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-16 11:02:37 -07:00
Andrew FerlitschandGitHub bf354adfd3 fix: filename consistency (#952)
* fix: filename consistency

* fix: package name
2022-09-16 09:56:02 -07:00
Andrew FerlitschandGitHub 55ad5701e4 fix: pip dependency fixes (#965) 2022-09-16 12:51:05 -04:00
Andrew FerlitschandGitHub 918564dcc7 fix: missing delete dataset (#963) 2022-09-16 12:44:17 -04:00
19b3b5da0f Add Vertex AI hyperparameter tuning notebook for R using custom containers (#958)
* add unfinished notebook on hpt using R

* clear output

* add working version of notebook

* finish R HPT notebook

* update CODEOWNERS

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-15 08:37:16 -07:00
2bdab9a9b8 Fix export_additional_model_without_custom_ops argument in AutoML Tabular Workflows notebook (#914)
Co-authored-by: Helin Wang <helin@google.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-15 08:09:25 -07:00
Andrew FerlitschandGitHub 88e5d5d236 feat: notebook for automl image online prediction (#953) 2022-09-14 15:20:56 -04:00
Andrew FerlitschandGitHub 79730d191f fix: add details on dataset input formats (#951) 2022-09-13 18:43:08 -04:00
Andrew FerlitschandGitHub 019040e4cb fix: links (#950) 2022-09-13 15:15:43 -04:00
Andrew FerlitschandGitHub 4fd3514d6d feat: add index to batch features/notebooks (#949) 2022-09-13 14:29:46 -04:00
Andrew FerlitschandGitHub bb17381b03 fix: detecting copyright cell (#948) 2022-09-13 11:14:19 -07:00
Andrew FerlitschandGitHub 3f06f48282 fix: filename rename (#943)
* fix: filename rename

* fix: lint issues
2022-09-13 10:01:22 -07:00
33abd1e427 Move model evaluation notebooks from community to official (#940)
* Add automl regression model eval first draft

* Remove extra file

* Pring evaluation results

* adds the automl-tabular-classification notebook in model_evaluation folder

* removes unnecessary imports

* adjusts the imports inside the pipeline

* adjusts the imports

* elaborates imports inside pipeline

* modified regression notebook

* renamed pipeline displayname to resolve error

* Add automl regression model eval first draft

* Remove extra file

* Pring evaluation results

* modified some text

* added suggested updates from review: remove dataflow params, add/change textual descriptions, add UUID

* removes the output from the notebooks

* removes the extra matplotlib import

* ran linter test

* addressed soheila's comments

* ran linter

* addresses the review comments

* ran linter test

* removes the artifacts comment

* ran linter test

* reviewed comments

* ran linter

* addresses review comments: textual updates, removes unnecessary parameters

* ran linter test

* addressed comments

* ran linter

* removed unwanted variables

* ran linter

* addresses the tech-writer's comments + updates the pipeline image with data-sampler task

* ran linter test

* Update text

* Move model eval folder to official

* Update CODEOWNERS

* Run linter

* Removed problem_type parameter

* Run linter

* addresses Andrew's review comments: textual updates and removes additional gcpc installation

* ran linter test

* comments addressed

* ran linter

* removed trailing comma on last parameter of trainingjob.run

* ran linter

Co-authored-by: krishr2d2 <krishna.movva@springml.com>
Co-authored-by: sudarshan-SpringML <sudarshan.c@springml.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-13 09:28:16 -07:00
Peter PingandGitHub 1d9bfe9934 Stream Update v2 (#946)
* Stream Update v2

* correct codeowner name
2022-09-12 18:24:53 -04:00
fb9defa985 Merge to sparkml branch (#881) (#882)
* Merge to sparkml branch (#881)

* feat: initial commit

* feat: WIP

* feat: still WIP, need to work on EDA

* fix: change name, still WIP

* fix: initial draft

* install geopandas in the notebook

* fix: add codeowners

* fix: install pyarrow

* fix: add condition for testing env

* fix: indentation

* fix: add dependencies for gpd

* fix: install seaborn

* fix: isort and codeowner

* fix: description

* fix: add debriefing the result

* fix: decrease sample size for testing

* fix: code review wip

* fix: code review

* fix: change dataset to 2017

* fix: code review

* fix: not using sql

* fix: lint

* fix: delete outputs

* fix: code review

* fix: typo

* fix: make sample pandas df if not testing

* Update spark_ml.ipynb (#884)

(Tech writer edit) Editing for syntax and clarification.

* small text updates

* lint fixes

* constraining plotting to non-test environments

* lint fixes

* put plotting back into tests

* address review feedback

* added comment to rerun cell if URLError thrown

Co-authored-by: Hyunuk Lim <hyunuklim@google.com>
Co-authored-by: aman-ebay <amancuso@google.com>
2022-09-12 17:28:09 -04:00
Soheila ZangenehandGitHub 824fb689e4 Bqml vertex model registry (#945)
* Add bqml-vertexai-model-registry notebook
2022-09-12 16:44:46 -04:00
Andrew FerlitschandGitHub c48dd8662b Issue 235883443 (#944)
* fix: remove obsoleted case

* fix: remove obsoleted case
2022-09-12 15:49:52 -04:00
gericdongandGitHub f251721d23 Enable Cloud Resource Manager API (#939)
* Enable Cloud Resource Manager API

* Reformatted file
2022-09-09 14:05:36 -07:00
Andrew FerlitschandGitHub e949eb128f fix: autoreview of mlops notebooks (#936)
* fix: tune for autoreview

* fix: tune for autoreview
2022-09-09 12:02:50 -04:00
df48e74f59 feat: Batch prediction for custom text model (#934)
* feat: notebook for custom text model batch prediction

* feat: notebook for custom text model batch prediction

Co-authored-by: gericdong <itseric@google.com>
2022-09-09 09:26:13 -04:00
MarcandGitHub ce9e6ecf62 add back pip install of xai sdk (#935) 2022-09-09 01:02:56 +01:00
9ab5f4274a Add automl regression and classification with model evaluation (#911)
* Add automl regression model eval first draft

* Remove extra file

* Pring evaluation results

* adds the automl-tabular-classification notebook in model_evaluation folder

* removes unnecessary imports

* adjusts the imports inside the pipeline

* adjusts the imports

* elaborates imports inside pipeline

* modified regression notebook

* renamed pipeline displayname to resolve error

* Add automl regression model eval first draft

* Remove extra file

* Pring evaluation results

* modified some text

* added suggested updates from review: remove dataflow params, add/change textual descriptions, add UUID

* removes the output from the notebooks

* removes the extra matplotlib import

* ran linter test

* addressed soheila's comments

* ran linter

* addresses the review comments

* ran linter test

* removes the artifacts comment

* ran linter test

* reviewed comments

* ran linter

* addresses review comments: textual updates, removes unnecessary parameters

* ran linter test

* addressed comments

* ran linter

* removed unwanted variables

* ran linter

* addresses the tech-writer's comments + updates the pipeline image with data-sampler task

* ran linter test

Co-authored-by: krishr2d2 <krishna.movva@springml.com>
Co-authored-by: sudarshan-SpringML <sudarshan.c@springml.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-08 14:42:04 -07:00
Andrew FerlitschandGitHub 29e584a422 feat: add batch automl video notebook (#933)
* feat: batch for automl video

* feat: batch for automl video

* feat: batch for automl video
2022-09-08 11:34:29 -07:00
MarcandGitHub beabb87cff fix import problem described in b/245553683 (#932)
* fix aiplatform import problem

* lint fix

* build fix, missing tensforflow

* lint fixes
2022-09-08 16:47:20 +01:00
e3f6717ff6 community -> official for bqml-online-prediction.ipynb (#788)
* move bqml-vertex notebook from community to official

* add to CODEOWNERS official

* fix errors for execution-test

* fix project_id line

* fix linting

* fixes re: comments from sarahcdugan

* fix links at top of notebook from community/ to official/

* added UUID to model name

* fix linting

* fix error in TIMESTAMP --> UUID

* fixing linting double space

* fixes re: ivanmkc comments

* fixed notebook after linting issues

* linting via cloud shell

* simplified run_bq_query function

* linting

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-09-07 18:20:02 -04:00
fd30c4014a Minor fixes for CPR Pytorch sample (#744)
* Minor fixes for CPR Pytorch sample: Add missing test data, add auth info to readme, scrub private project and bucket names from config, tolerate missing config.json in unit tests.

* Minor fixes for CPR Pytorch sample: Add missing test data, add auth info to readme, scrub private project and bucket names from config, tolerate missing config.json in unit tests.

* Fix merge conflicts

* fix typo

* Point CPR links to main branch of SDK repo.

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-07 13:02:55 -07:00
Andrew FerlitschandGitHub 4be8b0a59a fix: finetuning of batch notebooks (#930)
* fix: fine-tuning

* fix: fine-tuning
2022-09-07 10:44:44 -07:00
Andrew FerlitschandGitHub aa09d46265 feat: batch prediction for AutoML text models (#929)
* feat: Automl text model batch predict

* feat: Automl text model batch predict

* feat: Automl text model batch predict
2022-09-07 13:14:16 -04:00
Andrew FerlitschandGitHub 5667967131 feat: add BQ input example (#926)
* feat: add notebook for custom tabular batch predict

* feat: add notebook for custom tabular batch predict

* feat: add example for BQ input

* feat: add example for BQ input

* feat: add example for BQ input

* feat: add example for BQ input
2022-09-07 08:38:36 -07:00
4e4f532658 feat: batch prediction for automl tabular models (#928)
* feat: notebook for AutoML tabular batch prediction

* feat: notebook for AutoML tabular batch prediction

Co-authored-by: gericdong <itseric@google.com>
2022-09-06 15:53:54 -04:00
Andrew FerlitschandGitHub 14b2ce4f2e feat: notebook for batch predict for automl image models (#927)
* feat: batch predict for automl image model

* feat: batch predict for automl image model
2022-09-06 11:45:04 -04:00
Chun-Hsiang WangandGitHub c14b98c92d samples: Minor fix for the wording. (#924) 2022-09-05 10:42:25 -07:00
8275ea6c49 fix: correct the download_url (#923)
* fix: correct the download_url

* fix: fixed formatting issue

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-02 17:04:42 -04:00
40fbffcc95 Sdk automl image object detection batch (#869)
* changed to andrew comments

* changes according to andrew comments

* changes according to andrew comments

* review changes

* review changes

* review changes

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-02 13:34:25 -07:00
Andrew FerlitschandGitHub 08bb513488 feat: Batch prediction for custom tabular model (#920)
* feat: add notebook for custom tabular batch predict

* feat: add notebook for custom tabular batch predict
2022-09-01 20:33:34 -04:00
Chun-Hsiang WangandGitHub b298f83cd3 Vertex Prediction PyTorch Experimental: Add a sample for pre-built PyTorch deployments. (#898)
* samples: Add a new sample for pre-built Pytorch deployments. It's
borrowed from the examples in community-content/pytorch_text_classification_using_vertex_sdk_and_gcloud.

* samples: Removed all training related stuff in the notebooks.

* samples: Fixed comments.

* samples: Updated readme.

* samples: Updated emails for Pytorch launch.
2022-09-01 11:48:59 -07:00
Andrew FerlitschandGitHub 659cbb54c4 feat: add model monitoring with custom container (#919)
* feat: add notebook using custom deployment container

* feat: add notebook using custom deployment container
2022-09-01 10:22:05 -07:00
6ddcaa540a fix: tf serving workaround (#917)
* fix: pin TF serving image

* fix: pin TF serving image

Co-authored-by: gericdong <itseric@google.com>
2022-09-01 12:58:27 -04:00
1656c57b18 feat: extend image batch notebook (#916)
* feat: add notebook for custom image model batch prediction

* feat: add notebook for custom image model batch prediction

* fix: review comments

* fix: review comments

* feat: extend image batch notebook

* feat: extend image batch notebook

Co-authored-by: gericdong <itseric@google.com>
2022-09-01 09:56:36 -07:00
6cac60f74a Sdk feature store ver1 (#790)
* Added condition to create Featurestore if it doesn't exist

* Ran Linter Test

* Made changes mentioned in review

* Ran Linter Test

* Attached uuid to featurestore_id to avoid error while creating featurestore with existing name

* Ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-01 08:57:16 -07:00
Andrew FerlitschandGitHub 55e37f795c feat: notebook for batch prediction with custom image model (#915)
* feat: add notebook for custom image model batch prediction

* feat: add notebook for custom image model batch prediction

* fix: review comments

* fix: review comments
2022-08-31 10:38:31 -07:00
c030d7ef74 use dataset instead of datasets (#892)
less chance for an error and confusion in name clashing with the `datasets` pypi package also used in the notebook.

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-31 07:44:46 -07:00
Andrew FerlitschandGitHub 96be449c69 feat: add notebook for MM autoML (#912)
* feat: model monitoring for AutoML

* feat: model monitoring for AutoML

* fix: correction on AutoML

* fix: correction on AutoML
2022-08-30 12:45:45 -07:00
e40ddab4d5 Upgrade to DataprocPySparkBatch v1 component and add Vertex AI placeholder features (#910)
* Fix typo in notebook heading.

* Fix linting issues.

* Use gcpc v1 components and use Vertex AI for model upload and serving.

* Notebook cleanup

* Minor heading cleanup

* Fix linting issues

* Fix linting issues

* Fix linting issues

* Fix linting issues

Co-authored-by: Win Woo <wwoo@google.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-30 10:46:21 -07:00
Michael HuandGitHub d02bc2d56b pin arima notebook dependencies (#905)
Pins the versions of packages installed in the notebook in anticipation for a breaking change to the GCPC package.
2022-08-29 19:35:54 -04:00
76b641b23d fix: private endpoint example (#909)
* fix: remove gcloud usage

* fix: remove gcloud usage

* fix: review comments

* fix: review comments

Co-authored-by: nayaknishant <nishantnayak@google.com>
2022-08-29 12:16:18 -07:00
Andrew FerlitschandGitHub bbf4345e76 fix: remove Pantheon links (#908)
* fix: issue 194103604

* fix: issue 194103604
2022-08-28 11:24:32 -04:00
058358a795 Vertex SDK AutoML Image Object Detection (#808)
* new notebook Vertex SDK AutoML Image Object Detection

* new notebook Vertex SDK AutoML Image Object Detection

* new notebook of Vertex SDK AutoML Image Object Detection

* new notebook of Vertex SDK AutoML Image Object Detection

* linter test

* linter test

* andrew commented changes

* andrew commented changes

* review changes

* review changes

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-26 15:56:46 -07:00
Andrew FerlitschandGitHub 1c2f75f680 update: GetVertexModelOp (#907)
* update: use GetVertexModelOp

* update: use GetVertexModelOp
2022-08-26 12:12:09 -07:00
Andrew FerlitschandGitHub 999866fad1 feat: model monitoring custom (#906)
* feat: notebook for custom models

* feat: notebook for custom models

* fix: refining

* fix: refining

* fix: review updates

* fix: review updates
2022-08-26 08:58:54 -07:00
89f4571a2c Create explore_data_in_bigquery_with_workbench.ipynb (#885)
* Create explore_data_in_bigquery_with_workbench.ipynb

Adding in notebook for exploratory data analysis as part of "Data to AI" effort. See this Colab for what this notebook looks like after it is run: https://colab.research.google.com/drive/1JeNeMtj2A_5P5vo9wxSkrwHQM5JQSoAu. Submitting it with outputs shown since a lot of this about interactive visualization, which can inspire folks to use/read the notebook beyond just the code.

* Update CODEOWNERS

Adding owner for forthcoming exploratory data analysis notebook

* Update CODEOWNERS

* Updating exploratory data analysis notebook with latest updates from linter/review

* Updated notebook formatting to try to pass format test

* Trying again to pass notebook formatting test

* Trying again to pass notebook formatting test

* Trying again to pass notebook formatting test

* Linted version of notebook & better project picker

* Uploading linted version from ivanmkc@

* Update CODEOWNERS with EDA notebook

* Updated notebook w/ Tech Writer edits, re-ran all

* 1-2 minor text updates, try to pass linter again

* Trying w/ updated linted file from ivanmkc@

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-26 08:46:17 -07:00
eaff81fd97 New Build model experimentation lineage with prebuild code (#785)
* new changes of build model notebook

* new changes of build model notebook

* linter test issues

* linter test issues

* review changes

* review changes

* review changes

* review changes

* review changes

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-26 08:42:15 -07:00
976ed94cf2 metrics_viz_run_compare_kfp (#847)
* added new cell for is_colab condition

* added new cell for is_colab condition

* changes andrew comments

* changes andrew comments

* review changes

* review changes

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-26 08:26:58 -07:00
haomengchaoandGitHub 8ab8ef9ca9 update featurestore api version (#861)
* update api version

* fix tests

* remove unused import

* Run lint to format the change
2022-08-25 10:05:45 -07:00
eaff80a920 Fraud detection notebook2 (#821)
* Made minor changes

* Ran linter test

* Made changes mentioned in the review

* Ran Linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-25 09:49:24 -07:00
Andrew FerlitschandGitHub 8646285c26 fix: fine-tuning (#902)
* feat: new mm notebook

* feat: new mm notebook

* fix: fine-tuning

* fix: fine-tuning

* fix: review comments

* fix: review comments

* fix: review comments

* fix: review comments
2022-08-25 08:34:34 -07:00
7cad8680e1 Sdk automl tabular binary classification batch explain (#829)
* Changed prediction_output format from csv to jsonl to support generate_explanations

* ran linter test

* Made the changes as mentioned in the review

* Ran Linter Test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-25 08:05:21 -07:00
4f66324883 Google cloud pipeline components automl tabular (#843)
* Removed try except blocks from cleanup section

* Ran Linter test

* Made changes mentioned in review and removed globals

* Removed an unused variable

* Ran Linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-24 21:55:50 -07:00
468fd144d2 New auto ml tabular classification bean (#787)
* new notebook of classification beans

* new notebook of classification beans

* changes on andrew comments

* changes on andrew comments

* json file issues

* json file issue

* fixes issues from reviews: adds parameter descriptions, fixes clean up, textual updates and replaces gapic functionality

* ran linter test

* adds the missing machine-type parameter

* ran linter test

* retreives the metrics using dict method

* removes unused variables

* ran linter test

* replaces old code for resource-name with new one

* ran linter test

* updates fetching the resourceName from the training artifacts

* ran linter test

* adds wait method for endpoint deployment

* ran linter test

* removes the wait method

* ran linter test

* adds wait gcp resources component

* ran linter test

* updates colab link, removes wait component, sets force to true in delete endpoint step

* ran linter test

* adds endpoint.wait() method

* ran linter test

* moves model deletion down the endpoint deletion and removes endpoint.wait() method

* ran linter test

Co-authored-by: Krishna Chaitanya Movva <krishr2d2@gmail.com>
Co-authored-by: Krishna Chaitanya Movva <krishna.movva@springml.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-24 13:30:48 -07:00
Rosie ZouandGitHub 2503c3411c chore: fix typo in notebook (#900)
This fix was previously made by Yang Pan in https://github.com/googleapis/python-aiplatform/pull/1437 but closed due to the notebook being moved out of the main Vertex SDK repo.
2022-08-24 11:03:22 -07:00
Andrew FerlitschandGitHub 94b27550e8 feat: model monitor notebook (#899)
* feat: new mm notebook

* feat: new mm notebook
2022-08-24 08:56:18 -07:00
Soheila ZangenehandGitHub 3542e0b0a3 Add bqml vertexai model registry notebook (#842)
* Add bqml-vertexai-model-registry notebook

* Run linter

* Add notebook to CODEOWNERS file

* Update the links

* Ran linter again

* Rename bigquey-ml folder to model-registry

* Add bigquery-ml folder

* Moved the notebook

* Deleted folder

* Resolve comments

* Use UUID

* Remove using existing endpoint

* Remove try statement

* Get model sample based on model's name

* Use job.result to check query job status

* Run linter

* Fix dataset not found error by adding region in bq client creation

* Revert changes

* Fix bq bugs

* Run linter

* Resolve comments

* Display dataframe

* Updated the codeowner file
2022-08-24 10:58:46 -04:00
Andrew FerlitschandGitHub 5cf3b64618 fix: add BQ batch format info (#895)
* fix: add more info on BQ batch format

* fix: add more info on BQ batch format
2022-08-23 09:56:04 -07:00
885bfd56e5 Vertex AI Pipelines - Dataproc Serverless components - Notebook review (#866)
* review dataproc serverless notebook

* linter passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-23 09:44:34 -07:00
3a5eec64af Vertex AI Experiments - Compare pipeline runs - Notebook review (#854)
* experiments cuj1 review

* linter test passed

* typo

* linter test passed

* add correct library. add IAM roles

* linter test passed

* minor fix

* linter test passed

* add api

* linter test passed

* remove library

* linter test passed

* fix

* linter passed

* check

* linter passed

* add text

* linter passed

* minor changes

* andy reviews

* linter passed

* fix link. fix warnings

* linter passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-23 07:57:41 -07:00
8cdc7f1f79 Modified notebook multi_node_ddp_gloo_vertex_training_with_custom_container.ipynb (#886)
* modified notebook according to template

* ran linter

Co-authored-by: gericdong <itseric@google.com>
2022-08-22 10:57:24 -04:00
Ivan CheungandGitHub 84fd10f408 fix: Fixed kernel spec by forcing it to use python3 (#889) 2022-08-19 18:43:07 -07:00
Andrew FerlitschandGitHub 7804c860c5 fix: replace tabs with spaces in JSON template (#888)
* fix: replace tabs with spaces in JSON template

* fix: replace tabs with spaces in JSON template
2022-08-19 11:11:08 -07:00
Andrew FerlitschandGitHub ed0c1c74a6 fix: typo in serving_container_uri parameter (#887) 2022-08-19 08:49:12 -07:00
Andrew FerlitschandGitHub 5127a59e92 Model monitoring (#883)
* fix: notebook template tuning

* fix: notebook template tuning

* fix: possible confusion on when to wait for the email notification

* fix: possible confusion on when to wait for the email notification
2022-08-19 08:38:29 -07:00
d8df732d6b Replace GAPIC with SDK - Model Monitoring Notebook (#879)
* Replace GAPIC with SDK

* Run linter

* Remove unused variables

* Run linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-18 11:41:11 -07:00
9c10899db8 AutoML Video Classificaton (#871)
* changes according to andrew review comments

* changes according to andrew review comments

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-18 07:25:14 -07:00
Ivan NardiniandGitHub 80770188ec Vertex AI Experiments - Model training - Notebook review (#853)
* experiments cuj1 review

* linter test passed

* add IAM role

* linter test passed

* add rm local dir

* linter test passed

* add api

* linter test passed

* remove libraries

* linter test passed

* solve build error

* fix issue

* clean

* linter passed

* fix dependency

* linter passed

* add dependency

* linter passed

* add dependency

* linter passed

* delete bucket flag fix

* linter passed
2022-08-17 10:43:34 -04:00
fa91e45018 Adds the updated managed_notebooks/predictive_maintenance notebook to the official folder (#521)
* adds the updated predictive-maintenance (managed)notebook from community to official folder

* ran linter test

* resubmitting during phase2

* ran linter test

* addresses the review comments: updates based on the new template, sets delete_bucket to False

* ran linter test

* replaces timestamp with uuid

* ran linter test

Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-16 09:39:07 -07:00
fa27309134 Fixes the issues from the regression tests (#822)
* fixes tensorflow version, replaces timestamp with uuid, adds service-account and minor textual changes

* removes second defnition of random library

* ran linter test

* uncomments the user flag and updates the installation command

* ran linter test

* removes the extra backslash

* ran linter test

* updates the installation step to fix long running compatibility checks

* ran linter test

* updates the METADATA path during installation steps

* ran linter test

* adds google-api-core version in the installation

* ran linter test

* removes METADATA step during installation

* ran linter test

* updates google api-core & auth versions

* ran linter test

* fixes tensorflow version, replaces timestamp with uuid, adds service-account and minor textual changes

* removes second defnition of random library

* ran linter test

* uncomments the user flag and updates the installation command

* ran linter test

* removes the extra backslash

* ran linter test

* updates the installation step to fix long running compatibility checks

* ran linter test

* updates the METADATA path during installation steps

* ran linter test

* adds google-api-core version in the installation

* ran linter test

* removes METADATA step during installation

* ran linter test

* updates google api-core & auth versions

* ran linter test

* fixes the issues from review: cell descriptions, parameter definitions, tense changes, 3rd person --> 2nd person, list model after pipeline run

* ran linter test

* removes the METADATA hack and updates the installations

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-16 09:11:30 -07:00
udaypunnaandGitHub 7b85f76384 custom_model_training_and_batch_prediction (#873)
* changed based on andrew review comments

* changed based on andrew review comments

* import library issues

* import library issues

* import issues

* import issues
2022-08-16 08:40:33 -07:00
40a0477b08 modified notebook automl-text-classification.ipynb (#757)
* modified notebook

* modified notebook

* added new notebook

* added new notebook

* new auto_ml_text_classifiation

* new auto_ml_text_classifiation

* new automl text classification

* linter test

* linter test

* changes on andrew comments

* changes on andrew comments

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-15 17:53:52 -07:00
839c7dddb8 Vertex AI Experiments - Compare Models - Notebook review (#852)
* experiments cuj1 review

* linter test passed

* typo

* linter test passed

* add andy reviews

* linter test passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-15 09:49:50 -07:00
Andrew FerlitschandGitHub 578cfb7da7 fi: Issue 850 (#863)
* fix: add missing end_run() for experiment

* fix: add missing end_run() for experiment
2022-08-15 08:57:07 -07:00
Ivan CheungandGitHub b129c0bf43 Update CODEOWNERS (#864)
Use proper Github username.
2022-08-12 17:21:39 -04:00
07b4c37135 Automl links fix (#742)
* fixing links to open notebook - main and images

* linter test changes

* fixes the papermill execution error(hard-coded bucket link was the cause)

* ran linter test

* adds minor textual changes

* ran linter test

* fixes issues from review: future tense, copyright year, section placement, latest sdk methods, new updates from the template

* ran linter test

Co-authored-by: Manuel Amunategui <manuel.amunategui@springml.com>
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-12 12:34:53 -07:00
f48fb1c650 Modified file churn_prediction_for_game_developers (#809)
* made changes

* made changes

* ran linter test

* made changes

* ran linter

* made changes

* ran linter

* changes suggested by andrew done

* ran linter

* replaced timestamp with uuid

* ran linter

* changed bucket creation command according to template

* ran linter

* changed text in overview

* changed region cell from markdown to code

* made changes

* replaced dataset from constant to a variable

* replaced constant dataset_id with a variable

* ran linter

* changed suggested by andrew done

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-12 08:40:38 -07:00
3bbd59311c Made UUID Changes to SDK_BigQuery_Custom_Container_Training.ipynb (#849)
* MAde UUID changes

* Ran Linter test

* made some minor changes

* Ran Linter Test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-12 08:08:32 -07:00
Krishna Chaitanya MovvaandGitHub 15bb4cea73 Fixes the issues(missing variable) from regression tests, adds minor updates from the template. (#823)
* adds the missing delete_bucket variable, adds steps to configure SERVICE_ACCOUNT

* removes unnecessary random import

* ran linter test

* removes the src folder dependency to run on Colab, adds the pipeline.wait step, updates the cleanup steps

* ran linter test

* fixed issues from review: section posistions, tense changes, section descriptions, template updates

* ran linter test
2022-08-12 08:07:11 -07:00
Andrew FerlitschandGitHub 1511cc9fd1 fix: branding updates from autoreview (#862)
* autoreview: branding fixes

* fix: improve installation detection

* cleanup: rm tmp file

* fix: lint issues

* fix: 2nd try at lint fixes
2022-08-11 18:32:47 -07:00
2885a7a70f Migrated matching engine notebook to official and added VPC network support to CI (#836)
* Added matching engine notebook official

* Ran linter

* Added matching engine to .cloud-build/test_notebook_vm.txt

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 18:30:22 -07:00
ea36f5c43e Vertex SDK Custom Image Classification with pre-built training container (#833)
* new notebook of custom image classification

* new notebook of custome image classification

* andrew commented changes

* andrew commented changes

* andrew commented changes

* andrew commented changes

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 14:58:49 -07:00
a905a6305f fixed cleanup cell, cosmetic and doc improvements, and removed load test (to avoid flakiness), (#859)
* fix cleanup cell and print out more info on xai prediction test

* lint fix

* remove load test

* lint fixes

* lint fix

* fix andrews comments

* lint fix

* missing newline

* lint fixes

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 14:04:28 -07:00
Ivan CheungandGitHub aeaeddcc75 Update PULL_REQUEST_TEMPLATE.md (#860)
Updated PR template to emphasize need for a summary and checklist. Otherwise, people tend to skip this standard practice.
2022-08-11 16:18:54 -04:00
161965cfb0 Fixes the exception in batch-explain notebook in the official folder (#810)
* fixes exception(reg-test), replaces timestamp with uuid, minor changes

* ran linter test

* resolved review comments: license year, Vertex AI SDK, dataset after objective and future tense

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 10:25:51 -07:00
b9d4457474 Modified notebook forecasting-retail-demand (#827)
* deleted file in community and added file in official folder

* renamed file

* ran linter test

* renamed file

* ran linter

* made changes

* ran linter test

* made changes

* ran linter test

* made changes

* ran linter test

* made changes

* ran linter

* made change

* ran linter test

* changes suggested by andrew done

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 09:31:27 -07:00
a5b6bcfab1 those two files are moved to official folder.Deleting them in community content (#855)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 09:14:02 -07:00
5d55f5b0d2 Modified notebook pricing-optimization.ipynb (#834)
* modified notebook according to notebook_template.

* ran linter

* Added create dataset step

* ran linter

* replaced hardcoded dataset name with a variable

* ran linter

* changes suggested by nadrew done

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 09:00:13 -07:00
36ace6f4a6 deleted inventory_prediction_folder,folder moved to official (#856)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 08:24:39 -07:00
32d9b416c1 UUID changes done comparing_pipeline_runs.ipynb (#759)
* done UUID changes

* ran lintertest

* made changes in cleanup section

* ran lintertest

* done UUID changes

* ran lintertest

* made changes in cleanup section

* ran lintertest

* made changes in cleanup section

* Ran linter test

* made UUID changes

* RAN linter test

* Made Some minor Chanages notebook

* Ran Linter Test

* small changes made

* Ran Linter Test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-11 08:07:17 -07:00
1c6309f401 Modified notebook SDK_AutoML_Video_Classification.ipynb (#839)
* modified notebook according to template, tensorflow library is used only for file opening so instead of tf we used bucket.blob.download_as_string()

* ran linter

* all changes requested by andrew are done

* cleared all outputs

* making changes to run linter test

* making changes to run linter test

* ran linter

* removed region text in create bucket step

* ran linter

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-10 19:05:41 -07:00
728dec8526 Updates the custom-tabular-bq-managed-dataset notebook according to the new template (#780)
* updates the configuring steps, replaces timestamp with uuid, expands the imports

* ran linter test

* separates the vertex-ai and bigquery initialization steps

* adds comment to cell_24

* adds blank line to cell_24:7:1

* adds blank line to cell_24:7:1

* ran linter test

* fixes aiplatform+bigquery installation compatibility issue

* ran linter test

* fixes installation dependencies

* ran linter test

* fixes the issues from the review: future tense, section positions, updates from the latest template

* ran linter test

* fixes the issues from the review: Code formatting, delete redundant cells, resource name changes

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-10 08:41:50 -07:00
sudarshan-SpringMLandGitHub 7692f902dd Added minor changes to training-multi-class-classification-model-for-ads-targeting-usecase notebook (#735)
* added new file

* ran linter test

* made small changes

* ran linter

* added file

* ran linter

* changes requested by andrew done

* ran linter
2022-08-10 08:03:42 -07:00
9281403198 fix cleanup cell to undeploy models before deleting endpoint and remove BQ table and dataset (#846)
* fix artifact cleanup

* lint fixes

* remove extraneous echo

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-09 20:09:25 -07:00
2be602fbef Update comparing_local_trained_models.ipynb (#704)
Install from Pypi

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-09 15:39:54 -07:00
b140077eb1 Change REGION_NAME to REGION to match flag set earlier in notebook (#734)
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-09 14:54:22 -07:00
d3139f7df8 Added colab , installed some packages, added some code based on standard template and made changes in cleanup section for the file inventory_prediction.ipynb (#533)
* Added notebook

* Ran linter test

* added pyarrow to install

Co-authored-by: Andrew Ferlitsch <aferlitsch@gmail.com>
Co-authored-by: sudarshan-SpringML <82567512+sudarshan-SpringML@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-09 14:49:40 -07:00
72baced988 model monitoring notebook fixes (#841)
* fix model monitoring notebook

* lint fixes

* fixed Soheila's review comments

* fix Andrew's comments

* lint fixes

* clean up install packages per review request

* lint fixes

* fix more comments from Andrew

* lint fixes

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-09 14:16:54 -07:00
Soheila ZangenehandGitHub 5232654705 Update folder name to training (#845) 2022-08-09 12:29:34 -07:00
Andrew FerlitschandGitHub 125fe32eb2 feat: notebook for DASK training (#837)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review script

* tune: project ID and Region

* tune: project ID and Region

* fix: set MODEL_DIR for HPT

* fix: set MODEL_DIR for HPT

* feat: add batch example

* feat: add batch example

* feat: add batch example

* feat: add batch example

* feat: add notebook for DASK training

* feat: add notebook for DASK training
2022-08-08 16:17:28 -07:00
Andrew FerlitschandGitHub 614f4154dc fix: owner names 2022-08-08 15:50:33 -07:00
Andrew FerlitschandGitHub 970415398b fix: owner username 2022-08-08 15:46:57 -07:00
Hyunuk LimandGitHub a052a3d361 A new notebook for Spark Sample (#720)
* Created spark notebook with test code

* Implemented experimental code for poly_view

* implemented the table

* WIP-notebook

* moved experimental to tutorial

* delete experimental code and rename the notebook

* clear all outputs

* fix: delete outputs again

* fix: changed template to the newer one

* fix: modify link on workbench

* add creating a cluster

* Completed Before you begin part

* Change execution sequence

* completed write back process

* change order that switching kernel goes top

* modify pie chart to bar chart

* Completed write up part

* WIP: adding description and comments.

* WIP: delete outputs

* fix: nbqa done

* Completed the first draft

* Delete %%time from cells

* Apply changes as per the code review from Brad except SparkSql

* delete outputs

* Change SparkSQL to Spark API

* change label to xlabel

* fix: description in Dataset

* fix: change BUCKET_NAME to DATASET_NAME, link for the region, and add descriptions and examples for frequency table

* fix: move normalize_name to top of the cell

* fix: refactor udf functions and descriptions

* fix: add link for udf

* fix: description in Dataset

* fix: grammer

* fix: add declared in the sentence

* fix: small changes on grammar

* fix: delete string

* fix: change UserDefinedFunction to udf

* fix: as per TW's code review

* fix: reorder REGION and TIMESTAMP under Creating a GCS bucket

* fix: lint

* chore: add bmiro@ as a codeowner of this doc

* fix: change the variable to fix a bug

* fix: as per TW's second review

* fix: add installation part to pass the ci test

* fix: url for links to main

* fix: delete disabling API since it doesn't affect to the pricing

* fix: add conditions for CI test

* fix: changed jar for testing

* fix: add gcs connector

* fix: change writing method to direct

* fix: delete gcs connector

* fix: specify java folder

* fix: change java_home location

* fix: change unzip instruction

* fix: delete mono_ranking_avg_bytes from testing env

* fix: delete frequency_table from testing env

* fix: delete GCS bucket part

* fix: as per Brad's review

* fix: lint

* fix: add version

* fix: change comment

* fix: add package due to switching the kernel

* fix: delete dataproc cluster command

* fix: change link

* fix: change link

* fix: revert cluster deletion command

* fix: change parenthesis to encoded character

* fix: change the name of the notebook

* fix: change timestamp to UUID

* fix: change the link and add description

* fix: change metadata
2022-08-08 16:23:16 -04:00
Krishna Chaitanya MovvaandGitHub f8203b9f46 UUID replaces Timestamp in the notebook template (#745)
* replaces timestamp with uuid #create *task #tag1 replace the TIMESTAMP with uuid in other official notebooks

* ran linter test

* updates the uuid code

* fixes the comment style highlighted through linter-test

* ran linter test

* adds length argument to uuid function defaulted to 8

* ran linter test
2022-08-08 11:20:33 -04:00
Andrew FerlitschandGitHub fac8c4c9b1 fix: improve batch description (#830)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review script

* tune: project ID and Region

* tune: project ID and Region

* fix: set MODEL_DIR for HPT

* fix: set MODEL_DIR for HPT

* feat: add batch example

* feat: add batch example

* feat: add batch example

* feat: add batch example
2022-08-05 13:50:14 -07:00
Andrew FerlitschandGitHub d6c13c201e Ml ops v9v4 (#817)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review script

* tune: project ID and Region

* tune: project ID and Region

* fix: set MODEL_DIR for HPT

* fix: set MODEL_DIR for HPT

* feat: add batch example

* feat: add batch example
2022-08-05 09:40:11 -07:00
Soheila ZangenehandGitHub 8db9ce0415 Move download link up (#813) 2022-08-04 15:05:18 -04:00
Ivan CheungandGitHub 8c7fb38136 Added missing dependency (#814) 2022-08-04 14:53:17 -04:00
Andrew FerlitschandGitHub acec861ad5 tune: notebook template (#812)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review script

* tune: project ID and Region

* tune: project ID and Region
2022-08-04 10:51:08 -07:00
Andrew FerlitschandGitHub b5cc2b425e feat: auto review script tuning (#811)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review script
2022-08-04 09:30:13 -07:00
Soheila ZangenehandGitHub 710e6ea0d8 Run commands in quiet mode (#789)
* Run commands in quiet mode in both yaml files
* Test CI against single and multiple notebooks
2022-08-04 11:00:49 -04:00
4dce246b57 Add single notebook test file and remove broken notebook from the list (#801)
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-08-04 10:39:09 -04:00
Andrew FerlitschandGitHub 696efb00ee fix: auto review (#807)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review
2022-08-03 21:19:10 -07:00
Andrew FerlitschandGitHub fea73bb9c0 obsolete 2022-08-03 20:28:16 -07:00
Andrew FerlitschandGitHub f50ea24dd1 fix: auto review (#806)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review
2022-08-03 20:27:45 -07:00
Andrew FerlitschandGitHub 473e673d0a fix: auto review (#805)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review
2022-08-03 17:22:25 -07:00
Andrew FerlitschandGitHub 127297ee4e tune: grammar 2022-08-03 15:38:44 -07:00
Chun-Hsiang WangandGitHub fb528b60c6 samples: Minor fix for CPR existing image use cases. (#778) 2022-08-03 15:23:35 -07:00
Andrew FerlitschandGitHub 1c1a2b2097 fix: auto review (#804)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review

* feat: auto review

* fix: auto review
2022-08-03 14:56:26 -07:00
Andrew FerlitschandGitHub 8cb2a26817 fix: auto review (#803)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* feat: auto review

* feat: auto review
2022-08-03 14:38:14 -07:00
Andrew FerlitschandGitHub 3bf098b361 feat: auto review (#802)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review
2022-08-03 14:19:49 -07:00
433cffbf76 Tabnet (#732)
* Start a new branch for TabNet tutorial.

* format lint

* Clean version Created using Colaboratory

* Remove unused import

* Remove unused import

* Created using Colaboratory

* add import

* Add visualization for TabNet

* add gcs

* run format

* reformat

* reformat

* Rmove the - file

* run linter

* run linter

* Update the objective and data section

* Update the link.

* Update data description.

* Update data description.

Co-authored-by: Long Le <longtle@google.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 13:42:06 -07:00
0ec2f4fbe8 bugfix: pass Dataflow related parameters correct for AutoML Tabular pipeline notebook (#725)
Also corrected the required Roles for the service account.

Co-authored-by: Helin Wang <helin@google.com>
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 13:39:32 -07:00
a9af97f1b9 Added notebook demonstrating Tensorboard Custom Training with custom container. (#611)
* Added notebook demonstrating Tensorboard Custom Training with custom container.

* Added notebook demonstrating Tensorboard Custom Training with custom container.

* update codeowners file

* call Vertex API instead of gapic API

* resolve comments for custom container

* resolve comments and format

* resolve comments

* using --quiet for delete doctor repository

* address more comments

Co-authored-by: gericdong <itseric@google.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 13:37:14 -07:00
d6431fab4c Added notebook demonstrating Tensorboard Custom Training with prebuilt container. (#603)
* Added notebook demonstrating Tensorboard Custom Training with prebuilt container

* Added notebook demonstrating Tensorboard Custom Training with prebuilt container

* small fix

* address comments

* format

* update project id to be [your-project-id], and populate tensorboard resource name automatically

* Added notebook demonstrating Tensorboard Custom Training with prebuilt container

* Added notebook demonstrating Tensorboard Custom Training with prebuilt container

* small fix

* address comments

* format

* fix typo for service account

* use vertex api instead of gapic api

* address comments

* minor fix

* minor fix for link

* minor fix

* resolve more comments

* a minor fix for comment

* format the notebook

* resolve comments

* address more comments

Co-authored-by: gericdong <itseric@google.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 13:35:41 -07:00
dcfde86928 Added colab , installation packages and few other changes to chicago_taxi_fare_prediction.ipynb file (#515)
* Added notebook

* Made changes in installing packages code cell

* Ran linter test

* fixes the installation issues and updates some textual content

* fixes the # formatting for comments

* ran linter test

* adds pyarrow to the packages

* ran linter test

* replaces timestamp with uuid

* ran linter test

* updates the uuid code

* fixes the comment style highlighted through linter-test

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: krishr2d2 <krishna.movva@springml.com>
2022-08-03 13:33:08 -07:00
5d747ffa0d Refresh of PyTorch Image Classification Multi-Node Distributed Data Parallel Training on GPU using Vertex Training with Custom Container (#509)
* notebook refresh from vertex ai sdk project

* linter test

* notebook refresh from vertex ai sdk project with trainer folder

* linter test

* add pyarrow

* modified notebook

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@gmail.com>
Co-authored-by: sudarshan-SpringML <sudarshan.c@springml.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 13:32:44 -07:00
53f25201cc Made minor changes to SDK_Custom_Training_Python_Package_Managed_Text_Dataset_Tensorflow_Serving_Container notebook (#507)
* modified notebook

* small changes done

* modified notebook and moved notebook to official folder

* ran linter test

* resolved comments

* ran linter test

* sentence case heading added for some more text

* ran linter test

* made changes

* ran linter test

* made changes

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 13:32:01 -07:00
9b17db3025 Refresh of PyTorch Image Classification Multi-Node Distributed Data Parallel Training on CPU using Vertex Training with Custom Container Notebook (#489)
* multi_node_ddp_gloo_vertex_training_with_custom_container refresh and related trainer folder

* linter test

* various fixes and colab update

* linter test

* modified notebook

* modified notebook

* ran linter test

* Update multi_node_ddp_gloo_vertex_training_with_custom_container.ipynb

Co-authored-by: sudarshan-SpringML <sudarshan.c@springml.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 13:24:45 -07:00
423f7ac584 Adding PrivateEndpoint CUJ notebook to notebooks/community (#721)
* moving REGION up

* moving REGION up and csv file name

* fix: changed bucket URL to console

* removing TODOs from Tabnet notebook

* adding notebook and editing CODEOWNERS file

* fixing links

* adding to community because of test issue

* removing CODEOWNERS

* reverting CODEOWNERS

* linting?

* adding fixes

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-08-03 12:54:46 -07:00
aec82c7e5b inardini -- bqml new operators release update to v1 (#717)
* update to v1

* linter test passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 12:51:46 -07:00
b227509fbb chore(deps): update dependency black to v22.6.0 (#696)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-03 12:43:54 -07:00
Andrew FerlitschandGitHub e715e68273 fix: auto review (#800)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review
2022-08-03 12:39:06 -07:00
406de6fe9a Adds the updated sdk-feature-store-pandas notebook to official from community folder (#488)
* adds the updated sdk-feature-store-pandas notebook to official and removes it from the community

* ran linter test

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: nayaknishant <nishantnayak@google.com>
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-08-03 12:30:10 -07:00
Andrew FerlitschandGitHub eacc49d911 fix: auto review (#798)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auto review

* fix: auto review
2022-08-03 12:26:12 -07:00
Andrew FerlitschandGitHub b95959e7a1 cleanup 2022-08-03 10:58:57 -07:00
Andrew FerlitschandGitHub cc2cf876de fix: auto review (#797)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review
2022-08-03 10:58:27 -07:00
Andrew FerlitschandGitHub 1047237335 Ml ops v9v4 (#796)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review
2022-08-03 10:11:23 -07:00
Andrew FerlitschandGitHub 791d589d41 Ml ops v9v4 (#795)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review
2022-08-03 09:53:21 -07:00
Andrew FerlitschandGitHub f7bdf75d90 fix: auto-review (#794)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review
2022-08-03 09:37:14 -07:00
Andrew FerlitschandGitHub 785ca9f864 fix: auto review (#793)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review

* fix: auti review

* fix: auti review
2022-08-03 09:22:59 -07:00
Andrew FerlitschandGitHub aaa7d5c259 fix: auto review (#792)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auti review

* fix: auti review
2022-08-03 09:01:37 -07:00
Andrew FerlitschandGitHub e21cb948d6 feat: auto review (#784)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review

* fix: auto review

* fix: auto review
2022-08-02 18:46:08 -07:00
Andrew FerlitschandGitHub 5551c5f895 fix: auto review (#783)
* feat: tune template

* feat: tune template

* fix: auto review

* fix: auto review
2022-08-02 18:29:21 -07:00
Andrew FerlitschandGitHub e8853475bc feat: tune template (#782)
* feat: tune template

* feat: tune template
2022-08-02 17:33:32 -07:00
Andrew FerlitschandGitHub 33cb8139da Update get_started_vertex_training_lightgbm.ipynb 2022-08-02 16:33:03 -07:00
Andrew FerlitschandGitHub 0288fa3703 fix: link 2022-08-02 16:32:25 -07:00
Andrew FerlitschandGitHub d48edc2cb4 fix: links 2022-08-02 16:27:45 -07:00
Andrew FerlitschandGitHub 7b26f01671 fix: link 2022-08-02 16:25:45 -07:00
Andrew FerlitschandGitHub 59cd2cda3c fix: link 2022-08-02 16:23:46 -07:00
Andrew FerlitschandGitHub 3ac469f57c fix: link 2022-08-02 16:12:59 -07:00
Andrew FerlitschandGitHub 008833422c fix: link 2022-08-02 14:47:08 -07:00
Andrew FerlitschandGitHub 59c85c3085 fix: link 2022-08-02 14:44:57 -07:00
Andrew FerlitschandGitHub f2b5d0924e fix: link title 2022-08-02 14:35:38 -07:00
Andrew FerlitschandGitHub 772cd44cef fix: link 2022-08-02 14:28:58 -07:00
Andrew FerlitschandGitHub 379a4c6a1c fix: link 2022-08-02 14:27:16 -07:00
Andrew FerlitschandGitHub 5cea72848e fix: link 2022-08-02 14:25:47 -07:00
Andrew FerlitschandGitHub 9c12dd811b fix: links 2022-08-02 14:22:38 -07:00
Andrew FerlitschandGitHub 844cf5b047 fix: links 2022-08-02 14:19:52 -07:00
Andrew FerlitschandGitHub 1492051560 fix: link 2022-08-02 14:06:43 -07:00
Andrew FerlitschandGitHub 40bdd5fce3 fix: link 2022-08-02 14:03:36 -07:00
Andrew FerlitschandGitHub d1cc60e8d7 fix: link 2022-08-02 13:50:36 -07:00
Andrew FerlitschandGitHub 7ca4cf9912 fix: links 2022-08-02 13:34:59 -07:00
Andrew FerlitschandGitHub 294e40cb61 fix: link 2022-08-02 13:27:09 -07:00
Andrew FerlitschandGitHub f69e43d3d6 fix: link 2022-08-02 13:24:41 -07:00
Andrew FerlitschandGitHub 582c479dbe fix: link 2022-08-02 13:23:07 -07:00
Andrew FerlitschandGitHub f83660cf62 fix: link 2022-08-02 13:15:55 -07:00
Andrew FerlitschandGitHub e948fae793 fix: link 2022-08-02 13:13:57 -07:00
Andrew FerlitschandGitHub cd51333ff1 fix: link 2022-08-02 13:13:00 -07:00
Andrew FerlitschandGitHub cf5d266bd7 fix: link 2022-08-02 13:09:57 -07:00
Andrew FerlitschandGitHub 8ef840affb fix: link 2022-08-02 12:59:31 -07:00
Andrew FerlitschandGitHub 4dcc3d0183 fix: link 2022-08-02 12:31:11 -07:00
Andrew FerlitschandGitHub 0bcb6a8d8e fix: title 2022-08-02 12:24:32 -07:00
Andrew FerlitschandGitHub d26b385ec7 fix: title 2022-08-02 12:23:44 -07:00
Andrew FerlitschandGitHub d5a2766aa4 Update get_started_with_matching_engine.ipynb 2022-08-02 12:22:14 -07:00
Andrew FerlitschandGitHub 7abfbb5473 fix: title 2022-08-02 12:21:41 -07:00
Andrew FerlitschandGitHub 096423da33 fix: notice 2022-08-02 12:11:17 -07:00
Andrew FerlitschandGitHub 89a133549c fix: pinning (#779)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* fix: pinning

* fix: pinning
2022-08-01 19:56:29 -07:00
648f1c34e0 Add notebook to show how to deploy BQML models for online prediction via Vertex AI Model Registry (#736)
* adding new notebook on BQML online pred via Model Registry

* minor changes

* fixes to linting

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-08-01 08:42:51 -07:00
Andrew FerlitschandGitHub 3f21907c31 feat: autodiscover (#775)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover
2022-07-29 22:23:59 -07:00
Andrew FerlitschandGitHub fce66b3e57 fix: title (#774)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* fix: title

* fix: title
2022-07-29 22:19:45 -07:00
Andrew FerlitschandGitHub 3b140f9caa fix: title (#773)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title
2022-07-29 21:57:11 -07:00
Andrew FerlitschandGitHub 89325d7e52 feat: autodiscover (#772)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover
2022-07-29 19:58:21 -07:00
Andrew FerlitschandGitHub e4d44f02d6 feat: autodiscover (#771)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title
2022-07-29 19:54:08 -07:00
Andrew FerlitschandGitHub 78993c4729 fix: title (#770)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover

* fix: title

* fix: title
2022-07-29 16:28:15 -07:00
Andrew FerlitschandGitHub c29e7d86bd feat: autodiscover (#769)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title

* feat: autodiscover
2022-07-29 16:18:24 -07:00
Andrew FerlitschandGitHub a8793fb00a fix: title (#768)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover

* fix: title

* fix: title
2022-07-29 16:08:49 -07:00
Andrew FerlitschandGitHub bb60a7d0db Ml ops v9v3 (#767)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* feat: autodiscover

* feat: autodiscover
2022-07-29 15:08:27 -07:00
Andrew FerlitschandGitHub eef758c719 feat: autodiscover index (#766)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title
2022-07-29 15:06:34 -07:00
Andrew FerlitschandGitHub 486ef17ab8 fix: title (#765)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title

* fix: title
2022-07-29 14:57:39 -07:00
Andrew FerlitschandGitHub 90dfef3db6 fix: title (#764)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title
2022-07-29 14:35:34 -07:00
Andrew FerlitschandGitHub d59c87b387 fix: title (#763)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover

* fix: title

* fix: title
2022-07-29 13:27:46 -07:00
Andrew FerlitschandGitHub 9d69b77ac6 feat: autodiscover index (#762)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title

* feat: auto-discover
2022-07-29 13:04:48 -07:00
Andrew FerlitschandGitHub b0da5d69f8 update: tune title (#761)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release

* update: tune title

* update: tune title
2022-07-29 12:44:46 -07:00
Andrew FerlitschandGitHub 830e10e583 upgrade: updates for new release (#760)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template

* upgrade: updates for new release

* upgrade: updates for new release
2022-07-29 12:17:43 -07:00
kthytangandGitHub db904b424e chore: Update CPR notebooks. (#756)
* chore: Update CPR notebooks to pip install latest released Vertex SDK pypi package.

* Update CPR notebooks wording for experimental -> preview.

* Update Objectives wording

* Update github links to main branch.

* Update Sklearn interface.

* Fix formatting and typos.

* Update Predictor interface
2022-07-28 17:13:50 -07:00
Andrew FerlitschandGitHub c371f05bfa fix: split guidelines from template (#754)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template

* fix: split guidelines from template

* fix: split guidelines from template
2022-07-28 08:13:04 -07:00
Andrew FerlitschandGitHub 5f7de16e2d fix: split off authoring guidelines (#753)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF

* fix: split guidelines from template
2022-07-28 08:08:55 -07:00
Andrew FerlitschandGitHub 3908580ad6 feat: add notebook for non-TF HPT (#751)
* feat: import automl tabular model

* feat: import automl tabular model

* feat: HPT for non-TF

* feat: HPT for non-TF
2022-07-27 14:57:24 -07:00
Andrew FerlitschandGitHub 77d2cac20a Update README.md 2022-07-27 13:39:38 -07:00
Andrew FerlitschandGitHub a92d5ce473 Update README.md 2022-07-27 13:38:51 -07:00
Andrew FerlitschandGitHub 416ec74af3 add entry 2022-07-27 13:37:51 -07:00
Andrew FerlitschandGitHub 8443bbfe44 feat: notebook for importing automl tabular model (#750)
* feat: import automl tabular model

* feat: import automl tabular model
2022-07-27 13:35:04 -07:00
kthytangandGitHub 23a599068a Update CPR notebooks. (#741)
* Update CPR notebooks.

- Update interfaces
- Fix missing timestamp
- Rename some variables

* Update cpr preprocess notebook.

- Change preprocessor import path.

* Update SDK_Custom_Predict_SDK_Integration.ipynb

* Update SDK_Custom_Predict_and_Handler_SDK_Integration.ipynb

* Update SDK_Pytorch_Custom_Predict.ipynb

* Update SDK_Triton_PyTorch_Local_Prediction.ipynb

* Fix lint and revert path change for pickle dumping preprocessor.
2022-07-27 10:58:28 -07:00
gericdongandGitHub c63bb4c464 New notebook to demonstrate how to enable TensorBoard Profiler (#719)
* New notebook to demonstrate how to enable TensorBoard Profiler

* Reformatted with Lint

* Changed service account handling and added a step to monitor job state

* Addressed review comments

* Addressed technical writerreview comments

* Addressed Ivan review comments

* Switched from GAPIC to Vertex SDK

* Removed an unused package

* Addressed review comments
2022-07-26 14:39:37 -04:00
Ivan CheungandGitHub 2226e915c0 Update CODEOWNERS 2022-07-25 16:24:10 -04:00
Ivan CheungandGitHub cd9f8b1d89 Update CODEOWNERS 2022-07-25 15:01:46 -04:00
Ivan CheungandGitHub aae9ad0422 Update CODEOWNERS 2022-07-25 15:00:33 -04:00
Ivan CheungandGitHub 89d50579a6 Add @GoogleCloudPlatform/caiis-tw to CODEOWNERS
Add @GoogleCloudPlatform/caiis-tw to default.
2022-07-25 15:00:01 -04:00
Ivan CheungandGitHub 2d6afa8313 Added better download instructions (#738)
* Improve download instruc
tions

* Added web download to notebook results list
2022-07-22 18:21:05 -04:00
Ivan CheungandGitHub 00cfb20c36 Notebook CI: Fixed variable replacement to handle numbers (#739)
* Removed replacement of variable comparisons

* Fixed issue with numbers in replacement content
2022-07-22 11:50:39 -04:00
Ivan CheungandGitHub 14c87ae702 Removed replacement of variable comparisons (#737) 2022-07-21 19:21:02 -04:00
e2a6610c2d Add an example use case for custom prediction routines. (#709)
* Add an example use case for custom prediction routines.

* Addressing some PR comments: reworded the readme in a few places, added a 'probe' command to build.py that sends a sample predict request, and pinned versions in requirements. Also fixed a bug where the artifacts_uri passed in during deployment on Vertex AI was not recognized as a directory.

* Autoformat code with black and fix a couple of typing errors.

* Addressing PR comments: Add deployment machine type to the config and add docstring to probe_prediction method.

* Update example to work with new LocalModel interface.

* Update example to work with new LocalModel interface.

Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-07-21 12:42:31 -07:00
Ivan CheungandGitHub 145cdd0928 Added a service account injection (#695)
* Added a service account injection

* Revert this

* Added service account injection

* Fixed cloud build file

* Added gcloud version debug info

* Fixed sa injection

* Removed test file

* Revert CODEOWNERS
2022-07-21 15:04:10 -04:00
Michael HuandGitHub 04e1697bca fix workbench link in new tables notebooks (#714) 2022-07-21 09:29:06 -04:00
Ivan CheungandGitHub be785d0389 Allow outputs (#733) 2022-07-20 17:31:12 -04:00
MarcandGitHub 976e346a3d rm open in cloud notebook until tested there, also fix open links to use community for now (#731) 2022-07-20 21:48:07 +01:00
e37caca496 chore(deps): update dependency nbqa to v1.4.0 (#727)
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-07-19 13:06:00 -05:00
MarcandGitHub 7a48fe8850 add community notebook (#729) 2022-07-19 07:52:03 +01:00
Ivan NardiniandGitHub 915a1edba8 inardini - vertex explainable ai example based api example using sdk gapic (#716)
* new notebook

* linter test passed.

* add codeowners

* review

* reviews

* linter test passed.

* last review. linter test passed
2022-07-16 19:12:46 -04:00
MarcandGitHub 424f947b04 avoid linter reformatting that breaks this notebook in colab (#715)
* fix formatting for colab

* disable black formatting selectively
2022-07-12 16:23:29 -07:00
Andrew FerlitschandGitHub c95f73c1a8 fix: bad link (#712)
* feat: notebook on model registry

* feat: notebook on model registry

* feat: workflow notebook

* feat: workflow notebook

* feat: workflow notebook

* fix: objective

* fix: objective

* fix: link

* fix: link
2022-07-07 12:51:14 -07:00
Andrew FerlitschandGitHub 9da033c887 Update README.md 2022-07-06 14:40:51 -07:00
Andrew FerlitschandGitHub f61f9bfdc2 feat: notebook for automl tabular workflow (#710)
* feat: notebook on model registry

* feat: notebook on model registry

* feat: workflow notebook

* feat: workflow notebook

* feat: workflow notebook
2022-07-06 14:26:45 -07:00
b2a17dfc83 inardini - New 20+ Pipeline Operators for BQML notebook (#706)
* google_cloud_pipeline_components_bqml_pipeline_demand_forecasting notebook

* linter test to check with andy

* google_cloud_pipeline_components_bqml_pipeline_demand_forecasting notebook

* linter test to check with andy

* merge

* linter test minor fails. check with andy

* add code owner

* minor changes

* remove components

* linter test passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-07-06 08:38:28 -07:00
sasha-gitgandGitHub 7072219d8b Update build_model_experimentation_lineage_with_prebuild_code.ipynb (#703)
Switch to install from Pypi
2022-07-01 14:40:52 -07:00
Andrew FerlitschandGitHub 57db2f4014 Update README.md 2022-07-01 11:45:37 -07:00
Andrew FerlitschandGitHub 4604b0a0a9 Update README.md 2022-07-01 11:44:38 -07:00
Andrew FerlitschandGitHub c8c26a12ba fix: finish objective cell (#708)
* feat: notebook on model registry

* feat: notebook on model registry
2022-07-01 11:40:28 -07:00
Andrew FerlitschandGitHub 3a8fa3e312 feat: notebook for model registry (#707)
* update: refine experiment notebook

* update: refine experiment notebook

* update: new feature release

* update: new feature release

* update: new feature release

* update: new feature release

* feat: notebook on model registry

* feat: notebook on model registry
2022-07-01 11:25:20 -07:00
bbfba5aaaf add initial automl tables on vertex pipelines notebook (#694)
* add initial automl tables on vertex pipelines notebook

* apply template

* update bucket variable name

* reviewer requested changes

* update notebook with the updated API

* fix typo

* add stage_1_tuning_result_artifact_uri to skip architecture search pipeline

* update parameter for skip architecture search pipeline

* default evaluation to True; update data splits

* update dataset to gs://cloud-samples-data/vertex-ai/tabular-workflows/datasets/safe-driver/train.csv

Co-authored-by: Helin Wang <helin@google.com>
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-07-01 09:54:39 -07:00
Andrew FerlitschandGitHub e30b2182b0 Update get_started_with_vertex_endpoints.ipynb 2022-06-30 20:35:07 -07:00
4c4dade55a samples: Add Prediction CPR preprocess sample. (#662)
* samples: Add Prediction CPR preprocess sample.

* chore: Refined wording and used notebook template for CPR preprocessing
sample.

* samples: Fixed comments for CPR Preprocess sample.

* samples: Fixed wording.

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-30 20:14:35 -07:00
5690d50430 samples: Add Prediction CPR Triton sample. (#661)
* samples: Add Prediction CPR Triton sample.

* chore: Refined wording and used notebook template for CPR Triton sample.

* samples: Fixed comments for CPR Triton samples.

* samples: Fixed wording.

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-30 20:13:00 -07:00
Chun-Hsiang WangandGitHub 10c33f934f samples: Add Prediction CPR SDK sample. (#660)
* samples: Add Prediction CPR SDK sample.

* chore: Refined wording and used notebook template for CPR SDK sample.

* samples: Fixed comments for CPR SDK sample.

* samples: Fixed wording.
2022-06-30 20:07:29 -07:00
Andrew FerlitschandGitHub 0c43cbd563 update: remove install from git branch 2022-06-30 16:24:20 -07:00
Andrew FerlitschandGitHub b640a8f545 update: new feature release (#702)
* update: refine experiment notebook

* update: refine experiment notebook

* update: new feature release

* update: new feature release

* update: new feature release

* update: new feature release
2022-06-30 11:57:50 -07:00
Ivan CheungandGitHub a575528b11 Tweaks to matching engine notebook (#701)
* Tweaks to notebook

* Ran linter

* More tweaks
2022-06-30 11:59:05 -04:00
Andrew FerlitschandGitHub 42a2c4d082 fix: doc link 2022-06-30 08:36:57 -07:00
Andrew FerlitschandGitHub 0bcf44e9fa Update get_started_bqml_training.ipynb 2022-06-30 08:33:06 -07:00
Andrew FerlitschandGitHub 9ac2774ece Update README.md 2022-06-29 21:25:19 -07:00
Andrew FerlitschandGitHub 975c9fe6bc update: refine experiments notebook (#699)
* update: refine experiment notebook

* update: refine experiment notebook
2022-06-29 21:14:11 -07:00
Andrew FerlitschandGitHub 417410f382 Fix: remove hardwired project number (#698)
* fix: remove hardwired project number

* fix: remove hardwired project number
2022-06-29 14:42:51 -07:00
Andrew FerlitschandGitHub 8fdfbe4e31 fix: link 2022-06-29 14:20:04 -07:00
Andrew FerlitschandGitHub 80f977546c fix: title 2022-06-29 09:54:29 -07:00
Ivan NardiniandGitHub c5fe281e32 inardini - experiments cuj2 notebook release (#637)
* experiments cuj2 notebook release

* add andy reviews

* linter test passed

* align notebooks

* linter test passed

* minor changes

* karl bug review fix

* linter test passed

* add -q to install

* linter test passed

* debug

* linter test passed

* PR build fix

* linter test passed. delete debug notebook

* import import tempfile

* linter test passed

* remove pandas install

* linter test passed

* add sklearn

* linter test passed

* test pandas dep

* linter test passed

* minor changes

* linter test passed

* ivan fix
2022-06-29 12:38:16 -04:00
49a2ddaf08 fix: removing TODOs from TabNet notebook (#652)
* moving REGION up

* moving REGION up and csv file name

* fix: changed bucket URL to console

* removing TODOs from Tabnet notebook

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-28 07:26:01 -07:00
e9cba94bb4 inardini - experiments cuj3 notebook release (#638)
* experiments cuj3 notebook release

* add andy reviews

* linter test passed

* align notebooks

* linter test passed

* align notebooks

* linter test passed

* update CODEOWNERS

* sasha bug review fix

* linter test passed

* minor changes

* add -q to install

* linter test passed

* ivan dep fix

* linter test passed

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-06-27 19:15:13 -04:00
fc83cfcea5 samples: Add Prediction CPR PyTorch sample. (#659)
* samples: Add Prediction CPR PyTorch sample.

* chore: Refined wording and used notebook template for PyTorch sample.

* added missing bucket cleanup

Co-authored-by: Andrew Ferlitsch <aferlitsch@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-27 12:23:31 -07:00
e3aa9e8f35 samples: Add Prediction CPR handler sample. (#658)
* samples: Add Prediction CPR handler sample.

* chore: Refined wording and used notebook template.

* added missing bucket cleanup sequence

Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-27 12:09:20 -07:00
Ivan CheungandGitHub 37c52abc11 Added a virtualenv to the notebook execution tests which should help with dependency issues (#693)
* Added a virtualenv

* Added a virtualenv for the single yaml

* Debug

* Fixed diff logic for all notebooks case

* Added missing -c
2022-06-26 13:31:52 -04:00
Ivan CheungandGitHub c8320c8764 Revert "Add notebook for co-hosting model (#666)" (#692)
This reverts commit aa5464151d.
2022-06-24 18:26:28 -04:00
b5d51e61b6 inardini - experiments cuj1 notebook release (#636)
* experiments cuj1 notebook release

* add andy reviews

* linter test passed

* align notebooks

* linter test passed

* minor changes

* linter test passed

* minor changes

* linter test passed

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-06-24 15:35:32 -04:00
Ziye XingandGitHub aa5464151d Add notebook for co-hosting model (#666)
* Add notebook for co-hosting model

* Add co-hosting model notebook codeowner
2022-06-24 10:36:26 -07:00
Andrew FerlitschandGitHub 386cecf4c2 upgrade: current notebook standard (#677)
* upgrade: notebook standard

* upgrade: notebook standard

* Update custom_model_training_and_batch_prediction.ipynb
2022-06-24 09:59:49 -07:00
dffdb15c17 Add default kernel_name for notebook execution (#497)
Currently, there is no kernel_name. Hence, the execution test cannot run for notebooks that don't have kernels defined in their .ipynb file.

Side-note: We should use lint to remove the kernel_name from .ipynb as well, as it could include info specific to the author's environment.

Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-06-23 19:18:49 -04:00
Andrew FerlitschandGitHub 2f3691eb71 fix: workbench link 2022-06-23 13:55:29 -07:00
Andrew FerlitschandGitHub f456d86555 fix: open in workbench link 2022-06-23 13:52:39 -07:00
Andrew FerlitschandGitHub f534b4e7a5 upgrade: fine tune notebook standard 2022-06-23 13:28:00 -07:00
Andrew FerlitschandGitHub de247cd78b upgrade: current notebook standards (#681)
* upgrade: notebook standard

* upgrade: notebook standard

* fix: formatting
2022-06-23 12:03:55 -07:00
Andrew FerlitschandGitHub 22ad74eb8d Update README.md 2022-06-23 10:06:28 -07:00
Andrew FerlitschandGitHub baf69999fc update: fine-tuning notebook (#689)
* update: touchups

* update: touchups
2022-06-23 10:02:02 -07:00
Mohammad Al-AnsariandGitHub d5057da9bb Added new notebook that creates Vertex AI AutoML text entity extraction dataset from PDFs using Vision API (#683)
* Added new Stage 1 notebook to create unlabelled
Vertex AI AutoML text entity extraction dataset
from collection of PDF files on Google Cloud Storage

* Linted notebook

* Removed TODOs

* Updates per PR comments

* Revered to multiple imports per line
2022-06-23 08:38:14 -07:00
24904a5999 feat: adding code owners and updating graph_paysim (#645)
* adding code owners and updating graph_paysim

* formatted

Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
2022-06-22 21:31:55 -05:00
Ivan CheungandGitHub 881a2b45c5 Improved git diff logic (#687) 2022-06-22 21:49:09 -04:00
Andrew FerlitschandGitHub 41fc83ad03 upgrade: current notebook standards (#655)
* update: current standards

* update: current standards

* Update sdk_custom_image_classification_batch_explain.ipynb

* fix: bucket nit
2022-06-22 16:59:39 -07:00
Andrew FerlitschandGitHub 9928276dc3 upgrade: current notebook standard (#653)
* upgrade: current notebook standard

* upgrade: current notebook standard

* Update sdk_automl_tabular_binary_classification_batch_explain.ipynb

* fix: bucket nit
2022-06-22 16:58:42 -07:00
Andrew FerlitschandGitHub 6607f93f5e upgrade: updated curated notebook to current standards (#648)
* upgrade: current standards

* upgrade: current standards

* fix: missed nits

* fix: missed nits

* Update automl-text-classification.ipynb

* Update automl-text-classification.ipynb

* rm extra comma
2022-06-22 16:56:38 -07:00
Andrew FerlitschandGitHub dcc0cfe06e upgrade: current notebook standards (#686)
* upgrade: notebook standard

* upgrade: notebook standard
2022-06-22 16:50:13 -07:00
Andrew FerlitschandGitHub 00d5c5c4bf Update README.md 2022-06-22 15:34:01 -07:00
Andrew FerlitschandGitHub f8152dde19 Update README.md 2022-06-22 15:24:14 -07:00
Andrew FerlitschandGitHub 0586e04c21 upgrade: current notebook standards (#656)
* update: current standards

* update: current standards

* fix: bucket nit
2022-06-22 15:06:01 -07:00
Andrew FerlitschandGitHub 3de18a7fab upgrade: current notebook standards (#674)
* upgrade: current notebook standard

* upgrade: current notebook standard

* fix: bucket

* fix: bucket
2022-06-22 15:03:54 -07:00
Andrew FerlitschandGitHub dc0bf24cc5 Update README.md 2022-06-22 14:58:28 -07:00
Andrew FerlitschandGitHub 8ce4c3070c Update README.md 2022-06-22 14:53:54 -07:00
Andrew FerlitschandGitHub 13c3acb976 Update README.md 2022-06-22 14:50:45 -07:00
Andrew FerlitschandGitHub c1150ff584 Update README.md 2022-06-22 14:39:06 -07:00
Andrew FerlitschandGitHub 4f11d70f7e Update README.md 2022-06-22 14:34:02 -07:00
Andrew FerlitschandGitHub 2bf9a2b317 Update README.md 2022-06-22 14:24:53 -07:00
Andrew FerlitschandGitHub b1e0ad0c4f Update README.md 2022-06-22 14:15:22 -07:00
Andrew FerlitschandGitHub 5624f92f02 Update README.md 2022-06-22 14:12:18 -07:00
Andrew FerlitschandGitHub 1335032954 Update README.md 2022-06-22 14:05:24 -07:00
Andrew FerlitschandGitHub 0b13c66e07 Update README.md 2022-06-22 14:01:55 -07:00
Andrew FerlitschandGitHub ef25b54926 update: add index (#684) 2022-06-22 13:58:06 -07:00
Andrew FerlitschandGitHub 064dbfeefa fix: bucket nit 2022-06-22 12:34:50 -07:00
Andrew FerlitschandGitHub 044c69e7a5 upgrade: current notebook standards (#654)
* update: current standards

* update: current standards
2022-06-22 12:33:26 -07:00
Andrew FerlitschandGitHub 32a46e7471 upgrade: current standards (#649)
* upgrade: current standards

* upgrade: current standards

* fix: missed nits

* fix: missed nits
2022-06-22 12:30:16 -07:00
Andrew FerlitschandGitHub b52d59822d upgrade: current notebook standards (#657)
* update: current standards

* update: current standards

* update: current standards

* update: current standards

* Update sdk_custom_tabular_regression_batch_explain.ipynb

* fix: indent issue

* fix: indent issue

* fix: bucket

* fix: bucket

* fix: image

* fix: image

* fix: cleanup

* fix: cleanup

* fix: cleanup
2022-06-22 11:47:17 -07:00
Andrew FerlitschandGitHub 529995ecde upgrade: current notebook standard (#671)
* upgrade: current notebook standard

* upgrade: current notebook standard

* Update google_cloud_pipeline_components_automl_tabular.ipynb

* fix: bucket

* fix: bucket
2022-06-22 11:35:38 -07:00
Andrew FerlitschandGitHub 0726328c92 upgrade: current notebook standard (#667)
* upgrade: current notebook standard

* upgrade: current notebook standard

* Update model_monitoring.ipynb

* Update model_monitoring.ipynb
2022-06-22 11:21:32 -07:00
Andrew FerlitschandGitHub 090e83c286 fix: more broken links 2022-06-22 11:19:17 -07:00
Andrew FerlitschandGitHub c3802626b9 fix: links issue 672 2022-06-22 11:18:08 -07:00
Andrew FerlitschandGitHub 9570c2477f upgrade: current notebook standards (#682)
* upgrade: current notebook standards

* upgrade: current notebook standards
2022-06-22 11:09:27 -07:00
Andrew FerlitschandGitHub 2b1a898b2a upgrade: current notebook standards (#680)
* upgrade: current notebook standards

* upgrade: current notebook standards
2022-06-22 11:09:04 -07:00
Andrew FerlitschandGitHub f2a42aa66e upgrade: current notebook standard (#679)
* upgrade: notebook standard

* upgrade: notebook standard

* fix: bucket

* fix: bucket
2022-06-22 11:08:37 -07:00
Andrew FerlitschandGitHub 30a03f1fd1 upgrade: current notebook standards (#678)
* upgrade: notebook standard

* upgrade: notebook standard

* Update google_cloud_pipeline_components_model_train_upload_deploy.ipynb

* fix: bucket nits

* fix: bucket
2022-06-22 11:08:08 -07:00
Andrew FerlitschandGitHub ca25448f59 upgrade: current notebook standard (#673)
* upgrade: current notebook standard

* upgrade: current notebook standard

* fix: bucket nit

* fix: bucket nit
2022-06-22 11:07:37 -07:00
Andrew FerlitschandGitHub 8f922710b0 upgrade: current notebook standard (#670)
* upgrade: current notebook standard

* upgrade: current notebook standard

* Update google_cloud_pipeline_components_automl_images.ipynb

* fix: bucket

* fix: bucket
2022-06-22 11:06:31 -07:00
Andrew FerlitschandGitHub 9509c6ab9d upgrade: current notebook standard (#669)
* upgrade: current notebook standard

* upgrade: current notebook standard

* Update lightweight_functions_component_io_kfp.ipynb

* fix: nits

* fix: nits

* fix: nits

* fix: nits
2022-06-22 11:05:47 -07:00
Andrew FerlitschandGitHub ccba176979 upgrade: current notebook standard (#665)
* upgrade: notebook standard

* upgrade: notebook standard

* Update sdk-feature-store.ipynb

* Update sdk-feature-store.ipynb

* Update sdk-feature-store.ipynb

* fix: aip reference

* fix: nits

* fix: nits
2022-06-22 11:05:07 -07:00
Andrew FerlitschandGitHub 1b8f383897 upgrade: current notebook standard (#663)
* update: current standards

* update: current standards

* fix: bucket

* fix: bucket
2022-06-22 09:36:49 -07:00
Andrew FerlitschandGitHub e5cd9e86d2 upgrade: notebook to latest standard (#651)
* fix: missed nits

* fix: missed nits
2022-06-22 08:56:10 -07:00
Andrew FerlitschandGitHub a7e86a4f26 upgrade: current notebook standard (#668)
* upgrade: current notebook standard

* upgrade: current notebook standard

* Update sdk-metric-parameter-tracking-for-locally-trained-models.ipynb
2022-06-21 20:23:18 -07:00
Ivan CheungandGitHub 8f0c73b32c Fixed cleanup scripts (#676) 2022-06-21 20:13:37 -07:00
Andrew FerlitschandGitHub c7d7b48a91 upgrade: notebook to current standards (#650)
* upgrade: current standards

* upgrade: current standards
2022-06-21 18:25:25 -07:00
Karl WeinmeisterandGitHub 583eb90f07 fix: CONTRIBUTING.md did not have nbfmt as final step 2022-06-20 13:56:49 -05:00
c3a9249c0c Workaround tensorboard/GCS issue for Cloud Shell (#386)
* Workaround tensorboard/GCS issue for Cloud Shell

Without `--load_fast=false` there will be `401 Unauthorized` for GCS log loads. 
See https://github.com/tensorflow/tensorboard/issues/4784#issuecomment-868945650

* PR #386: Fix missing import

`import json` was missing.

Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-19 10:07:09 -05:00
Karl WeinmeisterandGitHub 81b70e779c ci: Remove protobuf from requirements.txt 2022-06-19 09:38:45 -05:00
Karl WeinmeisterandGitHub 085713a818 ci: Add protobuf to requirements.txt 2022-06-18 17:20:45 -05:00
Karl WeinmeisterandGitHub 5af7c851dc Fix: update typo in GAPIC Feature Store notebook 2022-06-18 17:10:49 -05:00
691312d467 Add import feature analysis config sample code into gapic-feature-sto… (#548)
* Add import feature analysis config sample code into gapic-feature-store.ipynb

* Fixing linter for gapic-feature-store.ipynb

Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-06-18 17:09:37 -05:00
650c256c13 Fixes link to colab (#627)
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-06-18 16:26:36 -05:00
9b00c4380b chore(deps): update actions/setup-python action to v4 (#622)
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-06-18 16:21:49 -05:00
Karl WeinmeisterandGitHub 4851457e93 ci: Add Python version to support setup-python v4 2022-06-18 16:19:09 -05:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>Karl Weinmeister
1c54878fab build(deps): bump tensorflow (#595)
Bumps [tensorflow](https://github.com/tensorflow/tensorflow) from 2.5.3 to 2.7.2.
- [Release notes](https://github.com/tensorflow/tensorflow/releases)
- [Changelog](https://github.com/tensorflow/tensorflow/blob/master/RELEASE.md)
- [Commits](https://github.com/tensorflow/tensorflow/compare/v2.5.3...v2.7.2)

---
updated-dependencies:
- dependency-name: tensorflow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-06-18 16:08:07 -05:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
c139b84454 build(deps): bump tensorflow (#593)
Bumps [tensorflow](https://github.com/tensorflow/tensorflow) from 2.5.3 to 2.7.2.
- [Release notes](https://github.com/tensorflow/tensorflow/releases)
- [Changelog](https://github.com/tensorflow/tensorflow/blob/master/RELEASE.md)
- [Commits](https://github.com/tensorflow/tensorflow/compare/v2.5.3...v2.7.2)

---
updated-dependencies:
- dependency-name: tensorflow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-18 16:02:53 -05:00
15c38b4ca6 chore(deps): update dependency pyupgrade to v2.34.0 (#457)
Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
2022-06-18 15:59:54 -05:00
Ivan CheungandGitHub 271c949a71 Update README.md (#642) 2022-06-17 14:59:05 -07:00
Andrew FerlitschandGitHub 09b5401434 update: fine-tuning notebook (#641)
* feat: add example of import from dataframe

* feat: add example of import from dataframe

* update: change in required perms

* update: change in required perms

* review: updates from review

* review: updates from review

* updates: fine tuning
2022-06-17 13:41:10 -07:00
dad76547f0 inardini - mobile gaming feature store blog review (#635)
* review content and image

* linter test passed

* andy review fixes

* linter test passed

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-17 10:39:18 -07:00
Andrew FerlitschandGitHub c14a110c81 Update get_started_with_custom_training_pipeline_components.ipynb 2022-06-16 14:24:08 -07:00
Andrew FerlitschandGitHub d1e16546cc Update get_started_with_bqml_pipeline_components.ipynb 2022-06-16 14:23:29 -07:00
Andrew FerlitschandGitHub f91bc3d0c9 Update get_started_with_bq_tfdv_pipeline_components.ipynb 2022-06-16 14:22:56 -07:00
Andrew FerlitschandGitHub 5168808b6c fix: colab link 2022-06-16 14:22:23 -07:00
Andrew FerlitschandGitHub 501cca7b5e fix: colab link 2022-06-16 14:21:31 -07:00
Andrew FerlitschandGitHub f19d40d858 Update mlops_experimentation.ipynb 2022-06-16 13:49:17 -07:00
Andrew FerlitschandGitHub 5a721ce01d Update get_started_with_visionapi_and_automl.ipynb 2022-06-16 13:48:31 -07:00
Andrew FerlitschandGitHub 66421fb4d8 fix: colab link 2022-06-16 13:47:47 -07:00
Andrew FerlitschandGitHub 3658ee8c88 Update get_started_with_tabnet.ipynb 2022-06-16 13:46:10 -07:00
Andrew FerlitschandGitHub afaab4bb02 Update get_started_with_cmek_training.ipynb 2022-06-16 13:45:08 -07:00
Andrew FerlitschandGitHub c1e004bdff fix: colab link 2022-06-16 13:44:22 -07:00
Andrew FerlitschandGitHub 874e5a3ef5 Update get_started_vertex_training_xgboost.ipynb 2022-06-16 13:43:11 -07:00
Andrew FerlitschandGitHub 51529f370c fix: broken table 2022-06-16 13:41:01 -07:00
Andrew FerlitschandGitHub 5ddf98866c Update get_started_vertex_training_sklearn.ipynb 2022-06-16 13:40:22 -07:00
Andrew FerlitschandGitHub fbb6830876 fix: colab link 2022-06-16 13:30:01 -07:00
Andrew FerlitschandGitHub ee1bb281da fix: colab link 2022-06-16 13:28:16 -07:00
Andrew FerlitschandGitHub da2f7e88fe fix: update location of public dataset bucket 2022-06-16 12:43:15 -07:00
Andrew FerlitschandGitHub 3fb28e353f fix: remove internal link 2022-06-16 12:40:02 -07:00
Andrew FerlitschandGitHub c8e7f44f0a fix: updates from review (#640)
* feat: add example of import from dataframe

* feat: add example of import from dataframe

* update: change in required perms

* update: change in required perms

* review: updates from review

* review: updates from review
2022-06-16 12:36:28 -07:00
3d9049aeeb remove old hard-coded instances for prediction (#633)
Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-16 11:50:01 -07:00
Andrew FerlitschandGitHub 7b8726af24 fix: perms for using MR in BQML (#634)
* feat: add example of import from dataframe

* feat: add example of import from dataframe

* update: change in required perms

* update: change in required perms
2022-06-15 14:55:17 -07:00
Andrew FerlitschandGitHub 0443b05360 feat: add create tabular dataset from dataframe example (#632)
* feat: add example of import from dataframe

* feat: add example of import from dataframe
2022-06-14 11:44:30 -07:00
Ivan CheungandGitHub e422dbdef2 Added official version of tabular regression batch bq (#331)
* Added official version of tabular regression batch bq

* Ran linter

* Fixed cleanup

* Additional cleanup

* Added working version

* Refactored and made work

* Ran linter and cleaned up

* Renamed aip to aiplatform

* Replaced online with batch

* Renamed notebook

* Ran linter and cleaned up

* Fixed bug

* Fixed SQL by adding backticks

* Install google-cloud-bigquery[all]

* Refactored datasets

* Ran linter

* Removed GCS cells

* Fixed import file

* Fixed SQL issues and added cleanup of training dataset

* Fixed hardcorded table

* Fixed brand names

* Fixed header

* Fixed results table

* Addressed tech writing review comments

* Ran linter
2022-06-14 14:14:06 -04:00
Andrew FerlitschandGitHub ec5fc0b1c8 Update get_started_vertex_training_r.ipynb 2022-06-14 10:05:36 -07:00
Andrew FerlitschandGitHub c52e3f20ba Update get_started_vertex_training_pytorch.ipynb 2022-06-14 10:04:45 -07:00
Andrew FerlitschandGitHub e367dceceb Update get_started_vertex_training_lightgbm.ipynb 2022-06-14 10:04:11 -07:00
Andrew FerlitschandGitHub 19b8666808 Update get_started_vertex_training.ipynb 2022-06-14 10:03:24 -07:00
Andrew FerlitschandGitHub a2df0e9fca Update get_started_vertex_tensorboard.ipynb 2022-06-14 10:01:52 -07:00
Andrew FerlitschandGitHub 73b094550e Update get_started_vertex_feature_store.ipynb 2022-06-14 09:59:24 -07:00
Andrew FerlitschandGitHub d05ae109e1 Update get_started_vertex_experiments.ipynb 2022-06-14 09:57:55 -07:00
Andrew FerlitschandGitHub fdb25791d5 Update get_started_vertex_distributed_training.ipynb 2022-06-14 09:57:19 -07:00
Andrew FerlitschandGitHub 5a88492498 Update get_started_bqml_training.ipynb 2022-06-14 09:56:34 -07:00
Andrew FerlitschandGitHub f19a12b829 Update get_started_automl_training.ipynb 2022-06-14 09:55:53 -07:00
Andrew FerlitschandGitHub 3ed0ea73f4 Update get_started_bq_datasets.ipynb 2022-06-14 09:08:47 -07:00
Andrew FerlitschandGitHub b98fd24a72 Update get_started_bq_datasets.ipynb 2022-06-13 21:29:41 -07:00
Andrew FerlitschandGitHub eb4e9a0f91 Update get_started_vertex_datasets.ipynb 2022-06-13 21:27:16 -07:00
Andrew FerlitschandGitHub ec7c136b0a Update get_started_vertex_datasets.ipynb 2022-06-13 21:26:24 -07:00
Andrew FerlitschandGitHub ee7e43cc1a Update mlops_data_management.ipynb 2022-06-13 20:24:57 -07:00
Andrew FerlitschandGitHub ea9f5f3c5c Update get_started_with_data_labeling.ipynb 2022-06-13 20:24:22 -07:00
Andrew FerlitschandGitHub bd44798412 Update get_started_vertex_datasets.ipynb 2022-06-13 20:23:37 -07:00
Andrew FerlitschandGitHub 2af0cc0f80 fix: test for local execution 2022-06-13 20:22:57 -07:00
Andrew FerlitschandGitHub 5c0fa14d2d Update get_started_bq_datasets.ipynb 2022-06-13 20:21:44 -07:00
Andrew FerlitschandGitHub 7cc50d3203 Update README.md 2022-06-13 13:58:20 -07:00
Andrew FerlitschandGitHub 9c7da13177 Update gapic-vizier-multi-objective-optimization.ipynb 2022-06-13 08:39:33 -07:00
Andrew FerlitschandGitHub 45e0645f0b Update gapic-vizier-multi-objective-optimization.ipynb 2022-06-13 08:38:55 -07:00
Andrew FerlitschandGitHub cb884cc74a Update gapic-vizier-multi-objective-optimization.ipynb 2022-06-13 08:38:22 -07:00
Ivan CheungandGitHub d3a6475580 Fixed mistake in batch prediction request section (#617)
* Fixed mistake in batch prediction request section

* Fixed linter requirements
2022-06-10 17:13:45 -04:00
4e7061b2db added MLPerf benchmark reference and updated Criteo sample to use GRPC for stock containers (#630)
* added MLPerf benchmark reference and updated Criteo sample to use GRPC for stock containers

* addressed feedback for BERT sample and did similar changes to Criteo sample

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-06-10 12:06:25 -07:00
Ivan CheungandGitHub 0250879f65 Added notebook substitution for common case of 1 notebook (#625) 2022-06-10 14:44:43 -04:00
Andrew FerlitschandGitHub 5cee23ae68 Update get_started_with_autoscaling.ipynb 2022-06-09 15:02:28 -07:00
Andrew FerlitschandGitHub d518558b3d Update README.md 2022-06-09 15:01:55 -07:00
Andrew FerlitschandGitHub 5c085c843f feat: notebook on autoscaling (#629)
* feat: XAI + custom server

* feat: add DIY MLMD for AutoML

* feat: add DIY MLMD for AutoML

* fix: replace BLAH

* fix: replace BLAH

* update: AutoML + MLMD

* update: AutoML + MLMD

* co-hosting

* co-hosting

* feat: new R notebook

* feat: new R notebook

* feat: airflow+vertex

* feat: airflow+vertex

* feat: notebook on autoscaling

* feat: notebook on autoscaling
2022-06-09 14:57:41 -07:00
395 changed files with 164730 additions and 29952 deletions
@@ -1 +1,2 @@
ratemate
google-cloud-aiplatform
+24 -15
View File
@@ -1,9 +1,15 @@
from typing import List
from ratemate import RateLimit
from resource_cleanup_manager import (
DatasetResourceCleanupManager,
ModelResourceCleanupManager,
EndpointResourceCleanupManager,
ResourceCleanupManager,
MatchingEngineIndexEndpointResourceCleanupManager,
MatchingEngineIndexResourceCleanupManager,
)
from resource_cleanup_manager import (DatasetResourceCleanupManager,
EndpointResourceCleanupManager,
ModelResourceCleanupManager,
ResourceCleanupManager)
rate_limit = RateLimit(max_count=25, per=60, greedy=False)
def run_cleanup_managers(managers: List[ResourceCleanupManager], is_dry_run: bool):
@@ -14,17 +20,18 @@ def run_cleanup_managers(managers: List[ResourceCleanupManager], is_dry_run: boo
resources = manager.list()
print(f"Found {len(resources)} {type_name}'s")
for resource in resources:
if not manager.is_deletable(resource):
continue
try:
if not manager.is_deletable(resource):
continue
if is_dry_run:
resource_name = manager.resource_name(resource)
print(f"Will delete '{type_name}': {resource_name}")
else:
try:
if is_dry_run:
resource_name = manager.resource_name(resource)
print(f"Will delete '{type_name}': {resource_name}")
else:
rate_limit.wait() # wait before deleting
manager.delete(resource)
except Exception as exception:
print(exception)
except Exception as exception:
print(exception)
print("")
@@ -35,10 +42,12 @@ if is_dry_run:
print("Starting cleanup in dry run mode...")
# List of all cleanup managers
managers = [
managers: List[ResourceCleanupManager] = [
DatasetResourceCleanupManager(),
EndpointResourceCleanupManager(),
ModelResourceCleanupManager(),
ModelResourceCleanupManager(), # ModelResourceCleanupManager must follow EndpointResourceCleanupManager due to deployed models blocking model deletion.
MatchingEngineIndexEndpointResourceCleanupManager(),
MatchingEngineIndexResourceCleanupManager(),
]
run_cleanup_managers(managers=managers, is_dry_run=is_dry_run)
@@ -1,5 +1,5 @@
import abc
from typing import Any
from typing import Any, Type
from google.cloud import aiplatform
from google.cloud.aiplatform import base
@@ -41,7 +41,7 @@ class ResourceCleanupManager(abc.ABC):
# Check that it wasn't created too recently, to prevent race conditions
if time_difference <= RESOURCE_UPDATE_BUFFER_IN_SECONDS:
print(
f"Skipping '{resource}' due update_time being '{time_difference}', which is less than '{RESOURCE_UPDATE_BUFFER_IN_SECONDS}'."
f"Skipping '{resource}' due to update_time being '{time_difference}', which is less than '{RESOURCE_UPDATE_BUFFER_IN_SECONDS}'."
)
return False
@@ -51,7 +51,7 @@ class ResourceCleanupManager(abc.ABC):
class VertexAIResourceCleanupManager(ResourceCleanupManager):
@property
@abc.abstractmethod
def vertex_ai_resource(self) -> base.VertexAiResourceNounWithFutureManager:
def vertex_ai_resource(self) -> Type[base.VertexAiResourceNounWithFutureManager]:
pass
@property
@@ -61,7 +61,9 @@ class VertexAIResourceCleanupManager(ResourceCleanupManager):
def list(self) -> Any:
return self.vertex_ai_resource.list()
def resource_name(self, resource: Any) -> str:
def resource_name(
self, resource: Type[base.VertexAiResourceNounWithFutureManager]
) -> str:
return resource.display_name
def delete(self, resource):
@@ -75,14 +77,43 @@ class VertexAIResourceCleanupManager(ResourceCleanupManager):
class DatasetResourceCleanupManager(VertexAIResourceCleanupManager):
vertex_ai_resource = aiplatform.datasets._Dataset
dataset_types = [
aiplatform.ImageDataset,
aiplatform.TabularDataset,
aiplatform.TextDataset,
aiplatform.TimeSeriesDataset,
aiplatform.VideoDataset,
]
def list(self) -> Any:
return [
dataset
for dataset_type in self.dataset_types
for dataset in dataset_type.list()
]
class EndpointResourceCleanupManager(VertexAIResourceCleanupManager):
vertex_ai_resource = aiplatform.Endpoint
def delete(self, resource):
# TODO: Remove this once https://github.com/googleapis/python-aiplatform/issues/1441 is fixed
resource._sync_gca_resource()
for deployed_model_id in [
models.id for models in resource._gca_resource.deployed_models
]:
resource._undeploy(deployed_model_id=deployed_model_id)
resource.delete(force=True)
class ModelResourceCleanupManager(VertexAIResourceCleanupManager):
vertex_ai_resource = aiplatform.Model
class MatchingEngineIndexResourceCleanupManager(VertexAIResourceCleanupManager):
vertex_ai_resource = aiplatform.MatchingEngineIndex
class MatchingEngineIndexEndpointResourceCleanupManager(VertexAIResourceCleanupManager):
vertex_ai_resource = aiplatform.MatchingEngineIndexEndpoint
+17 -3
View File
@@ -62,6 +62,18 @@ parser.add_argument(
help="The GCP region. This is used to inject a variable value into the notebook before running.",
required=True,
)
parser.add_argument(
"--variable_service_account",
type=str,
help="A service account. This is used to inject a variable value into the notebook before running. This is not the account that will run the notebook.",
required=True,
)
parser.add_argument(
"--variable_vpc_network",
type=str,
help="The full VPC network name. See https://cloud.google.com/compute/docs/networks-and-firewalls#networks. Format is projects/{project}/global/networks/{network}, where {project} is a project number, as in '12345', and {network} is network name. See <https://cloud.google.com/compute/docs/reference/rest/v1/networks/insert> for details. This is used to inject a variable value into the notebook before running.",
required=False,
)
parser.add_argument(
"--staging_bucket",
type=str,
@@ -108,9 +120,11 @@ execute_changed_notebooks_helper.process_and_execute_notebooks(
container_uri=args.container_uri,
staging_bucket=args.staging_bucket,
artifacts_bucket=args.artifacts_bucket,
variable_project_id=args.variable_project_id,
variable_region=args.variable_region,
private_pool_id=args.private_pool_id,
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,
)
+141 -23
View File
@@ -17,12 +17,16 @@ import concurrent
import dataclasses
import datetime
import functools
import json
import git
import operator
import os
import pathlib
import re
import subprocess
import utils
from typing import List, Optional
from utils import util
import execute_notebook_helper
import execute_notebook_remote
@@ -34,6 +38,7 @@ from utils import NotebookProcessors, util
# A buffer so that workers finish before the orchestrating job
WORKER_TIMEOUT_BUFFER_IN_SECONDS: int = 60 * 60
PYTHON_VERSION = "3.9" # Set default python version
def format_timedelta(delta: datetime.timedelta) -> str:
@@ -65,13 +70,23 @@ class NotebookExecutionResult:
log_url: str
output_uri: str
build_id: str
logs_bucket: str
error_message: Optional[str]
@property
def output_uri_web(self) -> Optional[str]:
if self.output_uri.startswith("gs://"):
return f"https://storage.googleapis.com/{self.output_uri[5:]}"
else:
return None
def _process_notebook(
notebook_path: str,
variable_project_id: str,
variable_region: str,
variable_service_account: str,
variable_vpc_network: Optional[str],
):
# Read notebook
with open(notebook_path) as f:
@@ -83,8 +98,11 @@ def _process_notebook(
replacement_map={
"PROJECT_ID": variable_project_id,
"REGION": variable_region,
"SERVICE_ACCOUNT": variable_service_account,
"VPC_NETWORK": variable_vpc_network,
},
)
unique_strings_preprocessor = NotebookProcessors.UniqueStringsPreprocessor()
# Use no-execute preprocessor
(
@@ -93,11 +111,41 @@ def _process_notebook(
) = remove_no_execute_cells_preprocessor.preprocess(nb)
(nb, resources) = update_variables_preprocessor.preprocess(nb, resources)
(nb, resources) = unique_strings_preprocessor.preprocess(nb, resources)
with open(notebook_path, mode="w", encoding="utf-8") as new_file:
nbformat.write(nb, new_file)
def _get_notebook_python_version(notebook_path: str) -> str:
"""
Get the python version for running the notebook if it is specified in
the notebook.
"""
python_version = PYTHON_VERSION
# Load the notebook
file = open(notebook_path)
src = file.read()
nb_json = json.loads(src)
# Iterate over the cells in the ipynb
for cell in nb_json["cells"]:
if cell["cell_type"] == "markdown":
markdown = str.join("", cell["source"])
# Look for the python version specification pattern
re_match = re.search(
"python version = (\d\.\d)", markdown, flags=re.IGNORECASE
)
if re_match:
# get the version number
python_version = re_match.group(1)
break
return python_version
def _create_tag(filepath: str) -> str:
tag = os.path.basename(os.path.normpath(filepath))
tag = re.sub("[^0-9a-zA-Z_.-]+", "-", tag)
@@ -117,8 +165,10 @@ def process_and_execute_notebook(
artifacts_bucket: str,
variable_project_id: str,
variable_region: str,
variable_service_account: str,
variable_vpc_network: Optional[str],
private_pool_id: Optional[str],
deadline: datetime,
deadline: datetime.datetime,
notebook: str,
should_get_tail_logs: bool = False,
) -> NotebookExecutionResult:
@@ -126,6 +176,13 @@ def process_and_execute_notebook(
print(f"Running notebook: {notebook}")
# Handle empty strings
if not variable_vpc_network:
variable_vpc_network = None
if not private_pool_id:
private_pool_id = None
# Create paths
notebook_output_uri = "/".join([artifacts_bucket, pathlib.Path(notebook).name])
@@ -139,6 +196,7 @@ def process_and_execute_notebook(
output_uri=notebook_output_uri,
log_url="",
build_id="",
logs_bucket="",
error_message=None,
)
@@ -146,11 +204,19 @@ def process_and_execute_notebook(
time_start = datetime.datetime.now()
operation = None
try:
# Get the python version for running the notebook if specified
notebook_exec_python_version = _get_notebook_python_version(
notebook_path=notebook
)
print(f"Running notebook with python {notebook_exec_python_version}")
# Pre-process notebook by substituting variable names
_process_notebook(
notebook_path=notebook,
variable_project_id=variable_project_id,
variable_region=variable_region,
variable_service_account=variable_service_account,
variable_vpc_network=variable_vpc_network,
)
# Upload the pre-processed code to a GCS bucket
@@ -170,14 +236,16 @@ def process_and_execute_notebook(
private_pool_id=private_pool_id,
private_pool_region=variable_region,
timeout_in_seconds=timeout_in_seconds,
python_version=notebook_exec_python_version,
)
operation_metadata = BuildOperationMetadata(mapping=operation.metadata)
result.build_id = operation_metadata.build.id
result.log_url = operation_metadata.build.log_url
result.logs_bucket = operation_metadata.build.logs_bucket
# Block and wait for the result
operation_result = operation.result()
operation_result = operation.result(timeout=86400)
result.duration = datetime.datetime.now() - time_start
result.is_pass = True
@@ -232,20 +300,40 @@ def get_changed_notebooks(
# Find notebooks
notebooks = []
# Instantiate GitPython objects
repo = git.Repo(os.getcwd())
index = repo.index
if base_branch:
print(f"Looking for notebooks that changed from branch: {base_branch}")
notebooks = subprocess.check_output(
["git", "diff", "--name-only", f"origin/{base_branch}..."] + test_paths
)
# Get the point at which this branch branches off from main
branching_commits = repo.merge_base("HEAD", f"origin/{base_branch}")
if len(branching_commits) > 0:
branching_commit = branching_commits[0]
print(f"Looking for notebooks that changed from branch: {branching_commit}")
notebooks = [
diff.b_path
for diff in index.diff(branching_commit, paths=test_paths)
if diff.b_path is not None
]
else:
notebooks = []
else:
print(f"Looking for all notebooks.")
notebooks = subprocess.check_output(["git", "ls-files"] + test_paths)
notebooks_str = subprocess.check_output(["git", "ls-files"] + test_paths)
notebooks = notebooks_str.decode("utf-8").split("\n")
notebooks = notebooks.decode("utf-8").split("\n")
notebooks = [notebook for notebook in notebooks if notebook.endswith(".ipynb")]
notebooks = [notebook for notebook in notebooks if len(notebook) > 0]
notebooks = [notebook for notebook in notebooks if pathlib.Path(notebook).exists()]
if len(notebooks) > 0:
print(f"Found {len(notebooks)} notebooks:")
for notebook in notebooks:
print(f"\t{notebook}")
return notebooks
@@ -254,11 +342,13 @@ def process_and_execute_notebooks(
container_uri: str,
staging_bucket: str,
artifacts_bucket: str,
variable_project_id: str,
variable_region: str,
private_pool_id: Optional[str],
should_parallelize: bool,
timeout: int,
variable_project_id: str,
variable_region: str,
variable_service_account: str,
variable_vpc_network: Optional[str] = None,
private_pool_id: Optional[str] = None,
):
"""
Run the notebooks that exist under the folders defined in the test_paths_file.
@@ -294,7 +384,7 @@ def process_and_execute_notebooks(
seconds=max(timeout - WORKER_TIMEOUT_BUFFER_IN_SECONDS, 0)
)
if len(notebooks) > 1:
if len(notebooks) >= 1:
notebook_execution_results: List[NotebookExecutionResult] = []
print(f"Found {len(notebooks)} modified notebooks: {notebooks}")
@@ -315,6 +405,8 @@ def process_and_execute_notebooks(
artifacts_bucket,
variable_project_id,
variable_region,
variable_service_account,
variable_vpc_network,
private_pool_id,
deadline,
),
@@ -329,6 +421,8 @@ def process_and_execute_notebooks(
artifacts_bucket=artifacts_bucket,
variable_project_id=variable_project_id,
variable_region=variable_region,
variable_service_account=variable_service_account,
variable_vpc_network=variable_vpc_network,
private_pool_id=private_pool_id,
deadline=deadline,
notebook=notebook,
@@ -354,13 +448,47 @@ def process_and_execute_notebooks(
format_timedelta(result.duration),
result.log_url,
result.output_uri,
result.output_uri_web,
result.logs_bucket,
]
for result in results_sorted
],
headers=["build_tag", "status", "duration", "log_url", "output_url"],
headers=[
"build_tag",
"status",
"duration",
"log_url",
"output_uri",
"output_uri_web",
"logs_bucket",
],
)
)
if len(notebooks) == 1:
print("=" * 100)
print("The notebook execution build log:\n")
print("=" * 100)
build_id = results_sorted[0].build_id
logs_bucket_name = (results_sorted[0].logs_bucket).removeprefix("gs://")
log_file_name = f"log-{build_id}.txt"
log_contents = util.download_blob_into_memory(
bucket_name=logs_bucket_name,
blob_name=log_file_name,
download_as_text=True,
)
# Remove extra steps from the log
match = re.search("starting Step #4", log_contents, flags=re.IGNORECASE)
if match is not None:
match_index = match.span()[0]
print(log_contents[match_index:])
else:
print(log_contents)
print("\n=== END RESULTS===\n")
total_notebook_duration = functools.reduce(
@@ -376,15 +504,5 @@ def process_and_execute_notebooks(
# Raise error if any notebooks failed
if not all([result.is_pass for result in results_sorted]):
raise RuntimeError("Notebook failures detected. See logs for details")
elif len(notebooks) == 1:
notebook = notebooks[0]
execute_notebook_helper.execute_notebook(
notebook_source=notebook,
output_file_or_uri="/".join(
[artifacts_bucket, pathlib.Path(notebook).name]
),
should_log_output=True,
)
else:
print("No notebooks modified in this pull request.")
+15 -4
View File
@@ -26,6 +26,9 @@ from utils import util
# This script is used to execute a notebook and write out the output notebook.
# This is used to force papermill to use this kernel to run the notebook instead of any defined inside the notebook itself
DEFAULT_KERNEL_NAME = "python3"
def execute_notebook(
notebook_source: str,
@@ -50,6 +53,17 @@ def execute_notebook(
execution_exception = None
print("\n=== DOWNLOAD EXECUTED NOTEBOOK ===\n")
print(f"Please debug the executed notebook by downloading the executed notebook:")
print("Option 1. Using gsutil. Run the following command in your terminal.")
print(f'\tgsutil cp "{output_file_or_uri}" .')
print("Option 2. Using this link.")
print(f"\thttps://storage.googleapis.com/{output_file_or_uri[5:]}")
print("\n======\n")
# Execute notebook
try:
# Execute notebook
@@ -58,6 +72,7 @@ def execute_notebook(
output_path=notebook_source,
progress_bar=should_log_output,
request_save_on_cell_execute=should_log_output,
kernel_name=DEFAULT_KERNEL_NAME,
log_output=should_log_output,
stdout_file=sys.stdout if should_log_output else None,
stderr_file=sys.stderr if should_log_output else None,
@@ -71,10 +86,6 @@ def execute_notebook(
util.upload_file(notebook_source, remote_file_path=output_file_or_uri)
print("\n=== EXECUTION FINISHED ===\n")
print(
f"Please debug the executed notebook by downloading: {output_file_or_uri}"
)
print("\n======\n")
else:
# Create directories if they don't exist
if not os.path.exists(os.path.dirname(output_file_or_uri)):
+5
View File
@@ -40,6 +40,7 @@ def execute_notebook_remote(
private_pool_region: Optional[str],
tag: Optional[str],
timeout_in_seconds: Optional[int] = None,
python_version: Optional[str] = None
) -> operation.Operation:
"""Create and execute a single notebook on Google Cloud Build"""
# Load build steps from YAML
@@ -50,8 +51,12 @@ def execute_notebook_remote(
"_PYTHON_IMAGE": container_uri,
"_NOTEBOOK_GCS_URI": notebook_uri,
"_NOTEBOOK_OUTPUT_GCS_URI": notebook_output_uri,
"_PYTHON_VERSION" : f"python{python_version}"
}
if python_version is not None:
substitutions["_PYTHON_VERSION"] = "python" + python_version
build = cloudbuild_v1.Build()
options: Optional[client_options.ClientOptions] = None
@@ -4,25 +4,35 @@ steps:
entrypoint: /bin/sh
args:
- -c
- 'gcloud config list'
- 'gcloud config list --quiet'
# Check the Python version
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- 'python3 .cloud-build/CheckPythonVersion.py'
- ${_PYTHON_VERSION} .cloud-build/CheckPythonVersion.py -q
# Create a virtual environment
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- ${_PYTHON_VERSION} -m venv workspace/env
# Install Python dependencies
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- 'python3 -m pip install -U pip && python3 -m pip install -U --user -r .cloud-build/requirements.txt'
- . workspace/env/bin/activate &&
python -m pip -q install -U pip &&
python -m pip -q install -U -r .cloud-build/requirements.txt
# Install Python dependencies and run testing script
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- 'python3 -m pip install -U pip && python3 -m pip freeze && python3 .cloud-build/execute_notebook_cli.py --notebook_source "${_NOTEBOOK_GCS_URI}" --output_file_or_uri "${_NOTEBOOK_OUTPUT_GCS_URI}"'
- |
. workspace/env/bin/activate &&
python .cloud-build/execute_notebook_cli.py --notebook_source "${_NOTEBOOK_GCS_URI}" --output_file_or_uri "${_NOTEBOOK_OUTPUT_GCS_URI}"
env:
- 'IS_TESTING=1'
timeout: 86400s
timeout: 86400s
@@ -4,35 +4,42 @@ steps:
entrypoint: /bin/sh
args:
- -c
- 'gcloud config list'
- gcloud config list --quiet
# Check the Python version
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- 'python3 .cloud-build/CheckPythonVersion.py'
# Fetch base branch if required
- python3 .cloud-build/CheckPythonVersion.py -q
# Fetch full repo for diff purposes
- name: gcr.io/cloud-builders/git
args: [fetch, --unshallow, --quiet]
# Create a virtual environment
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- 'if [ -n "${_BASE_BRANCH}" ]; then git fetch origin "${_BASE_BRANCH}":refs/remotes/origin/"${_BASE_BRANCH}"; else echo "Skipping fetch."; fi'
- python3 -m venv workspace/env
# Install Python dependencies
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- 'python3 -m pip install -U pip && python3 -m pip install -U --user -r .cloud-build/requirements.txt'
- . workspace/env/bin/activate &&
python3 -m pip -q install -U pip &&
python3 -m pip -q install -U -r .cloud-build/requirements.txt
# Install Python dependencies and run testing script
# TODO: Only pass in private_pool_id if it is set
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- 'python3 -m pip install -U pip && python3 -m pip freeze && 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} `if [ ! -z "${_PRIVATE_POOL_NAME}" ]; then echo "--private_pool_id ${_PRIVATE_POOL_NAME}"; fi`'
- |
. 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`
env:
- 'IS_TESTING=1'
timeout: 86400s
options:
pool:
name: ${_PRIVATE_POOL_NAME}
name: ${_PRIVATE_POOL_NAME}
+1
View File
@@ -10,3 +10,4 @@ google-cloud-aiplatform
google-cloud-storage
google-cloud-build
ratemate
GitPython
+2 -2
View File
@@ -1,5 +1,5 @@
notebooks/official/vizier/gapic-vizier-multi-objective-optimization.ipynb
notebooks/official/pipelines/lightweight_functions_component_io_kfp.ipynb
notebooks/official/matching_engine/intro-swivel.ipynb
notebooks/official/ml_metadata/sdk-metric-parameter-tracking-for-locally-trained-models.ipynb
notebooks/official/pipelines/metrics_viz_run_compare_kfp.ipynb
notebooks/official/custom/custom-tabular-bq-managed-dataset.ipynb
.cloud-build/tests/python_version_test.ipynb
+1
View File
@@ -0,0 +1 @@
notebooks/official/custom/custom-tabular-bq-managed-dataset.ipynb
@@ -0,0 +1,61 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "57a3d44ed8a8"
},
"source": [
"### Set up your Google Cloud project\n",
"\n",
"**_NOTE_**: This notebook has been tested in the following environment:\n",
"\n",
"* Python version = 3.7\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c6516f90311b"
},
"outputs": [],
"source": [
"# test if the right python version is being used\n",
"import sys\n",
"\n",
"actual_python_version = f\"{sys.version_info.major}.{sys.version_info.minor}\"\n",
"print(f\"Runtime python version: {actual_python_version}\")\n",
"\n",
"assert actual_python_version == \"3.7\", \"Wrong python version!\""
]
}
],
"metadata": {
"colab": {
"name": "python_version_test.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
+35
View File
@@ -14,6 +14,8 @@
# limitations under the License.
from typing import Dict
import random
import string
from nbconvert.preprocessors import Preprocessor
@@ -63,3 +65,36 @@ class UpdateVariablesPreprocessor(Preprocessor):
executable_cells.append(cell)
notebook.cells = executable_cells
return notebook, resources
# Generate a uuid of a specifed length
def generate_uuid(length: int = 8) -> str:
return "".join(random.choices(string.ascii_lowercase + string.digits, k=length))
class UniqueStringsPreprocessor(Preprocessor):
# A preprocessor that replaces strings that end with "-unique" or "_unique" with a uuid.
@staticmethod
def update_unique_strings(content: str):
# Replace strings that end with "-unique" or "_unique" with a uuid.
unique_id = generate_uuid()
return (
content.replace('-unique"', f'-{unique_id}"')
.replace("-unique'", f'-{unique_id}"')
.replace('_unique"', f'_{unique_id}"')
.replace("_unique'", f'_{unique_id}"')
)
def preprocess(self, notebook, resources=None):
executable_cells = []
for cell in notebook.cells:
if cell.cell_type == "code":
cell.source = self.update_unique_strings(
content=cell.source,
)
executable_cells.append(cell)
notebook.cells = executable_cells
return notebook, resources
+2 -41
View File
@@ -35,47 +35,8 @@ Variables in conditionals can also be replaced:
def get_updated_value(content: str, variable_name: str, variable_value: str) -> str:
return re.sub(
rf"({variable_name}.*?=.*?[\",\'])\[.+?\]([\",\'].*?)",
rf"\1{variable_value}\2",
rf"({variable_name}.*? = .*?[\",\'])\[.+?\]([\",\'].*?)",
rf"\g<1>{variable_value}\g<2>",
content,
flags=re.M,
)
def test_update_value():
new_content = get_updated_value(
content='asdf\nPROJECT_ID = "[your-project-id]" #@param {type:"string"} \nasdf',
variable_name="PROJECT_ID",
variable_value="sample-project",
)
assert (
new_content
== 'asdf\nPROJECT_ID = "sample-project" #@param {type:"string"} \nasdf'
)
def test_update_value_single_quotes():
new_content = get_updated_value(
content="PROJECT_ID = '[your-project-id]'",
variable_name="PROJECT_ID",
variable_value="sample-project",
)
assert new_content == "PROJECT_ID = 'sample-project'"
def test_update_value_avoidance():
new_content = get_updated_value(
content="PROJECT_ID = shell_output[0] ",
variable_name="PROJECT_ID",
variable_value="sample-project",
)
assert new_content == "PROJECT_ID = shell_output[0] "
def test_region():
new_content = get_updated_value(
content='REGION = "[your-region]" # @param {type:"string"}',
variable_name="REGION",
variable_value="us-central1",
)
assert new_content == 'REGION = "us-central1" # @param {type:"string"}'
@@ -0,0 +1,14 @@
from utils import NotebookProcessors
def test_update_value():
# Test that the content was updated
preprocessor = NotebookProcessors.UniqueStringsPreprocessor()
content = 'PROJECT_ID = "your-project-id-unique"'
new_content = preprocessor.update_unique_strings(content)
assert new_content != content
assert new_content.startswith('PROJECT_ID = "your-project-id-')
assert new_content.endswith('"')
@@ -0,0 +1,63 @@
from utils import UpdateNotebookVariables
def test_update_value():
new_content = UpdateNotebookVariables.get_updated_value(
content='asdf\nPROJECT_ID = "[your-project-id]" #@param {type:"string"} \nasdf',
variable_name="PROJECT_ID",
variable_value="sample-project",
)
assert (
new_content
== 'asdf\nPROJECT_ID = "sample-project" #@param {type:"string"} \nasdf'
)
def test_update_value_single_quotes():
new_content = UpdateNotebookVariables.get_updated_value(
content="PROJECT_ID = '[your-project-id]'",
variable_name="PROJECT_ID",
variable_value="sample-project",
)
assert new_content == "PROJECT_ID = 'sample-project'"
def test_update_value_avoidance():
new_content = UpdateNotebookVariables.get_updated_value(
content="PROJECT_ID = shell_output[0] ",
variable_name="PROJECT_ID",
variable_value="sample-project",
)
assert new_content == "PROJECT_ID = shell_output[0] "
def test_region():
new_content = UpdateNotebookVariables.get_updated_value(
content='REGION = "[your-region]" # @param {type:"string"}',
variable_name="REGION",
variable_value="us-central1",
)
assert new_content == 'REGION = "us-central1" # @param {type:"string"}'
def test_region_equal_equals_ignore():
# Tests that == is ignored
new_content = UpdateNotebookVariables.get_updated_value(
content='REGION == "[your-region]" # @param {type:"string"}',
variable_name="REGION",
variable_value="us-central1",
)
assert new_content == 'REGION == "[your-region]" # @param {type:"string"}'
def test_service_account():
# Tests that == is ignored
new_content = UpdateNotebookVariables.get_updated_value(
content='SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"}',
variable_name="SERVICE_ACCOUNT",
variable_value="12345-compute@developer.gserviceaccount.com",
)
assert (
new_content
== 'SERVICE_ACCOUNT = "12345-compute@developer.gserviceaccount.com" # @param {type:"string"}'
)
+27 -1
View File
@@ -3,7 +3,7 @@ import subprocess
import tarfile
import uuid
from datetime import datetime
from typing import Optional
from typing import Optional, Union
from google.auth import credentials as auth_credentials
from google.cloud import storage
@@ -58,3 +58,29 @@ def archive_code_and_upload(staging_bucket: str):
print(f"Uploaded source code archive to {source_archived_file_gcs}")
return source_archived_file_gcs
def download_blob_into_memory(
bucket_name: str, blob_name: str, download_as_text: Optional[bool] = False
) -> Union[bytes, str]:
"""
Downloads a blob into memory as byte or as text if
download_as_text is set to True.
"""
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
# Construct a client side representation of a blob.
blob = bucket.blob(blob_name)
# Download the blob content
if download_as_text:
contents = blob.download_as_text()
else:
contents = blob.download_as_bytes()
print(f"Downloaded storage object {blob_name} from bucket {bucket_name}.")
return contents
+13 -3
View File
@@ -1,4 +1,11 @@
If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
**REQUIRED:** Add a summary of your PR here, typically including why the change is needed and what was changed. Include any design alternatives for discussion purposes.
<br>
--- YOUR PR SUMMARY GOES HERE ---
<br><br><br>
**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [ ] Use the [notebook template](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [ ] Follow the style and grammar rules outlined in the above notebook template.
- [ ] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
@@ -7,12 +14,15 @@ If you are opening a PR for `Official Notebooks` under the [notebooks/official](
- [ ] This notebook has been added to the [CODEOWNERS](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [ ] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.
<br>
If you are opening a PR for `Community Notebooks` under the [notebooks/community](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community) folder:
2. If you are opening a PR for `Community Notebooks` under the [notebooks/community](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community) folder:
- [ ] This notebook has been added to the [CODEOWNERS](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/CODEOWNERS) file under the `Community Notebooks` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
If you are opening a PR for `Community Content` under the [community-content](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/community-content) folder:
<br>
3. If you are opening a PR for `Community Content` under the [community-content](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/community-content) folder:
- [ ] Make sure your main `Content Directory Name` is descriptive, informative, and includes some of the key products and attributes of your content, so that it is differentiable from other content
- [ ] The main content directory has been added to the [CODEOWNERS](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/community-content/CODEOWNERS) file under the `Community Content` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
+3 -1
View File
@@ -7,7 +7,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Python
uses: actions/setup-python@v3
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Fetch pull request branch
uses: actions/checkout@v3
with:
+20
View File
@@ -0,0 +1,20 @@
# To use this image, run this command with the desired notebook args from the top-level vertex-ai-samples directory:
# 1. To lint all changed notebooks:
# docker run -v ${PWD}:/setup/app gcr.io/python-docs-samples-tests/notebook_linter:latest
# 2. To lint specific notebooks:
# docker run -v ${PWD}:/setup/app gcr.io/python-docs-samples-tests/notebook_linter:latest notebooks/1.ipynb notebooks/2.ipynb
FROM python:3.10
WORKDIR setup
COPY ./requirements.txt .
COPY ./run_linter.sh .
# Install dependencies.
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
WORKDIR app
ENTRYPOINT ["/setup/run_linter.sh"]
+4 -4
View File
@@ -2,9 +2,9 @@ git+https://github.com/tensorflow/docs
ipython
jupyter
nbconvert
black==22.3.0
pyupgrade==2.31.1
black==22.10.0
pyupgrade==2.38.4
isort==5.10.1
flake8==4.0.1
nbqa==1.3.1
protobuf ==3.19.0
nbqa==1.5.3
+16 -6
View File
@@ -47,12 +47,22 @@ done
echo "Test mode: $is_test"
# Read in user-provided notebooks
notebooks=()
for arg in "$@"; do
if [[ $arg == *.ipynb ]]; then
notebooks+=("$arg")
fi
done
# Only check notebooks in test folders modified in this pull request.
# Note: Use process substitution to persist the data in the array
notebooks=()
while read -r file || [ -n "$line" ]; do
notebooks+=("$file")
done < <(git diff --name-only main... | grep '\.ipynb$')
if [ ${#notebooks[@]} -eq 0 ]; then
echo "Checking for changed notebooked using git"
while read -r file || [ -n "$line" ]; do
notebooks+=("$file")
done < <(git diff --name-only main... | grep '\.ipynb$')
fi
problematic_notebooks=()
if [ ${#notebooks[@]} -gt 0 ]; then
@@ -68,7 +78,7 @@ if [ ${#notebooks[@]} -gt 0 ]; then
if [ "$is_test" = true ]; then
echo "Running nbfmt..."
python3 -m tensorflow_docs.tools.nbfmt --remove_outputs --test "$notebook"
python3 -m tensorflow_docs.tools.nbfmt --test "$notebook"
NBFMT_RTN=$?
# echo "Running black..."
# python3 -m nbqa black "$notebook" --check
@@ -93,7 +103,7 @@ if [ ${#notebooks[@]} -gt 0 ]; then
python3 -m nbqa isort "$notebook"
ISORT_RTN=$?
echo "Running nbfmt..."
python3 -m tensorflow_docs.tools.nbfmt --remove_outputs "$notebook"
python3 -m tensorflow_docs.tools.nbfmt "$notebook"
NBFMT_RTN=$?
echo "Running flake8..."
python3 -m nbqa flake8 "$notebook" --show-source --extend-ignore=W391,E501,F821,E402,F404,W503,E203,E722,W293,W291
+1 -1
View File
@@ -48,8 +48,8 @@ then you will need to manually address them before submitting your PR.
nbqa black "$notebook"
nbqa pyupgrade "$notebook"
nbqa isort "$notebook"
python3 -m tensorflow_docs.tools.nbfmt --remove_outputs "$notebook"
nbqa flake8 "$notebook" --extend-ignore=W391,E501,F821,E402,F404,W503,E203,E722,W293,W291
python3 -m tensorflow_docs.tools.nbfmt --remove_outputs "$notebook"
```
## Code Reviews
+4
View File
@@ -1,6 +1,10 @@
* @vertex-ai-samples-contributors @GoogleCloudPlatform/cloudml-samples-owners
/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk @yinghsienwu
/pytorch_pre_built_images_deployment @googleapis/vertex-prediction-team
/pytorch_text_classification_using_vertex_sdk_and_gcloud @RajeshThallam
/pytorch_text_classification_using_vertex_sdk_and_gcloud @RajeshThallam @ultrons
/sklearn_text_classification_from_script_using_vertex_sdk @maxhardt
/pluto_on_workbench @wkharold
/cpr-examples @samthrasher
/Train_tabular_models_with_many_frameworks_and_import_to_Vertex_AI_using_Pipelines @Ark-kun
/pipeline_components @Ark-kun
@@ -0,0 +1,83 @@
name: Train tabular classification logistic regression model using Scikit learn pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_classification_logistic_regression_model_using_Scikit_learn_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":40,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":40,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":40,"y":250,"width":180,"height":54}'
Binarize column using Pandas on CSV data:
componentRef:
digest: d699afd4d7cae862708717cc160f4394ed0c04e536e9515923ef1e8865f01d44
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1e2558325f4c708aca75827c8acc13d230ee7e9f/components/pandas/Binarize_column/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
column_name: tips
predicate: '> 0'
new_column_name: class
annotations:
editor.position: '{"x":40,"y":380,"width":180,"height":54}'
Train logistic regression model using scikit learn from CSV:
componentRef:
digest: a864625a822e4b1c8ef6fe4ae1454fd90f15438f70a6712bb4c30e0dda4d35b7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/cb44b75c9c062fcc40c2b905b2024b4493dbc62b/components/ML_frameworks/Scikit_learn/Train_logistic_regression_model/from_CSV/component.yaml
arguments:
dataset:
taskOutput:
outputName: transformed_table
taskId: Binarize column using Pandas on CSV data
type: CSV
label_column_name: class
annotations:
editor.position: '{"x":40,"y":510,"width":180,"height":70}'
Upload Scikit learn pickle model to Google Cloud Vertex AI:
componentRef:
digest: 81c91c8d7d21ec97e0872f669d68bd89edea87279d703685db54aa94743bebcd
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Train logistic regression model using scikit learn from CSV
type: ScikitLearnPickleModel
annotations:
editor.position: '{"x":40,"y":660,"width":180,"height":70}'
outputValues: {}
@@ -0,0 +1,73 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
binarize_column_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Binarize_column/in_CSV_format/component.yaml")
train_logistic_regression_model_using_scikit_learn_from_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/ML_frameworks/Scikit_learn/Train_logistic_regression_model/from_CSV/component.yaml")
upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/1f5cf6e06409b704064b2086c0a705e4e6b4fcde/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/component.yaml")
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_classification_logistic_regression_model_using_Scikit_learn_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
# Deploying the model might incur additional costs over time
deploy_model = False
classification_label_column = "class"
all_columns = [label_column] + feature_columns
training_data = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
training_data = select_columns_using_Pandas_on_CSV_data_op(
table=training_data,
column_names=all_columns,
).outputs["transformed_table"]
# Cleaning the NaN values.
training_data = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=training_data,
replacement_value="0",
#replacement_type_name="float",
).outputs["transformed_table"]
classification_training_data = binarize_column_using_Pandas_on_CSV_data_op(
table=training_data,
column_name=label_column,
predicate="> 0",
new_column_name=classification_label_column,
).outputs["transformed_table"]
model = train_logistic_regression_model_using_scikit_learn_from_CSV_op(
dataset=classification_training_data,
label_column_name=classification_label_column,
# Optional:
#penalty="l2",
#solver="lbfgs",
#max_iterations=100,
#multi_class_mode="auto",
#random_seed=0,
).outputs["model"]
vertex_model_name = upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI_op(
model=model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
sklearn_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=vertex_model_name,
).outputs["endpoint_name"]
pipeline_func = train_tabular_classification_logistic_regression_model_using_Scikit_learn_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,114 @@
name: Train tabular classification model using PyTorch pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_classification_model_using_PyTorch_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":240,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":240,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":240,"y":250,"width":180,"height":54}'
Create fully connected pytorch network:
componentRef:
digest: d03d8248fd358a0275ec33568ee7dd7dce576cc112b09dfafe2651e4d97e04a9
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1a2ef3eeb77bc278f33cad0dd29008ea2431e191/components/PyTorch/Create_fully_connected_network/component.yaml
arguments:
input_size: '7'
hidden_layer_sizes: '[10]'
activation_name: elu
output_activation_name: sigmoid
annotations:
editor.position: '{"x":40,"y":360,"width":180,"height":54}'
Binarize column using Pandas on CSV data:
componentRef:
digest: d699afd4d7cae862708717cc160f4394ed0c04e536e9515923ef1e8865f01d44
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1e2558325f4c708aca75827c8acc13d230ee7e9f/components/pandas/Binarize_column/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
column_name: tips
predicate: ' > 0'
new_column_name: class
annotations:
editor.position: '{"x":240,"y":360,"width":180,"height":54}'
Train pytorch model from csv:
componentRef:
digest: 40f3185eb61e9727f41a4e0c05dd3d3b44bd802aa0f378cfc31756560033949a
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/d8c4cf5e6403bc65bcf8d606e6baf87e2528a3dc/components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Create fully connected pytorch network
type: PyTorchScriptModule
training_data:
taskOutput:
outputName: transformed_table
taskId: Binarize column using Pandas on CSV data
type: CSV
label_column_name: class
loss_function_name: binary_cross_entropy
annotations:
editor.position: '{"x":240,"y":490,"width":180,"height":40}'
Create PyTorch Model Archive with base handler:
componentRef:
digest: 8298b5ee1b0f0879f893add4cf352c8dec7cf9e21bb9db134c91a2d046cdb0ec
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/46d51383e6554b7f3ab4fd8cf614d8c2b422fb22/components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml
arguments:
Model:
taskOutput:
outputName: trained_model
taskId: Train pytorch model from csv
type: PyTorchScriptModule
Model name: model
Model version: '1.0'
annotations:
editor.position: '{"x":240,"y":590,"width":180,"height":54}'
Upload PyTorch model archive to Google Cloud Vertex AI:
componentRef:
digest: 4450212fae7b9001482aca7eb78b28413c205506eccf08a04e7754a8dfa99004
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model_archive:
taskOutput:
outputName: Model archive
taskId: Create PyTorch Model Archive with base handler
type: PyTorchModelArchive
annotations:
editor.position: '{"x":240,"y":720,"width":180,"height":70}'
outputValues: {}
@@ -0,0 +1,95 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
binarize_column_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Binarize_column/in_CSV_format/component.yaml")
create_fully_connected_pytorch_network_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Create_fully_connected_network/component.yaml")
train_pytorch_model_from_csv_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml")
create_pytorch_model_archive_with_base_handler_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml")
upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/component.yaml")
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_classification_model_using_PyTorch_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
# Deploying the model might incur additional costs over time
deploy_model = False
classification_label_column = "class"
all_columns = [label_column] + feature_columns
training_data = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
training_data = select_columns_using_Pandas_on_CSV_data_op(
table=training_data,
column_names=all_columns,
).outputs["transformed_table"]
# Cleaning the NaN values.
training_data = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=training_data,
replacement_value="0",
#replacement_type_name="float",
).outputs["transformed_table"]
classification_training_data = binarize_column_using_Pandas_on_CSV_data_op(
table=training_data,
column_name=label_column,
predicate=" > 0",
new_column_name=classification_label_column,
).outputs["transformed_table"]
network = create_fully_connected_pytorch_network_op(
input_size=len(feature_columns),
# Optional:
hidden_layer_sizes=[10],
activation_name="elu",
output_activation_name="sigmoid",
# output_size=1,
).outputs["model"]
model = train_pytorch_model_from_csv_op(
model=network,
training_data=classification_training_data,
label_column_name=classification_label_column,
loss_function_name="binary_cross_entropy",
# Optional:
#number_of_epochs=1,
#learning_rate=0.1,
#optimizer_name="Adadelta",
#optimizer_parameters={},
#batch_size=32,
#batch_log_interval=100,
#random_seed=0,
).outputs["trained_model"]
model_archive = create_pytorch_model_archive_with_base_handler_op(
model=model,
# Optional:
# model_name="model",
# model_version="1.0",
).outputs["Model archive"]
vertex_model_name = upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI_op(
model_archive=model_archive,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=vertex_model_name,
).outputs["endpoint_name"]
pipeline_func=train_tabular_classification_model_using_PyTorch_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,132 @@
name: Train tabular classification model using TensorFlow pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_classification_model_using_TensorFlow_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":40,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":40,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":40,"y":250,"width":180,"height":54}'
Binarize column using Pandas on CSV data:
componentRef:
digest: d699afd4d7cae862708717cc160f4394ed0c04e536e9515923ef1e8865f01d44
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1e2558325f4c708aca75827c8acc13d230ee7e9f/components/pandas/Binarize_column/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
column_name: tips
predicate: ' > 0'
new_column_name: class
annotations:
editor.position: '{"x":40,"y":370,"width":180,"height":54}'
Split rows into subsets:
componentRef:
digest: a609c3c9196484290f24a1174955f95b27f07a7b458aa5cb8cde28866cb2cb46
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/daae5a4abaa35e44501818b1534ed7827d7da073/components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Binarize column using Pandas on CSV data
type: CSV
fraction_1: '0.8'
annotations:
editor.position: '{"x":170,"y":500,"width":180,"height":40}'
Create fully connected tensorflow network:
componentRef:
digest: bfcafbc5ce711b1f69cabf1338212d10d50136a73db9f9f7c984de7b80b4bfb0
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/9ca0f9eecf5f896f65b8538bbd809747052617d1/components/tensorflow/Create_fully_connected_network/component.yaml
arguments:
input_size: '7'
hidden_layer_sizes: '[10]'
activation_name: elu
output_activation_name: sigmoid
annotations:
editor.position: '{"x":370,"y":500,"width":180,"height":54}'
Train model using Keras on CSV:
componentRef:
digest: 42ae60c889034dbad74815653e95b4f7d576b5f47f803173e8679c7b54984609
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c504a4010348c50eaaf6d4337586ccc008f4dcef/components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml
arguments:
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: model
taskId: Create fully connected tensorflow network
type: TensorflowSavedModel
label_column_name: class
loss_function_name: binary_crossentropy
number_of_epochs: '10'
annotations:
editor.position: '{"x":40,"y":620,"width":180,"height":54}'
Upload Tensorflow model to Google Cloud Vertex AI:
componentRef:
digest: 2e45263ff640b1a688e359b6936e27a81b2407749a84f340af2aa5547e0cb92c
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: trained_model
taskId: Train model using Keras on CSV
type: TensorflowSavedModel
annotations:
editor.position: '{"x":40,"y":750,"width":180,"height":54}'
Predict with TensorFlow model on CSV data:
componentRef:
digest: 921bb1563e93a78233b8acceab87055b9154ccf5595d056028cf0396ca224cd4
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/59c759ce6f543184e30db6817d2a703879bc0f39/components/tensorflow/Predict/on_CSV/component.yaml
arguments:
dataset:
taskOutput:
outputName: split_2
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: trained_model
taskId: Train model using Keras on CSV
type: TensorflowSavedModel
label_column_name: class
annotations:
editor.position: '{"x":240,"y":750,"width":180,"height":54}'
outputValues: {}
@@ -0,0 +1,106 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
binarize_column_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Binarize_column/in_CSV_format/component.yaml")
split_rows_into_subsets_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml")
create_fully_connected_tensorflow_network_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Create_fully_connected_network/component.yaml")
train_model_using_Keras_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml")
predict_with_TensorFlow_model_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Predict/on_CSV/component.yaml")
upload_Tensorflow_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/component.yaml")
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_classification_model_using_TensorFlow_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
training_set_fraction = 0.8
# Deploying the model might incur additional costs over time
deploy_model = False
classification_label_column = "class"
all_columns = [label_column] + feature_columns
dataset = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
dataset = select_columns_using_Pandas_on_CSV_data_op(
table=dataset,
column_names=all_columns,
).outputs["transformed_table"]
dataset = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=dataset,
replacement_value="0",
# # Optional:
# column_names=None, # =[...]
).outputs["transformed_table"]
classification_dataset = binarize_column_using_Pandas_on_CSV_data_op(
table=dataset,
column_name=label_column,
predicate=" > 0",
new_column_name=classification_label_column,
).outputs["transformed_table"]
split_task = split_rows_into_subsets_op(
table=classification_dataset,
fraction_1=training_set_fraction,
)
classification_training_data = split_task.outputs["split_1"]
classification_testing_data = split_task.outputs["split_2"]
network = create_fully_connected_tensorflow_network_op(
input_size=len(feature_columns),
# Optional:
hidden_layer_sizes=[10],
activation_name="elu",
output_activation_name="sigmoid",
# output_size=1,
).outputs["model"]
model = train_model_using_Keras_on_CSV_op(
training_data=classification_training_data,
model=network,
label_column_name=classification_label_column,
# Optional:
loss_function_name="binary_crossentropy",
number_of_epochs=10,
#learning_rate=0.1,
#optimizer_name="Adadelta",
#optimizer_parameters={},
#batch_size=32,
#metric_names=["mean_absolute_error"],
#random_seed=0,
).outputs["trained_model"]
predictions = predict_with_TensorFlow_model_on_CSV_data_op(
dataset=classification_testing_data,
model=model,
# label_column_name needs to be set when doing prediction on a dataset that has labels
label_column_name=classification_label_column,
# Optional:
# batch_size=1000,
).outputs["predictions"]
vertex_model_name = upload_Tensorflow_model_to_Google_Cloud_Vertex_AI_op(
model=model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=vertex_model_name,
).outputs["endpoint_name"]
pipeline_func = train_tabular_classification_model_using_TensorFlow_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,115 @@
name: Train tabular classification model using XGBoost pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_classification_model_using_XGBoost_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":40,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":40,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":40,"y":250,"width":180,"height":54}'
Binarize column using Pandas on CSV data:
componentRef:
digest: d699afd4d7cae862708717cc160f4394ed0c04e536e9515923ef1e8865f01d44
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1e2558325f4c708aca75827c8acc13d230ee7e9f/components/pandas/Binarize_column/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
column_name: tips
predicate: '> 0'
new_column_name: class
annotations:
editor.position: '{"x":40,"y":380,"width":180,"height":54}'
Split rows into subsets:
componentRef:
digest: a609c3c9196484290f24a1174955f95b27f07a7b458aa5cb8cde28866cb2cb46
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/daae5a4abaa35e44501818b1534ed7827d7da073/components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Binarize column using Pandas on CSV data
type: CSV
fraction_1: '0.8'
annotations:
editor.position: '{"x":170,"y":510,"width":180,"height":40}'
Train XGBoost model on CSV:
componentRef:
digest: 538c5a01eb38deaf532d619f0bbeaff4efc550fe1f0f776fc06791097b68ceac
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/58d3a47f904f32a64af8403330ba7e2134cae46d/components/XGBoost/Train/component.yaml
arguments:
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
label_column_name: class
objective: binary:logistic
annotations:
editor.position: '{"x":40,"y":630,"width":180,"height":40}'
Upload XGBoost model to Google Cloud Vertex AI:
componentRef:
digest: 5a5a273c403670743820986c03a4175b7cb4595a556524fefcce403656286977
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Train XGBoost model on CSV
type: XGBoostModel
annotations:
editor.position: '{"x":40,"y":750,"width":180,"height":54}'
Xgboost predict on CSV:
componentRef:
digest: 0876233a0c7306fefec188bd70f059b46d1fb5aa57be231799570e3bbbdd0d95
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/4694ec97baccf59284c2a1db4aa2250c22291eab/components/XGBoost/Predict/component.yaml
arguments:
data:
taskOutput:
outputName: split_2
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: model
taskId: Train XGBoost model on CSV
type: XGBoostModel
label_column_name: class
annotations:
editor.position: '{"x":240,"y":750,"width":180,"height":40}'
outputValues: {}
@@ -0,0 +1,94 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
binarize_column_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Binarize_column/in_CSV_format/component.yaml")
split_rows_into_subsets_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml")
train_XGBoost_model_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/XGBoost/Train/component.yaml")
xgboost_predict_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/XGBoost/Predict/component.yaml")
upload_XGBoost_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/component.yaml")
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_classification_model_using_XGBoost_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
training_set_fraction = 0.8
# Deploying the model might incur additional costs over time
deploy_model = False
classification_label_column = "class"
all_columns = [label_column] + feature_columns
dataset = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
dataset = select_columns_using_Pandas_on_CSV_data_op(
table=dataset,
column_names=all_columns,
).outputs["transformed_table"]
dataset = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=dataset,
replacement_value="0",
# # Optional:
# column_names=None, # =[...]
).outputs["transformed_table"]
classification_dataset = binarize_column_using_Pandas_on_CSV_data_op(
table=dataset,
column_name=label_column,
predicate="> 0",
new_column_name=classification_label_column,
).outputs["transformed_table"]
split_task = split_rows_into_subsets_op(
table=classification_dataset,
fraction_1=training_set_fraction,
)
classification_training_data = split_task.outputs["split_1"]
classification_testing_data = split_task.outputs["split_2"]
model = train_XGBoost_model_on_CSV_op(
training_data=classification_training_data,
label_column_name=classification_label_column,
objective="binary:logistic",
# Optional:
#starting_model=None,
#num_iterations=10,
#booster_params={},
#booster="gbtree",
#learning_rate=0.3,
#min_split_loss=0,
#max_depth=6,
).outputs["model"]
# Predicting on the testing data
predictions = xgboost_predict_on_CSV_op(
data=classification_testing_data,
model=model,
# label_column needs to be set when doing prediction on a dataset that has labels
label_column_name=classification_label_column,
).outputs["predictions"]
vertex_model_name = upload_XGBoost_model_to_Google_Cloud_Vertex_AI_op(
model=model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=vertex_model_name,
).outputs["endpoint_name"]
pipeline_func = train_tabular_classification_model_using_XGBoost_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,257 @@
name: Train tabular classification model using all frameworks pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_classification_model_using_all_frameworks_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":550,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":550,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":550,"y":250,"width":180,"height":54}'
Binarize column using Pandas on CSV data:
componentRef:
digest: d699afd4d7cae862708717cc160f4394ed0c04e536e9515923ef1e8865f01d44
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1e2558325f4c708aca75827c8acc13d230ee7e9f/components/pandas/Binarize_column/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
column_name: tips
predicate: ' > 0'
new_column_name: class
annotations:
editor.position: '{"x":550,"y":380,"width":180,"height":54}'
Split rows into subsets:
componentRef:
digest: a609c3c9196484290f24a1174955f95b27f07a7b458aa5cb8cde28866cb2cb46
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/daae5a4abaa35e44501818b1534ed7827d7da073/components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Binarize column using Pandas on CSV data
type: CSV
fraction_1: '0.8'
annotations:
editor.position: '{"x":550,"y":490,"width":180,"height":40}'
Create fully connected pytorch network:
componentRef:
digest: d03d8248fd358a0275ec33568ee7dd7dce576cc112b09dfafe2651e4d97e04a9
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1a2ef3eeb77bc278f33cad0dd29008ea2431e191/components/PyTorch/Create_fully_connected_network/component.yaml
arguments:
input_size: '7'
hidden_layer_sizes: '[10]'
activation_name: elu
output_activation_name: sigmoid
annotations:
editor.position: '{"x":380,"y":620,"width":180,"height":54}'
Create fully connected tensorflow network:
componentRef:
digest: bfcafbc5ce711b1f69cabf1338212d10d50136a73db9f9f7c984de7b80b4bfb0
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/9ca0f9eecf5f896f65b8538bbd809747052617d1/components/tensorflow/Create_fully_connected_network/component.yaml
arguments:
input_size: '7'
hidden_layer_sizes: '[10]'
activation_name: elu
output_activation_name: sigmoid
annotations:
editor.position: '{"x":40,"y":630,"width":180,"height":54}'
Train model using Keras on CSV:
componentRef:
digest: 42ae60c889034dbad74815653e95b4f7d576b5f47f803173e8679c7b54984609
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c504a4010348c50eaaf6d4337586ccc008f4dcef/components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml
arguments:
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: model
taskId: Create fully connected tensorflow network
type: TensorflowSavedModel
label_column_name: class
loss_function_name: binary_crossentropy
number_of_epochs: '10'
annotations:
editor.position: '{"x":40,"y":750,"width":180,"height":54}'
Train pytorch model from csv:
componentRef:
digest: 40f3185eb61e9727f41a4e0c05dd3d3b44bd802aa0f378cfc31756560033949a
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/d8c4cf5e6403bc65bcf8d606e6baf87e2528a3dc/components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Create fully connected pytorch network
type: PyTorchScriptModule
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
label_column_name: class
loss_function_name: binary_cross_entropy
annotations:
editor.position: '{"x":380,"y":750,"width":180,"height":40}'
Train XGBoost model on CSV:
componentRef:
digest: 538c5a01eb38deaf532d619f0bbeaff4efc550fe1f0f776fc06791097b68ceac
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/58d3a47f904f32a64af8403330ba7e2134cae46d/components/XGBoost/Train/component.yaml
arguments:
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
label_column_name: class
objective: binary:logistic
annotations:
editor.position: '{"x":720,"y":750,"width":180,"height":40}'
Train logistic regression model using scikit learn from CSV:
componentRef:
digest: a864625a822e4b1c8ef6fe4ae1454fd90f15438f70a6712bb4c30e0dda4d35b7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/cb44b75c9c062fcc40c2b905b2024b4493dbc62b/components/ML_frameworks/Scikit_learn/Train_logistic_regression_model/from_CSV/component.yaml
arguments:
dataset:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
label_column_name: class
annotations:
editor.position: '{"x":1030,"y":750,"width":180,"height":70}'
Predict with TensorFlow model on CSV data:
componentRef:
digest: 921bb1563e93a78233b8acceab87055b9154ccf5595d056028cf0396ca224cd4
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/59c759ce6f543184e30db6817d2a703879bc0f39/components/tensorflow/Predict/on_CSV/component.yaml
arguments:
dataset:
taskOutput:
outputName: split_2
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: trained_model
taskId: Train model using Keras on CSV
type: TensorflowSavedModel
label_column_name: class
annotations:
editor.position: '{"x":160,"y":880,"width":180,"height":54}'
Create PyTorch Model Archive with base handler:
componentRef:
digest: 8298b5ee1b0f0879f893add4cf352c8dec7cf9e21bb9db134c91a2d046cdb0ec
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/46d51383e6554b7f3ab4fd8cf614d8c2b422fb22/components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml
arguments:
Model:
taskOutput:
outputName: trained_model
taskId: Train pytorch model from csv
type: PyTorchScriptModule
Model name: model
Model version: '1.0'
annotations:
editor.position: '{"x":380,"y":880,"width":180,"height":54}'
Xgboost predict on CSV:
componentRef:
digest: 0876233a0c7306fefec188bd70f059b46d1fb5aa57be231799570e3bbbdd0d95
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/4694ec97baccf59284c2a1db4aa2250c22291eab/components/XGBoost/Predict/component.yaml
arguments:
data:
taskOutput:
outputName: split_2
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: model
taskId: Train XGBoost model on CSV
type: XGBoostModel
label_column_name: class
annotations:
editor.position: '{"x":810,"y":880,"width":180,"height":40}'
Upload Scikit learn pickle model to Google Cloud Vertex AI:
componentRef:
digest: 81c91c8d7d21ec97e0872f669d68bd89edea87279d703685db54aa94743bebcd
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Train logistic regression model using scikit learn from CSV
type: ScikitLearnPickleModel
annotations:
editor.position: '{"x":1030,"y":880,"width":180,"height":70}'
Upload Tensorflow model to Google Cloud Vertex AI:
componentRef:
digest: 2e45263ff640b1a688e359b6936e27a81b2407749a84f340af2aa5547e0cb92c
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: trained_model
taskId: Train model using Keras on CSV
type: TensorflowSavedModel
annotations:
editor.position: '{"x":40,"y":1010,"width":180,"height":54}'
Upload PyTorch model archive to Google Cloud Vertex AI:
componentRef:
digest: 4450212fae7b9001482aca7eb78b28413c205506eccf08a04e7754a8dfa99004
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model_archive:
taskOutput:
outputName: Model archive
taskId: Create PyTorch Model Archive with base handler
type: PyTorchModelArchive
annotations:
editor.position: '{"x":380,"y":1010,"width":180,"height":70}'
Upload XGBoost model to Google Cloud Vertex AI:
componentRef:
digest: 5a5a273c403670743820986c03a4175b7cb4595a556524fefcce403656286977
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Train XGBoost model on CSV
type: XGBoostModel
annotations:
editor.position: '{"x":720,"y":1010,"width":180,"height":54}'
outputValues: {}
@@ -0,0 +1,224 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
binarize_column_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Binarize_column/in_CSV_format/component.yaml")
split_rows_into_subsets_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml")
# TensorFlow
create_fully_connected_tensorflow_network_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Create_fully_connected_network/component.yaml")
train_model_using_Keras_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml")
predict_with_TensorFlow_model_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Predict/on_CSV/component.yaml")
upload_Tensorflow_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/component.yaml")
# PyTorch
create_fully_connected_pytorch_network_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Create_fully_connected_network/component.yaml")
train_pytorch_model_from_csv_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml")
create_pytorch_model_archive_with_base_handler_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml")
upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/component.yaml")
# XGBoost
train_XGBoost_model_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/XGBoost/Train/component.yaml")
xgboost_predict_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/XGBoost/Predict/component.yaml")
upload_XGBoost_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/component.yaml")
# Scikit-learn
#train_linear_regression_model_using_scikit_learn_from_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/1f5cf6e06409b704064b2086c0a705e4e6b4fcde/community-content/pipeline_components/ML_frameworks/Scikit_learn/Train_linear_regression_model/from_CSV/component.yaml")
train_logistic_regression_model_using_scikit_learn_from_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/1f5cf6e06409b704064b2086c0a705e4e6b4fcde/community-content/pipeline_components/ML_frameworks/Scikit_learn/Train_logistic_regression_model/from_CSV/component.yaml")
upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/component.yaml")
# Vertex AI
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_classification_model_using_all_frameworks_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
training_set_fraction = 0.8
# Deploying the model might incur additional costs over time
deploy_model = False
classification_label_column = "class"
all_columns = [label_column] + feature_columns
dataset = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
dataset = select_columns_using_Pandas_on_CSV_data_op(
table=dataset,
column_names=all_columns,
).outputs["transformed_table"]
dataset = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=dataset,
replacement_value="0",
# # Optional:
# column_names=None, # =[...]
).outputs["transformed_table"]
classification_dataset = binarize_column_using_Pandas_on_CSV_data_op(
table=dataset,
column_name=label_column,
predicate=" > 0",
new_column_name=classification_label_column,
).outputs["transformed_table"]
split_task = split_rows_into_subsets_op(
table=classification_dataset,
fraction_1=training_set_fraction,
)
classification_training_data = split_task.outputs["split_1"]
classification_testing_data = split_task.outputs["split_2"]
# TensorFlow
tensorflow_network = create_fully_connected_tensorflow_network_op(
input_size=len(feature_columns),
# Optional:
hidden_layer_sizes=[10],
activation_name="elu",
output_activation_name="sigmoid",
# output_size=1,
).outputs["model"]
tensorflow_model = train_model_using_Keras_on_CSV_op(
training_data=classification_training_data,
model=tensorflow_network,
label_column_name=classification_label_column,
# Optional:
loss_function_name="binary_crossentropy",
number_of_epochs=10,
#learning_rate=0.1,
#optimizer_name="Adadelta",
#optimizer_parameters={},
#batch_size=32,
#metric_names=["mean_absolute_error"],
#random_seed=0,
).outputs["trained_model"]
tensorflow_predictions = predict_with_TensorFlow_model_on_CSV_data_op(
dataset=classification_testing_data,
model=tensorflow_model,
# label_column_name needs to be set when doing prediction on a dataset that has labels
label_column_name=classification_label_column,
# Optional:
# batch_size=1000,
).outputs["predictions"]
tensorflow_vertex_model_name = upload_Tensorflow_model_to_Google_Cloud_Vertex_AI_op(
model=tensorflow_model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
tensorflow_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=tensorflow_vertex_model_name,
).outputs["endpoint_name"]
# PyTorch
pytorch_network = create_fully_connected_pytorch_network_op(
input_size=len(feature_columns),
# Optional:
hidden_layer_sizes=[10],
activation_name="elu",
output_activation_name="sigmoid",
# output_size=1,
).outputs["model"]
pytorch_model = train_pytorch_model_from_csv_op(
model=pytorch_network,
training_data=classification_training_data,
label_column_name=classification_label_column,
loss_function_name="binary_cross_entropy",
# Optional:
#number_of_epochs=1,
#learning_rate=0.1,
#optimizer_name="Adadelta",
#optimizer_parameters={},
#batch_size=32,
#batch_log_interval=100,
#random_seed=0,
).outputs["trained_model"]
pytorch_model_archive = create_pytorch_model_archive_with_base_handler_op(
model=pytorch_model,
# Optional:
# model_name="model",
# model_version="1.0",
).outputs["Model archive"]
pytorch_vertex_model_name = upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI_op(
model_archive=pytorch_model_archive,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
pytorch_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=pytorch_vertex_model_name,
).outputs["endpoint_name"]
# XGBoost
xgboost_model = train_XGBoost_model_on_CSV_op(
training_data=classification_training_data,
label_column_name=classification_label_column,
objective="binary:logistic",
# Optional:
#starting_model=None,
#num_iterations=10,
#booster_params={},
#booster="gbtree",
#learning_rate=0.3,
#min_split_loss=0,
#max_depth=6,
).outputs["model"]
# Predicting on the testing data
xgboost_predictions = xgboost_predict_on_CSV_op(
data=classification_testing_data,
model=xgboost_model,
# label_column needs to be set when doing prediction on a dataset that has labels
label_column_name=classification_label_column,
).outputs["predictions"]
xgboost_vertex_model_name = upload_XGBoost_model_to_Google_Cloud_Vertex_AI_op(
model=xgboost_model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
xgboost_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=xgboost_vertex_model_name,
).outputs["endpoint_name"]
# Scikit-learn
sklearn_model = train_logistic_regression_model_using_scikit_learn_from_CSV_op(
dataset=classification_training_data,
label_column_name=classification_label_column,
# Optional:
#penalty="l2",
#solver="lbfgs",
#max_iterations=100,
#multi_class_mode="auto",
#random_seed=0,
).outputs["model"]
sklearn_vertex_model_name = upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI_op(
model=sklearn_model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
sklearn_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=sklearn_vertex_model_name,
).outputs["endpoint_name"]
pipeline_func=train_tabular_classification_model_using_all_frameworks_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,68 @@
name: Train tabular regression linear model using Scikit learn pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_regression_linear_model_using_Scikit_learn_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":40,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":40,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":40,"y":250,"width":180,"height":54}'
Train linear regression model using scikit learn from CSV:
componentRef:
digest: c7fe7912ab0d1fb45d201d452e9ce6be5544e7d8c6d229db7a4b931ff58560f3
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/f807e02b54d4886c65a05f40848fd51c72407f40/components/ML_frameworks/Scikit_learn/Train_linear_regression_model/from_CSV/component.yaml
arguments:
dataset:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
label_column_name: tips
annotations:
editor.position: '{"x":40,"y":360,"width":180,"height":54}'
Upload Scikit learn pickle model to Google Cloud Vertex AI:
componentRef:
digest: 81c91c8d7d21ec97e0872f669d68bd89edea87279d703685db54aa94743bebcd
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Train linear regression model using scikit learn from CSV
type: ScikitLearnPickleModel
annotations:
editor.position: '{"x":40,"y":490,"width":180,"height":70}'
outputValues: {}
@@ -0,0 +1,57 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
train_linear_regression_model_using_scikit_learn_from_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/1f5cf6e06409b704064b2086c0a705e4e6b4fcde/community-content/pipeline_components/ML_frameworks/Scikit_learn/Train_linear_regression_model/from_CSV/component.yaml")
upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/component.yaml")
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_regression_linear_model_using_Scikit_learn_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
all_columns = [label_column] + feature_columns
# Deploying the model might incur additional costs over time
deploy_model = False
training_data = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
training_data = select_columns_using_Pandas_on_CSV_data_op(
table=training_data,
column_names=all_columns,
).outputs["transformed_table"]
# Cleaning the NaN values.
training_data = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=training_data,
replacement_value="0",
#replacement_type_name="float",
).outputs["transformed_table"]
model = train_linear_regression_model_using_scikit_learn_from_CSV_op(
dataset=training_data,
label_column_name=label_column,
).outputs["model"]
vertex_model_name = upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI_op(
model=model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
sklearn_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=vertex_model_name,
).outputs["endpoint_name"]
pipeline_func = train_tabular_regression_linear_model_using_Scikit_learn_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,97 @@
name: Train tabular regression model using PyTorch pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_regression_model_using_PyTorch_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":240,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":240,"y":130,"width":180,"height":54}'
Create fully connected pytorch network:
componentRef:
digest: d03d8248fd358a0275ec33568ee7dd7dce576cc112b09dfafe2651e4d97e04a9
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1a2ef3eeb77bc278f33cad0dd29008ea2431e191/components/PyTorch/Create_fully_connected_network/component.yaml
arguments:
input_size: '7'
hidden_layer_sizes: '[10]'
activation_name: elu
annotations:
editor.position: '{"x":40,"y":240,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":240,"y":240,"width":180,"height":54}'
Train pytorch model from csv:
componentRef:
digest: 40f3185eb61e9727f41a4e0c05dd3d3b44bd802aa0f378cfc31756560033949a
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/d8c4cf5e6403bc65bcf8d606e6baf87e2528a3dc/components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Create fully connected pytorch network
type: PyTorchScriptModule
training_data:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
label_column_name: tips
annotations:
editor.position: '{"x":240,"y":380,"width":180,"height":40}'
Create PyTorch Model Archive with base handler:
componentRef:
digest: 8298b5ee1b0f0879f893add4cf352c8dec7cf9e21bb9db134c91a2d046cdb0ec
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/46d51383e6554b7f3ab4fd8cf614d8c2b422fb22/components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml
arguments:
Model:
taskOutput:
outputName: trained_model
taskId: Train pytorch model from csv
type: PyTorchScriptModule
Model name: model
Model version: '1.0'
annotations:
editor.position: '{"x":240,"y":500,"width":180,"height":54}'
Upload PyTorch model archive to Google Cloud Vertex AI:
componentRef:
digest: 4450212fae7b9001482aca7eb78b28413c205506eccf08a04e7754a8dfa99004
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model_archive:
taskOutput:
outputName: Model archive
taskId: Create PyTorch Model Archive with base handler
type: PyTorchModelArchive
annotations:
editor.position: '{"x":240,"y":630,"width":180,"height":70}'
outputValues: {}
@@ -0,0 +1,85 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
create_fully_connected_pytorch_network_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Create_fully_connected_network/component.yaml")
train_pytorch_model_from_csv_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml")
create_pytorch_model_archive_with_base_handler_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml")
upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/component.yaml")
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_regression_model_using_PyTorch_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
all_columns = [label_column] + feature_columns
# Deploying the model might incur additional costs over time
deploy_model = False
training_data = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
training_data = select_columns_using_Pandas_on_CSV_data_op(
table=training_data,
column_names=all_columns,
).outputs["transformed_table"]
# Cleaning the NaN values.
training_data = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=training_data,
replacement_value="0",
#replacement_type_name="float",
).outputs["transformed_table"]
network = create_fully_connected_pytorch_network_op(
input_size=len(feature_columns),
# Optional:
hidden_layer_sizes=[10],
activation_name="elu",
# output_activation_name=None,
# output_size=1,
).outputs["model"]
model = train_pytorch_model_from_csv_op(
model=network,
training_data=training_data,
label_column_name=label_column,
# Optional:
#loss_function_name="mse_loss",
#number_of_epochs=1,
#learning_rate=0.1,
#optimizer_name="Adadelta",
#optimizer_parameters={},
#batch_size=32,
#batch_log_interval=100,
#random_seed=0,
).outputs["trained_model"]
model_archive = create_pytorch_model_archive_with_base_handler_op(
model=model,
# Optional:
# model_name="model",
# model_version="1.0",
).outputs["Model archive"]
vertex_model_name = upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI_op(
model_archive=model_archive,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=vertex_model_name,
).outputs["endpoint_name"]
pipeline_func=train_tabular_regression_model_using_PyTorch_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,116 @@
name: Train tabular regression model using Tensorflow pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_regression_model_using_TensorFlow_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":40,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":40,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":40,"y":250,"width":180,"height":54}'
Split rows into subsets:
componentRef:
digest: a609c3c9196484290f24a1174955f95b27f07a7b458aa5cb8cde28866cb2cb46
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/daae5a4abaa35e44501818b1534ed7827d7da073/components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
fraction_1: '0.8'
annotations:
editor.position: '{"x":170,"y":380,"width":180,"height":40}'
Create fully connected tensorflow network:
componentRef:
digest: bfcafbc5ce711b1f69cabf1338212d10d50136a73db9f9f7c984de7b80b4bfb0
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/9ca0f9eecf5f896f65b8538bbd809747052617d1/components/tensorflow/Create_fully_connected_network/component.yaml
arguments:
input_size: '7'
hidden_layer_sizes: '[10]'
activation_name: elu
annotations:
editor.position: '{"x":370,"y":380,"width":180,"height":54}'
Train model using Keras on CSV:
componentRef:
digest: 42ae60c889034dbad74815653e95b4f7d576b5f47f803173e8679c7b54984609
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c504a4010348c50eaaf6d4337586ccc008f4dcef/components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml
arguments:
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: model
taskId: Create fully connected tensorflow network
type: TensorflowSavedModel
label_column_name: tips
number_of_epochs: '10'
metric_names: '["mean_absolute_error"]'
annotations:
editor.position: '{"x":40,"y":500,"width":180,"height":54}'
Upload Tensorflow model to Google Cloud Vertex AI:
componentRef:
digest: 2e45263ff640b1a688e359b6936e27a81b2407749a84f340af2aa5547e0cb92c
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: trained_model
taskId: Train model using Keras on CSV
type: TensorflowSavedModel
annotations:
editor.position: '{"x":40,"y":630,"width":180,"height":54}'
Predict with TensorFlow model on CSV data:
componentRef:
digest: 921bb1563e93a78233b8acceab87055b9154ccf5595d056028cf0396ca224cd4
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/59c759ce6f543184e30db6817d2a703879bc0f39/components/tensorflow/Predict/on_CSV/component.yaml
arguments:
dataset:
taskOutput:
outputName: split_2
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: trained_model
taskId: Train model using Keras on CSV
type: TensorflowSavedModel
label_column_name: tips
annotations:
editor.position: '{"x":240,"y":630,"width":180,"height":54}'
outputValues: {}
@@ -0,0 +1,97 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
split_rows_into_subsets_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml")
create_fully_connected_tensorflow_network_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Create_fully_connected_network/component.yaml")
train_model_using_Keras_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml")
predict_with_TensorFlow_model_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Predict/on_CSV/component.yaml")
upload_Tensorflow_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/component.yaml")
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_regression_model_using_Tensorflow_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
training_set_fraction = 0.8
# Deploying the model might incur additional costs over time
deploy_model = False
all_columns = [label_column] + feature_columns
dataset = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
dataset = select_columns_using_Pandas_on_CSV_data_op(
table=dataset,
column_names=all_columns,
).outputs["transformed_table"]
dataset = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=dataset,
replacement_value="0",
# # Optional:
# column_names=None, # =[...]
).outputs["transformed_table"]
split_task = split_rows_into_subsets_op(
table=dataset,
fraction_1=training_set_fraction,
)
training_data = split_task.outputs["split_1"]
testing_data = split_task.outputs["split_2"]
network = create_fully_connected_tensorflow_network_op(
input_size=len(feature_columns),
# Optional:
hidden_layer_sizes=[10],
activation_name="elu",
# output_activation_name=None,
# output_size=1,
).outputs["model"]
model = train_model_using_Keras_on_CSV_op(
training_data=training_data,
model=network,
label_column_name=label_column,
# Optional:
#loss_function_name="mean_squared_error",
number_of_epochs=10,
#learning_rate=0.1,
#optimizer_name="Adadelta",
#optimizer_parameters={},
#batch_size=32,
metric_names=["mean_absolute_error"],
#random_seed=0,
).outputs["trained_model"]
predictions = predict_with_TensorFlow_model_on_CSV_data_op(
dataset=testing_data,
model=model,
# label_column_name needs to be set when doing prediction on a dataset that has labels
label_column_name=label_column,
# Optional:
# batch_size=1000,
).outputs["predictions"]
vertex_model_name = upload_Tensorflow_model_to_Google_Cloud_Vertex_AI_op(
model=model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=vertex_model_name,
).outputs["endpoint_name"]
pipeline_func=train_tabular_regression_model_using_Tensorflow_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,99 @@
name: Train tabular regression model using XGBoost pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_regression_model_using_XGBoost_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":40,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":40,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":40,"y":250,"width":180,"height":54}'
Split rows into subsets:
componentRef:
digest: a609c3c9196484290f24a1174955f95b27f07a7b458aa5cb8cde28866cb2cb46
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/daae5a4abaa35e44501818b1534ed7827d7da073/components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
fraction_1: '0.8'
annotations:
editor.position: '{"x":170,"y":360,"width":180,"height":40}'
Train XGBoost model on CSV:
componentRef:
digest: 538c5a01eb38deaf532d619f0bbeaff4efc550fe1f0f776fc06791097b68ceac
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/58d3a47f904f32a64af8403330ba7e2134cae46d/components/XGBoost/Train/component.yaml
arguments:
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
label_column_name: tips
annotations:
editor.position: '{"x":40,"y":480,"width":180,"height":40}'
Upload XGBoost model to Google Cloud Vertex AI:
componentRef:
digest: 5a5a273c403670743820986c03a4175b7cb4595a556524fefcce403656286977
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Train XGBoost model on CSV
type: XGBoostModel
annotations:
editor.position: '{"x":40,"y":600,"width":180,"height":54}'
Xgboost predict on CSV:
componentRef:
digest: 0876233a0c7306fefec188bd70f059b46d1fb5aa57be231799570e3bbbdd0d95
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/4694ec97baccf59284c2a1db4aa2250c22291eab/components/XGBoost/Predict/component.yaml
arguments:
data:
taskOutput:
outputName: split_2
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: model
taskId: Train XGBoost model on CSV
type: XGBoostModel
label_column_name: tips
annotations:
editor.position: '{"x":240,"y":600,"width":180,"height":40}'
outputValues: {}
@@ -0,0 +1,85 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
split_rows_into_subsets_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml")
train_XGBoost_model_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/XGBoost/Train/component.yaml")
xgboost_predict_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/XGBoost/Predict/component.yaml")
upload_XGBoost_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/component.yaml")
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_regression_model_using_XGBoost_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
training_set_fraction = 0.8
# Deploying the model might incur additional costs over time
deploy_model = False
all_columns = [label_column] + feature_columns
dataset = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
dataset = select_columns_using_Pandas_on_CSV_data_op(
table=dataset,
column_names=all_columns,
).outputs["transformed_table"]
dataset = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=dataset,
replacement_value="0",
# # Optional:
# column_names=None, # =[...]
).outputs["transformed_table"]
split_task = split_rows_into_subsets_op(
table=dataset,
fraction_1=training_set_fraction,
)
training_data = split_task.outputs["split_1"]
testing_data = split_task.outputs["split_2"]
model = train_XGBoost_model_on_CSV_op(
training_data=training_data,
label_column_name=label_column,
# Optional:
#starting_model=None,
#num_iterations=10,
#booster_params={},
#objective="reg:squarederror",
#booster="gbtree",
#learning_rate=0.3,
#min_split_loss=0,
#max_depth=6,
).outputs["model"]
# Predicting on the testing data
predictions = xgboost_predict_on_CSV_op(
data=testing_data,
model=model,
# label_column needs to be set when doing prediction on a dataset that has labels
label_column_name=label_column,
).outputs["predictions"]
vertex_model_name = upload_XGBoost_model_to_Google_Cloud_Vertex_AI_op(
model=model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=vertex_model_name,
).outputs["endpoint_name"]
pipeline_func = train_tabular_regression_model_using_XGBoost_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,238 @@
name: Train tabular regression model using all frameworks pipeline
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/samples/Google_Cloud_Vertex_AI/Train_tabular_regression_model_using_all_frameworks_and_import_to_Vertex_AI/pipeline.component.yaml
sdk: https://cloud-pipelines.net/pipeline-editor/
implementation:
graph:
tasks:
Download from GCS:
componentRef:
digest: 4175c9ff143cb8cc75d05451c0a0ebdf5a0d6d020816e29f5e9cefbb7d56f241
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/27a5ea25e849c9e8c0cb6ed65518bc3ece259aaf/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
GCS path: gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv
annotations:
editor.position: '{"x":550,"y":40,"width":180,"height":40}'
Select columns using Pandas on CSV data:
componentRef:
digest: 9b9500f461c1d04f1e48992de9138db14a6800f23649d73048673d5ea6dc56ad
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/8c78aae096806cff3bc331a40566f42f5c3e9d4b/components/pandas/Select_columns/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: Data
taskId: Download from GCS
column_names: '["tips", "trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"]'
annotations:
editor.position: '{"x":550,"y":140,"width":180,"height":54}'
Fill all missing values using Pandas on CSV data:
componentRef:
digest: a1b0c29a4615f2e3652aa5d31b9255fa15700e146627c755f8fc172f82e71af7
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/23405971f5f16a41b16c343129b893c52e4d1d48/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Select columns using Pandas on CSV data
type: CSV
replacement_value: '0'
annotations:
editor.position: '{"x":550,"y":250,"width":180,"height":54}'
Split rows into subsets:
componentRef:
digest: a609c3c9196484290f24a1174955f95b27f07a7b458aa5cb8cde28866cb2cb46
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/daae5a4abaa35e44501818b1534ed7827d7da073/components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml
arguments:
table:
taskOutput:
outputName: transformed_table
taskId: Fill all missing values using Pandas on CSV data
type: CSV
fraction_1: '0.8'
annotations:
editor.position: '{"x":550,"y":360,"width":180,"height":40}'
Create fully connected pytorch network:
componentRef:
digest: d03d8248fd358a0275ec33568ee7dd7dce576cc112b09dfafe2651e4d97e04a9
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/1a2ef3eeb77bc278f33cad0dd29008ea2431e191/components/PyTorch/Create_fully_connected_network/component.yaml
arguments:
input_size: '7'
hidden_layer_sizes: '[10]'
activation_name: elu
annotations:
editor.position: '{"x":380,"y":490,"width":180,"height":54}'
Create fully connected tensorflow network:
componentRef:
digest: bfcafbc5ce711b1f69cabf1338212d10d50136a73db9f9f7c984de7b80b4bfb0
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/9ca0f9eecf5f896f65b8538bbd809747052617d1/components/tensorflow/Create_fully_connected_network/component.yaml
arguments:
input_size: '7'
hidden_layer_sizes: '[10]'
activation_name: elu
annotations:
editor.position: '{"x":40,"y":500,"width":180,"height":54}'
Train model using Keras on CSV:
componentRef:
digest: 42ae60c889034dbad74815653e95b4f7d576b5f47f803173e8679c7b54984609
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c504a4010348c50eaaf6d4337586ccc008f4dcef/components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml
arguments:
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: model
taskId: Create fully connected tensorflow network
type: TensorflowSavedModel
label_column_name: tips
number_of_epochs: '10'
metric_names: '["mean_absolute_error"]'
annotations:
editor.position: '{"x":40,"y":620,"width":180,"height":54}'
Train pytorch model from csv:
componentRef:
digest: 40f3185eb61e9727f41a4e0c05dd3d3b44bd802aa0f378cfc31756560033949a
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/d8c4cf5e6403bc65bcf8d606e6baf87e2528a3dc/components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Create fully connected pytorch network
type: PyTorchScriptModule
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
label_column_name: tips
annotations:
editor.position: '{"x":380,"y":620,"width":180,"height":40}'
Train XGBoost model on CSV:
componentRef:
digest: 538c5a01eb38deaf532d619f0bbeaff4efc550fe1f0f776fc06791097b68ceac
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/58d3a47f904f32a64af8403330ba7e2134cae46d/components/XGBoost/Train/component.yaml
arguments:
training_data:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
label_column_name: tips
annotations:
editor.position: '{"x":720,"y":620,"width":180,"height":40}'
Train linear regression model using scikit learn from CSV:
componentRef:
digest: c7fe7912ab0d1fb45d201d452e9ce6be5544e7d8c6d229db7a4b931ff58560f3
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/f807e02b54d4886c65a05f40848fd51c72407f40/components/ML_frameworks/Scikit_learn/Train_linear_regression_model/from_CSV/component.yaml
arguments:
dataset:
taskOutput:
outputName: split_1
taskId: Split rows into subsets
type: CSV
label_column_name: tips
annotations:
editor.position: '{"x":1030,"y":620,"width":180,"height":54}'
Predict with TensorFlow model on CSV data:
componentRef:
digest: 921bb1563e93a78233b8acceab87055b9154ccf5595d056028cf0396ca224cd4
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/59c759ce6f543184e30db6817d2a703879bc0f39/components/tensorflow/Predict/on_CSV/component.yaml
arguments:
dataset:
taskOutput:
outputName: split_2
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: trained_model
taskId: Train model using Keras on CSV
type: TensorflowSavedModel
label_column_name: tips
annotations:
editor.position: '{"x":160,"y":750,"width":180,"height":54}'
Create PyTorch Model Archive with base handler:
componentRef:
digest: 8298b5ee1b0f0879f893add4cf352c8dec7cf9e21bb9db134c91a2d046cdb0ec
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/46d51383e6554b7f3ab4fd8cf614d8c2b422fb22/components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml
arguments:
Model:
taskOutput:
outputName: trained_model
taskId: Train pytorch model from csv
type: PyTorchScriptModule
Model name: model
Model version: '1.0'
annotations:
editor.position: '{"x":380,"y":750,"width":180,"height":54}'
Xgboost predict on CSV:
componentRef:
digest: 0876233a0c7306fefec188bd70f059b46d1fb5aa57be231799570e3bbbdd0d95
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/4694ec97baccf59284c2a1db4aa2250c22291eab/components/XGBoost/Predict/component.yaml
arguments:
data:
taskOutput:
outputName: split_2
taskId: Split rows into subsets
type: CSV
model:
taskOutput:
outputName: model
taskId: Train XGBoost model on CSV
type: XGBoostModel
label_column_name: tips
annotations:
editor.position: '{"x":810,"y":750,"width":180,"height":40}'
Upload Scikit learn pickle model to Google Cloud Vertex AI:
componentRef:
digest: 81c91c8d7d21ec97e0872f669d68bd89edea87279d703685db54aa94743bebcd
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Train linear regression model using scikit learn from CSV
type: ScikitLearnPickleModel
annotations:
editor.position: '{"x":1030,"y":750,"width":180,"height":70}'
Upload Tensorflow model to Google Cloud Vertex AI:
componentRef:
digest: 2e45263ff640b1a688e359b6936e27a81b2407749a84f340af2aa5547e0cb92c
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: trained_model
taskId: Train model using Keras on CSV
type: TensorflowSavedModel
annotations:
editor.position: '{"x":40,"y":880,"width":180,"height":54}'
Upload PyTorch model archive to Google Cloud Vertex AI:
componentRef:
digest: 4450212fae7b9001482aca7eb78b28413c205506eccf08a04e7754a8dfa99004
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model_archive:
taskOutput:
outputName: Model archive
taskId: Create PyTorch Model Archive with base handler
type: PyTorchModelArchive
annotations:
editor.position: '{"x":380,"y":880,"width":180,"height":70}'
Upload XGBoost model to Google Cloud Vertex AI:
componentRef:
digest: 5a5a273c403670743820986c03a4175b7cb4595a556524fefcce403656286977
url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c6a8b67d1ada2cc17665c99ff6b410df588bee28/components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/workaround_for_buggy_KFPv2_compiler/component.yaml
arguments:
model:
taskOutput:
outputName: model
taskId: Train XGBoost model on CSV
type: XGBoostModel
annotations:
editor.position: '{"x":720,"y":880,"width":180,"height":54}'
outputValues: {}
@@ -0,0 +1,208 @@
# python3 -m pip install "kfp<2.0.0" "google-cloud-aiplatform>=1.16.0" --upgrade --quiet
from kfp import components
# %% Loading components
download_from_gcs_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/storage/download/component.yaml")
select_columns_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Select_columns/in_CSV_format/component.yaml")
fill_all_missing_values_using_Pandas_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml")
split_rows_into_subsets_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml")
# TensorFlow
create_fully_connected_tensorflow_network_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Create_fully_connected_network/component.yaml")
train_model_using_Keras_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml")
predict_with_TensorFlow_model_on_CSV_data_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/tensorflow/Predict/on_CSV/component.yaml")
upload_Tensorflow_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/component.yaml")
# PyTorch
create_fully_connected_pytorch_network_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Create_fully_connected_network/component.yaml")
train_pytorch_model_from_csv_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml")
create_pytorch_model_archive_with_base_handler_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml")
upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/component.yaml")
# XGBoost
train_XGBoost_model_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/XGBoost/Train/component.yaml")
xgboost_predict_on_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/XGBoost/Predict/component.yaml")
upload_XGBoost_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/component.yaml")
# Scikit-learn
train_linear_regression_model_using_scikit_learn_from_CSV_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/1f5cf6e06409b704064b2086c0a705e4e6b4fcde/community-content/pipeline_components/ML_frameworks/Scikit_learn/Train_linear_regression_model/from_CSV/component.yaml")
upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/component.yaml")
# Vertex AI
deploy_model_to_endpoint_op = components.load_component_from_url("https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/399405402d95f4a011e2d2e967c96f8508ba5688/community-content/pipeline_components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/component.yaml")
# %% Pipeline definition
def train_tabular_regression_model_using_all_frameworks_pipeline():
dataset_gcs_uri = "gs://ml-pipeline-dataset/Chicago_taxi_trips/chicago_taxi_trips_2019-01-01_-_2019-02-01_limit=10000.csv"
feature_columns = ["trip_seconds", "trip_miles", "pickup_community_area", "dropoff_community_area", "fare", "tolls", "extras"] # Excluded "trip_total"
label_column = "tips"
training_set_fraction = 0.8
# Deploying the model might incur additional costs over time
deploy_model = False
all_columns = [label_column] + feature_columns
dataset = download_from_gcs_op(
gcs_path=dataset_gcs_uri
).outputs["Data"]
dataset = select_columns_using_Pandas_on_CSV_data_op(
table=dataset,
column_names=all_columns,
).outputs["transformed_table"]
dataset = fill_all_missing_values_using_Pandas_on_CSV_data_op(
table=dataset,
replacement_value="0",
# # Optional:
# column_names=None, # =[...]
).outputs["transformed_table"]
split_task = split_rows_into_subsets_op(
table=dataset,
fraction_1=training_set_fraction,
)
training_data = split_task.outputs["split_1"]
testing_data = split_task.outputs["split_2"]
# TensorFlow
tensorflow_network = create_fully_connected_tensorflow_network_op(
input_size=len(feature_columns),
# Optional:
hidden_layer_sizes=[10],
activation_name="elu",
# output_activation_name=None,
# output_size=1,
).outputs["model"]
tensorflow_model = train_model_using_Keras_on_CSV_op(
training_data=training_data,
model=tensorflow_network,
label_column_name=label_column,
# Optional:
#loss_function_name="mean_squared_error",
number_of_epochs=10,
#learning_rate=0.1,
#optimizer_name="Adadelta",
#optimizer_parameters={},
#batch_size=32,
metric_names=["mean_absolute_error"],
#random_seed=0,
).outputs["trained_model"]
tensorflow_predictions = predict_with_TensorFlow_model_on_CSV_data_op(
dataset=testing_data,
model=tensorflow_model,
# label_column_name needs to be set when doing prediction on a dataset that has labels
label_column_name=label_column,
# Optional:
# batch_size=1000,
).outputs["predictions"]
tensorflow_vertex_model_name = upload_Tensorflow_model_to_Google_Cloud_Vertex_AI_op(
model=tensorflow_model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
tensorflow_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=tensorflow_vertex_model_name,
).outputs["endpoint_name"]
# PyTorch
pytorch_network = create_fully_connected_pytorch_network_op(
input_size=len(feature_columns),
# Optional:
hidden_layer_sizes=[10],
activation_name="elu",
# output_activation_name=None,
# output_size=1,
).outputs["model"]
pytorch_model = train_pytorch_model_from_csv_op(
model=pytorch_network,
training_data=training_data,
label_column_name=label_column,
# Optional:
#loss_function_name="mse_loss",
#number_of_epochs=1,
#learning_rate=0.1,
#optimizer_name="Adadelta",
#optimizer_parameters={},
#batch_size=32,
#batch_log_interval=100,
#random_seed=0,
).outputs["trained_model"]
pytorch_model_archive = create_pytorch_model_archive_with_base_handler_op(
model=pytorch_model,
# Optional:
# model_name="model",
# model_version="1.0",
).outputs["Model archive"]
pytorch_vertex_model_name = upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI_op(
model_archive=pytorch_model_archive,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
pytorch_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=pytorch_vertex_model_name,
).outputs["endpoint_name"]
# XGBoost
xgboost_model = train_XGBoost_model_on_CSV_op(
training_data=training_data,
label_column_name=label_column,
# Optional:
#starting_model=None,
#num_iterations=10,
#booster_params={},
#objective="reg:squarederror",
#booster="gbtree",
#learning_rate=0.3,
#min_split_loss=0,
#max_depth=6,
).outputs["model"]
# Predicting on the testing data
xgboost_predictions = xgboost_predict_on_CSV_op(
data=testing_data,
model=xgboost_model,
# label_column needs to be set when doing prediction on a dataset that has labels
label_column_name=label_column,
).outputs["predictions"]
xgboost_vertex_model_name = upload_XGBoost_model_to_Google_Cloud_Vertex_AI_op(
model=xgboost_model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
xgboost_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=xgboost_vertex_model_name,
).outputs["endpoint_name"]
# Scikit-learn
sklearn_model = train_linear_regression_model_using_scikit_learn_from_CSV_op(
dataset=training_data,
label_column_name=label_column,
).outputs["model"]
sklearn_vertex_model_name = upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI_op(
model=sklearn_model,
).outputs["model_name"]
# Deploying the model might incur additional costs over time
if deploy_model:
sklearn_vertex_endpoint_name = deploy_model_to_endpoint_op(
model_name=sklearn_vertex_model_name,
).outputs["endpoint_name"]
pipeline_func=train_tabular_regression_model_using_all_frameworks_pipeline
# %% Pipeline submission
if __name__ == '__main__':
from google.cloud import aiplatform
aiplatform.PipelineJob.from_pipeline_func(pipeline_func=pipeline_func).submit()
@@ -0,0 +1,5 @@
testdata/*
build.py
test.py
state_dict.pth
config.json
@@ -0,0 +1,6 @@
cpr_model_server.py
entrypoint.py
state_dict.pth
config.json
**/__pycache__
!testdata/**
@@ -0,0 +1,110 @@
# CPR Example: PyTorch Image Models (timm)
## About CPR
CPR ([custom prediction routines](https://github.com/googleapis/python-aiplatform/blob/main/google/cloud/aiplatform/prediction/README.md)) is a framework designed by Google Cloud developers to make it easier to combine machine learning models with custom preprocessing and postprocessing logic in a real-time serving application.
## Using this example
This code is a self-contained example of a custom model server project built using CPR.
As is, you can use it to serve the ViT-Small image classification model from Ross Wightman's [`timm`](https://github.com/rwightman/pytorch-image-models) library of image model implementations in PyTorch. Both CPU and GPU are supported.
You can also consider using the code here as a template for your own CPR project if you want to use a different model from `timm`, a different PyTorch model, or an entirely different framework.
### Requirements
In order to use this example, you'll need Docker and Python 3 installed on your system.
To get started, first create a virtual environment in an empty directory:
```sh
mkdir cpr-example
python3 -m venv cpr-example
cd cpr-example && source bin/activate
```
Then, clone the [vertex-ai-samples repo](https://github.com/GoogleCloudPlatform/vertex-ai-samples) in that directory:
```sh
git clone https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
cd vertex-ai-samples/community-content/cpr-examples/timm_serving
```
Finally, install the Python modules required to build and run the model server:
```sh
pip install -r requirements.txt
```
### Auth
This example uses Google Cloud Storage for hosting model artifacts and Artifact Registry to store the container image.
You'll need to authorize yourself before you can interact with these.
First, log in to GCP with application default credentials:
```sh
gcloud auth application-default login
```
Next, if you haven't done so already, set up the [gcloud credential helper](https://cloud.google.com/artifact-registry/docs/docker/authentication)
for the Artifact Registry region where you intend to host the image.
```
gcloud auth configure-docker <region>-docker.pkg.dev
```
### Predictor
The `TimmPredictor` class in `timm_serving/predictor.py` implements most of the important logic for the server.
- `load(artifacts_dir)`: The predictor's `load` method is called when the server starts up in order to set up the predictor, usually by loading model weights and any artifacts needed for preprocessing and postprocessing. In this example, we initialize the saved model from the `state_dict.pth` file located inside the `artifacts_dir` folder and create the preprocessing transform from the model config.
- `preprocess`, `predict`, `postprocess`: These methods are applied in sequence to the deserialized JSON data from each request.
- `preprocess` decodes images from base64 and apply cropping, scaling and normalizing transforms.
- `predict` runs the ViT-Small model on the preprocessed images and returns class scores.
- `postprocess` finds the top five classes and packs the class names, probabilities, and indices in a serializable result.
### Building the container
To build the model server locally, run the build command:
```sh
python build.py build
```
You can edit configuration values such as the model server's base image, the name and tag assigned to the image, and the path where model weights are stored locally.
When you run the build command, model weights are downloaded and the model server container is built.
### Running local tests
`test.py` contains a suite of unit tests for the predictor as well as end-to-end tests for the model server.
To run the tests:
```sh
python test.py
```
All of the test images are public domain.
- [Cat](https://commons.wikimedia.org/wiki/File:Stray_cat_on_wall.jpg)
- [Airplane](https://commons.wikimedia.org/wiki/File:Airplanes_jets.jpg)
- The infamous [mandrill](https://commons.wikimedia.org/wiki/File:Wikipedia-sipi-image-db-mandrill-4.2.03.png)
### Deploying to Vertex AI
Before uploading or deploying the container, you'll need to modify `config.py` to set appropriate values for:
- `project_id`: Your GCP project id.
- `region`: Region where the model will be uploaded and deployed.
- `repository`: [Artifact Registry repository](https://cloud.google.com/artifact-registry/docs/repositories/create-repos) in your project where the container image will be uploaded.
- `artifacts_gcs_dir`: Folder in a [Google Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) where the model weights will be uploaded.
Once this is done, first upload the model:
```sh
python build.py upload
```
Then deploy it:
```sh
python build.py deploy
```
If you run the deploy command again, it will create a new endpoint. If you want to undeploy the model, you can do so using the Vertex AI dashboard on the Google Cloud console, or use `gcloud ai endpoints undeploy` from the command line.
After deploying successfully, you can run `python build.py probe` to send a sample request to the deployed model.
@@ -0,0 +1,117 @@
# Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Build the model server container."""
import json
import logging
import os
import pathlib
from typing import Sequence
from absl import app
from absl import logging
from config import CPRConfig
from google.cloud import aiplatform
from google.cloud.aiplatform import prediction as cpr
import smart_open
import timm
from timm_serving import predictor
import torch
def build_container(config: CPRConfig, tag: str) -> cpr.LocalModel:
"""Build the model server container.
Args:
tag: Output image tag.
Returns:
LocalModel exposing the built model server.
"""
return cpr.LocalModel.build_cpr_model(
src_dir=os.path.join(os.getcwd()),
output_image_uri=tag,
base_image=config.base_image,
predictor=predictor.TimmPredictor,
requirements_path=os.path.join(os.getcwd(), "requirements.txt"),
)
def save_model_artifact(destination: str) -> None:
"""Save a copy of the model state dict."""
model = timm.create_model(predictor.TimmPredictor.TIMM_MODEL_NAME, pretrained=True)
dest_file = os.path.join(destination, predictor.TimmPredictor.WEIGHTS_FILE)
with smart_open.open(dest_file, "wb") as f:
torch.save(model, f)
logging.info("Saved model to %s", dest_file)
logging.info("%s parameters", sum(p.numel() for p in model.parameters()))
def upload_model(config: CPRConfig) -> aiplatform.Model:
"""Tag and upload the model server."""
ar_tag = (
f"{config.region}-docker.pkg.dev/{config.project_id}"
f"/{config.repository}/{config.image}"
)
local_model = build_container(config, tag=ar_tag)
aiplatform.init(project=config.project_id, location=config.region)
local_model.push_image()
aip_model = aiplatform.Model.upload(
local_model=local_model,
display_name=predictor.TimmPredictor.TIMM_MODEL_NAME,
artifact_uri=config.artifact_gcs_dir,
)
config.model_name = aip_model.resource_name
config.save()
return aip_model
def deploy_model(config: CPRConfig) -> aiplatform.Endpoint:
"""Deploy the model server to a Vertex Prediction endpoint."""
aiplatform.init(project=config.project_id, location=config.region)
aip_model = aiplatform.Model(model_name=config.model_name)
endpoint = aip_model.deploy(machine_type=config.machine_type)
config.endpoint_name = endpoint.resource_name
config.save()
return endpoint
def probe_prediction(config: CPRConfig, request_path: str) -> None:
"""Send a sample prediction request to the Vertex Prediction endpoint."""
aiplatform.init(project=config.project_id, location=config.region)
aip_endpoint = aiplatform.Endpoint(endpoint_name=config.endpoint_name)
with open(request_path) as f:
logging.info(aip_endpoint.predict(**json.load(f)))
def main(argv: Sequence[str]):
config = CPRConfig()
if pathlib.Path(config.config_file).exists():
config.load()
actions = set(argv[1:])
if "build" in actions:
build_container(config, config.image)
save_model_artifact(config.artifact_local_dir)
if "upload" in actions:
save_model_artifact(config.artifact_gcs_dir)
upload_model(config)
if "deploy" in actions:
deploy_model(config)
if "probe" in actions:
probe_prediction(config, request_path="sample_request.json")
if __name__ == "__main__":
app.run(main)
@@ -0,0 +1,76 @@
# Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dataclasses
import json
@dataclasses.dataclass
class CPRConfig(object):
"""Configure the build process by editing the default values here.
config_file: File path used to save values in this config. (Some
values, such as the model name, are generated at build time and
depended on by future steps, so saving it allows this script to
deploy the model without re-uploading it, for example.)
base_image: Base Docker image on top of which the model server will
be built. By default, a Debian-based Python 3 image without GPU
support will be used.
image: Name and tag assigned to the built model server image.
artifact_local_dir: Local directory where a copy of the pretrained model weights
will be saved.
region: Google Cloud Region where the model will be uploaded during the
build process.
project_id: Google Cloud project ID.
repository: Name of the Artifact Registry repository where the container
will be uploaded.
artifact_gcs_dir: Location on GCS where a copy of the pretrained model
weights will be uploaded.
model_name: Full resource path of the uploaded model. This is a write-only
field, the value is generated by Vertex AI when the model is uploaded.
endpoint_name: Full resource path of the created endpoint. This is a
write-only field, the value is generated by Vertex AI when the model is
deployed to an endpoint.
machine_type: Machine type to use when deploying the model.
"""
config_file: str = "config.json"
base_image: str = "python:3.10-bullseye"
image: str = "timm_predictor:latest"
artifact_local_dir: str = ""
region: str = "us-central1"
project_id: str = "<your project ID here>"
repository: str = "cpr-images"
artifact_gcs_dir: str = "gs://<your bucket ID here>/timm-vit224/"
model_name: str = ""
endpoint_name: str = ""
machine_type: str = "n1-standard-2"
def save(self):
with open(self.config_file, "w") as f:
json.dump(dataclasses.asdict(self), f, indent=2)
def load(self):
with open(self.config_file) as f:
self.__init__(**json.load(f))
@@ -0,0 +1,8 @@
absl-py==1.1.0
fastapi==0.75.2
uvicorn==0.18.2
timm==0.5.4
smart_open==6.0.0
google-cloud-storage>=1.26.0,<2.0.0dev
google-cloud-aiplatform[prediction]>=1.16.0
File diff suppressed because one or more lines are too long
@@ -0,0 +1,255 @@
"""Test the timm_serving predictor."""
import base64
import json
import logging
import os
import pickle
from typing import List, Dict
from absl import flags
from absl import logging
from absl.testing import absltest
from config import CPRConfig
import fastapi
from google.cloud import aiplatform
from google.cloud.aiplatform import prediction as cpr
import PIL
from timm_serving import predictor
import torch
VIT_SMALL_PARAMS = 22878952
def b64_encode_file(path: str) -> str:
"""Encode a file's contents as base64.
Args:
path: Path to the file.
Returns:
Base64-encoded contents of the file.
"""
with open(path, "rb") as f:
return str(base64.b64encode(f.read()), encoding="utf-8")
def make_instance_dict(
image_paths: List[str], base64_encodings: List[str]
) -> Dict[str, List[str]]:
"""Generate a dictionary similar to a parsed prediction server request.
Args:
image_paths: Paths to image files to include.
base64_encodings: Pre-encoded base64 strings.
Returns:
Dictionary of instances in the format accepted by the preprocessor.
"""
instances = [s for s in base64_encodings]
for path in image_paths:
instances.append(b64_encode_file(path))
return {"instances": instances}
def count_parameters(model: torch.nn.Module):
"""Count the parameters in a Pytorch model.
Args:
model: Pytorch model (nn.Module).
Returns:
Number of parameters in the model.
"""
return sum(p.numel() for p in model.parameters())
class PredictorUnitTests(absltest.TestCase):
"""Unit tests for timm_serving.predictor."""
def setUp(self):
super().setUp()
self.config = CPRConfig()
try:
self.config.load()
except FileNotFoundError:
logging.info("No saved config file found, using default values.")
self.predictor = predictor.TimmPredictor()
def test_load_from_saved_state_dict_ok(self):
self.predictor.load(self.config.artifact_local_dir)
self.assertEqual(count_parameters(self.predictor._model), VIT_SMALL_PARAMS)
def test_load_bad_path(self):
with self.assertRaises(FileNotFoundError):
self.predictor.load("testdata/")
with self.assertRaisesRegex(ValueError, "not a directory"):
self.predictor.load("blah")
def test_load_bad_data(self):
with self.assertRaises(pickle.UnpicklingError):
self.predictor.load("testdata/bad_model_1")
with self.assertRaisesRegex(RuntimeError, "Invalid magic number"):
self.predictor.load("testdata/bad_model_2")
def test_preprocess_ok(self):
self.predictor.load(self.config.artifact_local_dir)
instance_dict = make_instance_dict(
base64_encodings=[],
image_paths=[
"testdata/airplane.jpg",
"testdata/mandrill.tiff",
"testdata/mandrill.tiff",
"testdata/cat_alpha.png",
],
)
result = self.predictor.preprocess(instance_dict)
self.assertEqual(result.size(), torch.Size([4, 3, 224, 224]))
self.assertEqual(result.dtype, torch.float32)
def test_preprocess_no_instances(self):
self.predictor.load(self.config.artifact_local_dir)
with self.assertRaises(fastapi.HTTPException) as ctx:
self.predictor.preprocess({})
self.assertEqual(ctx.exception.status_code, 400)
self.assertRegex(ctx.exception.detail, 'must contain "instances"')
def test_preprocess_wrong_shape_instances(self):
self.predictor.load(self.config.artifact_local_dir)
instance_dict = {"instances": [[b64_encode_file("testdata/mandrill.tiff")]]}
with self.assertRaises(fastapi.HTTPException) as ctx:
self.predictor.preprocess(instance_dict)
self.assertEqual(ctx.exception.status_code, 400)
self.assertRegex(ctx.exception.detail, "not 'list'")
def test_preprocess_bad_base64(self):
self.predictor.load(self.config.artifact_local_dir)
instance_dict = make_instance_dict(base64_encodings=["!@#$"], image_paths=[])
with self.assertRaises(fastapi.HTTPException) as ctx:
self.predictor.preprocess(instance_dict)
self.assertEqual(ctx.exception.status_code, 400)
self.assertRegex(ctx.exception.detail, "[Bb]ase64")
def test_preprocess_not_image_data(self):
self.predictor.load(self.config.artifact_local_dir)
instance_dict = make_instance_dict(
base64_encodings=[], image_paths=["testdata/bad.jpg"]
)
with self.assertRaises(fastapi.HTTPException) as ctx:
self.predictor.preprocess(instance_dict)
self.assertEqual(ctx.exception.status_code, 400)
self.assertRegex(ctx.exception.detail, "image file")
def test_predict_ok(self):
self.predictor.load(self.config.artifact_local_dir)
inputs = torch.zeros(size=[2, 3, 224, 224], dtype=torch.float32)
if torch.cuda.device_count() > 0:
inputs = inputs.cuda()
result = self.predictor.predict(inputs)
self.assertEqual(result.size(), torch.Size([2, 1000]))
self.assertEqual(result.dtype, torch.float32)
def test_postprocess_ok(self):
class_probs = torch.zeros(size=[2, 1000])
class_probs[0, 0] = 1
class_probs[1, 123] = 1
result = self.predictor.postprocess(class_probs)
predictions = result["predictions"]
self.assertLen(predictions[0]["class_names"], 5)
self.assertLen(predictions[0]["indices"], 5)
self.assertLen(predictions[0]["probabilities"], 5)
self.assertLen(predictions[1]["class_names"], 5)
self.assertLen(predictions[1]["indices"], 5)
self.assertLen(predictions[1]["probabilities"], 5)
self.assertContainsSubsequence(predictions[0]["class_names"][0], "tench")
self.assertContainsSubsequence(
predictions[1]["class_names"][0], "spiny lobster"
)
class ServerEndToEndTests(absltest.TestCase):
"""End-to-end tests for the model server, using LocalEndpoint."""
def setUp(self):
super().setUp()
self.config = CPRConfig()
try:
self.config.load()
except FileNotFoundError:
logging.info("No saved config file found, using default values.")
self.local_model = cpr.LocalModel(
serving_container_spec=aiplatform.gapic.ModelContainerSpec(
image_uri=self.config.image
)
)
self.local_endpoint = self.local_model.deploy_to_local_endpoint(
artifact_uri=self.config.artifact_local_dir or os.getcwd()
)
self.local_endpoint.serve()
def tearDown(self):
self.local_endpoint.stop()
super().tearDown()
def test_e2e_healthcheck_ok(self):
health_check_response = self.local_endpoint.run_health_check()
self.assertEqual(health_check_response.status_code, 200)
self.assertEqual(health_check_response.content, b"{}")
def test_e2e_predict_ok(self):
predict_request = json.dumps(
make_instance_dict(
base64_encodings=[],
image_paths=[
"testdata/mandrill.tiff",
],
)
)
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 200)
predictions = response.json()["predictions"]
self.assertContainsSubsequence(predictions[0]["class_names"][0], "baboon")
def test_e2e_predict_bad_json_returns_400(self):
predict_request = "blah"
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 400)
def test_e2e_predict_no_instances_returns_400(self):
predict_request = json.dumps({})
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 400)
def test_e2e_predict_bad_base64_returns_400(self):
predict_request = json.dumps(
make_instance_dict(base64_encodings=["blah"], image_paths=[])
)
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 400)
def test_e2e_predict_bad_image_returns_400(self):
predict_request = json.dumps(
make_instance_dict(base64_encodings=[], image_paths=["testdata/bad.jpg"])
)
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 400)
if __name__ == "__main__":
absltest.main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

@@ -0,0 +1 @@
some non-image data
@@ -0,0 +1 @@
some non-image data
@@ -0,0 +1 @@
blah
Binary file not shown.

After

Width:  |  Height:  |  Size: 348 KiB

File diff suppressed because it is too large Load Diff
@@ -0,0 +1,178 @@
# Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Adapts a pretrained TIMM image classification model to the CPR framework.
Documentation for the TIMM (Torch IMage Models) library is here:
https://rwightman.github.io/pytorch-image-models/
Its source can also be found here:
https://github.com/rwightman/pytorch-image-models
"""
import base64
import binascii
import io
import os
from typing import Dict, List, Union
from fastapi import HTTPException
from google.cloud.aiplatform import prediction as cpr
from pathlib import Path
import PIL
import smart_open
import timm
import torch
import torch.nn.functional as F
with open(Path(__file__).parent.absolute().joinpath("imagenet.txt")) as f:
IMAGENET_CLASSES = f.read().splitlines()
class TimmPredictor(cpr.predictor.Predictor):
"""Predictor class for image models based on TIMM."""
TIMM_MODEL_NAME = os.getenv("TIMM_MODEL_NAME", default="vit_small_patch32_224")
WEIGHTS_FILE = "state_dict.pth"
NUM_TOP_CLASSES_TO_RETURN = 5
def __init__(self):
self._cuda = torch.cuda.device_count() > 0
def load(self, artifacts_uri: str = ""):
"""Initializes the model and preprocessing transforms.
Args:
artifacts_uri: Directory where state dict is stored. Can be a
GCS URI or local path.
"""
if artifacts_uri:
artifact_path = os.path.join(artifacts_uri)
if not (os.path.isdir(artifact_path) or artifact_path.startswith("gs://")):
raise ValueError("Provided artifact_uri is not a directory.")
else:
artifact_path = os.getcwd()
artifact_path = os.path.join(artifact_path, self.WEIGHTS_FILE)
with smart_open.open(artifact_path, "rb") as f:
self._model = torch.load(f)
if self._cuda:
self._model.cuda()
config = timm.data.resolve_data_config(model=self.TIMM_MODEL_NAME, args=[])
self._transform = timm.data.create_transform(
is_training=False, use_prefetcher=False, **config
)
def preprocess(self, request_dict: Dict[str, List[str]]) -> torch.Tensor:
"""Performs preprocessing.
By default, the server expects a request body consisting of a valid JSON
object. This will be parsed by the handler before it's evaluated by the
preprocess method.
Args:
request_dict: Parsed request body. We expect that the input consists of
a list of base64-encoded image files under the "instances" key. (Any
image format that PIL.image.open can handle is okay.)
Returns:
torch.Tensor containing the preprocessed images as a batch. If GPU is
available, the result tensor will be stored on GPU.
"""
if "instances" not in request_dict:
raise HTTPException(
status_code=400,
detail='Request must contain "instances" as a top-level key.',
)
tensors = []
for (i, image) in enumerate(request_dict["instances"]):
# We use Base64 encoding to handle image data.
# This is probably the best we can do while still using JSON input.
# Overriding the input format requires building a custom Handler.
try:
image_bytes = base64.b64decode(image, validate=True)
except (binascii.Error, TypeError) as e:
raise HTTPException(
status_code=400,
detail=f"Base64 decoding of the input image at index {i} failed:"
f" {str(e)}",
)
try:
pil_image = PIL.Image.open(io.BytesIO(image_bytes)).convert("RGB")
except PIL.UnidentifiedImageError:
raise HTTPException(
status_code=400,
detail=f"The input image at index {i} could not be identified as an"
" image file.",
)
tensors.append(self._transform(pil_image))
with torch.inference_mode():
result = torch.stack(tensors)
if self._cuda:
result = result.cuda()
return result
def predict(self, instances: torch.Tensor) -> torch.Tensor:
"""Performs prediction.
Args:
instances: torch.Tensor with type torch.float32 and shape
[?, 3, 224, 224], containing the pre-processed input images.
Returns:
Vector of scores with type torch.float32 and shape [?, 1000],
representing the model's estimate of the likelihood that the
input belongs to the Imagenet class with that index.
"""
with torch.inference_mode():
class_scores = self._model(instances)
return class_scores
def postprocess(
self, class_scores: torch.Tensor
) -> Dict[str, List[Dict[str, Union[str, int, float]]]]:
"""Translate the model output into a classification result.
Args:
class_scores: torch.Tensor with type torch.float32 and shape
[?, 1000], containing the scores assigned to each class by
the model.
Returns:
Dictionary containing the list of classification results. Each
classification result contains the probabilities, class names, and
class indices of the classes with the top class scores as reported by
the model.
"""
class_probs = F.softmax(class_scores, dim=1)
top_k = class_probs.topk(self.NUM_TOP_CLASSES_TO_RETURN)
top_k_values = top_k.values.numpy().tolist()
top_k_indices = top_k.indices.numpy().tolist()
predictions = [
dict(
probabilities=values,
indices=indices,
class_names=[IMAGENET_CLASSES[int(class_num)] for class_num in indices],
)
for (values, indices) in zip(top_k_values, top_k_indices)
]
return {"predictions": predictions}
@@ -0,0 +1,64 @@
name: Train linear regression model using scikit learn from CSV
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/ML_frameworks/Scikit_learn/Train_linear_regression_model/from_CSV/component.yaml'}
inputs:
- {name: dataset, type: CSV}
- {name: label_column_name, type: String}
outputs:
- {name: model, type: ScikitLearnPickleModel}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'scikit-learn==1.0.2' 'pandas==1.4.3' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'scikit-learn==1.0.2' 'pandas==1.4.3'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def train_linear_regression_model_using_scikit_learn_from_CSV(
dataset_path,
model_path,
label_column_name,
):
import pandas
import pickle
from sklearn import linear_model
df = pandas.read_csv(dataset_path)
model = linear_model.LinearRegression()
model.fit(
X=df.drop(columns=label_column_name),
y=df[label_column_name],
)
with open(model_path, "wb") as f:
pickle.dump(model, f)
import argparse
_parser = argparse.ArgumentParser(prog='Train linear regression model using scikit learn from CSV', description='')
_parser.add_argument("--dataset", dest="dataset_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = train_linear_regression_model_using_scikit_learn_from_CSV(**_parsed_args)
args:
- --dataset
- {inputPath: dataset}
- --label-column-name
- {inputValue: label_column_name}
- --model
- {outputPath: model}
@@ -0,0 +1,163 @@
name: Train logistic regression model using scikit learn from CSV
description: Train logistic regression model using Scikit-learn
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/ML_frameworks/Scikit_learn/Train_logistic_regression_model/from_CSV/component.yaml'}
inputs:
- {name: dataset, type: CSV}
- {name: label_column_name, type: String}
- {name: penalty, type: String, default: l2, optional: true}
- {name: solver, type: String, default: lbfgs, optional: true}
- {name: max_iterations, type: Integer, default: '100', optional: true}
- {name: multi_class_mode, type: String, default: auto, optional: true}
- {name: random_seed, type: Integer, default: '0', optional: true}
outputs:
- {name: model, type: ScikitLearnPickleModel}
- {name: model_parameters, type: JsonObject}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'scikit-learn==1.0.2' 'pandas==1.4.3' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'scikit-learn==1.0.2' 'pandas==1.4.3'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def train_logistic_regression_model_using_scikit_learn_from_CSV(
dataset_path,
model_path,
label_column_name,
penalty = "l2", # l1, l2, elasticnet, none
solver = "lbfgs", # newton-cg, lbfgs, liblinear, sag, saga
max_iterations = 100,
multi_class_mode = "auto", # auto, ovr, multinomial
random_seed = 0,
):
"""Train logistic regression model using Scikit-learn
See https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html
"""
import json
import pandas
import pickle
from sklearn import linear_model
df = pandas.read_csv(dataset_path)
model = linear_model.LogisticRegression(
penalty=penalty,
#dual=False,
#tol=1e-4,
#C=1.0,
#fit_intercept=True,
#intercept_scaling=1,
#class_weight=None,
random_state=random_seed,
solver=solver,
max_iter=max_iterations,
multi_class=multi_class_mode,
#l1_ratio=None,
verbose=1,
)
model_parameters = model.get_params()
model_parameters_json = json.dumps(model_parameters, indent=2)
print("Model parameters:")
print(model_parameters_json)
print()
model.fit(
X=df.drop(columns=label_column_name),
y=df[label_column_name],
)
with open(model_path, "wb") as f:
pickle.dump(model, f)
return (model_parameters_json,)
def _serialize_json(obj) -> str:
if isinstance(obj, str):
return obj
import json
def default_serializer(obj):
if hasattr(obj, 'to_struct'):
return obj.to_struct()
else:
raise TypeError("Object of type '%s' is not JSON serializable and does not have .to_struct() method." % obj.__class__.__name__)
return json.dumps(obj, default=default_serializer, sort_keys=True)
import argparse
_parser = argparse.ArgumentParser(prog='Train logistic regression model using scikit learn from CSV', description='Train logistic regression model using Scikit-learn')
_parser.add_argument("--dataset", dest="dataset_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--penalty", dest="penalty", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--solver", dest="solver", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--max-iterations", dest="max_iterations", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--multi-class-mode", dest="multi_class_mode", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--random-seed", dest="random_seed", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parser.add_argument("----output-paths", dest="_output_paths", type=str, nargs=1)
_parsed_args = vars(_parser.parse_args())
_output_files = _parsed_args.pop("_output_paths", [])
_outputs = train_logistic_regression_model_using_scikit_learn_from_CSV(**_parsed_args)
_output_serializers = [
_serialize_json,
]
import os
for idx, output_file in enumerate(_output_files):
try:
os.makedirs(os.path.dirname(output_file))
except OSError:
pass
with open(output_file, 'w') as f:
f.write(_output_serializers[idx](_outputs[idx]))
args:
- --dataset
- {inputPath: dataset}
- --label-column-name
- {inputValue: label_column_name}
- if:
cond: {isPresent: penalty}
then:
- --penalty
- {inputValue: penalty}
- if:
cond: {isPresent: solver}
then:
- --solver
- {inputValue: solver}
- if:
cond: {isPresent: max_iterations}
then:
- --max-iterations
- {inputValue: max_iterations}
- if:
cond: {isPresent: multi_class_mode}
then:
- --multi-class-mode
- {inputValue: multi_class_mode}
- if:
cond: {isPresent: random_seed}
then:
- --random-seed
- {inputValue: random_seed}
- --model
- {outputPath: model}
- '----output-paths'
- {outputPath: model_parameters}
@@ -0,0 +1,41 @@
name: Create PyTorch Model Archive with base handler
inputs:
- {name: Model, type: PyTorchScriptModule}
- {name: Model name, type: String, default: model}
- {name: Model version, type: String, default: "1.0"}
outputs:
- {name: Model archive, type: PyTorchModelArchive}
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/PyTorch/Create_PyTorch_Model_Archive/with_base_handler/component.yaml'
implementation:
container:
image: pytorch/torchserve:0.6.0-cpu
command:
- bash
- -exc
- |
model_path=$0
model_name=$1
model_version=$2
output_model_archive_path=$3
mkdir -p "$(dirname "$output_model_archive_path")"
# TODO: Use the built-in base_handler once my fix is merged: https://github.com/pytorch/serve/pull/1682
echo '
from ts.torch_handler import base_handler
class BaseHandler(base_handler.BaseHandler):
pass
' > base_handler.py # torch-model-archiver needs the handler to have .py extension
torch-model-archiver --model-name "$model_name" --version "$model_version" --serialized-file "$model_path" --handler base_handler.py
# torch-model-archiver does not allow specifying the output path, but always writes to "${model_name}.<format>"
expected_model_archive_path="${model_name}.mar"
mv "$expected_model_archive_path" "$output_model_archive_path"
- {inputPath: Model}
- {inputValue: Model name}
- {inputValue: Model version}
- {outputPath: Model archive}
@@ -0,0 +1,117 @@
name: Create fully connected pytorch network
description: Creates fully-connected network in PyTorch ScriptModule format
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/PyTorch/Create_fully_connected_network/component.yaml'}
inputs:
- {name: input_size, type: Integer}
- {name: hidden_layer_sizes, type: JsonArray, default: '[]', optional: true}
- {name: output_size, type: Integer, default: '1', optional: true}
- {name: activation_name, type: String, default: relu, optional: true}
- {name: output_activation_name, type: String, optional: true}
- {name: random_seed, type: Integer, default: '0', optional: true}
outputs:
- {name: model, type: PyTorchScriptModule}
implementation:
container:
image: pytorch/pytorch:1.7.1-cuda11.0-cudnn8-runtime
command:
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def create_fully_connected_pytorch_network(
input_size,
model_path,
hidden_layer_sizes = [],
output_size = 1,
activation_name = 'relu',
output_activation_name = None,
random_seed = 0,
):
'''Creates fully-connected network in PyTorch ScriptModule format'''
import torch
torch.manual_seed(random_seed)
activation = getattr(torch, activation_name, None) or getattr(torch.nn.functional, activation_name, None)
if not activation:
raise ValueError(f'Activation "{activation_name}" was not found.')
class ActivationLayer(torch.nn.Module):
def forward(self, input):
return activation(input)
layers = []
prev_layer_size = input_size
for layer_size in hidden_layer_sizes:
layer = torch.nn.Linear(prev_layer_size, layer_size)
prev_layer_size = layer_size
layers.append(layer)
layers.append(ActivationLayer())
# Adding the output layer
layers.append(torch.nn.Linear(prev_layer_size, output_size))
# Adding the optional activation after the output layer
if output_activation_name:
output_activation = getattr(torch, output_activation_name, None) or getattr(torch.nn.functional, output_activation_name, None)
class OutputActivationLayer(torch.nn.Module):
def forward(self, input):
return output_activation(input)
layers.append(OutputActivationLayer())
network = torch.nn.Sequential(*layers)
script_module = torch.jit.script(network)
print(script_module)
script_module.save(model_path)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Create fully connected pytorch network', description='Creates fully-connected network in PyTorch ScriptModule format')
_parser.add_argument("--input-size", dest="input_size", type=int, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--hidden-layer-sizes", dest="hidden_layer_sizes", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--output-size", dest="output_size", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--activation-name", dest="activation_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--output-activation-name", dest="output_activation_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--random-seed", dest="random_seed", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = create_fully_connected_pytorch_network(**_parsed_args)
args:
- --input-size
- {inputValue: input_size}
- if:
cond: {isPresent: hidden_layer_sizes}
then:
- --hidden-layer-sizes
- {inputValue: hidden_layer_sizes}
- if:
cond: {isPresent: output_size}
then:
- --output-size
- {inputValue: output_size}
- if:
cond: {isPresent: activation_name}
then:
- --activation-name
- {inputValue: activation_name}
- if:
cond: {isPresent: output_activation_name}
then:
- --output-activation-name
- {inputValue: output_activation_name}
- if:
cond: {isPresent: random_seed}
then:
- --random-seed
- {inputValue: random_seed}
- --model
- {outputPath: model}
@@ -0,0 +1,209 @@
name: Train pytorch model from csv
description: Trains PyTorch model
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/PyTorch/Train_PyTorch_model/from_CSV/component.yaml'
inputs:
- {name: model, type: PyTorchScriptModule}
- {name: training_data, type: CSV}
- {name: label_column_name, type: String}
- {name: loss_function_name, type: String, default: mse_loss, optional: true}
- {name: number_of_epochs, type: Integer, default: '1', optional: true}
- {name: learning_rate, type: Float, default: '0.1', optional: true}
- {name: optimizer_name, type: String, default: Adadelta, optional: true}
- {name: optimizer_parameters, type: JsonObject, optional: true}
- {name: batch_size, type: Integer, default: '32', optional: true}
- {name: batch_log_interval, type: Integer, default: '100', optional: true}
- {name: random_seed, type: Integer, default: '0', optional: true}
outputs:
- {name: trained_model, type: PyTorchScriptModule}
implementation:
container:
image: pytorch/pytorch:1.7.1-cuda11.0-cudnn8-runtime
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'pandas==1.4.3' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet
--no-warn-script-location 'pandas==1.4.3' --user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def train_pytorch_model_from_csv(
model_path,
training_data_path,
trained_model_path,
label_column_name,
loss_function_name = 'mse_loss',
number_of_epochs = 1,
learning_rate = 0.1,
optimizer_name = 'Adadelta',
optimizer_parameters = None,
batch_size = 32,
batch_log_interval = 100,
random_seed = 0,
):
'''Trains PyTorch model'''
import pandas
import torch
torch.manual_seed(random_seed)
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
model = torch.jit.load(model_path)
model.to(device)
model.train()
optimizer_class = getattr(torch.optim, optimizer_name, None)
if not optimizer_class:
raise ValueError(f'Optimizer "{optimizer_name}" was not found.')
optimizer_parameters = optimizer_parameters or {}
optimizer_parameters['lr'] = learning_rate
optimizer = optimizer_class(model.parameters(), **optimizer_parameters)
loss_function = getattr(torch, loss_function_name, None) or getattr(torch.nn, loss_function_name, None) or getattr(torch.nn.functional, loss_function_name, None)
if not loss_function:
raise ValueError(f'Loss function "{loss_function_name}" was not found.')
class CsvDataset(torch.utils.data.Dataset):
def __init__(self, file_path, label_column_name, drop_nan_columns_or_rows = 'columns'):
dataframe = pandas.read_csv(file_path).convert_dtypes()
# Preventing error: default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found object
if drop_nan_columns_or_rows == 'columns':
non_nan_data = dataframe.dropna(axis='columns')
removed_columns = set(dataframe.columns) - set(non_nan_data.columns)
if removed_columns:
print('Skipping columns with NaNs: ' + str(removed_columns))
dataframe = non_nan_data
if drop_nan_columns_or_rows == 'rows':
non_nan_data = dataframe.dropna(axis='index')
number_of_removed_rows = len(dataframe) - len(non_nan_data)
if number_of_removed_rows:
print(f'Skipped {number_of_removed_rows} rows with NaNs.')
dataframe = non_nan_data
numerical_data = dataframe.select_dtypes(include='number')
non_numerical_data = dataframe.select_dtypes(exclude='number')
if not non_numerical_data.empty:
print('Skipping non-number columns:')
print(non_numerical_data.dtypes)
self._dataframe = dataframe
self.labels = numerical_data[[label_column_name]]
self.features = numerical_data.drop(columns=[label_column_name])
def __len__(self):
return len(self._dataframe)
def __getitem__(self, index):
return [self.features.loc[index].to_numpy(dtype='float32'), self.labels.loc[index].to_numpy(dtype='float32')]
dataset = CsvDataset(
file_path=training_data_path,
label_column_name=label_column_name,
)
train_loader = torch.utils.data.DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=True,
)
last_full_batch_loss = None
for epoch in range(1, number_of_epochs + 1):
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = loss_function(output, target)
loss.backward()
optimizer.step()
if len(data) == batch_size:
last_full_batch_loss = loss.item()
if batch_idx % batch_log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
print(f'Training epoch {epoch} completed. Last full batch loss: {last_full_batch_loss:.6f}')
# print(optimizer.state_dict())
model.save(trained_model_path)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Train pytorch model from csv', description='Trains PyTorch model')
_parser.add_argument("--model", dest="model_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--training-data", dest="training_data_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--loss-function-name", dest="loss_function_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--number-of-epochs", dest="number_of_epochs", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--learning-rate", dest="learning_rate", type=float, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--optimizer-name", dest="optimizer_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--optimizer-parameters", dest="optimizer_parameters", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--batch-size", dest="batch_size", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--batch-log-interval", dest="batch_log_interval", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--random-seed", dest="random_seed", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--trained-model", dest="trained_model_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = train_pytorch_model_from_csv(**_parsed_args)
args:
- --model
- {inputPath: model}
- --training-data
- {inputPath: training_data}
- --label-column-name
- {inputValue: label_column_name}
- if:
cond: {isPresent: loss_function_name}
then:
- --loss-function-name
- {inputValue: loss_function_name}
- if:
cond: {isPresent: number_of_epochs}
then:
- --number-of-epochs
- {inputValue: number_of_epochs}
- if:
cond: {isPresent: learning_rate}
then:
- --learning-rate
- {inputValue: learning_rate}
- if:
cond: {isPresent: optimizer_name}
then:
- --optimizer-name
- {inputValue: optimizer_name}
- if:
cond: {isPresent: optimizer_parameters}
then:
- --optimizer-parameters
- {inputValue: optimizer_parameters}
- if:
cond: {isPresent: batch_size}
then:
- --batch-size
- {inputValue: batch_size}
- if:
cond: {isPresent: batch_log_interval}
then:
- --batch-log-interval
- {inputValue: batch_log_interval}
- if:
cond: {isPresent: random_seed}
then:
- --random-seed
- {inputValue: random_seed}
- --trained-model
- {outputPath: trained_model}
@@ -0,0 +1,110 @@
name: Xgboost predict on CSV
description: Makes predictions using a trained XGBoost model.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/XGBoost/Predict/component.yaml'}
inputs:
- {name: data, type: CSV, description: Feature data in Apache Parquet format.}
- {name: model, type: XGBoostModel, description: Trained model in binary XGBoost format.}
- {name: label_column_name, type: String, description: Optional. Name of the column
containing the label data that is excluded during the prediction., optional: true}
outputs:
- {name: predictions, description: Model predictions.}
implementation:
container:
image: python:3.10
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'xgboost==1.6.1' 'pandas==1.4.3' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'xgboost==1.6.1' 'pandas==1.4.3'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def xgboost_predict_on_CSV(
data_path,
model_path,
predictions_path,
label_column_name = None,
):
"""Makes predictions using a trained XGBoost model.
Args:
data_path: Feature data in Apache Parquet format.
model_path: Trained model in binary XGBoost format.
predictions_path: Model predictions.
label_column_name: Optional. Name of the column containing the label data that is excluded during the prediction.
Annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
"""
from pathlib import Path
import numpy
import pandas
import xgboost
df = pandas.read_csv(
data_path,
).convert_dtypes()
print("Evaluation data information:")
df.info(verbose=True)
# Converting column types that XGBoost does not support
for column_name, dtype in df.dtypes.items():
if dtype in ["string", "object"]:
print(f"Treating the {dtype.name} column '{column_name}' as categorical.")
df[column_name] = df[column_name].astype("category")
print(f"Inferred {len(df[column_name].cat.categories)} categories for the '{column_name}' column.")
# Working around the XGBoost issue with nullable floats: https://github.com/dmlc/xgboost/issues/8213
if pandas.api.types.is_float_dtype(dtype):
# Converting from "Float64" to "float64"
df[column_name] = df[column_name].astype(dtype.name.lower())
print("Final evaluation data information:")
df.info(verbose=True)
if label_column_name is not None:
df = df.drop(columns=[label_column_name])
testing_data = xgboost.DMatrix(
data=df,
enable_categorical=True,
)
model = xgboost.Booster(model_file=model_path)
predictions = model.predict(testing_data)
Path(predictions_path).parent.mkdir(parents=True, exist_ok=True)
numpy.savetxt(predictions_path, predictions)
import argparse
_parser = argparse.ArgumentParser(prog='Xgboost predict on CSV', description='Makes predictions using a trained XGBoost model.')
_parser.add_argument("--data", dest="data_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--predictions", dest="predictions_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = xgboost_predict_on_CSV(**_parsed_args)
args:
- --data
- {inputPath: data}
- --model
- {inputPath: model}
- if:
cond: {isPresent: label_column_name}
then:
- --label-column-name
- {inputValue: label_column_name}
- --predictions
- {outputPath: predictions}
@@ -0,0 +1,241 @@
name: Train XGBoost model on CSV
description: Trains an XGBoost model.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/XGBoost/Train/component.yaml'}
inputs:
- {name: training_data, type: CSV, description: Training data in CSV format.}
- {name: label_column_name, type: String, description: Name of the column containing
the label data.}
- {name: starting_model, type: XGBoostModel, description: Existing trained model to
start from (in the binary XGBoost format)., optional: true}
- {name: num_iterations, type: Integer, description: Number of boosting iterations.,
default: '10', optional: true}
- name: objective
type: String
description: |-
The learning task and the corresponding learning objective.
See https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters
The most common values are:
"reg:squarederror" - Regression with squared loss (default).
"reg:logistic" - Logistic regression.
"binary:logistic" - Logistic regression for binary classification, output probability.
"binary:logitraw" - Logistic regression for binary classification, output score before logistic transformation
"rank:pairwise" - Use LambdaMART to perform pairwise ranking where the pairwise loss is minimized
"rank:ndcg" - Use LambdaMART to perform list-wise ranking where Normalized Discounted Cumulative Gain (NDCG) is maximized
default: reg:squarederror
optional: true
- {name: booster, type: String, description: 'The booster to use. Can be `gbtree`,
`gblinear` or `dart`; `gbtree` and `dart` use tree based models while `gblinear`
uses linear functions.', default: gbtree, optional: true}
- {name: learning_rate, type: Float, description: 'Step size shrinkage used in update
to prevents overfitting. Range: [0,1].', default: '0.3', optional: true}
- name: min_split_loss
type: Float
description: |-
Minimum loss reduction required to make a further partition on a leaf node of the tree.
The larger `min_split_loss` is, the more conservative the algorithm will be. Range: [0,Inf].
default: '0'
optional: true
- name: max_depth
type: Integer
description: |-
Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit.
0 indicates no limit on depth. Range: [0,Inf].
default: '6'
optional: true
- {name: booster_params, type: JsonObject, description: 'Parameters for the booster.
See https://xgboost.readthedocs.io/en/latest/parameter.html', optional: true}
outputs:
- {name: model, type: XGBoostModel, description: Trained model in the binary XGBoost
format.}
- {name: model_config, type: XGBoostModelConfig, description: The internal parameter
configuration of Booster as a JSON string.}
implementation:
container:
image: python:3.10
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'xgboost==1.6.1' 'pandas==1.4.3' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'xgboost==1.6.1' 'pandas==1.4.3'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def train_XGBoost_model_on_CSV(
training_data_path,
model_path,
model_config_path,
label_column_name,
starting_model_path = None,
num_iterations = 10,
# Booster parameters
objective = "reg:squarederror",
booster = "gbtree",
learning_rate = 0.3,
min_split_loss = 0,
max_depth = 6,
booster_params = None,
):
"""Trains an XGBoost model.
Args:
training_data_path: Training data in CSV format.
model_path: Trained model in the binary XGBoost format.
model_config_path: The internal parameter configuration of Booster as a JSON string.
starting_model_path: Existing trained model to start from (in the binary XGBoost format).
label_column_name: Name of the column containing the label data.
num_iterations: Number of boosting iterations.
booster_params: Parameters for the booster. See https://xgboost.readthedocs.io/en/latest/parameter.html
objective: The learning task and the corresponding learning objective.
See https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters
The most common values are:
"reg:squarederror" - Regression with squared loss (default).
"reg:logistic" - Logistic regression.
"binary:logistic" - Logistic regression for binary classification, output probability.
"binary:logitraw" - Logistic regression for binary classification, output score before logistic transformation
"rank:pairwise" - Use LambdaMART to perform pairwise ranking where the pairwise loss is minimized
"rank:ndcg" - Use LambdaMART to perform list-wise ranking where Normalized Discounted Cumulative Gain (NDCG) is maximized
booster: The booster to use. Can be `gbtree`, `gblinear` or `dart`; `gbtree` and `dart` use tree based models while `gblinear` uses linear functions.
learning_rate: Step size shrinkage used in update to prevents overfitting. Range: [0,1].
min_split_loss: Minimum loss reduction required to make a further partition on a leaf node of the tree.
The larger `min_split_loss` is, the more conservative the algorithm will be. Range: [0,Inf].
max_depth: Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit.
0 indicates no limit on depth. Range: [0,Inf].
Annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
"""
import pandas
import xgboost
df = pandas.read_csv(
training_data_path,
).convert_dtypes()
print("Training data information:")
df.info(verbose=True)
# Converting column types that XGBoost does not support
for column_name, dtype in df.dtypes.items():
if dtype in ["string", "object"]:
print(f"Treating the {dtype.name} column '{column_name}' as categorical.")
df[column_name] = df[column_name].astype("category")
print(f"Inferred {len(df[column_name].cat.categories)} categories for the '{column_name}' column.")
# Working around the XGBoost issue with nullable floats: https://github.com/dmlc/xgboost/issues/8213
if pandas.api.types.is_float_dtype(dtype):
# Converting from "Float64" to "float64"
df[column_name] = df[column_name].astype(dtype.name.lower())
print()
print("Final training data information:")
df.info(verbose=True)
training_data = xgboost.DMatrix(
data=df.drop(columns=[label_column_name]),
label=df[[label_column_name]],
enable_categorical=True,
)
booster_params = booster_params or {}
booster_params.setdefault("objective", objective)
booster_params.setdefault("booster", booster)
booster_params.setdefault("learning_rate", learning_rate)
booster_params.setdefault("min_split_loss", min_split_loss)
booster_params.setdefault("max_depth", max_depth)
starting_model = None
if starting_model_path:
starting_model = xgboost.Booster(model_file=starting_model_path)
print()
print("Training the model:")
model = xgboost.train(
params=booster_params,
dtrain=training_data,
num_boost_round=num_iterations,
xgb_model=starting_model,
evals=[(training_data, "training_data")],
)
# Saving the model in binary format
model.save_model(model_path)
model_config_str = model.save_config()
with open(model_config_path, "w") as model_config_file:
model_config_file.write(model_config_str)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Train XGBoost model on CSV', description='Trains an XGBoost model.')
_parser.add_argument("--training-data", dest="training_data_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--starting-model", dest="starting_model_path", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--num-iterations", dest="num_iterations", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--objective", dest="objective", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--booster", dest="booster", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--learning-rate", dest="learning_rate", type=float, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--min-split-loss", dest="min_split_loss", type=float, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--max-depth", dest="max_depth", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--booster-params", dest="booster_params", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--model-config", dest="model_config_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = train_XGBoost_model_on_CSV(**_parsed_args)
args:
- --training-data
- {inputPath: training_data}
- --label-column-name
- {inputValue: label_column_name}
- if:
cond: {isPresent: starting_model}
then:
- --starting-model
- {inputPath: starting_model}
- if:
cond: {isPresent: num_iterations}
then:
- --num-iterations
- {inputValue: num_iterations}
- if:
cond: {isPresent: objective}
then:
- --objective
- {inputValue: objective}
- if:
cond: {isPresent: booster}
then:
- --booster
- {inputValue: booster}
- if:
cond: {isPresent: learning_rate}
then:
- --learning-rate
- {inputValue: learning_rate}
- if:
cond: {isPresent: min_split_loss}
then:
- --min-split-loss
- {inputValue: min_split_loss}
- if:
cond: {isPresent: max_depth}
then:
- --max-depth
- {inputValue: max_depth}
- if:
cond: {isPresent: booster_params}
then:
- --booster-params
- {inputValue: booster_params}
- --model
- {outputPath: model}
- --model-config
- {outputPath: model_config}
@@ -0,0 +1,204 @@
name: Split rows into subsets
description: Splits the data table according to the split fractions.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/dataset_manipulation/Split_rows_into_subsets/in_CSV/component.yaml'}
inputs:
- {name: table, type: CSV}
- {name: fraction_1, type: Float, description: 'The proportion of the lines to put
into the 1st split. Range: [0, 1]'}
- name: fraction_2
type: Float
description: |-
The proportion of the lines to put into the 2nd split. Range: [0, 1]
If fraction_2 is not specified, then fraction_2 = 1 - fraction_1.
The remaining lines go to the 3rd split (if any).
optional: true
- {name: random_seed, type: Integer, default: '0', optional: true}
outputs:
- {name: split_1, type: CSV}
- {name: split_2, type: CSV}
- {name: split_3, type: CSV}
- {name: split_1_count, type: Integer}
- {name: split_2_count, type: Integer}
- {name: split_3_count, type: Integer}
implementation:
container:
image: python:3.9
command:
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def split_rows_into_subsets(
table_path,
split_1_path,
split_2_path,
split_3_path,
fraction_1,
fraction_2 = None,
random_seed = 0,
):
"""Splits the data table according to the split fractions.
Args:
fraction_1: The proportion of the lines to put into the 1st split. Range: [0, 1]
fraction_2: The proportion of the lines to put into the 2nd split. Range: [0, 1]
If fraction_2 is not specified, then fraction_2 = 1 - fraction_1.
The remaining lines go to the 3rd split (if any).
"""
import random
random.seed(random_seed)
SHUFFLE_BUFFER_SIZE = 10000
num_splits = 3
if fraction_1 < 0 or fraction_1 > 1:
raise ValueError("fraction_1 must be in between 0 and 1.")
if fraction_2 is None:
fraction_2 = 1 - fraction_1
if fraction_2 < 0 or fraction_2 > 1:
raise ValueError("fraction_2 must be in between 0 and 1.")
fraction_3 = 1 - fraction_1 - fraction_2
fractions = [
fraction_1,
fraction_2,
fraction_3,
]
assert sum(fractions) == 1
written_line_counts = [0] * num_splits
output_files = [
open(split_1_path, "wb"),
open(split_2_path, "wb"),
open(split_3_path, "wb"),
]
with open(table_path, "rb") as input_file:
# Writing the headers
header_line = input_file.readline()
for output_file in output_files:
output_file.write(header_line)
while True:
line_buffer = []
for i in range(SHUFFLE_BUFFER_SIZE):
line = input_file.readline()
if not line:
break
line_buffer.append(line)
# We need to exactly partition the lines between the output files
# To overcome possible systematic bias, we could calculate the total numbers
# of lines written to each file and take that into account.
num_read_lines = len(line_buffer)
number_of_lines_for_files = [0] * num_splits
# List that will have the index of the destination file for each line
file_index_for_line = []
remaining_lines = num_read_lines
remaining_fraction = 1
for i in range(num_splits):
number_of_lines_for_file = (
round(remaining_lines * (fractions[i] / remaining_fraction))
if remaining_fraction > 0
else 0
)
number_of_lines_for_files[i] = number_of_lines_for_file
remaining_lines -= number_of_lines_for_file
remaining_fraction -= fractions[i]
file_index_for_line.extend([i] * number_of_lines_for_file)
assert remaining_lines == 0, f"{remaining_lines}"
assert len(file_index_for_line) == num_read_lines
random.shuffle(file_index_for_line)
for i in range(num_read_lines):
output_files[file_index_for_line[i]].write(line_buffer[i])
written_line_counts[file_index_for_line[i]] += 1
# Exit if the file ended before we were able to fully fill the buffer
if len(line_buffer) != SHUFFLE_BUFFER_SIZE:
break
for output_file in output_files:
output_file.close()
return written_line_counts
def _serialize_int(int_value: int) -> str:
if isinstance(int_value, str):
return int_value
if not isinstance(int_value, int):
raise TypeError('Value "{}" has type "{}" instead of int.'.format(str(int_value), str(type(int_value))))
return str(int_value)
import argparse
_parser = argparse.ArgumentParser(prog='Split rows into subsets', description='Splits the data table according to the split fractions.')
_parser.add_argument("--table", dest="table_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--fraction-1", dest="fraction_1", type=float, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--fraction-2", dest="fraction_2", type=float, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--random-seed", dest="random_seed", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--split-1", dest="split_1_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--split-2", dest="split_2_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--split-3", dest="split_3_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parser.add_argument("----output-paths", dest="_output_paths", type=str, nargs=3)
_parsed_args = vars(_parser.parse_args())
_output_files = _parsed_args.pop("_output_paths", [])
_outputs = split_rows_into_subsets(**_parsed_args)
_output_serializers = [
_serialize_int,
_serialize_int,
_serialize_int,
]
import os
for idx, output_file in enumerate(_output_files):
try:
os.makedirs(os.path.dirname(output_file))
except OSError:
pass
with open(output_file, 'w') as f:
f.write(_output_serializers[idx](_outputs[idx]))
args:
- --table
- {inputPath: table}
- --fraction-1
- {inputValue: fraction_1}
- if:
cond: {isPresent: fraction_2}
then:
- --fraction-2
- {inputValue: fraction_2}
- if:
cond: {isPresent: random_seed}
then:
- --random-seed
- {inputValue: random_seed}
- --split-1
- {outputPath: split_1}
- --split-2
- {outputPath: split_2}
- --split-3
- {outputPath: split_3}
- '----output-paths'
- {outputPath: split_1_count}
- {outputPath: split_2_count}
- {outputPath: split_3_count}
@@ -0,0 +1,241 @@
name: Deploy model to endpoint for Google Cloud Vertex AI Model
description: Deploys Google Cloud Vertex AI Model to a Google Cloud Vertex AI Endpoint.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/KFPv2_hell/components/google-cloud/Vertex_AI/Models/Deploy_to_endpoint/workaround_for_buggy_KFPv2_compiler/component.yaml'}
inputs:
- {name: model_name, type: String, description: Full resource name of a Google Cloud
Vertex AI Model}
- name: endpoint_name
type: String
description: |-
Optional. Full name of Google Cloud Vertex Endpoint. A new
endpoint is created if the name is not passed.
optional: true
- name: machine_type
type: String
description: |-
The type of the machine. See the [list of machine types
supported for prediction
](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute#machine-types).
Defaults to "n1-standard-2"
default: n1-standard-2
optional: true
- name: min_replica_count
type: Integer
description: |-
Optional. The minimum number of machine replicas this deployed
model will be always deployed on. If traffic against it increases,
it may dynamically be deployed onto more replicas, and as traffic
decreases, some of these extra replicas may be freed.
default: '1'
optional: true
- name: max_replica_count
type: Integer
description: |-
Optional. The maximum number of replicas this deployed model may
be deployed on when the traffic against it increases. If requested
value is too large, the deployment will error, but if deployment
succeeds then the ability to scale the model to that many replicas
is guaranteed (barring service outages). If traffic against the
deployed model increases beyond what its replicas at maximum may
handle, a portion of the traffic will be dropped. If this value
is not provided, the smaller value of min_replica_count or 1 will
be used.
default: '1'
optional: true
- name: accelerator_type
type: String
description: |-
Optional. Hardware accelerator type. Must also set accelerator_count if used.
One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100,
NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4
optional: true
- {name: accelerator_count, type: Integer, description: Optional. The number of accelerators
to attach to a worker replica., optional: true}
outputs:
- {name: endpoint_name, type: String}
- {name: endpoint_dict, type: JsonObject}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'google-cloud-aiplatform==1.7.0' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'google-cloud-aiplatform==1.7.0'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def deploy_model_to_endpoint_for_Google_Cloud_Vertex_AI_Model(
model_name,
endpoint_name = None,
machine_type = "n1-standard-2",
min_replica_count = 1,
max_replica_count = 1,
accelerator_type = None,
accelerator_count = None,
#
# Uncomment when anyone requests these:
# deployed_model_display_name: str = None,
# traffic_percentage: int = 0,
# traffic_split: dict = None,
# service_account: str = None,
# explanation_metadata: "google.cloud.aiplatform_v1.types.explanation_metadata.ExplanationMetadata" = None,
# explanation_parameters: "google.cloud.aiplatform_v1.types.explanation.ExplanationParameters" = None,
#
# encryption_spec_key_name: str = None,
):
"""Deploys Google Cloud Vertex AI Model to a Google Cloud Vertex AI Endpoint.
Args:
model_name: Full resource name of a Google Cloud Vertex AI Model
endpoint_name: Optional. Full name of Google Cloud Vertex Endpoint. A new
endpoint is created if the name is not passed.
machine_type: The type of the machine. See the [list of machine types
supported for prediction
](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute#machine-types).
Defaults to "n1-standard-2"
min_replica_count (int):
Optional. The minimum number of machine replicas this deployed
model will be always deployed on. If traffic against it increases,
it may dynamically be deployed onto more replicas, and as traffic
decreases, some of these extra replicas may be freed.
max_replica_count (int):
Optional. The maximum number of replicas this deployed model may
be deployed on when the traffic against it increases. If requested
value is too large, the deployment will error, but if deployment
succeeds then the ability to scale the model to that many replicas
is guaranteed (barring service outages). If traffic against the
deployed model increases beyond what its replicas at maximum may
handle, a portion of the traffic will be dropped. If this value
is not provided, the smaller value of min_replica_count or 1 will
be used.
accelerator_type (str):
Optional. Hardware accelerator type. Must also set accelerator_count if used.
One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100,
NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4
accelerator_count (int):
Optional. The number of accelerators to attach to a worker replica.
"""
import json
from google.cloud import aiplatform
model = aiplatform.Model(model_name=model_name)
if endpoint_name:
endpoint = aiplatform.Endpoint(endpoint_name=endpoint_name)
else:
endpoint_display_name = model.display_name[:118] + "_endpoint"
endpoint = aiplatform.Endpoint.create(
display_name=endpoint_display_name,
project=model.project,
location=model.location,
# encryption_spec_key_name=encryption_spec_key_name,
labels={"component-source": "github-com-ark-kun-pipeline-components"},
)
endpoint = model.deploy(
endpoint=endpoint,
# deployed_model_display_name=deployed_model_display_name,
machine_type=machine_type,
min_replica_count=min_replica_count,
max_replica_count=max_replica_count,
accelerator_type=accelerator_type,
accelerator_count=accelerator_count,
# service_account=service_account,
# explanation_metadata=explanation_metadata,
# explanation_parameters=explanation_parameters,
# encryption_spec_key_name=encryption_spec_key_name,
)
endpoint_json = json.dumps(endpoint.to_dict(), indent=2)
print(endpoint_json)
return (endpoint.resource_name, endpoint_json)
def _serialize_json(obj) -> str:
if isinstance(obj, str):
return obj
import json
def default_serializer(obj):
if hasattr(obj, 'to_struct'):
return obj.to_struct()
else:
raise TypeError("Object of type '%s' is not JSON serializable and does not have .to_struct() method." % obj.__class__.__name__)
return json.dumps(obj, default=default_serializer, sort_keys=True)
def _serialize_str(str_value: str) -> str:
if not isinstance(str_value, str):
raise TypeError('Value "{}" has type "{}" instead of str.'.format(str(str_value), str(type(str_value))))
return str_value
import argparse
_parser = argparse.ArgumentParser(prog='Deploy model to endpoint for Google Cloud Vertex AI Model', description='Deploys Google Cloud Vertex AI Model to a Google Cloud Vertex AI Endpoint.')
_parser.add_argument("--model-name", dest="model_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--endpoint-name", dest="endpoint_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--machine-type", dest="machine_type", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--min-replica-count", dest="min_replica_count", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--max-replica-count", dest="max_replica_count", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--accelerator-type", dest="accelerator_type", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--accelerator-count", dest="accelerator_count", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("----output-paths", dest="_output_paths", type=str, nargs=2)
_parsed_args = vars(_parser.parse_args())
_output_files = _parsed_args.pop("_output_paths", [])
_outputs = deploy_model_to_endpoint_for_Google_Cloud_Vertex_AI_Model(**_parsed_args)
_output_serializers = [
_serialize_str,
_serialize_json,
]
import os
for idx, output_file in enumerate(_output_files):
try:
os.makedirs(os.path.dirname(output_file))
except OSError:
pass
with open(output_file, 'w') as f:
f.write(_output_serializers[idx](_outputs[idx]))
args:
- --model-name
- {inputValue: model_name}
- if:
cond: {isPresent: endpoint_name}
then:
- --endpoint-name
- {inputValue: endpoint_name}
- if:
cond: {isPresent: machine_type}
then:
- --machine-type
- {inputValue: machine_type}
- if:
cond: {isPresent: min_replica_count}
then:
- --min-replica-count
- {inputValue: min_replica_count}
- if:
cond: {isPresent: max_replica_count}
then:
- --max-replica-count
- {inputValue: max_replica_count}
- if:
cond: {isPresent: accelerator_type}
then:
- --accelerator-type
- {inputValue: accelerator_type}
- if:
cond: {isPresent: accelerator_count}
then:
- --accelerator-count
- {inputValue: accelerator_count}
- '----output-paths'
- {outputPath: endpoint_name}
- {outputPath: endpoint_dict}
@@ -0,0 +1,297 @@
name: Upload PyTorch model archive to Google Cloud Vertex AI
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/KFPv2_hell/components/google-cloud/Vertex_AI/Models/Upload_PyTorch_model_archive/workaround_for_buggy_KFPv2_compiler/component.yaml'}
inputs:
- {name: model_archive, type: PyTorchModelArchive}
- {name: torchserve_version, type: String, default: 0.6.0, optional: true}
- name: use_gpu
type: Boolean
default: "False"
optional: true
- {name: display_name, type: String, optional: true}
- {name: description, type: String, optional: true}
- {name: project, type: String, optional: true}
- {name: location, type: String, optional: true}
- {name: labels, type: JsonObject, optional: true}
- {name: staging_bucket, type: String, optional: true}
outputs:
- {name: model_name, type: String}
- {name: model_dict, type: JsonObject}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'google-cloud-aiplatform==1.13.1' 'google-cloud-build==3.8.3' || PIP_DISABLE_PIP_VERSION_CHECK=1
python3 -m pip install --quiet --no-warn-script-location 'google-cloud-aiplatform==1.13.1'
'google-cloud-build==3.8.3' --user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI(
model_archive_path,
torchserve_version = "0.6.0",
use_gpu = False,
display_name = None,
description = None,
# Uncomment when anyone requests these:
# instance_schema_uri: str = None,
# parameters_schema_uri: str = None,
# prediction_schema_uri: str = None,
# explanation_metadata: "google.cloud.aiplatform_v1.types.explanation_metadata.ExplanationMetadata" = None,
# explanation_parameters: "google.cloud.aiplatform_v1.types.explanation.ExplanationParameters" = None,
project = None,
location = None,
labels = None,
# encryption_spec_key_name: str = None,
staging_bucket = None,
):
import json
import os
from google.cloud import aiplatform
if not location:
location = os.environ.get("CLOUD_ML_REGION")
if not labels:
labels = {}
labels["component-source"] = "github-com-ark-kun-pipeline-components"
container_image_tag = torchserve_version + "-" + ("gpu" if use_gpu else "cpu")
container_image_uri = f"pytorch/torchserve:{container_image_tag}"
# Vertex Endpoints refuse to support non-Google container registries.
# We have to work around this to reduce user frustration
# TODO: Remove this code when Vertex Endpoints service starts supporting other container registries.
def copy_container_image(
src_container_image_uri,
dst_container_image_uri,
project_id,
):
from google.cloud.devtools import cloudbuild
from google import protobuf
build_client = cloudbuild.CloudBuildClient()
build_config = cloudbuild.Build(
images=[dst_container_image_uri],
steps=[
cloudbuild.BuildStep(
name="gcr.io/cloud-builders/docker",
entrypoint="bash",
args=[
"-exc",
'docker pull --quiet "$0" && docker tag "$0" "$1"',
src_container_image_uri,
dst_container_image_uri,
],
),
],
timeout=protobuf.duration_pb2.Duration(
seconds=1800,
),
)
build_operation = build_client.create_build(
project_id=project_id,
build=build_config,
)
try:
result = build_operation.result()
except:
print(f"Logs are available at [{build_operation.metadata.build.log_url}].")
raise
return result
project_id = aiplatform.initializer.global_config.project
mirrored_container_uri = f"gcr.io/{project_id}/container_mirror/{container_image_uri}"
# FIX: Only mirror when image does not exist
# docker does is unable to get the registry data from inside container (it cannot connecto to docker socket):
# docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
# import docker
# try:
# docker_client = docker.from_env()
# docker_client.images.get_registry_data(mirrored_container_uri)
# except docker.errors.NotFound:
if True:
print(f"Mirroring {container_image_uri} to {mirrored_container_uri}")
copy_container_image(
src_container_image_uri=container_image_uri,
dst_container_image_uri=mirrored_container_uri,
project_id=project_id,
)
container_image_uri = mirrored_container_uri
# End of container image mirroring code
model_archive_file_name = os.path.basename(model_archive_path)
model_archive_dir = os.path.dirname(model_archive_path)
model = aiplatform.Model.upload(
# FIX: Use public image or mirror the official image
#serving_container_image_uri="gcr.io/avolkov-31337/mirror/pytorch/torchserve",
serving_container_image_uri=container_image_uri,
artifact_uri=model_archive_dir,
serving_container_command=[
"bash",
"-exc",
'''
model_archive_uri="$0"
#model_archive_local_path=$(mktemp --suffix ".mar")
# For some reason the model must already be inside the model-store directory.
model_archive_local_path=./model-store/model.mar
# Downloading the model archive from GCS
# TODO: Fix gsutil bugs (requires project ID, has auth issues) and use gsutil instead.
# gsutil cp "$model_archive_uri" "$model_archive_local_path"
pip install google-cloud-storage
python -c '
import sys
from google.cloud import storage
model_archive_uri = sys.argv[1]
model_archive_local_path = sys.argv[2]
storage_client = storage.Client()
blob = storage.Blob.from_string(uri=model_archive_uri, client=storage_client)
blob.download_to_filename(filename=model_archive_local_path)
' "$model_archive_uri" "$model_archive_local_path"
#Note: config.properties is owned by root. Our user is not root.
echo "
service_envelope=json
# Needed for external access
inference_address=http://0.0.0.0:8080
management_address=http://0.0.0.0:8081
" > config2.properties
torchserve --start --foreground --no-config-snapshots --models main-model="$model_archive_local_path" --model-store ./model-store/ --ts-config config2.properties
''',
"$(AIP_STORAGE_URI)/" + model_archive_file_name,
],
serving_container_predict_route="/predictions/main-model",
#serving_container_predict_route="/v1/models/main-model:predict",
serving_container_health_route="/ping",
serving_container_ports=[8080],
display_name=display_name,
description=description,
# instance_schema_uri=instance_schema_uri,
# parameters_schema_uri=parameters_schema_uri,
# prediction_schema_uri=prediction_schema_uri,
# explanation_metadata=explanation_metadata,
# explanation_parameters=explanation_parameters,
project=project,
location=location,
labels=labels,
# encryption_spec_key_name=encryption_spec_key_name,
staging_bucket=staging_bucket,
)
model_json = json.dumps(model.to_dict(), indent=2)
print(model_json)
return (model.resource_name, model_json)
def _deserialize_bool(s) -> bool:
from distutils.util import strtobool
return strtobool(s) == 1
def _serialize_json(obj) -> str:
if isinstance(obj, str):
return obj
import json
def default_serializer(obj):
if hasattr(obj, 'to_struct'):
return obj.to_struct()
else:
raise TypeError("Object of type '%s' is not JSON serializable and does not have .to_struct() method." % obj.__class__.__name__)
return json.dumps(obj, default=default_serializer, sort_keys=True)
def _serialize_str(str_value: str) -> str:
if not isinstance(str_value, str):
raise TypeError('Value "{}" has type "{}" instead of str.'.format(str(str_value), str(type(str_value))))
return str_value
import json
import argparse
_parser = argparse.ArgumentParser(prog='Upload PyTorch model archive to Google Cloud Vertex AI', description='')
_parser.add_argument("--model-archive", dest="model_archive_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--torchserve-version", dest="torchserve_version", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--use-gpu", dest="use_gpu", type=_deserialize_bool, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--display-name", dest="display_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--description", dest="description", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--project", dest="project", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--location", dest="location", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--labels", dest="labels", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--staging-bucket", dest="staging_bucket", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("----output-paths", dest="_output_paths", type=str, nargs=2)
_parsed_args = vars(_parser.parse_args())
_output_files = _parsed_args.pop("_output_paths", [])
_outputs = upload_PyTorch_model_archive_to_Google_Cloud_Vertex_AI(**_parsed_args)
_output_serializers = [
_serialize_str,
_serialize_json,
]
import os
for idx, output_file in enumerate(_output_files):
try:
os.makedirs(os.path.dirname(output_file))
except OSError:
pass
with open(output_file, 'w') as f:
f.write(_output_serializers[idx](_outputs[idx]))
args:
- --model-archive
- {inputPath: model_archive}
- if:
cond: {isPresent: torchserve_version}
then:
- --torchserve-version
- {inputValue: torchserve_version}
- if:
cond: {isPresent: use_gpu}
then:
- --use-gpu
- {inputValue: use_gpu}
- if:
cond: {isPresent: display_name}
then:
- --display-name
- {inputValue: display_name}
- if:
cond: {isPresent: description}
then:
- --description
- {inputValue: description}
- if:
cond: {isPresent: project}
then:
- --project
- {inputValue: project}
- if:
cond: {isPresent: location}
then:
- --location
- {inputValue: location}
- if:
cond: {isPresent: labels}
then:
- --labels
- {inputValue: labels}
- if:
cond: {isPresent: staging_bucket}
then:
- --staging-bucket
- {inputValue: staging_bucket}
- '----output-paths'
- {outputPath: model_name}
- {outputPath: model_dict}
@@ -0,0 +1,181 @@
name: Upload Scikit learn pickle model to Google Cloud Vertex AI
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/KFPv2_hell/components/google-cloud/Vertex_AI/Models/Upload_Scikit-learn_pickle_model/workaround_for_buggy_KFPv2_compiler/component.yaml'}
inputs:
- {name: model, type: ScikitLearnPickleModel}
- {name: sklearn_version, type: String, optional: true}
- {name: display_name, type: String, optional: true}
- {name: description, type: String, optional: true}
- {name: project, type: String, optional: true}
- {name: location, type: String, optional: true}
- {name: labels, type: JsonObject, optional: true}
- {name: staging_bucket, type: String, optional: true}
outputs:
- {name: model_name, type: String}
- {name: model_dict, type: JsonObject}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'google-cloud-aiplatform==1.16.0' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'google-cloud-aiplatform==1.16.0'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI(
model_path,
sklearn_version = None,
display_name = None,
description = None,
# Uncomment when anyone requests these:
# instance_schema_uri: str = None,
# parameters_schema_uri: str = None,
# prediction_schema_uri: str = None,
# explanation_metadata: "google.cloud.aiplatform_v1.types.explanation_metadata.ExplanationMetadata" = None,
# explanation_parameters: "google.cloud.aiplatform_v1.types.explanation.ExplanationParameters" = None,
project = None,
location = None,
labels = None,
# encryption_spec_key_name: str = None,
staging_bucket = None,
):
import json
import os
import shutil
import tempfile
from google.cloud import aiplatform
if not location:
location = os.environ.get("CLOUD_ML_REGION")
if not labels:
labels = {}
labels["component-source"] = "github-com-ark-kun-pipeline-components"
# The serving container decides the model type based on the model file extension.
# So we need to rename the mode file (e.g. /tmp/inputs/model/data) to *.pkl
_, renamed_model_path = tempfile.mkstemp(suffix=".pkl")
shutil.copyfile(src=model_path, dst=renamed_model_path)
model = aiplatform.Model.upload_scikit_learn_model_file(
model_file_path=renamed_model_path,
sklearn_version=sklearn_version,
display_name=display_name,
description=description,
# instance_schema_uri=instance_schema_uri,
# parameters_schema_uri=parameters_schema_uri,
# prediction_schema_uri=prediction_schema_uri,
# explanation_metadata=explanation_metadata,
# explanation_parameters=explanation_parameters,
project=project,
location=location,
labels=labels,
# encryption_spec_key_name=encryption_spec_key_name,
staging_bucket=staging_bucket,
)
model_json = json.dumps(model.to_dict(), indent=2)
print(model_json)
return (model.resource_name, model_json)
def _serialize_json(obj) -> str:
if isinstance(obj, str):
return obj
import json
def default_serializer(obj):
if hasattr(obj, 'to_struct'):
return obj.to_struct()
else:
raise TypeError("Object of type '%s' is not JSON serializable and does not have .to_struct() method." % obj.__class__.__name__)
return json.dumps(obj, default=default_serializer, sort_keys=True)
def _serialize_str(str_value: str) -> str:
if not isinstance(str_value, str):
raise TypeError('Value "{}" has type "{}" instead of str.'.format(str(str_value), str(type(str_value))))
return str_value
import json
import argparse
_parser = argparse.ArgumentParser(prog='Upload Scikit learn pickle model to Google Cloud Vertex AI', description='')
_parser.add_argument("--model", dest="model_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--sklearn-version", dest="sklearn_version", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--display-name", dest="display_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--description", dest="description", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--project", dest="project", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--location", dest="location", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--labels", dest="labels", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--staging-bucket", dest="staging_bucket", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("----output-paths", dest="_output_paths", type=str, nargs=2)
_parsed_args = vars(_parser.parse_args())
_output_files = _parsed_args.pop("_output_paths", [])
_outputs = upload_Scikit_learn_pickle_model_to_Google_Cloud_Vertex_AI(**_parsed_args)
_output_serializers = [
_serialize_str,
_serialize_json,
]
import os
for idx, output_file in enumerate(_output_files):
try:
os.makedirs(os.path.dirname(output_file))
except OSError:
pass
with open(output_file, 'w') as f:
f.write(_output_serializers[idx](_outputs[idx]))
args:
- --model
- {inputPath: model}
- if:
cond: {isPresent: sklearn_version}
then:
- --sklearn-version
- {inputValue: sklearn_version}
- if:
cond: {isPresent: display_name}
then:
- --display-name
- {inputValue: display_name}
- if:
cond: {isPresent: description}
then:
- --description
- {inputValue: description}
- if:
cond: {isPresent: project}
then:
- --project
- {inputValue: project}
- if:
cond: {isPresent: location}
then:
- --location
- {inputValue: location}
- if:
cond: {isPresent: labels}
then:
- --labels
- {inputValue: labels}
- if:
cond: {isPresent: staging_bucket}
then:
- --staging-bucket
- {inputValue: staging_bucket}
- '----output-paths'
- {outputPath: model_name}
- {outputPath: model_dict}
@@ -0,0 +1,190 @@
name: Upload Tensorflow model to Google Cloud Vertex AI
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/KFPv2_hell/components/google-cloud/Vertex_AI/Models/Upload_Tensorflow_model/workaround_for_buggy_KFPv2_compiler/component.yaml'}
inputs:
- {name: model, type: TensorflowSavedModel}
- {name: tensorflow_version, type: String, optional: true}
- name: use_gpu
type: Boolean
default: "False"
optional: true
- {name: display_name, type: String, optional: true}
- {name: description, type: String, optional: true}
- {name: project, type: String, optional: true}
- {name: location, type: String, optional: true}
- {name: labels, type: JsonObject, optional: true}
- {name: staging_bucket, type: String, optional: true}
outputs:
- {name: model_name, type: String}
- {name: model_dict, type: JsonObject}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'google-cloud-aiplatform==1.16.0' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'google-cloud-aiplatform==1.16.0'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def upload_Tensorflow_model_to_Google_Cloud_Vertex_AI(
model_path,
tensorflow_version = None,
use_gpu = False,
display_name = None,
description = None,
# Uncomment when anyone requests these:
# instance_schema_uri: str = None,
# parameters_schema_uri: str = None,
# prediction_schema_uri: str = None,
# explanation_metadata: "google.cloud.aiplatform_v1.types.explanation_metadata.ExplanationMetadata" = None,
# explanation_parameters: "google.cloud.aiplatform_v1.types.explanation.ExplanationParameters" = None,
project = None,
location = None,
labels = None,
# encryption_spec_key_name: str = None,
staging_bucket = None,
):
import json
import os
from google.cloud import aiplatform
if not location:
location = os.environ.get("CLOUD_ML_REGION")
if not labels:
labels = {}
labels["component-source"] = "github-com-ark-kun-pipeline-components"
model = aiplatform.Model.upload_tensorflow_saved_model(
saved_model_dir=model_path,
tensorflow_version=tensorflow_version,
use_gpu=use_gpu,
display_name=display_name,
description=description,
# instance_schema_uri=instance_schema_uri,
# parameters_schema_uri=parameters_schema_uri,
# prediction_schema_uri=prediction_schema_uri,
# explanation_metadata=explanation_metadata,
# explanation_parameters=explanation_parameters,
project=project,
location=location,
labels=labels,
# encryption_spec_key_name=encryption_spec_key_name,
staging_bucket=staging_bucket,
)
model_json = json.dumps(model.to_dict(), indent=2)
print(model_json)
return (model.resource_name, model_json)
def _deserialize_bool(s) -> bool:
from distutils.util import strtobool
return strtobool(s) == 1
def _serialize_json(obj) -> str:
if isinstance(obj, str):
return obj
import json
def default_serializer(obj):
if hasattr(obj, 'to_struct'):
return obj.to_struct()
else:
raise TypeError("Object of type '%s' is not JSON serializable and does not have .to_struct() method." % obj.__class__.__name__)
return json.dumps(obj, default=default_serializer, sort_keys=True)
def _serialize_str(str_value: str) -> str:
if not isinstance(str_value, str):
raise TypeError('Value "{}" has type "{}" instead of str.'.format(str(str_value), str(type(str_value))))
return str_value
import json
import argparse
_parser = argparse.ArgumentParser(prog='Upload Tensorflow model to Google Cloud Vertex AI', description='')
_parser.add_argument("--model", dest="model_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--tensorflow-version", dest="tensorflow_version", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--use-gpu", dest="use_gpu", type=_deserialize_bool, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--display-name", dest="display_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--description", dest="description", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--project", dest="project", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--location", dest="location", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--labels", dest="labels", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--staging-bucket", dest="staging_bucket", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("----output-paths", dest="_output_paths", type=str, nargs=2)
_parsed_args = vars(_parser.parse_args())
_output_files = _parsed_args.pop("_output_paths", [])
_outputs = upload_Tensorflow_model_to_Google_Cloud_Vertex_AI(**_parsed_args)
_output_serializers = [
_serialize_str,
_serialize_json,
]
import os
for idx, output_file in enumerate(_output_files):
try:
os.makedirs(os.path.dirname(output_file))
except OSError:
pass
with open(output_file, 'w') as f:
f.write(_output_serializers[idx](_outputs[idx]))
args:
- --model
- {inputPath: model}
- if:
cond: {isPresent: tensorflow_version}
then:
- --tensorflow-version
- {inputValue: tensorflow_version}
- if:
cond: {isPresent: use_gpu}
then:
- --use-gpu
- {inputValue: use_gpu}
- if:
cond: {isPresent: display_name}
then:
- --display-name
- {inputValue: display_name}
- if:
cond: {isPresent: description}
then:
- --description
- {inputValue: description}
- if:
cond: {isPresent: project}
then:
- --project
- {inputValue: project}
- if:
cond: {isPresent: location}
then:
- --location
- {inputValue: location}
- if:
cond: {isPresent: labels}
then:
- --labels
- {inputValue: labels}
- if:
cond: {isPresent: staging_bucket}
then:
- --staging-bucket
- {inputValue: staging_bucket}
- '----output-paths'
- {outputPath: model_name}
- {outputPath: model_dict}
@@ -0,0 +1,181 @@
name: Upload XGBoost model to Google Cloud Vertex AI
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/google-cloud/Vertex_AI/Models/Upload_XGBoost_model/workaround_for_buggy_KFPv2_compiler/component.yaml'}
inputs:
- {name: model, type: XGBoostModel}
- {name: xgboost_version, type: String, optional: true}
- {name: display_name, type: String, optional: true}
- {name: description, type: String, optional: true}
- {name: project, type: String, optional: true}
- {name: location, type: String, optional: true}
- {name: labels, type: JsonObject, optional: true}
- {name: staging_bucket, type: String, optional: true}
outputs:
- {name: model_name, type: String}
- {name: model_dict, type: JsonObject}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'google-cloud-aiplatform==1.16.0' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'google-cloud-aiplatform==1.16.0'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def upload_XGBoost_model_to_Google_Cloud_Vertex_AI(
model_path,
xgboost_version = None,
display_name = None,
description = None,
# Uncomment when anyone requests these:
# instance_schema_uri: str = None,
# parameters_schema_uri: str = None,
# prediction_schema_uri: str = None,
# explanation_metadata: "google.cloud.aiplatform_v1.types.explanation_metadata.ExplanationMetadata" = None,
# explanation_parameters: "google.cloud.aiplatform_v1.types.explanation.ExplanationParameters" = None,
project = None,
location = None,
labels = None,
# encryption_spec_key_name: str = None,
staging_bucket = None,
):
import json
import os
import shutil
import tempfile
from google.cloud import aiplatform
if not location:
location = os.environ.get("CLOUD_ML_REGION")
if not labels:
labels = {}
labels["component-source"] = "github-com-ark-kun-pipeline-components"
# The serving container decides the model type based on the model file extension.
# So we need to rename the mode file (e.g. /tmp/inputs/model/data) to *.pkl
_, renamed_model_path = tempfile.mkstemp(suffix=".pkl")
shutil.copyfile(src=model_path, dst=renamed_model_path)
model = aiplatform.Model.upload_xgboost_model_file(
model_file_path=renamed_model_path,
xgboost_version=xgboost_version,
display_name=display_name,
description=description,
# instance_schema_uri=instance_schema_uri,
# parameters_schema_uri=parameters_schema_uri,
# prediction_schema_uri=prediction_schema_uri,
# explanation_metadata=explanation_metadata,
# explanation_parameters=explanation_parameters,
project=project,
location=location,
labels=labels,
# encryption_spec_key_name=encryption_spec_key_name,
staging_bucket=staging_bucket,
)
model_json = json.dumps(model.to_dict(), indent=2)
print(model_json)
return (model.resource_name, model_json)
def _serialize_json(obj) -> str:
if isinstance(obj, str):
return obj
import json
def default_serializer(obj):
if hasattr(obj, 'to_struct'):
return obj.to_struct()
else:
raise TypeError("Object of type '%s' is not JSON serializable and does not have .to_struct() method." % obj.__class__.__name__)
return json.dumps(obj, default=default_serializer, sort_keys=True)
def _serialize_str(str_value: str) -> str:
if not isinstance(str_value, str):
raise TypeError('Value "{}" has type "{}" instead of str.'.format(str(str_value), str(type(str_value))))
return str_value
import json
import argparse
_parser = argparse.ArgumentParser(prog='Upload XGBoost model to Google Cloud Vertex AI', description='')
_parser.add_argument("--model", dest="model_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--xgboost-version", dest="xgboost_version", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--display-name", dest="display_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--description", dest="description", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--project", dest="project", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--location", dest="location", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--labels", dest="labels", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--staging-bucket", dest="staging_bucket", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("----output-paths", dest="_output_paths", type=str, nargs=2)
_parsed_args = vars(_parser.parse_args())
_output_files = _parsed_args.pop("_output_paths", [])
_outputs = upload_XGBoost_model_to_Google_Cloud_Vertex_AI(**_parsed_args)
_output_serializers = [
_serialize_str,
_serialize_json,
]
import os
for idx, output_file in enumerate(_output_files):
try:
os.makedirs(os.path.dirname(output_file))
except OSError:
pass
with open(output_file, 'w') as f:
f.write(_output_serializers[idx](_outputs[idx]))
args:
- --model
- {inputPath: model}
- if:
cond: {isPresent: xgboost_version}
then:
- --xgboost-version
- {inputValue: xgboost_version}
- if:
cond: {isPresent: display_name}
then:
- --display-name
- {inputValue: display_name}
- if:
cond: {isPresent: description}
then:
- --description
- {inputValue: description}
- if:
cond: {isPresent: project}
then:
- --project
- {inputValue: project}
- if:
cond: {isPresent: location}
then:
- --location
- {inputValue: location}
- if:
cond: {isPresent: labels}
then:
- --labels
- {inputValue: labels}
- if:
cond: {isPresent: staging_bucket}
then:
- --staging-bucket
- {inputValue: staging_bucket}
- '----output-paths'
- {outputPath: model_name}
- {outputPath: model_dict}
@@ -0,0 +1,35 @@
name: Download from GCS
inputs:
- {name: GCS path, type: String}
outputs:
- {name: Data}
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/google-cloud/storage/download/workaround_for_buggy_KFPv2_compiler/component.yaml'
implementation:
container:
image: google/cloud-sdk
command:
- bash # Pattern comparison only works in Bash
- -ex
- -c
- |
if [ -n "${GOOGLE_APPLICATION_CREDENTIALS}" ]; then
gcloud auth activate-service-account --key-file="${GOOGLE_APPLICATION_CREDENTIALS}"
fi
uri="$0"
output_path="$1"
# Checking whether the URI points to a single blob, a directory or a URI pattern
# URI points to a blob when that URI does not end with slash and listing that URI only yields the same URI
if [[ "$uri" != */ ]] && (gsutil ls "$uri" | grep --fixed-strings --line-regexp "$uri"); then
mkdir -p "$(dirname "$output_path")"
gsutil -m cp -r "$uri" "$output_path"
else
mkdir -p "$output_path" # When source path is a directory, gsutil requires the destination to also be a directory
gsutil -m rsync -r "$uri" "$output_path" # gsutil cp has different path handling than Linux cp. It always puts the source directory (name) inside the destination directory. gsutil rsync does not have that problem.
fi
- inputValue: GCS path
- outputPath: Data
@@ -0,0 +1,113 @@
name: Binarize column using Pandas on CSV data
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/pandas/Binarize_column/in_CSV_format/component.yaml'}
inputs:
- {name: table, type: CSV}
- {name: column_name, type: String}
- {name: predicate, type: String, default: '> 0', optional: true}
- {name: new_column_name, type: String, optional: true}
- name: keep_original_column
type: Boolean
default: "False"
optional: true
outputs:
- {name: transformed_table, type: CSV}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'pandas==1.4.3' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet
--no-warn-script-location 'pandas==1.4.3' --user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def binarize_column_using_Pandas_on_CSV_data(
table_path,
transformed_table_path,
column_name,
predicate = "> 0",
new_column_name = None,
keep_original_column = False,
):
import pandas
df = pandas.read_csv(table_path).convert_dtypes()
original_series = df[column_name]
# Dynamically executing the predicate code
# Variable namespace for code execution
namespace = dict(x=original_series)
# I though that there should be no space before `predicate` so that "dot" predicate methods like ".between(min, max)" work.
# However Python allows spaces before dot: `df .isna()`.
# So having a space is not a problem
transform_code = f"""new_series_boolean = x {predicate}"""
# Note: exec() takes no keyword arguments
# exec(__source=transform_code, __globals=namespace)
exec(transform_code, namespace)
new_series_boolean = namespace["new_series_boolean"]
# There are multiple ways to convert boolean column to integer.
# .apply(int) might be faster. https://stackoverflow.com/a/49804868/1497385
# TODO: Do a proper benchmark.
new_series = new_series_boolean.apply(int)
# new_series = new_series_boolean.astype(int)
# new_series = new_series_boolean.replace({False: 0, True: 1})
if new_column_name:
df.insert(loc=0, column=new_column_name, value=new_series)
if not keep_original_column:
df = df.drop(columns=[column_name])
else:
df[column_name] = new_series
df.to_csv(transformed_table_path, index=False)
def _deserialize_bool(s) -> bool:
from distutils.util import strtobool
return strtobool(s) == 1
import argparse
_parser = argparse.ArgumentParser(prog='Binarize column using Pandas on CSV data', description='')
_parser.add_argument("--table", dest="table_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--column-name", dest="column_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--predicate", dest="predicate", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--new-column-name", dest="new_column_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--keep-original-column", dest="keep_original_column", type=_deserialize_bool, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--transformed-table", dest="transformed_table_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = binarize_column_using_Pandas_on_CSV_data(**_parsed_args)
args:
- --table
- {inputPath: table}
- --column-name
- {inputValue: column_name}
- if:
cond: {isPresent: predicate}
then:
- --predicate
- {inputValue: predicate}
- if:
cond: {isPresent: new_column_name}
then:
- --new-column-name
- {inputValue: new_column_name}
- if:
cond: {isPresent: keep_original_column}
then:
- --keep-original-column
- {inputValue: keep_original_column}
- --transformed-table
- {outputPath: transformed_table}
@@ -0,0 +1,75 @@
name: Fill all missing values using Pandas on CSV data
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/pandas/Fill_all_missing_values/in_CSV_format/component.yaml'}
inputs:
- {name: table, type: CSV}
- {name: replacement_value, type: String, default: '0', optional: true}
- {name: column_names, type: JsonArray, optional: true}
outputs:
- {name: transformed_table, type: CSV}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'pandas==1.4.1' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet
--no-warn-script-location 'pandas==1.4.1' --user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def fill_all_missing_values_using_Pandas_on_CSV_data(
table_path,
transformed_table_path,
replacement_value = "0",
column_names = None,
):
import pandas
df = pandas.read_csv(
table_path,
dtype="string",
)
for column_name in column_names or df.columns:
df[column_name] = df[column_name].fillna(value=replacement_value)
df.to_csv(
transformed_table_path, index=False,
)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Fill all missing values using Pandas on CSV data', description='')
_parser.add_argument("--table", dest="table_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--replacement-value", dest="replacement_value", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--column-names", dest="column_names", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--transformed-table", dest="transformed_table_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = fill_all_missing_values_using_Pandas_on_CSV_data(**_parsed_args)
args:
- --table
- {inputPath: table}
- if:
cond: {isPresent: replacement_value}
then:
- --replacement-value
- {inputValue: replacement_value}
- if:
cond: {isPresent: column_names}
then:
- --column-names
- {inputValue: column_names}
- --transformed-table
- {outputPath: transformed_table}
@@ -0,0 +1,59 @@
name: Select columns using Pandas on CSV data
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/pandas/Select_columns/in_CSV_format/component.yaml'}
inputs:
- {name: table, type: CSV}
- {name: column_names, type: JsonArray}
outputs:
- {name: transformed_table, type: CSV}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'pandas==1.4.2' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet
--no-warn-script-location 'pandas==1.4.2' --user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def select_columns_using_Pandas_on_CSV_data(
table_path,
transformed_table_path,
column_names,
):
import pandas
df = pandas.read_csv(
table_path,
dtype="string",
)
df = df[column_names]
df.to_csv(transformed_table_path, index=False)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Select columns using Pandas on CSV data', description='')
_parser.add_argument("--table", dest="table_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--column-names", dest="column_names", type=json.loads, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--transformed-table", dest="transformed_table_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = select_columns_using_Pandas_on_CSV_data(**_parsed_args)
args:
- --table
- {inputPath: table}
- --column-names
- {inputValue: column_names}
- --transformed-table
- {outputPath: transformed_table}
@@ -0,0 +1,102 @@
name: Create fully connected tensorflow network
description: Creates fully-connected network in Tensorflow SavedModel format
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/tensorflow/Create_fully_connected_network/component.yaml'}
inputs:
- {name: input_size, type: Integer}
- {name: hidden_layer_sizes, type: JsonArray, default: '[]', optional: true}
- {name: output_size, type: Integer, default: '1', optional: true}
- {name: activation_name, type: String, default: relu, optional: true}
- {name: output_activation_name, type: String, optional: true}
- {name: random_seed, type: Integer, default: '0', optional: true}
outputs:
- {name: model, type: TensorflowSavedModel}
implementation:
container:
image: tensorflow/tensorflow:2.7.0
command:
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def create_fully_connected_tensorflow_network(
input_size,
model_path,
hidden_layer_sizes = [],
output_size = 1,
activation_name = "relu",
output_activation_name = None,
random_seed = 0,
):
"""Creates fully-connected network in Tensorflow SavedModel format"""
import tensorflow as tf
tf.random.set_seed(seed=random_seed)
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(input_size,)))
for layer_size in hidden_layer_sizes:
model.add(tf.keras.layers.Dense(units=layer_size, activation=activation_name))
# The last layer is left without activation
model.add(tf.keras.layers.Dense(units=output_size, activation=output_activation_name))
print(model.summary())
# Using tf.keras.models.save_model instead of tf.saved_model.save to prevent downstream error:
#tf.saved_model.save(model, model_path)
# ValueError: Unable to create a Keras model from this SavedModel.
# This SavedModel was created with `tf.saved_model.save`, and lacks the Keras metadata.
# Please save your Keras model by calling `model.save`or `tf.keras.models.save_model`.
# See https://github.com/keras-team/keras/issues/16451
tf.keras.models.save_model(model, model_path)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Create fully connected tensorflow network', description='Creates fully-connected network in Tensorflow SavedModel format')
_parser.add_argument("--input-size", dest="input_size", type=int, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--hidden-layer-sizes", dest="hidden_layer_sizes", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--output-size", dest="output_size", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--activation-name", dest="activation_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--output-activation-name", dest="output_activation_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--random-seed", dest="random_seed", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = create_fully_connected_tensorflow_network(**_parsed_args)
args:
- --input-size
- {inputValue: input_size}
- if:
cond: {isPresent: hidden_layer_sizes}
then:
- --hidden-layer-sizes
- {inputValue: hidden_layer_sizes}
- if:
cond: {isPresent: output_size}
then:
- --output-size
- {inputValue: output_size}
- if:
cond: {isPresent: activation_name}
then:
- --activation-name
- {inputValue: activation_name}
- if:
cond: {isPresent: output_activation_name}
then:
- --output-activation-name
- {inputValue: output_activation_name}
- if:
cond: {isPresent: random_seed}
then:
- --random-seed
- {inputValue: random_seed}
- --model
- {outputPath: model}
@@ -0,0 +1,100 @@
name: Predict with TensorFlow model on CSV data
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/tensorflow/Predict/on_CSV/component.yaml'}
inputs:
- {name: dataset, type: CSV}
- {name: model, type: TensorflowSavedModel}
- {name: label_column_name, type: String, optional: true}
- {name: batch_size, type: Integer, default: '1000', optional: true}
outputs:
- {name: predictions}
implementation:
container:
image: tensorflow/tensorflow:2.9.1
command:
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def predict_with_TensorFlow_model_on_CSV_data(
dataset_path,
model_path,
predictions_path,
label_column_name = None,
batch_size = 1000,
):
import numpy
import tensorflow as tf
model = tf.saved_model.load(export_dir=model_path)
dataset = tf.data.experimental.make_csv_dataset(
file_pattern=dataset_path,
batch_size=batch_size,
label_name=label_column_name,
header=True,
num_epochs=1,
shuffle=False,
ignore_errors=False,
)
def stack_feature_batches(features_batch):
# Need to stack individual feature columns to create a single feature tensor
# Need to cast all column tensor types to float to prevent errors.
list_of_feature_batches = list(
tf.cast(x=feature_batch, dtype=tf.float32)
for feature_batch in features_batch.values()
)
return tf.stack(list_of_feature_batches, axis=-1)
def transform_features_and_drop_labels(features_batch, labels_batch):
return stack_feature_batches(features_batch)
dataset_map_fn = (
transform_features_and_drop_labels
if label_column_name
else stack_feature_batches
)
dataset = dataset.map(dataset_map_fn)
with open(predictions_path, "w") as predictions_file:
for features_batch in dataset:
predictions_tensor = model(features_batch)
numpy.savetxt(predictions_file, predictions_tensor.numpy())
import argparse
_parser = argparse.ArgumentParser(prog='Predict with TensorFlow model on CSV data', description='')
_parser.add_argument("--dataset", dest="dataset_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--batch-size", dest="batch_size", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--predictions", dest="predictions_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = predict_with_TensorFlow_model_on_CSV_data(**_parsed_args)
args:
- --dataset
- {inputPath: dataset}
- --model
- {inputPath: model}
- if:
cond: {isPresent: label_column_name}
then:
- --label-column-name
- {inputValue: label_column_name}
- if:
cond: {isPresent: batch_size}
then:
- --batch-size
- {inputValue: batch_size}
- --predictions
- {outputPath: predictions}
@@ -0,0 +1,170 @@
name: Train model using Keras on CSV
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/tensorflow/Train_model_using_Keras/on_CSV/component.yaml'}
inputs:
- {name: training_data, type: CSV}
- {name: model, type: TensorflowSavedModel}
- {name: label_column_name, type: String}
- {name: loss_function_name, type: String, default: mean_squared_error, optional: true}
- {name: number_of_epochs, type: Integer, default: '1', optional: true}
- {name: learning_rate, type: Float, default: '0.1', optional: true}
- {name: optimizer_name, type: String, default: Adadelta, optional: true}
- {name: optimizer_parameters, type: JsonObject, optional: true}
- {name: batch_size, type: Integer, default: '32', optional: true}
- {name: metric_names, type: JsonArray, optional: true}
- {name: random_seed, type: Integer, default: '0', optional: true}
outputs:
- {name: trained_model, type: TensorflowSavedModel}
implementation:
container:
image: tensorflow/tensorflow:2.8.0
command:
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def train_model_using_Keras_on_CSV(
training_data_path,
model_path,
trained_model_path,
label_column_name,
loss_function_name = "mean_squared_error",
number_of_epochs = 1,
learning_rate = 0.1,
optimizer_name = "Adadelta",
optimizer_parameters = None,
batch_size = 32,
metric_names = None,
random_seed = 0,
):
import tensorflow as tf
tf.random.set_seed(seed=random_seed)
# Loading model using Keras. Model loaded using TensorFlow does not have .fit.
#model = tf.saved_model.load(export_dir=model_path)
keras_model = tf.keras.models.load_model(filepath=model_path)
optimizer_parameters = optimizer_parameters or {}
optimizer_parameters["learning_rate"] = learning_rate
optimizer_config = {
"class_name": optimizer_name,
"config": optimizer_parameters,
}
optimizer = tf.keras.optimizers.get(optimizer_config)
loss = tf.keras.losses.get(loss_function_name)
training_dataset = tf.data.experimental.make_csv_dataset(
file_pattern=training_data_path,
batch_size=batch_size,
label_name=label_column_name,
header=True,
# Need to specify num_epochs=1 otherwise the training becomes infinite
num_epochs=1,
shuffle=True,
shuffle_seed=random_seed,
ignore_errors=True,
)
def stack_feature_batches(features_batch, labels_batch):
# Need to stack individual feature columns to create a single feature tensor
# Need to cast all column tensor types to float to prevent error:
# TypeError: Tensors in list passed to 'values' of 'Pack' Op have types [int32, float32, float32, int32, int32] that don't all match.
list_of_feature_batches = list(tf.cast(x=feature_batch, dtype=tf.float32) for feature_batch in features_batch.values())
return tf.stack(list_of_feature_batches, axis=-1), labels_batch
training_dataset = training_dataset.map(stack_feature_batches)
# Need to compile the model to prevent error:
# ValueError: No gradients provided for any variable: [..., ...].
keras_model.compile(
optimizer=optimizer,
loss=loss,
metrics=metric_names,
)
keras_model.fit(
training_dataset,
epochs=number_of_epochs,
)
# Using tf.keras.models.save_model instead of tf.saved_model.save to prevent downstream error:
#tf.saved_model.save(keras_model, trained_model_path)
# ValueError: Unable to create a Keras model from this SavedModel.
# This SavedModel was created with `tf.saved_model.save`, and lacks the Keras metadata.
# Please save your Keras model by calling `model.save`or `tf.keras.models.save_model`.
# See https://github.com/keras-team/keras/issues/16451
tf.keras.models.save_model(keras_model, trained_model_path)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Train model using Keras on CSV', description='')
_parser.add_argument("--training-data", dest="training_data_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--loss-function-name", dest="loss_function_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--number-of-epochs", dest="number_of_epochs", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--learning-rate", dest="learning_rate", type=float, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--optimizer-name", dest="optimizer_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--optimizer-parameters", dest="optimizer_parameters", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--batch-size", dest="batch_size", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--metric-names", dest="metric_names", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--random-seed", dest="random_seed", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--trained-model", dest="trained_model_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = train_model_using_Keras_on_CSV(**_parsed_args)
args:
- --training-data
- {inputPath: training_data}
- --model
- {inputPath: model}
- --label-column-name
- {inputValue: label_column_name}
- if:
cond: {isPresent: loss_function_name}
then:
- --loss-function-name
- {inputValue: loss_function_name}
- if:
cond: {isPresent: number_of_epochs}
then:
- --number-of-epochs
- {inputValue: number_of_epochs}
- if:
cond: {isPresent: learning_rate}
then:
- --learning-rate
- {inputValue: learning_rate}
- if:
cond: {isPresent: optimizer_name}
then:
- --optimizer-name
- {inputValue: optimizer_name}
- if:
cond: {isPresent: optimizer_parameters}
then:
- --optimizer-parameters
- {inputValue: optimizer_parameters}
- if:
cond: {isPresent: batch_size}
then:
- --batch-size
- {inputValue: batch_size}
- if:
cond: {isPresent: metric_names}
then:
- --metric-names
- {inputValue: metric_names}
- if:
cond: {isPresent: random_seed}
then:
- --random-seed
- {inputValue: random_seed}
- --trained-model
- {outputPath: trained_model}
@@ -0,0 +1,33 @@
# PyTorch Efficient Training Examples
This folder provides PyTorch efficient training examples using ResNet-50 and ImageNet data.
## Requirements
```shell
pip install --upgrade pip
pip install -r requirements.txt
```
## Description
* resnet.py - Train ResNet-50 on single GPU.
* resnet_dp.py - Train ResNet-50 on single node multiple GPUs with `DataParallel` strategy.
* resnet_ddp.py - Train ResNet-50 on single node multiple GPUs with `DistributedDataParallel` strategy.
* resnet_ddp_wds.py - Train ResNet-50 on single node multiple GPUs with `DistributedDataParallel` strategy and `Webdataset`.
* resnet_fsdp.py - Train ResNet-50 on single node multiple GPUs with `FullyShardedDataParallel` strategy.
* resnet_fsdp_wds.py - Train ResNet-50 on single node multiple GPUs with `FullyShardedDataParallel` strategy and `Webdataset`.
* shard_imagenet.py - Shard ImagNet individual files into `tar` files.
## Benchmark
When run the benchmark on Nvidia T4 GPUs using ImageNet validation dataset, you can get the result like:
Strategy | Seconds/Epoch - Local Data | Seconds/Epoch - Cloud Data
---------------------- | -------------------------- | --------------------------
On 1 GPU | 489 | 804 (2x slower)
On 4 GPUs (DP) | 157 | 738 (5x slower)
On 4 GPUs (DDP) | 134 | 432 (3x slower)
On 4 GPUs (DDP + WDS) | 131 | 133 (same performance)
On 4 GPUs (FSDP) | 139 | 353 (3x slower)
On 4 GPUs (FSDP + WDS) | 138 | 135 (same performance)
@@ -0,0 +1 @@
webdataset == 0.2.26
@@ -0,0 +1,197 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.\n",
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Train resnet on single GPU."""
import argparse
import time
from PIL import Image
import torch
from torch import nn
import torchmetrics
import torchvision
from torchvision.models import resnet50
class ImageFolder(torchvision.datasets.ImageFolder):
"""Class for loading imagenet."""
def __init__(self, image_list_file, transform=None, target_transform=None):
self.samples = self._make_dataset(image_list_file)
self.loader = self._loader
self.imgs = self.samples
self.targets = [s[1] for s in self.samples]
self.transform = transform
self.target_transform = target_transform
def _make_dataset(self, image_list_file):
items = []
with open(image_list_file, 'r') as f:
for line in f:
item = line.strip().split(' ')
items.append((item[0], int(item[1])))
return items
def _loader(self, image_path):
with open(image_path, 'rb') as f:
img = Image.open(f)
img = img.convert('RGB')
return img
def train(model, device, dataloader, optimizer):
model.train()
for image, target in dataloader:
image, target = image.to(device), target.to(device)
pred = model(image)
# pred.shape (N, C), target.shape (N)
loss = nn.functional.cross_entropy(pred, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss
def evaluate(model, device, dataloader, metric):
model.eval()
with torch.no_grad():
for image, target in dataloader:
image, target = image.to(device), target.to(device)
pred = model(image)
metric.update(pred, target)
accuracy = metric.compute()
metric.reset()
return accuracy
def run_training(args):
"""Run training and evaluation."""
# Create model.
model = resnet50(weights=None)
model = model.to(args.device)
# Create train dataloader.
train_dataset = ImageFolder(
image_list_file=args.train_data_path,
transform=torchvision.transforms.Compose([
torchvision.transforms.RandomResizedCrop(224),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]))
train_dataloader = torch.utils.data.DataLoader(
dataset=train_dataset,
batch_size=args.train_batch_size,
shuffle=True,
num_workers=args.dataloader_num_workers,
pin_memory=True)
print(f'Train dataloader | samples: {len(train_dataloader.dataset)}, '
f'num workers: {train_dataloader.num_workers}, '
f'batch size: {args.train_batch_size}, '
f'batches/epoch: {len(train_dataloader)}')
# Create eval dataloader.
eval_dataset = ImageFolder(
image_list_file=args.eval_data_path,
transform=torchvision.transforms.Compose([
torchvision.transforms.Resize(256),
torchvision.transforms.CenterCrop(224),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]))
eval_dataloader = torch.utils.data.DataLoader(
dataset=eval_dataset,
batch_size=args.eval_batch_size,
shuffle=False,
num_workers=args.dataloader_num_workers,
pin_memory=True,
drop_last=True)
print(f'Eval dataloader | samples: {len(eval_dataloader.dataset)}, '
f'num workers: {eval_dataloader.num_workers}, '
f'batch size: {args.eval_batch_size}, '
f'batches/epoch: {len(eval_dataloader)}')
# Optimizer.
optimizer = torch.optim.SGD(model.parameters(), 0.1)
# Main loop.
metric = torchmetrics.classification.Accuracy(top_k=1).to(args.device)
for epoch in range(1, args.epochs + 1):
print(f'Running epoch {epoch}')
start = time.time()
train(model, args.device, train_dataloader, optimizer)
end = time.time()
print(f'Training finished in {(end - start):>0.3f} seconds')
start = time.time()
evaluate(model, args.device, eval_dataloader, metric)
end = time.time()
print(f'Evaluation finished in {(end - start):>0.3f} seconds')
print('Done')
def create_args():
"""Create main args."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--epochs',
default=1,
type=int,
help='number of total epochs to run')
parser.add_argument(
'--dataloader_num_workers',
default=2,
type=int,
help='number of workders for dataloader')
parser.add_argument(
'--train_data_path',
default='',
type=str,
help='path to training data')
parser.add_argument(
'--train_batch_size',
default=32,
type=int,
help='batch size for training')
parser.add_argument(
'--eval_data_path',
default='',
type=str,
help='path to evaluation data')
parser.add_argument(
'--eval_batch_size',
default=32,
type=int,
help='batch size for evaluation')
args = parser.parse_args()
return args
def main():
args = create_args()
args.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print('Launch job on 1 GPU')
run_training(args)
if __name__ == '__main__':
main()
@@ -0,0 +1,234 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.\n",
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Train resnet on multiple GPUs with DDP."""
import argparse
import os
import time
from PIL import Image
import torch
from torch import nn
import torch.distributed as dist
import torch.multiprocessing as mp
import torchmetrics
import torchvision
from torchvision.models import resnet50
class ImageFolder(torchvision.datasets.ImageFolder):
"""Class for loading imagenet."""
def __init__(self, image_list_file, transform=None, target_transform=None):
self.samples = self._make_dataset(image_list_file)
self.loader = self._loader
self.imgs = self.samples
self.targets = [s[1] for s in self.samples]
self.transform = transform
self.target_transform = target_transform
def _make_dataset(self, image_list_file):
items = []
with open(image_list_file, 'r') as f:
for line in f:
item = line.strip().split(' ')
items.append((item[0], int(item[1])))
return items
def _loader(self, image_path):
with open(image_path, 'rb') as f:
img = Image.open(f)
img = img.convert('RGB')
return img
def train(model, device, dataloader, optimizer):
model.train()
for image, target in dataloader:
image = image.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
pred = model(image)
# pred.shape (N, C), target.shape (N)
loss = nn.functional.cross_entropy(pred, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss
def evaluate(model, device, dataloader, metric):
model.eval()
with torch.no_grad():
for image, target in dataloader:
image = image.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
pred = model(image)
metric.update(pred, target)
accuracy = metric.compute()
metric.reset()
return accuracy
def worker(gpu, args):
"""Run training and evaluation."""
# Init process group.
print(f'Initiating process {gpu}')
dist.init_process_group(
backend='nccl',
init_method='env://',
world_size=args.gpus,
rank=gpu)
# Create model.
model = resnet50(weights=None)
torch.cuda.set_device(gpu)
model.to(args.device)
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = nn.parallel.DistributedDataParallel(model, device_ids=[gpu])
# Create train dataloader.
train_dataset = ImageFolder(
image_list_file=args.train_data_path,
transform=torchvision.transforms.Compose([
torchvision.transforms.RandomResizedCrop(224),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]))
train_sampler = torch.utils.data.distributed.DistributedSampler(
train_dataset, num_replicas=args.gpus, rank=gpu)
train_dataloader = torch.utils.data.DataLoader(
dataset=train_dataset,
batch_size=args.train_batch_size,
shuffle=False,
num_workers=args.dataloader_num_workers,
pin_memory=True,
sampler=train_sampler)
if gpu == 0:
print(f'Train dataloader | samples: {len(train_dataloader.dataset)}, '
f'num workers: {train_dataloader.num_workers}, '
f'global batch size: {args.train_batch_size * args.gpus}, '
f'batches/epoch: {len(train_dataloader)}')
# Create eval dataloader.
eval_dataset = ImageFolder(
image_list_file=args.eval_data_path,
transform=torchvision.transforms.Compose([
torchvision.transforms.Resize(256),
torchvision.transforms.CenterCrop(224),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]))
eval_sampler = torch.utils.data.distributed.DistributedSampler(
eval_dataset, num_replicas=args.gpus, rank=gpu)
eval_dataloader = torch.utils.data.DataLoader(
dataset=eval_dataset,
batch_size=args.eval_batch_size,
shuffle=False,
num_workers=args.dataloader_num_workers,
pin_memory=True,
drop_last=True,
sampler=eval_sampler)
if gpu == 0:
print(f'Eval dataloader | samples: {len(eval_dataloader.dataset)}, '
f'num workers: {eval_dataloader.num_workers}, '
f'batch size: {args.eval_batch_size}, '
f'batches/epoch: {len(eval_dataloader)}')
# Optimizer.
optimizer = torch.optim.SGD(model.parameters(), 0.1)
# Main loop.
metric = torchmetrics.classification.Accuracy(top_k=1).to(args.device)
for epoch in range(1, args.epochs + 1):
if gpu == 0:
print(f'Running epoch {epoch}')
train_sampler.set_epoch(epoch)
start = time.time()
train(model, args.device, train_dataloader, optimizer)
end = time.time()
if gpu == 0:
print(f'Training finished in {(end - start):>0.3f} seconds')
start = time.time()
evaluate(model, args.device, eval_dataloader, metric)
end = time.time()
if gpu == 0:
print(f'Evaluation finished in {(end - start):>0.3f} seconds')
if gpu == 0:
print('Done')
def create_args():
"""Create main args."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--gpus',
default=4,
type=int,
help='number of gpus to use')
parser.add_argument(
'--epochs',
default=1,
type=int,
help='number of total epochs to run')
parser.add_argument(
'--dataloader_num_workers',
default=2,
type=int,
help='number of workders for dataloader')
parser.add_argument(
'--train_data_path',
default='',
type=str,
help='path to training data')
parser.add_argument(
'--train_batch_size',
default=32,
type=int,
help='batch size for training per gpu')
parser.add_argument(
'--eval_data_path',
default='',
type=str,
help='path to evaluation data')
parser.add_argument(
'--eval_batch_size',
default=32,
type=int,
help='batch size for evaluation per gpu')
args = parser.parse_args()
return args
def main():
args = create_args()
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '8888'
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f'Launch job on {args.gpus} GPUs with DDP')
mp.spawn(worker, nprocs=args.gpus, args=(args,))
if __name__ == '__main__':
main()
@@ -0,0 +1,249 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.\n",
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Train resnet on multiple GPUs with DDP."""
import argparse
import functools
import itertools
import math
import os
import time
import torch
from torch import nn
import torch.distributed as dist
import torch.multiprocessing as mp
import torchmetrics
from torchvision.models import resnet50
from torchvision.transforms import transforms
import webdataset as wds
def wds_split(src, rank, world_size):
"""Shards split function for webdataset."""
# The context of caller of this function is within multiple processes
# (by DDP world_size) and multiple workers (by dataloader_num_workers).
# So we totally have (world_size * num_workers) workers for processing data.
# NOTE: Raw data should be sharded to enough shards to make sure one process
# can handle at least one shard, otherwise the process may hang.
worker_id = 0
num_workers = 1
worker_info = torch.utils.data.get_worker_info()
if worker_info:
worker_id = worker_info.id
num_workers = worker_info.num_workers
for s in itertools.islice(src, rank * num_workers + worker_id, None,
world_size * num_workers):
yield s
def identity(x):
return x
def create_wds_dataloader(rank, args, mode):
"""Create webdataset dataset and dataloader."""
if mode == 'train':
transform = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
data_path = args.train_data_path
data_size = args.train_data_size
batch_size_local = args.train_batch_size
batch_size_global = args.train_batch_size * args.gpus
# Since webdataset disallows partial batch, we pad the last batch for train.
batches = int(math.ceil(data_size / batch_size_global))
else:
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
data_path = args.eval_data_path
data_size = args.eval_data_size
batch_size_local = args.eval_batch_size
batch_size_global = args.eval_batch_size * args.gpus
# Since webdataset disallows partial batch, we drop the last batch for eval.
batches = int(data_size / batch_size_global)
dataset = wds.DataPipeline(
wds.SimpleShardList(data_path),
functools.partial(wds_split, rank=rank, world_size=args.gpus),
wds.tarfile_to_samples(),
wds.decode('pil'),
wds.to_tuple('jpg;png;jpeg cls'),
wds.map_tuple(transform, identity),
wds.batched(batch_size_local, partial=False),
)
num_workers = args.dataloader_num_workers
dataloader = wds.WebLoader(
dataset=dataset,
batch_size=None,
shuffle=False,
num_workers=num_workers,
persistent_workers=True if num_workers > 0 else False,
pin_memory=True).repeat(nbatches=batches)
print(f'{mode} dataloader | samples: {data_size}, '
f'num_workers: {num_workers}, '
f'local batch size: {batch_size_local}, '
f'global batch size: {batch_size_global}, '
f'batches: {batches}')
return dataloader
def train(model, device, dataloader, optimizer):
model.train()
for image, target in dataloader:
image = image.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
pred = model(image)
# pred.shape (N, C), target.shape (N)
loss = nn.functional.cross_entropy(pred, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss
def evaluate(model, device, dataloader, metric):
model.eval()
with torch.no_grad():
for image, target in dataloader:
image = image.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
pred = model(image)
metric.update(pred, target)
accuracy = metric.compute()
metric.reset()
return accuracy
def worker(gpu, args):
"""Run training and evaluation."""
# Init process group.
print(f'Initiating process {gpu}')
dist.init_process_group(
backend='nccl',
init_method='env://',
world_size=args.gpus,
rank=gpu)
# Create model.
model = resnet50(weights=None)
torch.cuda.set_device(gpu)
model.to(args.device)
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = nn.parallel.DistributedDataParallel(model, device_ids=[gpu])
# Create dataloader.
train_dataloader = create_wds_dataloader(gpu, args, 'train')
eval_dataloader = create_wds_dataloader(gpu, args, 'eval')
# Optimizer.
optimizer = torch.optim.SGD(model.parameters(), 0.1)
# Main loop.
metric = torchmetrics.classification.Accuracy(top_k=1).to(args.device)
for epoch in range(1, args.epochs + 1):
if gpu == 0:
print(f'Running epoch {epoch}')
start = time.time()
train(model, args.device, train_dataloader, optimizer)
end = time.time()
if gpu == 0:
print(f'Training finished in {(end - start):>0.3f} seconds')
start = time.time()
evaluate(model, args.device, eval_dataloader, metric)
end = time.time()
if gpu == 0:
print(f'Evaluation finished in {(end - start):>0.3f} seconds')
if gpu == 0:
print('Done')
def create_args():
"""Create main args."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--gpus',
default=4,
type=int,
help='number of gpus to use')
parser.add_argument(
'--epochs',
default=1,
type=int,
help='number of total epochs to run')
parser.add_argument(
'--dataloader_num_workers',
default=2,
type=int,
help='number of workders for dataloader')
parser.add_argument(
'--train_data_path',
default='',
type=str,
help='path to training data')
parser.add_argument(
'--train_batch_size',
default=32,
type=int,
help='batch size for training per gpu')
parser.add_argument(
'--train_data_size',
default=50000,
type=int,
help='data size for training')
parser.add_argument(
'--eval_data_path',
default='',
type=str,
help='path to evaluation data')
parser.add_argument(
'--eval_batch_size',
default=32,
type=int,
help='batch size for evaluation per gpu')
parser.add_argument(
'--eval_data_size',
default=50000,
type=int,
help='data size for evaluation')
args = parser.parse_args()
return args
def main():
args = create_args()
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '8888'
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f'Launch job on {args.gpus} GPUs with DDP')
mp.spawn(worker, nprocs=args.gpus, args=(args,))
if __name__ == '__main__':
main()
@@ -0,0 +1,207 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.\n",
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Train resnet on multiple GPUs with DP."""
import argparse
import time
from PIL import Image
import torch
from torch import nn
import torchmetrics
import torchvision
from torchvision.models import resnet50
class ImageFolder(torchvision.datasets.ImageFolder):
"""Class for loading imagenet."""
def __init__(self, image_list_file, transform=None, target_transform=None):
self.samples = self._make_dataset(image_list_file)
self.loader = self._loader
self.imgs = self.samples
self.targets = [s[1] for s in self.samples]
self.transform = transform
self.target_transform = target_transform
def _make_dataset(self, image_list_file):
items = []
with open(image_list_file, 'r') as f:
for line in f:
item = line.strip().split(' ')
items.append((item[0], int(item[1])))
return items
def _loader(self, image_path):
with open(image_path, 'rb') as f:
img = Image.open(f)
img = img.convert('RGB')
return img
def train(model, device, dataloader, optimizer):
model.train()
for image, target in dataloader:
image, target = image.to(device), target.to(device)
pred = model(image)
# pred.shape (N, C), target.shape (N)
loss = nn.functional.cross_entropy(pred, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss
def evaluate(model, device, dataloader, metric):
model.eval()
with torch.no_grad():
for image, target in dataloader:
image, target = image.to(device), target.to(device)
pred = model(image)
metric.update(pred, target)
accuracy = metric.compute()
metric.reset()
return accuracy
def run_training(args):
"""Run training and evaluation."""
# Create model.
model = resnet50(weights=None)
model = nn.DataParallel(model)
model = model.to(args.device)
# Create train dataloader.
train_dataset = ImageFolder(
image_list_file=args.train_data_path,
transform=torchvision.transforms.Compose([
torchvision.transforms.RandomResizedCrop(224),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]))
train_dataloader = torch.utils.data.DataLoader(
dataset=train_dataset,
batch_size=args.train_batch_size,
shuffle=True,
num_workers=args.dataloader_num_workers,
pin_memory=True)
print(f'Train dataloader | samples: {len(train_dataloader.dataset)}, '
f'num workers: {train_dataloader.num_workers}, '
f'global batch size: {args.train_batch_size}, '
f'batches/epoch: {len(train_dataloader)}')
# Create eval dataloader.
eval_dataset = ImageFolder(
image_list_file=args.eval_data_path,
transform=torchvision.transforms.Compose([
torchvision.transforms.Resize(256),
torchvision.transforms.CenterCrop(224),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]))
eval_dataloader = torch.utils.data.DataLoader(
dataset=eval_dataset,
batch_size=args.eval_batch_size,
shuffle=False,
num_workers=args.dataloader_num_workers,
pin_memory=True,
drop_last=True)
print(f'Eval dataloader | samples: {len(eval_dataloader.dataset)}, '
f'num workers: {eval_dataloader.num_workers}, '
f'global batch size: {args.eval_batch_size}, '
f'batches/epoch: {len(eval_dataloader)}')
# Optimizer.
optimizer = torch.optim.SGD(model.parameters(), 0.1)
# Main loop.
metric = torchmetrics.classification.Accuracy(top_k=1).to(args.device)
for epoch in range(1, args.epochs + 1):
print(f'Running epoch {epoch}')
start = time.time()
train(model, args.device, train_dataloader, optimizer)
end = time.time()
print(f'Training finished in {(end - start):>0.3f} seconds')
start = time.time()
evaluate(model, args.device, eval_dataloader, metric)
end = time.time()
print(f'Evaluation finished in {(end - start):>0.3f} seconds')
print('Done')
def create_args():
"""Create main args."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--gpus',
default=4,
type=int,
help='number of gpus to use')
parser.add_argument(
'--epochs',
default=1,
type=int,
help='number of total epochs to run')
parser.add_argument(
'--dataloader_num_workers',
default=2,
type=int,
help='number of workders for dataloader')
parser.add_argument(
'--train_data_path',
default='',
type=str,
help='path to training data')
parser.add_argument(
'--train_batch_size',
default=32,
type=int,
help='batch size for training per gpu')
parser.add_argument(
'--eval_data_path',
default='',
type=str,
help='path to evaluation data')
parser.add_argument(
'--eval_batch_size',
default=32,
type=int,
help='batch size for evaluation per gpu')
args = parser.parse_args()
return args
def main():
args = create_args()
args.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
args.train_batch_size *= args.gpus
args.eval_batch_size *= args.gpus
args.dataloader_num_workers *= args.gpus
print(f'Launch job on {args.gpus} GPU with nn.DataParallel')
run_training(args)
if __name__ == '__main__':
main()
@@ -0,0 +1,242 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.\n",
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Train resnet on multiple GPUs with FSDP."""
import argparse
import functools
import os
import time
from PIL import Image
import torch
from torch import nn
import torch.distributed as dist
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy
import torch.multiprocessing as mp
import torchmetrics
import torchvision
from torchvision.models import resnet50
class ImageFolder(torchvision.datasets.ImageFolder):
"""Class for loading imagenet."""
def __init__(self, image_list_file, transform=None, target_transform=None):
self.samples = self._make_dataset(image_list_file)
self.loader = self._loader
self.imgs = self.samples
self.targets = [s[1] for s in self.samples]
self.transform = transform
self.target_transform = target_transform
def _make_dataset(self, image_list_file):
items = []
with open(image_list_file, 'r') as f:
for line in f:
item = line.strip().split(' ')
items.append((item[0], int(item[1])))
return items
def _loader(self, image_path):
with open(image_path, 'rb') as f:
img = Image.open(f)
img = img.convert('RGB')
return img
def train(model, device, dataloader, optimizer):
model.train()
for image, target in dataloader:
image = image.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
pred = model(image)
# pred.shape (N, C), target.shape (N)
loss = nn.functional.cross_entropy(pred, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss
def evaluate(model, device, dataloader, metric):
model.eval()
with torch.no_grad():
for image, target in dataloader:
image = image.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
pred = model(image)
metric.update(pred, target)
accuracy = metric.compute()
metric.reset()
return accuracy
def worker(gpu, args):
"""Run training and evaluation."""
# Init process group.
print(f'Initiating process {gpu}')
dist.init_process_group(
backend='nccl',
init_method='env://',
world_size=args.gpus,
rank=gpu)
# Create train dataloader.
train_dataset = ImageFolder(
image_list_file=args.train_data_path,
transform=torchvision.transforms.Compose([
torchvision.transforms.RandomResizedCrop(224),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]))
train_sampler = torch.utils.data.distributed.DistributedSampler(
train_dataset, num_replicas=args.gpus, rank=gpu)
train_dataloader = torch.utils.data.DataLoader(
dataset=train_dataset,
batch_size=args.train_batch_size,
shuffle=False,
num_workers=args.dataloader_num_workers,
pin_memory=True,
sampler=train_sampler)
if gpu == 0:
print(f'Train dataloader | samples: {len(train_dataloader.dataset)}, '
f'num workers: {train_dataloader.num_workers}, '
f'global batch size: {args.train_batch_size * args.gpus}, '
f'batches/epoch: {len(train_dataloader)}')
# Create eval dataloader.
eval_dataset = ImageFolder(
image_list_file=args.eval_data_path,
transform=torchvision.transforms.Compose([
torchvision.transforms.Resize(256),
torchvision.transforms.CenterCrop(224),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]))
eval_sampler = torch.utils.data.distributed.DistributedSampler(
eval_dataset, num_replicas=args.gpus, rank=gpu)
eval_dataloader = torch.utils.data.DataLoader(
dataset=eval_dataset,
batch_size=args.eval_batch_size,
shuffle=False,
num_workers=args.dataloader_num_workers,
pin_memory=True,
drop_last=True,
sampler=eval_sampler)
if gpu == 0:
print(f'Eval dataloader | samples: {len(eval_dataloader.dataset)}, '
f'num workers: {eval_dataloader.num_workers}, '
f'batch size: {args.eval_batch_size}, '
f'batches/epoch: {len(eval_dataloader)}')
# Wrap policy.
my_auto_wrap_policy = functools.partial(
size_based_auto_wrap_policy, min_num_params=100)
torch.cuda.set_device(gpu)
# Create model.
model = resnet50(weights=None)
model.to(args.device)
model = FSDP(model, auto_wrap_policy=my_auto_wrap_policy)
# Optimizer.
optimizer = torch.optim.SGD(model.parameters(), 0.1)
# Main loop.
metric = torchmetrics.classification.Accuracy(top_k=1).to(args.device)
for epoch in range(1, args.epochs + 1):
if gpu == 0:
print(f'Running epoch {epoch}')
train_sampler.set_epoch(epoch)
start = time.time()
train(model, args.device, train_dataloader, optimizer)
end = time.time()
if gpu == 0:
print(f'Training finished in {(end - start):>0.3f} seconds')
start = time.time()
evaluate(model, args.device, eval_dataloader, metric)
end = time.time()
if gpu == 0:
print(f'Evaluation finished in {(end - start):>0.3f} seconds')
if gpu == 0:
print('Done')
dist.destroy_process_group()
def create_args():
"""Create main args."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--gpus',
default=4,
type=int,
help='number of gpus to use')
parser.add_argument(
'--epochs',
default=2,
type=int,
help='number of total epochs to run')
parser.add_argument(
'--dataloader_num_workers',
default=2,
type=int,
help='number of workders for dataloader')
parser.add_argument(
'--train_data_path',
default='',
type=str,
help='path to training data')
parser.add_argument(
'--train_batch_size',
default=32,
type=int,
help='batch size for training per gpu')
parser.add_argument(
'--eval_data_path',
default='',
type=str,
help='path to evaluation data')
parser.add_argument(
'--eval_batch_size',
default=32,
type=int,
help='batch size for evaluation per gpu')
args = parser.parse_args()
return args
def main():
args = create_args()
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '8888'
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f'Launch job on {args.gpus} GPUs with FSDP')
mp.spawn(worker, nprocs=args.gpus, args=(args,))
if __name__ == '__main__':
main()
@@ -0,0 +1,240 @@
"""Train resnet on multiple GPUs with DDP."""
import argparse
import functools
import itertools
import math
import os
import time
import torch
from torch import nn
import torch.distributed as dist
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy
import torch.multiprocessing as mp
import torchmetrics
from torchvision.models import resnet50
from torchvision.transforms import transforms
import webdataset as wds
def wds_split(src, rank, world_size):
"""Shards split function for webdataset."""
# The context of caller of this function is within multiple processes
# (by DDP world_size) and multiple workers (by dataloader_num_workers).
# So we totally have (world_size * num_workers) workers for processing data.
# NOTE: Raw data should be sharded to enough shards to make sure one process
# can handle at least one shard, otherwise the process may hang.
worker_id = 0
num_workers = 1
worker_info = torch.utils.data.get_worker_info()
if worker_info:
worker_id = worker_info.id
num_workers = worker_info.num_workers
for s in itertools.islice(src, rank * num_workers + worker_id, None,
world_size * num_workers):
yield s
def identity(x):
return x
def create_wds_dataloader(rank, args, mode):
"""Create webdataset dataset and dataloader."""
if mode == 'train':
transform = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
data_path = args.train_data_path
data_size = args.train_data_size
batch_size_local = args.train_batch_size
batch_size_global = args.train_batch_size * args.gpus
# Since webdataset disallows partial batch, we pad the last batch for train.
batches = int(math.ceil(data_size / batch_size_global))
else:
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
data_path = args.eval_data_path
data_size = args.eval_data_size
batch_size_local = args.eval_batch_size
batch_size_global = args.eval_batch_size * args.gpus
# Since webdataset disallows partial batch, we drop the last batch for eval.
batches = int(data_size / batch_size_global)
dataset = wds.DataPipeline(
wds.SimpleShardList(data_path),
functools.partial(wds_split, rank=rank, world_size=args.gpus),
wds.tarfile_to_samples(),
wds.decode('pil'),
wds.to_tuple('jpg;png;jpeg cls'),
wds.map_tuple(transform, identity),
wds.batched(batch_size_local, partial=False),
)
num_workers = args.dataloader_num_workers
dataloader = wds.WebLoader(
dataset=dataset,
batch_size=None,
shuffle=False,
num_workers=num_workers,
persistent_workers=True if num_workers > 0 else False,
pin_memory=True).repeat(nbatches=batches)
print(f'{mode} dataloader | samples: {data_size}, '
f'num_workers: {num_workers}, '
f'local batch size: {batch_size_local}, '
f'global batch size: {batch_size_global}, '
f'batches: {batches}')
return dataloader
def train(model, device, dataloader, optimizer):
model.train()
for image, target in dataloader:
image = image.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
pred = model(image)
# pred.shape (N, C), target.shape (N)
loss = nn.functional.cross_entropy(pred, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss
def evaluate(model, device, dataloader, metric):
model.eval()
with torch.no_grad():
for image, target in dataloader:
image = image.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
pred = model(image)
metric.update(pred, target)
accuracy = metric.compute()
metric.reset()
return accuracy
def worker(gpu, args):
"""Run training and evaluation."""
# Init process group.
print(f'Initiating process {gpu}')
dist.init_process_group(
backend='nccl',
init_method='env://',
world_size=args.gpus,
rank=gpu)
# Create dataloader.
train_dataloader = create_wds_dataloader(gpu, args, 'train')
eval_dataloader = create_wds_dataloader(gpu, args, 'eval')
# Wrap policy.
my_auto_wrap_policy = functools.partial(
size_based_auto_wrap_policy, min_num_params=100)
torch.cuda.set_device(gpu)
# Create model.
model = resnet50(weights=None)
model.to(args.device)
model = FSDP(model, auto_wrap_policy=my_auto_wrap_policy)
# Optimizer.
optimizer = torch.optim.SGD(model.parameters(), 0.1)
# Main loop.
metric = torchmetrics.classification.Accuracy(top_k=1).to(args.device)
for epoch in range(1, args.epochs + 1):
if gpu == 0:
print(f'Running epoch {epoch}')
start = time.time()
train(model, args.device, train_dataloader, optimizer)
end = time.time()
if gpu == 0:
print(f'Training finished in {(end - start):>0.3f} seconds')
start = time.time()
evaluate(model, args.device, eval_dataloader, metric)
end = time.time()
if gpu == 0:
print(f'Evaluation finished in {(end - start):>0.3f} seconds')
if gpu == 0:
print('Done')
def create_args():
"""Create main args."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--gpus',
default=4,
type=int,
help='number of gpus to use')
parser.add_argument(
'--epochs',
default=2,
type=int,
help='number of total epochs to run')
parser.add_argument(
'--dataloader_num_workers',
default=2,
type=int,
help='number of workders for dataloader')
parser.add_argument(
'--train_data_path',
default='',
type=str,
help='path to training data')
parser.add_argument(
'--train_batch_size',
default=32,
type=int,
help='batch size for training per gpu')
parser.add_argument(
'--train_data_size',
default=50000,
type=int,
help='data size for training')
parser.add_argument(
'--eval_data_path',
default='',
type=str,
help='path to evaluation data')
parser.add_argument(
'--eval_batch_size',
default=32,
type=int,
help='batch size for evaluation per gpu')
parser.add_argument(
'--eval_data_size',
default=50000,
type=int,
help='data size for evaluation')
args = parser.parse_args()
return args
def main():
args = create_args()
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '8888'
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f'Launch job on {args.gpus} GPUs with FSDP')
mp.spawn(worker, nprocs=args.gpus, args=(args,))
if __name__ == '__main__':
main()
@@ -0,0 +1,98 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.\n",
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Main function to shard ImageNet dataset.
Example usage:
python3 -u shard_imagenet.py \
--image_list_file=/home/jupyter/data/imagenet/train_list.txt \
--output_pattern=/home/jupyter/data/imagenet/validation-%06d.tar
"""
import argparse
import os
import random
import webdataset as wds # version: 0.2.26
# NOTE: only supports writing to local path,
# need gcsfuse mounting if want to write to gcs bucket.
def write_shards(args):
"""Shard individual data files."""
output_dir = os.path.dirname(args.output_pattern)
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
items = []
# Image list file is a text file, each line is a pair (image_path, label).
with open(args.image_list_file, 'r') as f:
for line in f:
item = line.strip().split(' ')
items.append((item[0], int(item[1])))
# Shuffle items to avoid any large sequences of a single class
# in the dataset.
random.shuffle(items)
def _read_image(image_path):
with open(image_path, 'rb') as f:
return f.read()
with wds.ShardWriter(pattern=args.output_pattern,
maxcount=args.max_images_per_shard,
maxsize=args.max_bytes_per_shard) as sink:
for i, (image_path, target) in enumerate(items):
key = str(i)
image = _read_image(image_path)
sample = {'__key__': key, 'jpg': image, 'cls': target}
sink.write(sample)
if len(items) != sink.total:
raise ValueError('Items read {} != items written {}'.format(
len(items), sink.total))
def create_args():
"""Creates arg parser."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--image_list_file',
default='',
type=str,
help='path to image list file')
parser.add_argument(
'--output_pattern',
default='',
type=str,
help='the pattern for output shards, like /path/to/train-%06d.tar')
parser.add_argument(
'--max_images_per_shard',
default=10 * 1024,
type=int,
help='max number of images per shard')
parser.add_argument(
'--max_bytes_per_shard',
default=300 * 1024 * 1024,
type=int,
help='max bytes per shard')
args = parser.parse_args()
return args
def main():
args = create_args()
write_shards(args)
if __name__ == '__main__':
main()
@@ -1,474 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a6b56b1c7b76"
},
"outputs": [],
"source": [
"# Copyright 2021 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": "c414a395a19b"
},
"source": [
"# PyTorch Image Classification Multi-Node Distributed Data Parallel Training on CPU using Vertex Training with Custom Container"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b98238e32cf7"
},
"source": [
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/community-content/pytorch_image_classification_distributed_data_parallel_training_with_vertex_sdk/multi_node_ddp_gloo_vertex_training_with_custom_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",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "03d216c7f7b1"
},
"source": [
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c5ac73516218"
},
"outputs": [],
"source": [
"PROJECT_ID = \"YOUR PROJECT ID\"\n",
"BUCKET_NAME = \"gs://YOUR BUCKET NAME\"\n",
"REGION = \"YOUR REGION\"\n",
"SERVICE_ACCOUNT = \"YOUR SERVICE ACCOUNT\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0b5ae674177e"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_NAME"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "19a9b3bdd553"
},
"outputs": [],
"source": [
"content_name = \"pt-img-cls-multi-node-ddp-cust-cont\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "57bf6f8b4361"
},
"source": [
"## Local Training"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e5d8a3443da0"
},
"outputs": [],
"source": [
"! ls trainer"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "07f79309472d"
},
"outputs": [],
"source": [
"! cat trainer/requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e16cd8bb7483"
},
"outputs": [],
"source": [
"! pip install -r trainer/requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0b8a210718c4"
},
"outputs": [],
"source": [
"! cat trainer/task.py"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c0c6e7dfb3c6"
},
"outputs": [],
"source": [
"%run trainer/task.py --epochs 5 --no-cuda --local-mode"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "31dfdeede587"
},
"outputs": [],
"source": [
"! ls ./tmp"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "48d56ec621cc"
},
"outputs": [],
"source": [
"! rm -rf ./tmp"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8f3ea1210749"
},
"source": [
"## Vertex Training using Vertex SDK and Custom Container"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "93002a20a2a6"
},
"source": [
"### Build Custom Container"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4130ce43fd08"
},
"outputs": [],
"source": [
"hostname = \"gcr.io\"\n",
"image_name = content_name\n",
"tag = \"latest\"\n",
"\n",
"custom_container_image_uri = f\"{hostname}/{PROJECT_ID}/{image_name}:{tag}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2f1fc5b05240"
},
"outputs": [],
"source": [
"! cd trainer && docker build -t $custom_container_image_uri -f Dockerfile ."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b4f274f499ac"
},
"outputs": [],
"source": [
"! docker run --rm $custom_container_image_uri --epochs 5 --no-cuda --local-mode"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ee1a0a06d0b4"
},
"outputs": [],
"source": [
"! docker push $custom_container_image_uri"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cb763be12fc9"
},
"outputs": [],
"source": [
"! gcloud container images list --repository $hostname/$PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "10c8cc6b3334"
},
"source": [
"### Initialize Vertex SDK"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1a12348169fa"
},
"outputs": [],
"source": [
"! pip install -r requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "42e981cefe41"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(\n",
" project=PROJECT_ID,\n",
" staging_bucket=BUCKET_NAME,\n",
" location=REGION,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "73c92c9298e9"
},
"source": [
"### Create a Vertex Tensorboard Instance"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bde509558cd5"
},
"outputs": [],
"source": [
"content_name = content_name + \"-cpu\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6d7908c0083c"
},
"outputs": [],
"source": [
"tensorboard = aiplatform.Tensorboard.create(\n",
" display_name=content_name,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a1f0a4f54037"
},
"source": [
"#### Option: Use a Previously Created Vertex Tensorboard Instance\n",
"\n",
"```\n",
"tensorboard_name = \"Your Tensorboard Resource Name or Tensorboard ID\"\n",
"tensorboard = aiplatform.Tensorboard(tensorboard_name=tensorboard_name)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a4cac84e04ac"
},
"source": [
"### Run a Vertex SDK CustomContainerTrainingJob"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f92e8fdd44ee"
},
"outputs": [],
"source": [
"display_name = content_name\n",
"gcs_output_uri_prefix = f\"{BUCKET_NAME}/{display_name}\"\n",
"\n",
"replica_count = 4\n",
"machine_type = \"n1-standard-4\"\n",
"\n",
"args = [\n",
" \"--backend\",\n",
" \"gloo\",\n",
" \"--no-cuda\",\n",
" \"--batch-size\",\n",
" \"128\",\n",
" \"--epochs\",\n",
" \"25\",\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ae4c57df7e07"
},
"outputs": [],
"source": [
"custom_container_training_job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=display_name,\n",
" container_uri=custom_container_image_uri,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "35cf3ecdf0df"
},
"outputs": [],
"source": [
"custom_container_training_job.run(\n",
" args=args,\n",
" base_output_dir=gcs_output_uri_prefix,\n",
" replica_count=replica_count,\n",
" machine_type=machine_type,\n",
" tensorboard=tensorboard.resource_name,\n",
" service_account=SERVICE_ACCOUNT,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "49d10dded73b"
},
"outputs": [],
"source": [
"print(f\"Custom Training Job Name: {custom_container_training_job.resource_name}\")\n",
"print(f\"GCS Output URI Prefix: {gcs_output_uri_prefix}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "78398f52807b"
},
"source": [
"### Training Output Artifact"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fc74422de1d1"
},
"outputs": [],
"source": [
"! gsutil ls $gcs_output_uri_prefix"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5e99a6a05b10"
},
"source": [
"## Clean Up Artifact"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b0c1b3f7466b"
},
"outputs": [],
"source": [
"! gsutil rm -rf $gcs_output_uri_prefix"
]
}
],
"metadata": {
"colab": {
"name": "multi_node_ddp_gloo_vertex_training_with_custom_container.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -1,347 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a6b56b1c7b76"
},
"outputs": [],
"source": [
"# Copyright 2021 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": "20a5ea0081d0"
},
"source": [
"# PyTorch Image Classification Multi-Node Distributed Data Parallel Training on GPU using Vertex Training with Custom Container"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8752d4a255fb"
},
"source": [
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/community-content/pytorch_image_classification_distributed_data_parallel_training_with_vertex_sdk/multi_node_ddp_nccl_vertex_training_with_custom_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",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "03d216c7f7b1"
},
"source": [
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c5ac73516218"
},
"outputs": [],
"source": [
"PROJECT_ID = \"YOUR PROJECT ID\"\n",
"BUCKET_NAME = \"gs://YOUR BUCKET NAME\"\n",
"REGION = \"YOUR REGION\"\n",
"SERVICE_ACCOUNT = \"YOUR SERVICE ACCOUNT\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0b5ae674177e"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_NAME"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "19a9b3bdd553"
},
"outputs": [],
"source": [
"content_name = \"pt-img-cls-multi-node-ddp-cust-cont\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5307fe28b633"
},
"source": [
"## Vertex Training using Vertex SDK and Custom Container"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "46cb58c7fbf9"
},
"source": [
"### Built Custom Container"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "97e66e9f9bab"
},
"outputs": [],
"source": [
"hostname = \"gcr.io\"\n",
"image_name = content_name\n",
"tag = \"latest\"\n",
"\n",
"custom_container_image_uri = f\"{hostname}/{PROJECT_ID}/{image_name}:{tag}\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ae9b29c4773f"
},
"source": [
"### Initialize Vertex SDK"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dc1e84d5dec2"
},
"outputs": [],
"source": [
"! pip install -r requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6964be27b98e"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(\n",
" project=PROJECT_ID,\n",
" staging_bucket=BUCKET_NAME,\n",
" location=REGION,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "594a91f438f2"
},
"source": [
"### Create a Vertex Tensorboard Instance"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "93134273261e"
},
"outputs": [],
"source": [
"content_name = content_name + \"-gpu\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c2bd82dbcd9b"
},
"outputs": [],
"source": [
"tensorboard = aiplatform.Tensorboard.create(\n",
" display_name=content_name,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ebc593c6472e"
},
"source": [
"#### Option: Use a Previously Created Vertex Tensorboard Instance\n",
"\n",
"```\n",
"tensorboard_name = \"Your Tensorboard Resource Name or Tensorboard ID\"\n",
"tensorboard = aiplatform.Tensorboard(tensorboard_name=tensorboard_name)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0769e8e34c2f"
},
"source": [
"### Run a Vertex SDK CustomContainerTrainingJob"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "023f33ece826"
},
"outputs": [],
"source": [
"display_name = content_name\n",
"gcs_output_uri_prefix = f\"{BUCKET_NAME}/{display_name}\"\n",
"\n",
"replica_count = 1\n",
"machine_type = \"n1-standard-4\"\n",
"accelerator_count = 4\n",
"accelerator_type = \"NVIDIA_TESLA_K80\"\n",
"\n",
"args = [\n",
" \"--backend\",\n",
" \"nccl\",\n",
" \"--batch-size\",\n",
" \"128\",\n",
" \"--epochs\",\n",
" \"25\",\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d4b599e726ef"
},
"outputs": [],
"source": [
"custom_container_training_job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=display_name,\n",
" container_uri=custom_container_image_uri,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "81321e3bdf7f"
},
"outputs": [],
"source": [
"custom_container_training_job.run(\n",
" args=args,\n",
" base_output_dir=gcs_output_uri_prefix,\n",
" replica_count=replica_count,\n",
" machine_type=machine_type,\n",
" accelerator_count=accelerator_count,\n",
" accelerator_type=accelerator_type,\n",
" tensorboard=tensorboard.resource_name,\n",
" service_account=SERVICE_ACCOUNT,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5100712c2c4c"
},
"outputs": [],
"source": [
"print(f\"Custom Training Job Name: {custom_container_training_job.resource_name}\")\n",
"print(f\"GCS Output URI Prefix: {gcs_output_uri_prefix}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f9b77676e5a6"
},
"source": [
"### Training Output Artifact"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0e171ce95ace"
},
"outputs": [],
"source": [
"! gsutil ls $gcs_output_uri_prefix"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cf1b74a12b87"
},
"source": [
"## Clean Up Artifact"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a0b15089c341"
},
"outputs": [],
"source": [
"! gsutil rm -rf $gcs_output_uri_prefix"
]
}
],
"metadata": {
"colab": {
"name": "multi_node_ddp_nccl_vertex_training_with_custom_container.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,30 @@
# PyTorch Deployment on Google Cloud: Text Classification
**This is an Experimental release**, covered by the Pre-GA Offerings Terms of your Google Cloud Platform [Terms of Service](https://cloud.google.com/terms).
Experiments are focused on validating a prototype and are not guaranteed to be released. They are not intended for production use or covered by any SLA, support obligation, or deprecation policy and might be subject to backward-incompatible changes.
**Kindly drop us a note before you run any scale tests.**
**Do not hesitate to contact vertexai-prediction-preview-feedback@google.com if you have any questions or run into any issues.**
The projects need to be added to the allowlist in order to deploy PyTorch models using Vertex AI Prediction pre-built PyTorch images. If you are interested in the feature, please send an email to vertexai-prediction-preview-feedback@google.com to provide your project numbers OR project ids.
## Overview
In the PyTorch on Google Cloud series of blog posts, we aim to share how to deploy PyTorch models at scale on [Vertex AI](https://cloud.google.com/vertex-ai).
This tutorial on text classification shows how to deploy a PyTorch based text classification model on [Vertex AI](https://cloud.google.com/vertex-ai/docs/start/client-libraries#python) using Vertex SDK and [`gcloud ai`](https://cloud.google.com/sdk/gcloud/reference/beta/ai).
## Notebooks
| <h4>Notebook</h4> | <h4>Description</h4> |
| :-------- | :------- |
| [pytorch-text-classification-vertex-ai-deploy.ipynb](./pytorch-text-classification-vertex-ai-deploy.ipynb) | Notebook to show deploying a PyTorch model on Vertex AI |
## Folders
| <h4>Folder Name</h4> | <h4>Description</h4> |
| :-------- | :------- |
| [`predictor`](./predictor) | Folder with custom prediction handler to deploy a PyTorch model to Vertex Prediction. In the [notebook](./pytorch-text-classification-vertex-ai-deploy.ipynb), this folder is used for deploying a PyTorch model on Vertex AI using Vertex Prediction pre-built PyTorch images |
@@ -0,0 +1,91 @@
import os
import json
import logging
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from ts.torch_handler.base_handler import BaseHandler
logger = logging.getLogger(__name__)
class TransformersClassifierHandler(BaseHandler):
"""
The handler takes an input string and returns the classification text
based on the serialized transformers checkpoint.
"""
def __init__(self):
super(TransformersClassifierHandler, self).__init__()
self.initialized = False
def initialize(self, ctx):
""" Loads the model.pt file and initialized the model object.
Instantiates Tokenizer for preprocessor to use
Loads labels to name mapping file for post-processing inference response
"""
self.manifest = ctx.manifest
properties = ctx.system_properties
model_dir = properties.get("model_dir")
self.device = torch.device("cuda:" + str(properties.get("gpu_id")) if torch.cuda.is_available() else "cpu")
# Read model serialize/pt file
serialized_file = self.manifest["model"]["serializedFile"]
model_pt_path = os.path.join(model_dir, serialized_file)
if not os.path.isfile(model_pt_path):
raise RuntimeError("Missing the model.pt or pytorch_model.bin file")
# Load model
self.model = AutoModelForSequenceClassification.from_pretrained(model_dir)
self.model.to(self.device)
self.model.eval()
logger.debug('Transformer model from path {0} loaded successfully'.format(model_dir))
# Ensure to use the same tokenizer used during training
self.tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')
# Read the mapping file, index to object name
mapping_file_path = os.path.join(model_dir, "index_to_name.json")
if os.path.isfile(mapping_file_path):
with open(mapping_file_path) as f:
self.mapping = json.load(f)
else:
logger.warning('Missing the index_to_name.json file. Inference output will default.')
self.mapping = {"0": "Negative", "1": "Positive"}
self.initialized = True
def preprocess(self, data):
""" Preprocessing input request by tokenizing
Extend with your own preprocessing steps as needed
"""
text = data[0].get("data")
if text is None:
text = data[0].get("body")
sentences = text.decode('utf-8')
logger.info("Received text: '%s'", sentences)
# Tokenize the texts
tokenizer_args = ((sentences,))
inputs = self.tokenizer(*tokenizer_args,
padding='max_length',
max_length=128,
truncation=True,
return_tensors = "pt")
return inputs
def inference(self, inputs):
""" Predict the class of a text using a trained transformer model.
"""
prediction = self.model(inputs['input_ids'].to(self.device))[0].argmax().item()
if self.mapping:
prediction = self.mapping[str(prediction)]
logger.info("Model predicted: '%s'", prediction)
return [prediction]
def postprocess(self, inference_output):
return inference_output
@@ -0,0 +1,5 @@
{
"0": "Negative",
"1": "Positive"
}
@@ -658,8 +658,8 @@
},
"outputs": [],
"source": [
"datasets = load_dataset(\"imdb\")\n",
"datasets"
"dataset = load_dataset(\"imdb\")\n",
"dataset"
]
},
{
@@ -668,7 +668,7 @@
"id": "RzfPtOMoIrIu"
},
"source": [
"The `datasets` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasetdict), which contains one key for the training, validation and test set."
"The `dataset` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasetdict), which contains one key for the training, validation and test set."
]
},
{
@@ -681,12 +681,12 @@
"source": [
"print(\n",
" \"Total # of rows in training dataset {} and size {:5.2f} MB\".format(\n",
" datasets[\"train\"].shape[0], datasets[\"train\"].size_in_bytes / (1024 * 1024)\n",
" dataset[\"train\"].shape[0], dataset[\"train\"].size_in_bytes / (1024 * 1024)\n",
" )\n",
")\n",
"print(\n",
" \"Total # of rows in test dataset {} and size {:5.2f} MB\".format(\n",
" datasets[\"test\"].shape[0], datasets[\"test\"].size_in_bytes / (1024 * 1024)\n",
" dataset[\"test\"].shape[0], dataset[\"test\"].size_in_bytes / (1024 * 1024)\n",
" )\n",
")"
]
@@ -708,7 +708,7 @@
},
"outputs": [],
"source": [
"datasets[\"train\"][0]"
"dataset[\"train\"][0]"
]
},
{
@@ -728,7 +728,7 @@
},
"outputs": [],
"source": [
"label_list = datasets[\"train\"].unique(\"label\")\n",
"label_list = dataset[\"train\"].unique(\"label\")\n",
"label_list"
]
},
@@ -779,7 +779,7 @@
},
"outputs": [],
"source": [
"show_random_elements(datasets[\"train\"])"
"show_random_elements(dataset[\"train\"])"
]
},
{
@@ -883,7 +883,7 @@
},
"outputs": [],
"source": [
"example = datasets[\"train\"][4]\n",
"example = dataset[\"train\"][4]\n",
"print(example)"
]
},
@@ -920,7 +920,7 @@
"source": [
"# Dataset loading repeated here to make this cell idempotent\n",
"# Since we are over-writing datasets variable\n",
"datasets = load_dataset(\"imdb\")\n",
"dataset = load_dataset(\"imdb\")\n",
"\n",
"# Mapping labels to ids\n",
"# NOTE: We can extract this automatically but the `Unique` method of the datasets\n",
@@ -948,7 +948,7 @@
"\n",
"\n",
"# apply preprocessing function to input examples\n",
"datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=True)"
"dataset = dataset.map(preprocess_function, batched=True, load_from_cache_file=True)"
]
},
{
@@ -1091,8 +1091,8 @@
"trainer = Trainer(\n",
" model,\n",
" args,\n",
" train_dataset=datasets[\"train\"],\n",
" eval_dataset=datasets[\"test\"],\n",
" train_dataset=dataset[\"train\"],\n",
" eval_dataset=dataset[\"test\"],\n",
" data_collator=default_data_collator,\n",
" tokenizer=tokenizer,\n",
" compute_metrics=compute_metrics,\n",
@@ -1,4 +1,4 @@
google-cloud-bigquery==2.20.0
tensorflow==2.5.3
tensorflow==2.7.2
pillow==9.0.1
tf-agents==0.8.0

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