├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── README.md ├── build ├── README.md └── pipeline-deployment.yaml ├── figures ├── overview.png ├── workflow1.png ├── workflow2-1.png └── workflow2.png ├── notebooks ├── README.md └── cloud_build_tfx_part_i.ipynb └── tfx-pipeline ├── .gitignore ├── __init__.py ├── data └── data.csv ├── data_validation.ipynb ├── kubeflow_runner.py ├── kubeflow_v2_runner.py ├── local_runner.py ├── model_analysis.ipynb ├── models ├── __init__.py ├── features.py ├── features_test.py ├── keras_model │ ├── __init__.py │ ├── constants.py │ ├── model.py │ └── model_test.py ├── preprocessing.py └── preprocessing_test.py └── pipeline ├── __init__.py ├── configs.py └── pipeline.py /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | 7 | # Allows you to run this workflow manually from the Actions tab 8 | workflow_dispatch: 9 | 10 | env: 11 | SUBSTITUTIONS: " 12 | _PROJECT=gcp-ml-172005,\ 13 | _REGION=us-central1,\ 14 | _REPO_URL=https://github.com/deep-diver/Model-Training-as-a-CI-CD-System,\ 15 | _BRANCH=main,\ 16 | _PIPELINE_NAME=tfx-pipeline 17 | " 18 | 19 | jobs: 20 | build: 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | - uses: actions/checkout@v2 25 | 26 | - uses: google-github-actions/setup-gcloud@master 27 | with: 28 | version: '286.0.0' 29 | service_account_email: ${{ secrets.RUN_SA_EMAIL }} 30 | service_account_key: ${{ secrets.RUN_SA_KEY }} 31 | project_id: ${{ secrets.RUN_PROJECT }} 32 | 33 | - name: check if tfx-pipeline folder has anything changed 34 | uses: dorny/paths-filter@v2 35 | id: my-pipeline-change 36 | with: 37 | filters: | 38 | src: 39 | - 'tfx-pipeline/**' 40 | 41 | - name: trigger cloud build based on component changes 42 | if: steps.my-pipeline-change.outputs.src == 'true' 43 | run: | 44 | gcloud builds submit --no-source --timeout=60m \ 45 | --config build/pipeline-deployment.yaml \ 46 | --substitutions $SUBSTITUTIONS \ 47 | --machine-type=n1-highcpu-8 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints/ 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Model Training as a CI/CD System 2 | 3 | This project demonstrates the machine model training as a CI/CD system in GCP platform. You will see more detailed workflow in the below section, but it is about rebuilding and redeploying (continuous integration) the currently deployed machine learning pipeline based on changes in code. Such changes could happen in the training data, data pre-processing logic, model architecture and training code, custom pipeline components, and so on. 4 | 5 | An accompanying blog post for this project is available on Google Cloud: [Model training as a CI/CD system: Part I](https://cloud.google.com/blog/topics/developers-practitioners/model-training-cicd-system-part-i). Part II can be found [here](https://cloud.google.com/blog/topics/developers-practitioners/model-training-cicd-system-part-ii) (code: [sayakpaul/ 6 | CI-CD-for-Model-Training](https://github.com/sayakpaul/CI-CD-for-Model-Training)). 7 | 8 | 9 | ## Workflow #1 10 | 11 | ![workflow1](figures/workflow1.png) 12 | 13 | 1. We create initial code, or we make some changes in the existing codebase for pipeline. 14 | 15 | 2. Based on the changes in the step 2, a GitHub action gets triggered to initiate a Cloud Build process. 16 | 17 | 3. The Cloud Build runs unit tests to see if those components work without errors. 18 | 19 | 4. If there is no error at all, there are two common sub-workflows from this point. 20 | - Cloud Build containerizes the current codebase. This is an optional step. If you have any custom components unchanges, this step might be omitted. 21 | - The Cloud Build compiles a new pipeline. It creates an updated docker image, and it uploads the new docker image to GCR 22 | - If there is any codes changed in data preprocessing, modeling, training steps, we only have to upload those source files to designated GCS bucket 23 | 24 | 5. The final step of the Cloud Build is to execute a pipeline run on Vertex AI 25 | 26 | ## Workflow #2 27 | 28 | ![workflow2](figures/workflow2.png) 29 | 30 | ## Workflow in a nutshell 31 | 32 | 1. We create initial code, or we make some changes in the existing codebase for modules. 33 | 34 | 2. Based on the changes in the step 2, a GitHub action gets triggered to initiate a Cloud Build process. 35 | 36 | 3. The Cloud Build runs unit tests to see if those components work without errors. 37 | 38 | 4. If there is no error at all, there are two common sub-workflows from this point. 39 | - If there is any codes changed in data preprocessing and models, we only have to upload those source files to designated GCS bucket. 40 | 41 | 5. The final step of the Cloud Build is to execute a pipeline run on Vertex AI. Trainer and Transform TFX components will look up the changed modules accordingly. 42 | 43 | ## Acknowledgements 44 | 45 | [ML-GDE program](https://developers.google.com/programs/experts/) for providing GCP credits. Thanks to [Karl Weinmeister](https://twitter.com/kweinmeister) for providing review feedback on this project. 46 | -------------------------------------------------------------------------------- /build/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deep-diver/Model-Training-as-a-CI-CD-System/1496cfdf2f7c7d37cf4727fe7b1a8176352072b7/build/README.md -------------------------------------------------------------------------------- /build/pipeline-deployment.yaml: -------------------------------------------------------------------------------- 1 | ###################################################################################################### 2 | # CI/CD steps for Cloud Build to get a compiled TFX pipeline ready for exectuion. 3 | # Referenced from: 4 | # https://github.com/GoogleCloudPlatform/mlops-with-vertex-ai/blob/main/build/pipeline-deployment.yaml 5 | ###################################################################################################### 6 | 7 | steps: 8 | # Clone the repository. 9 | - name: 'gcr.io/cloud-builders/git' 10 | args: ['clone', '--single-branch', '--branch', 11 | '$_BRANCH', '$_REPO_URL', 12 | '--depth', '1', 13 | '--verbose'] 14 | id: 'Clone Repository' 15 | 16 | - name: 'gcr.io/gcp-ml-172005/cb-tfx:latest' 17 | entrypoint: python 18 | args: ['-m', 'pytest', '.'] 19 | dir: 'Model-Training-as-a-CI-CD-System/tfx-pipeline/models' 20 | id: 'Unit Test' 21 | waitFor: ['Clone Repository'] 22 | 23 | - name: 'gcr.io/gcp-ml-172005/cb-tfx:latest' 24 | entrypoint: 'tfx' 25 | args: ['pipeline', 'compile', 26 | '--pipeline-path', 'kubeflow_v2_runner.py', 27 | '--engine', 'vertex', 28 | ] 29 | dir: 'Model-Training-as-a-CI-CD-System/tfx-pipeline' 30 | id: 'Compile Pipeline' 31 | waitFor: ['Unit Test'] 32 | 33 | - name: 'gcr.io/gcp-ml-172005/cb-tfx:latest' 34 | entrypoint: 'tfx' 35 | args: ['pipeline', 'create', 36 | '--pipeline-path', 'kubeflow_v2_runner.py', 37 | '--engine', 'vertex', 38 | '--build-image' 39 | ] 40 | dir: 'Model-Training-as-a-CI-CD-System/tfx-pipeline' 41 | id: 'Create Pipeline' 42 | waitFor: ['Compile Pipeline'] 43 | 44 | # --project=gcp-ml-172005 --region=us-central1 45 | - name: 'gcr.io/gcp-ml-172005/cb-tfx:latest' 46 | entrypoint: 'tfx' 47 | args: ['run', 'create', 48 | '--engine', 'vertex', 49 | '--pipeline-name', '$_PIPELINE_NAME', 50 | '--project', '$_PROJECT', 51 | '--region', '$_REGION' 52 | ] 53 | dir: 'Model-Training-as-a-CI-CD-System/tfx-pipeline' 54 | id: 'Create Pipeline Run' 55 | waitFor: ['Create Pipeline'] 56 | -------------------------------------------------------------------------------- /figures/overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deep-diver/Model-Training-as-a-CI-CD-System/1496cfdf2f7c7d37cf4727fe7b1a8176352072b7/figures/overview.png -------------------------------------------------------------------------------- /figures/workflow1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deep-diver/Model-Training-as-a-CI-CD-System/1496cfdf2f7c7d37cf4727fe7b1a8176352072b7/figures/workflow1.png -------------------------------------------------------------------------------- /figures/workflow2-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deep-diver/Model-Training-as-a-CI-CD-System/1496cfdf2f7c7d37cf4727fe7b1a8176352072b7/figures/workflow2-1.png -------------------------------------------------------------------------------- /figures/workflow2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deep-diver/Model-Training-as-a-CI-CD-System/1496cfdf2f7c7d37cf4727fe7b1a8176352072b7/figures/workflow2.png -------------------------------------------------------------------------------- /notebooks/README.md: -------------------------------------------------------------------------------- 1 | # Notebooks -------------------------------------------------------------------------------- /notebooks/cloud_build_tfx_part_i.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "In this notebook, we will walk you through the steps to launch a [Cloud Build](https://cloud.google.com/build) job to:\n", 8 | "\n", 9 | "* Clone the repository where the code is hosted.\n", 10 | "* Compile a TFX (TensorFlow Extended) pipeline.\n", 11 | "* Build a Docker image with custom TFX components.\n", 12 | "* Submit the pipeline to Vertex AI for execution. \n", 13 | "\n", 14 | "Below you can find a pictorial overview of the overall workflow:\n", 15 | "\n", 16 | "![](https://i.ibb.co/bzS8vzZ/first-workflow.png)\n", 17 | "\n", 18 | "**Note** that we won't be covering the part related to GitHub Actions. For that, we refer the interested readers to our blog post instead.\n", 19 | "\n", 20 | "For the best experience, we suggest running this notebook from [Vertex AI Notebooks](https://cloud.google.com/vertex-ai/docs/general/notebooks).\n" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## Step 0\n", 28 | "\n", 29 | "We first need to have a Docker image ready which we could use with Cloud Build to perform the mentioned steps. We first write a `Dockerfile` which is going to be used to build and push the image to Google Container Registry (GCR)." 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "%%writefile Dockerfile\n", 39 | "\n", 40 | "FROM tensorflow/tfx:1.2.0\n", 41 | "RUN pip install kfp==1.7.1 pytest" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "TFX_IMAGE_URI = \"gcr.io/{gcp-project}/{name}\"\n", 51 | "!gcloud builds submit --tag $TFX_IMAGE_URI . --timeout=15m --machine-type=e2-highcpu-8" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "This may take some time. " 59 | ] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "metadata": {}, 64 | "source": [ 65 | "## Step 1\n", 66 | "\n", 67 | "With the initial Docker image ready, we are good to proceed to the next steps. Here we will be manually triggering a build and for that we need to define a couple of variables. But note that this project is configured with a GitHub Action workflow that monitors code changes made to a certain directory and triggers builds automatically based on that." 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "metadata": {}, 74 | "outputs": [], 75 | "source": [ 76 | "# You'd need to change these values accordingly.\n", 77 | "\n", 78 | "SUBSTITUTIONS= \"\"\"\n", 79 | " _PROJECT=gcp-ml-172005,\n", 80 | " _REGION=us-central1,\n", 81 | " _REPO_URL=https://github.com/deep-diver/Model-Training-as-a-CI-CD-System,\n", 82 | " _BRANCH=main,\n", 83 | " _PIPELINE_NAME=tfx-pipeline\n", 84 | "\"\"\"" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "## Step 2\n", 92 | "\n", 93 | "Clone the repository to get the build specification. You can know more about specification files needed for Cloud Build from [here](https://cloud.google.com/build/docs/build-config-file-schema)." 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "!git clone https://github.com/deep-diver/Model-Training-as-a-CI-CD-System" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "metadata": {}, 108 | "source": [ 109 | "## Step 3\n", 110 | "\n", 111 | "Now, we can submit to Cloud Build." 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "%cd Model-Training-as-a-CI-CD-System\n", 121 | "!gcloud builds submit --no-source --timeout=60m \\\n", 122 | " --config build/pipeline-deployment.yaml \\\n", 123 | " --substitutions $SUBSTITUTIONS \\\n", 124 | " --machine-type=n1-highcpu-8" 125 | ] 126 | } 127 | ], 128 | "metadata": { 129 | "kernelspec": { 130 | "display_name": "Python 3", 131 | "language": "python", 132 | "name": "python3" 133 | }, 134 | "language_info": { 135 | "codemirror_mode": { 136 | "name": "ipython", 137 | "version": 3 138 | }, 139 | "file_extension": ".py", 140 | "mimetype": "text/x-python", 141 | "name": "python", 142 | "nbconvert_exporter": "python", 143 | "pygments_lexer": "ipython3", 144 | "version": "3.8.6" 145 | } 146 | }, 147 | "nbformat": 4, 148 | "nbformat_minor": 4 149 | } 150 | -------------------------------------------------------------------------------- /tfx-pipeline/.gitignore: -------------------------------------------------------------------------------- 1 | tfx-pipeline.tar.gz # Pipeline definition file in argo format for Kubeflow. 2 | tfx_pipeline_output # Default pipeline output directory 3 | tfx_metadata # Default tfx metadata SQLite DB directory 4 | -------------------------------------------------------------------------------- /tfx-pipeline/__init__.py: -------------------------------------------------------------------------------- 1 | # Lint as: python2, python3 2 | # Copyright 2020 Google LLC. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | -------------------------------------------------------------------------------- /tfx-pipeline/data_validation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "# import required libs\n", 10 | "import glob\n", 11 | "import os\n", 12 | "\n", 13 | "import tensorflow as tf\n", 14 | "import tensorflow_data_validation as tfdv\n", 15 | "print('TF version: {}'.format(tf.version.VERSION))\n", 16 | "print('TFDV version: {}'.format(tfdv.version.__version__))" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "# Read artifact information from metadata store.\n", 26 | "import beam_dag_runner\n", 27 | "\n", 28 | "from tfx.orchestration import metadata\n", 29 | "from tfx.types import standard_artifacts\n", 30 | "\n", 31 | "metadata_connection_config = metadata.sqlite_metadata_connection_config(\n", 32 | " beam_dag_runner.METADATA_PATH)\n", 33 | "with metadata.Metadata(metadata_connection_config) as store:\n", 34 | " stats_artifacts = store.get_artifacts_by_type(standard_artifacts.ExampleStatistics.TYPE_NAME)\n", 35 | " schema_artifacts = store.get_artifacts_by_type(standard_artifacts.Schema.TYPE_NAME)\n", 36 | " anomalies_artifacts = store.get_artifacts_by_type(standard_artifacts.ExampleAnomalies.TYPE_NAME)" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "# configure output paths\n", 46 | "# Exact paths to output artifacts can also be found on KFP Web UI if you are using kubeflow.\n", 47 | "stats_path = stats_artifacts[-1].uri\n", 48 | "train_stats_file = os.path.join(stats_path, 'train', 'stats_tfrecord')\n", 49 | "eval_stats_file = os.path.join(stats_path, 'eval', 'stats_tfrecord')\n", 50 | "print(\"Train stats file:{}, Eval stats file:{}\".format(\n", 51 | " train_stats_file, eval_stats_file))\n", 52 | "\n", 53 | "schema_file = os.path.join(schema_artifacts[-1].uri, 'schema.pbtxt')\n", 54 | "print(\"Generated schame file:{}\".format(schema_file))\n", 55 | "anomalies_file = os.path.join(anomalies_artifacts[-1].uri, 'anomalies.pbtxt')\n", 56 | "print(\"Generated anomalies file:{}\".format(anomalies_file))" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "# load generated statistics from StatisticsGen\n", 66 | "train_stats = tfdv.load_statistics(train_stats_file)\n", 67 | "eval_stats = tfdv.load_statistics(eval_stats_file)\n", 68 | "tfdv.visualize_statistics(lhs_statistics=eval_stats, rhs_statistics=train_stats,\n", 69 | " lhs_name='EVAL_DATASET', rhs_name='TRAIN_DATASET')" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "# load generated schema from SchemaGen\n", 79 | "schema = tfdv.load_schema_text(schema_file)\n", 80 | "tfdv.display_schema(schema=schema)" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "# load data vaildation result from ExampleValidator\n", 90 | "anomalies = tfdv.load_anomalies_text(anomalies_file)\n", 91 | "tfdv.display_anomalies(anomalies)" 92 | ] 93 | } 94 | ], 95 | "metadata": { 96 | "kernelspec": { 97 | "display_name": "Python 3", 98 | "language": "python", 99 | "name": "python3" 100 | }, 101 | "language_info": { 102 | "codemirror_mode": { 103 | "name": "ipython", 104 | "version": 3 105 | }, 106 | "file_extension": ".py", 107 | "mimetype": "text/x-python", 108 | "name": "python", 109 | "nbconvert_exporter": "python", 110 | "pygments_lexer": "ipython3", 111 | "version": "3.7.5rc1" 112 | }, 113 | "pycharm": { 114 | "stem_cell": { 115 | "cell_type": "raw", 116 | "source": [], 117 | "metadata": { 118 | "collapsed": false 119 | } 120 | } 121 | } 122 | }, 123 | "nbformat": 4, 124 | "nbformat_minor": 2 125 | } -------------------------------------------------------------------------------- /tfx-pipeline/kubeflow_runner.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Define KubeflowDagRunner to run the pipeline using Kubeflow.""" 15 | 16 | import os 17 | from absl import logging 18 | 19 | from tfx import v1 as tfx 20 | from pipeline import configs 21 | from pipeline import pipeline 22 | 23 | # TFX pipeline produces many output files and metadata. All output data will be 24 | # stored under this OUTPUT_DIR. 25 | OUTPUT_DIR = os.path.join('gs://', configs.GCS_BUCKET_NAME) 26 | 27 | # TFX produces two types of outputs, files and metadata. 28 | # - Files will be created under PIPELINE_ROOT directory. 29 | PIPELINE_ROOT = os.path.join(OUTPUT_DIR, 'tfx_pipeline_output', 30 | configs.PIPELINE_NAME) 31 | 32 | # The last component of the pipeline, "Pusher" will produce serving model under 33 | # SERVING_MODEL_DIR. 34 | SERVING_MODEL_DIR = os.path.join(PIPELINE_ROOT, 'serving_model') 35 | 36 | # Specifies data file directory. DATA_PATH should be a directory containing CSV 37 | # files for CsvExampleGen in this example. By default, data files are in the 38 | # GCS path: `gs://{GCS_BUCKET_NAME}/tfx-template/data/`. Using a GCS path is 39 | # recommended for KFP. 40 | # 41 | # One can optionally choose to use a data source located inside of the container 42 | # built by the template, by specifying 43 | # DATA_PATH = 'data'. Note that Dataflow does not support use container as a 44 | # dependency currently, so this means CsvExampleGen cannot be used with Dataflow 45 | # (step 8 in the template notebook). 46 | 47 | DATA_PATH = 'gs://{}/tfx-template/data/taxi/'.format(configs.GCS_BUCKET_NAME) 48 | 49 | 50 | def run(): 51 | """Define a kubeflow pipeline.""" 52 | 53 | # Metadata config. The defaults works work with the installation of 54 | # KF Pipelines using Kubeflow. If installing KF Pipelines using the 55 | # lightweight deployment option, you may need to override the defaults. 56 | # If you use Kubeflow, metadata will be written to MySQL database inside 57 | # Kubeflow cluster. 58 | metadata_config = tfx.orchestration.experimental.get_default_kubeflow_metadata_config( 59 | ) 60 | 61 | runner_config = tfx.orchestration.experimental.KubeflowDagRunnerConfig( 62 | kubeflow_metadata_config=metadata_config, 63 | tfx_image=configs.PIPELINE_IMAGE) 64 | pod_labels = { 65 | 'add-pod-env': 'true', 66 | tfx.orchestration.experimental.LABEL_KFP_SDK_ENV: 'tfx-template' 67 | } 68 | tfx.orchestration.experimental.KubeflowDagRunner( 69 | config=runner_config, pod_labels_to_attach=pod_labels 70 | ).run( 71 | pipeline.create_pipeline( 72 | pipeline_name=configs.PIPELINE_NAME, 73 | pipeline_root=PIPELINE_ROOT, 74 | data_path=DATA_PATH, 75 | # TODO(step 7): (Optional) Uncomment below to use BigQueryExampleGen. 76 | # query=configs.BIG_QUERY_QUERY, 77 | preprocessing_fn=configs.PREPROCESSING_FN, 78 | run_fn=configs.RUN_FN, 79 | train_args=tfx.proto.TrainArgs(num_steps=configs.TRAIN_NUM_STEPS), 80 | eval_args=tfx.proto.EvalArgs(num_steps=configs.EVAL_NUM_STEPS), 81 | eval_accuracy_threshold=configs.EVAL_ACCURACY_THRESHOLD, 82 | serving_model_dir=SERVING_MODEL_DIR, 83 | # TODO(step 7): (Optional) Uncomment below to use provide GCP related 84 | # config for BigQuery with Beam DirectRunner. 85 | # beam_pipeline_args=configs 86 | # .BIG_QUERY_WITH_DIRECT_RUNNER_BEAM_PIPELINE_ARGS, 87 | # TODO(step 8): (Optional) Uncomment below to use Dataflow. 88 | # beam_pipeline_args=configs.DATAFLOW_BEAM_PIPELINE_ARGS, 89 | # TODO(step 9): (Optional) Uncomment below to use Cloud AI Platform. 90 | # ai_platform_training_args=configs.GCP_AI_PLATFORM_TRAINING_ARGS, 91 | # TODO(step 9): (Optional) Uncomment below to use Cloud AI Platform. 92 | # ai_platform_serving_args=configs.GCP_AI_PLATFORM_SERVING_ARGS, 93 | )) 94 | 95 | 96 | if __name__ == '__main__': 97 | logging.set_verbosity(logging.INFO) 98 | run() 99 | -------------------------------------------------------------------------------- /tfx-pipeline/kubeflow_v2_runner.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Define KubeflowV2DagRunner to run the pipeline.""" 15 | 16 | import os 17 | from absl import logging 18 | 19 | from pipeline import configs 20 | from pipeline import pipeline 21 | from tfx.orchestration.kubeflow.v2 import kubeflow_v2_dag_runner 22 | from tfx.proto import trainer_pb2 23 | 24 | # TFX pipeline produces many output files and metadata. All output data will be 25 | # stored under this OUTPUT_DIR. 26 | # NOTE: It is recommended to have a separated OUTPUT_DIR which is *outside* of 27 | # the source code structure. Please change OUTPUT_DIR to other location 28 | # where we can store outputs of the pipeline. 29 | _OUTPUT_DIR = os.path.join('gs://', configs.GCS_BUCKET_NAME) 30 | 31 | # TFX produces two types of outputs, files and metadata. 32 | # - Files will be created under PIPELINE_ROOT directory. 33 | # - Metadata will be written to metadata service backend. 34 | _PIPELINE_ROOT = os.path.join(_OUTPUT_DIR, 'tfx_pipeline_output', 35 | configs.PIPELINE_NAME) 36 | 37 | # The last component of the pipeline, "Pusher" will produce serving model under 38 | # SERVING_MODEL_DIR. 39 | _SERVING_MODEL_DIR = os.path.join(_PIPELINE_ROOT, 'serving_model') 40 | 41 | _DATA_PATH = 'gs://{}/tfx-template/data/taxi/'.format(configs.GCS_BUCKET_NAME) 42 | 43 | def run(): 44 | """Define a pipeline to be executed using Kubeflow V2 runner.""" 45 | 46 | runner_config = kubeflow_v2_dag_runner.KubeflowV2DagRunnerConfig( 47 | default_image=configs.PIPELINE_IMAGE) 48 | 49 | dsl_pipeline = pipeline.create_pipeline( 50 | pipeline_name=configs.PIPELINE_NAME, 51 | pipeline_root=_PIPELINE_ROOT, 52 | data_path=_DATA_PATH, 53 | # TODO(step 7): (Optional) Uncomment here to use BigQueryExampleGen. 54 | # query=configs.BIG_QUERY_QUERY, 55 | preprocessing_fn=configs.PREPROCESSING_FN, 56 | run_fn=configs.RUN_FN, 57 | train_args=trainer_pb2.TrainArgs(num_steps=configs.TRAIN_NUM_STEPS), 58 | eval_args=trainer_pb2.EvalArgs(num_steps=configs.EVAL_NUM_STEPS), 59 | eval_accuracy_threshold=configs.EVAL_ACCURACY_THRESHOLD, 60 | serving_model_dir=_SERVING_MODEL_DIR, 61 | 62 | # Uncomment below to use Dataflow. 63 | # beam_pipeline_args=configs.DATAFLOW_BEAM_PIPELINE_ARGS, 64 | 65 | ai_platform_training_args=configs.GCP_AI_PLATFORM_TRAINING_ARGS, 66 | 67 | # Uncomment below to use Cloud AI Platform. 68 | # ai_platform_serving_args=configs.GCP_AI_PLATFORM_SERVING_ARGS, 69 | ) 70 | 71 | runner = kubeflow_v2_dag_runner.KubeflowV2DagRunner(config=runner_config) 72 | 73 | runner.run(pipeline=dsl_pipeline) 74 | 75 | 76 | if __name__ == '__main__': 77 | logging.set_verbosity(logging.INFO) 78 | run() 79 | -------------------------------------------------------------------------------- /tfx-pipeline/local_runner.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Define LocalDagRunner to run the pipeline locally.""" 15 | 16 | import os 17 | from absl import logging 18 | 19 | from tfx import v1 as tfx 20 | from pipeline import configs 21 | from pipeline import pipeline 22 | 23 | # TFX pipeline produces many output files and metadata. All output data will be 24 | # stored under this OUTPUT_DIR. 25 | # NOTE: It is recommended to have a separated OUTPUT_DIR which is *outside* of 26 | # the source code structure. Please change OUTPUT_DIR to other location 27 | # where we can store outputs of the pipeline. 28 | OUTPUT_DIR = '.' 29 | 30 | # TFX produces two types of outputs, files and metadata. 31 | # - Files will be created under PIPELINE_ROOT directory. 32 | # - Metadata will be written to SQLite database in METADATA_PATH. 33 | PIPELINE_ROOT = os.path.join(OUTPUT_DIR, 'tfx_pipeline_output', 34 | configs.PIPELINE_NAME) 35 | METADATA_PATH = os.path.join(OUTPUT_DIR, 'tfx_metadata', configs.PIPELINE_NAME, 36 | 'metadata.db') 37 | 38 | # The last component of the pipeline, "Pusher" will produce serving model under 39 | # SERVING_MODEL_DIR. 40 | SERVING_MODEL_DIR = os.path.join(PIPELINE_ROOT, 'serving_model') 41 | 42 | # Specifies data file directory. DATA_PATH should be a directory containing CSV 43 | # files for CsvExampleGen in this example. By default, data files are in the 44 | # `data` directory. 45 | # NOTE: If you upload data files to GCS(which is recommended if you use 46 | # Kubeflow), you can use a path starting "gs://YOUR_BUCKET_NAME/path" for 47 | # DATA_PATH. For example, 48 | # DATA_PATH = 'gs://bucket/chicago_taxi_trips/csv/'. 49 | DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') 50 | 51 | 52 | def run(): 53 | """Define a local pipeline.""" 54 | 55 | tfx.orchestration.LocalDagRunner().run( 56 | pipeline.create_pipeline( 57 | pipeline_name=configs.PIPELINE_NAME, 58 | pipeline_root=PIPELINE_ROOT, 59 | data_path=DATA_PATH, 60 | # TODO(step 7): (Optional) Uncomment here to use BigQueryExampleGen. 61 | # query=configs.BIG_QUERY_QUERY, 62 | preprocessing_fn=configs.PREPROCESSING_FN, 63 | run_fn=configs.RUN_FN, 64 | train_args=tfx.proto.TrainArgs(num_steps=configs.TRAIN_NUM_STEPS), 65 | eval_args=tfx.proto.EvalArgs(num_steps=configs.EVAL_NUM_STEPS), 66 | eval_accuracy_threshold=configs.EVAL_ACCURACY_THRESHOLD, 67 | serving_model_dir=SERVING_MODEL_DIR, 68 | # TODO(step 7): (Optional) Uncomment here to use provide GCP related 69 | # config for BigQuery with Beam DirectRunner. 70 | # beam_pipeline_args=configs. 71 | # BIG_QUERY_WITH_DIRECT_RUNNER_BEAM_PIPELINE_ARGS, 72 | metadata_connection_config=tfx.orchestration.metadata 73 | .sqlite_metadata_connection_config(METADATA_PATH))) 74 | 75 | 76 | if __name__ == '__main__': 77 | logging.set_verbosity(logging.INFO) 78 | run() 79 | -------------------------------------------------------------------------------- /tfx-pipeline/model_analysis.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "# import required libs\n", 10 | "import glob\n", 11 | "import os\n", 12 | "\n", 13 | "import tensorflow as tf\n", 14 | "import tensorflow_model_analysis as tfma\n", 15 | "print('TF version: {}'.format(tf.version.VERSION))\n", 16 | "print('TFMA version: {}'.format(tfma.version.VERSION_STRING))" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "# Read artifact information from metadata store.\n", 26 | "import beam_dag_runner\n", 27 | "\n", 28 | "from tfx.orchestration import metadata\n", 29 | "from tfx.types import standard_artifacts\n", 30 | "\n", 31 | "metadata_connection_config = metadata.sqlite_metadata_connection_config(\n", 32 | " beam_dag_runner.METADATA_PATH)\n", 33 | "with metadata.Metadata(metadata_connection_config) as store:\n", 34 | " model_eval_artifacts = store.get_artifacts_by_type(standard_artifacts.ModelEvaluation.TYPE_NAME)" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "# configure output paths\n", 44 | "# Exact paths to output artifacts can be found in the execution logs\n", 45 | "# or KFP Web UI if you are using kubeflow.\n", 46 | "model_eval_path = model_eval_artifacts[-1].uri\n", 47 | "print(\"Generated model evaluation result:{}\".format(model_eval_path))" 48 | ] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "metadata": {}, 53 | "source": [ 54 | "## Install Jupyter Extensions\n", 55 | "Note: If running in a local Jupyter notebook, then these Jupyter extensions must be installed in the environment before running Jupyter.\n", 56 | "\n", 57 | "```bash\n", 58 | "jupyter nbextension enable --py widgetsnbextension\n", 59 | "jupyter nbextension install --py --symlink tensorflow_model_analysis\n", 60 | "jupyter nbextension enable --py tensorflow_model_analysis\n", 61 | "```" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "eval_result = tfma.load_eval_result(model_eval_path)\n", 71 | "tfma.view.render_slicing_metrics(eval_result, slicing_spec = tfma.slicer.SingleSliceSpec(columns=['trip_start_hour']))" 72 | ] 73 | } 74 | ], 75 | "metadata": { 76 | "kernelspec": { 77 | "display_name": "Python 3", 78 | "language": "python", 79 | "name": "python3" 80 | }, 81 | "language_info": { 82 | "codemirror_mode": { 83 | "name": "ipython", 84 | "version": 3 85 | }, 86 | "file_extension": ".py", 87 | "mimetype": "text/x-python", 88 | "name": "python", 89 | "nbconvert_exporter": "python", 90 | "pygments_lexer": "ipython3", 91 | "version": "3.7.5rc1" 92 | }, 93 | "pycharm": { 94 | "stem_cell": { 95 | "cell_type": "raw", 96 | "source": [], 97 | "metadata": { 98 | "collapsed": false 99 | } 100 | } 101 | } 102 | }, 103 | "nbformat": 4, 104 | "nbformat_minor": 2 105 | } -------------------------------------------------------------------------------- /tfx-pipeline/models/__init__.py: -------------------------------------------------------------------------------- 1 | # Lint as: python2, python3 2 | # Copyright 2020 Google LLC. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | -------------------------------------------------------------------------------- /tfx-pipeline/models/features.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """TFX taxi model features. 15 | 16 | Define constants here that are common across all models 17 | including features names, label and size of vocabulary. 18 | """ 19 | 20 | from typing import Text, List 21 | 22 | # At least one feature is needed. 23 | 24 | # Name of features which have continuous float values. These features will be 25 | # used as their own values. 26 | DENSE_FLOAT_FEATURE_KEYS = ['trip_miles'] 27 | 28 | # Name of features which have continuous float values. These features will be 29 | # bucketized using `tft.bucketize`, and will be used as categorical features. 30 | BUCKET_FEATURE_KEYS = ['pickup_latitude'] 31 | # Number of buckets used by tf.transform for encoding each feature. The length 32 | # of this list should be the same with BUCKET_FEATURE_KEYS. 33 | BUCKET_FEATURE_BUCKET_COUNT = [10] 34 | 35 | # Name of features which have categorical values which are mapped to integers. 36 | # These features will be used as categorical features. 37 | CATEGORICAL_FEATURE_KEYS = ['trip_start_hour'] 38 | # Number of buckets to use integer numbers as categorical features. The length 39 | # of this list should be the same with CATEGORICAL_FEATURE_KEYS. 40 | CATEGORICAL_FEATURE_MAX_VALUES = [24] 41 | 42 | # Name of features which have string values and are mapped to integers. 43 | VOCAB_FEATURE_KEYS = [] 44 | 45 | # Uncomment below to add more features to the model 46 | # DENSE_FLOAT_FEATURE_KEYS = ['trip_miles', 'fare', 'trip_seconds'] 47 | # 48 | # BUCKET_FEATURE_KEYS = [ 49 | # 'pickup_latitude', 'pickup_longitude', 'dropoff_latitude', 50 | # 'dropoff_longitude' 51 | # ] 52 | # # Number of buckets used by tf.transform for encoding each feature. 53 | # BUCKET_FEATURE_BUCKET_COUNT = [10, 10, 10, 10] 54 | # 55 | # CATEGORICAL_FEATURE_KEYS = [ 56 | # 'trip_start_hour', 'trip_start_day', 'trip_start_month' 57 | # ] 58 | # # Number of buckets to use integer numbers as categorical features. 59 | # CATEGORICAL_FEATURE_MAX_VALUES = [24, 31, 12] 60 | # 61 | # 62 | # VOCAB_FEATURE_KEYS = [ 63 | # 'payment_type', 64 | # 'company', 65 | # ] 66 | 67 | # Number of vocabulary terms used for encoding VOCAB_FEATURES by tf.transform 68 | VOCAB_SIZE = 1000 69 | 70 | # Count of out-of-vocab buckets in which unrecognized VOCAB_FEATURES are hashed. 71 | OOV_SIZE = 10 72 | 73 | # Keys 74 | LABEL_KEY = 'tips' 75 | FARE_KEY = 'fare' 76 | 77 | 78 | def transformed_name(key: Text) -> Text: 79 | """Generate the name of the transformed feature from original name.""" 80 | return key + '_xf' 81 | 82 | 83 | def vocabulary_name(key: Text) -> Text: 84 | """Generate the name of the vocabulary feature from original name.""" 85 | return key + '_vocab' 86 | 87 | 88 | def transformed_names(keys: List[Text]) -> List[Text]: 89 | """Transform multiple feature names at once.""" 90 | return [transformed_name(key) for key in keys] 91 | -------------------------------------------------------------------------------- /tfx-pipeline/models/features_test.py: -------------------------------------------------------------------------------- 1 | # Lint as: python2, python3 2 | # Copyright 2020 Google LLC. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from __future__ import absolute_import 17 | from __future__ import division 18 | from __future__ import print_function 19 | 20 | import tensorflow as tf 21 | from models import features 22 | 23 | class FeaturesTest(tf.test.TestCase): 24 | 25 | def testNumberOfBucketFeatureBucketCount(self): 26 | self.assertEqual( 27 | len(features.BUCKET_FEATURE_KEYS), 28 | len(features.BUCKET_FEATURE_BUCKET_COUNT)) 29 | self.assertEqual( 30 | len(features.CATEGORICAL_FEATURE_KEYS), 31 | len(features.CATEGORICAL_FEATURE_MAX_VALUES)) 32 | 33 | def testTransformedNames(self): 34 | names = ["f1", "cf"] 35 | self.assertEqual(["f1_xf", "cf_xf"], features.transformed_names(names)) 36 | 37 | 38 | if __name__ == "__main__": 39 | tf.test.main() 40 | -------------------------------------------------------------------------------- /tfx-pipeline/models/keras_model/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /tfx-pipeline/models/keras_model/constants.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Constants for the taxi model. 15 | 16 | These values can be tweaked to affect model training performance. 17 | """ 18 | 19 | HIDDEN_UNITS = [16, 8] 20 | LEARNING_RATE = 0.001 21 | 22 | TRAIN_BATCH_SIZE = 40 23 | EVAL_BATCH_SIZE = 40 24 | -------------------------------------------------------------------------------- /tfx-pipeline/models/keras_model/model.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """TFX template taxi model. 15 | 16 | A DNN keras model which uses features defined in features.py and network 17 | parameters defined in constants.py. 18 | """ 19 | 20 | from absl import logging 21 | import tensorflow as tf 22 | import tensorflow_transform as tft 23 | 24 | from models import features 25 | from models.keras_model import constants 26 | from tfx_bsl.public import tfxio 27 | 28 | 29 | def _get_tf_examples_serving_signature(model, tf_transform_output): 30 | """Returns a serving signature that accepts `tensorflow.Example`.""" 31 | 32 | # We need to track the layers in the model in order to save it. 33 | # TODO(b/162357359): Revise once the bug is resolved. 34 | model.tft_layer_inference = tf_transform_output.transform_features_layer() 35 | 36 | @tf.function(input_signature=[ 37 | tf.TensorSpec(shape=[None], dtype=tf.string, name='examples') 38 | ]) 39 | def serve_tf_examples_fn(serialized_tf_example): 40 | """Returns the output to be used in the serving signature.""" 41 | raw_feature_spec = tf_transform_output.raw_feature_spec() 42 | # Remove label feature since these will not be present at serving time. 43 | raw_feature_spec.pop(features.LABEL_KEY) 44 | raw_features = tf.io.parse_example(serialized_tf_example, raw_feature_spec) 45 | transformed_features = model.tft_layer_inference(raw_features) 46 | logging.info('serve_transformed_features = %s', transformed_features) 47 | 48 | outputs = model(transformed_features) 49 | # TODO(b/154085620): Convert the predicted labels from the model using a 50 | # reverse-lookup (opposite of transform.py). 51 | return {'outputs': outputs} 52 | 53 | return serve_tf_examples_fn 54 | 55 | 56 | def _get_transform_features_signature(model, tf_transform_output): 57 | """Returns a serving signature that applies tf.Transform to features.""" 58 | 59 | # We need to track the layers in the model in order to save it. 60 | # TODO(b/162357359): Revise once the bug is resolved. 61 | model.tft_layer_eval = tf_transform_output.transform_features_layer() 62 | 63 | @tf.function(input_signature=[ 64 | tf.TensorSpec(shape=[None], dtype=tf.string, name='examples') 65 | ]) 66 | def transform_features_fn(serialized_tf_example): 67 | """Returns the transformed_features to be fed as input to evaluator.""" 68 | raw_feature_spec = tf_transform_output.raw_feature_spec() 69 | raw_features = tf.io.parse_example(serialized_tf_example, raw_feature_spec) 70 | transformed_features = model.tft_layer_eval(raw_features) 71 | logging.info('eval_transformed_features = %s', transformed_features) 72 | return transformed_features 73 | 74 | return transform_features_fn 75 | 76 | 77 | def _input_fn(file_pattern, data_accessor, tf_transform_output, batch_size=200): 78 | """Generates features and label for tuning/training. 79 | 80 | Args: 81 | file_pattern: List of paths or patterns of input tfrecord files. 82 | data_accessor: DataAccessor for converting input to RecordBatch. 83 | tf_transform_output: A TFTransformOutput. 84 | batch_size: representing the number of consecutive elements of returned 85 | dataset to combine in a single batch 86 | 87 | Returns: 88 | A dataset that contains (features, indices) tuple where features is a 89 | dictionary of Tensors, and indices is a single Tensor of label indices. 90 | """ 91 | return data_accessor.tf_dataset_factory( 92 | file_pattern, 93 | tfxio.TensorFlowDatasetOptions( 94 | batch_size=batch_size, 95 | label_key=features.transformed_name(features.LABEL_KEY)), 96 | tf_transform_output.transformed_metadata.schema).repeat() 97 | 98 | 99 | def _build_keras_model(hidden_units, learning_rate): 100 | """Creates a DNN Keras model for classifying taxi data. 101 | 102 | Args: 103 | hidden_units: [int], the layer sizes of the DNN (input layer first). 104 | learning_rate: [float], learning rate of the Adam optimizer. 105 | 106 | Returns: 107 | A keras Model. 108 | """ 109 | real_valued_columns = [ 110 | tf.feature_column.numeric_column(key, shape=()) 111 | for key in features.transformed_names(features.DENSE_FLOAT_FEATURE_KEYS) 112 | ] 113 | categorical_columns = [ 114 | tf.feature_column.categorical_column_with_identity( # pylint: disable=g-complex-comprehension 115 | key, 116 | num_buckets=features.VOCAB_SIZE + features.OOV_SIZE, 117 | default_value=0) 118 | for key in features.transformed_names(features.VOCAB_FEATURE_KEYS) 119 | ] 120 | categorical_columns += [ 121 | tf.feature_column.categorical_column_with_identity( # pylint: disable=g-complex-comprehension 122 | key, 123 | num_buckets=num_buckets, 124 | default_value=0) for key, num_buckets in zip( 125 | features.transformed_names(features.BUCKET_FEATURE_KEYS), 126 | features.BUCKET_FEATURE_BUCKET_COUNT) 127 | ] 128 | categorical_columns += [ 129 | tf.feature_column.categorical_column_with_identity( # pylint: disable=g-complex-comprehension 130 | key, 131 | num_buckets=num_buckets, 132 | default_value=0) for key, num_buckets in zip( 133 | features.transformed_names(features.CATEGORICAL_FEATURE_KEYS), 134 | features.CATEGORICAL_FEATURE_MAX_VALUES) 135 | ] 136 | indicator_column = [ 137 | tf.feature_column.indicator_column(categorical_column) 138 | for categorical_column in categorical_columns 139 | ] 140 | 141 | model = _wide_and_deep_classifier( 142 | # TODO(b/140320729) Replace with premade wide_and_deep keras model 143 | wide_columns=indicator_column, 144 | deep_columns=real_valued_columns, 145 | dnn_hidden_units=hidden_units, 146 | learning_rate=learning_rate) 147 | return model 148 | 149 | 150 | def _wide_and_deep_classifier(wide_columns, deep_columns, dnn_hidden_units, 151 | learning_rate): 152 | """Build a simple keras wide and deep model. 153 | 154 | Args: 155 | wide_columns: Feature columns wrapped in indicator_column for wide (linear) 156 | part of the model. 157 | deep_columns: Feature columns for deep part of the model. 158 | dnn_hidden_units: [int], the layer sizes of the hidden DNN. 159 | learning_rate: [float], learning rate of the Adam optimizer. 160 | 161 | Returns: 162 | A Wide and Deep Keras model 163 | """ 164 | # Keras needs the feature definitions at compile time. 165 | # TODO(b/139081439): Automate generation of input layers from FeatureColumn. 166 | input_layers = { 167 | colname: tf.keras.layers.Input(name=colname, shape=(), dtype=tf.float32) 168 | for colname in features.transformed_names( 169 | features.DENSE_FLOAT_FEATURE_KEYS) 170 | } 171 | input_layers.update({ 172 | colname: tf.keras.layers.Input(name=colname, shape=(), dtype='int32') 173 | for colname in features.transformed_names(features.VOCAB_FEATURE_KEYS) 174 | }) 175 | input_layers.update({ 176 | colname: tf.keras.layers.Input(name=colname, shape=(), dtype='int32') 177 | for colname in features.transformed_names(features.BUCKET_FEATURE_KEYS) 178 | }) 179 | input_layers.update({ 180 | colname: tf.keras.layers.Input(name=colname, shape=(), dtype='int32') for 181 | colname in features.transformed_names(features.CATEGORICAL_FEATURE_KEYS) 182 | }) 183 | 184 | # TODO(b/161952382): Replace with Keras premade models and 185 | # Keras preprocessing layers. 186 | deep = tf.keras.layers.DenseFeatures(deep_columns)(input_layers) 187 | for numnodes in dnn_hidden_units: 188 | deep = tf.keras.layers.Dense(numnodes)(deep) 189 | wide = tf.keras.layers.DenseFeatures(wide_columns)(input_layers) 190 | 191 | output = tf.keras.layers.Dense( 192 | 1, activation='sigmoid')( 193 | tf.keras.layers.concatenate([deep, wide])) 194 | output = tf.squeeze(output, -1) 195 | 196 | model = tf.keras.Model(input_layers, output) 197 | model.compile( 198 | loss='binary_crossentropy', 199 | optimizer=tf.keras.optimizers.Adam(lr=learning_rate), 200 | metrics=[tf.keras.metrics.BinaryAccuracy()]) 201 | model.summary(print_fn=logging.info) 202 | return model 203 | 204 | 205 | # TFX Trainer will call this function. 206 | def run_fn(fn_args): 207 | """Train the model based on given args. 208 | 209 | Args: 210 | fn_args: Holds args used to train the model as name/value pairs. 211 | """ 212 | 213 | tf_transform_output = tft.TFTransformOutput(fn_args.transform_output) 214 | 215 | train_dataset = _input_fn(fn_args.train_files, fn_args.data_accessor, 216 | tf_transform_output, constants.TRAIN_BATCH_SIZE) 217 | eval_dataset = _input_fn(fn_args.eval_files, fn_args.data_accessor, 218 | tf_transform_output, constants.EVAL_BATCH_SIZE) 219 | 220 | mirrored_strategy = tf.distribute.MirroredStrategy() 221 | with mirrored_strategy.scope(): 222 | model = _build_keras_model( 223 | hidden_units=constants.HIDDEN_UNITS, 224 | learning_rate=constants.LEARNING_RATE) 225 | 226 | # Write logs to path 227 | tensorboard_callback = tf.keras.callbacks.TensorBoard( 228 | log_dir=fn_args.model_run_dir, update_freq='batch') 229 | 230 | model.fit( 231 | train_dataset, 232 | steps_per_epoch=fn_args.train_steps, 233 | validation_data=eval_dataset, 234 | validation_steps=fn_args.eval_steps, 235 | callbacks=[tensorboard_callback]) 236 | 237 | signatures = { 238 | 'serving_default': 239 | _get_tf_examples_serving_signature(model, tf_transform_output), 240 | 'transform_features': 241 | _get_transform_features_signature(model, tf_transform_output), 242 | } 243 | model.save(fn_args.serving_model_dir, save_format='tf', signatures=signatures) 244 | -------------------------------------------------------------------------------- /tfx-pipeline/models/keras_model/model_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import tensorflow as tf 16 | 17 | from models.keras_model import model 18 | 19 | 20 | class ModelTest(tf.test.TestCase): 21 | 22 | def testBuildKerasModel(self): 23 | built_model = model._build_keras_model( 24 | hidden_units=[1, 1], learning_rate=0.1) # pylint: disable=protected-access 25 | self.assertEqual(len(built_model.layers), 10) 26 | 27 | built_model = model._build_keras_model(hidden_units=[1], learning_rate=0.1) # pylint: disable=protected-access 28 | self.assertEqual(len(built_model.layers), 9) 29 | 30 | 31 | if __name__ == '__main__': 32 | tf.test.main() 33 | -------------------------------------------------------------------------------- /tfx-pipeline/models/preprocessing.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """TFX taxi preprocessing. 15 | 16 | This file defines a template for TFX Transform component. 17 | """ 18 | 19 | import tensorflow as tf 20 | import tensorflow_transform as tft 21 | 22 | from models import features 23 | 24 | 25 | def _fill_in_missing(x): 26 | """Replace missing values in a SparseTensor. 27 | 28 | Fills in missing values of `x` with '' or 0, and converts to a dense tensor. 29 | 30 | Args: 31 | x: A `SparseTensor` of rank 2. Its dense shape should have size at most 1 32 | in the second dimension. 33 | 34 | Returns: 35 | A rank 1 tensor where missing values of `x` have been filled in. 36 | """ 37 | if not isinstance(x, tf.sparse.SparseTensor): 38 | return x 39 | 40 | default_value = '' if x.dtype == tf.string else 0 41 | return tf.squeeze( 42 | tf.sparse.to_dense( 43 | tf.SparseTensor(x.indices, x.values, [x.dense_shape[0], 1]), 44 | default_value), 45 | axis=1) 46 | 47 | 48 | def preprocessing_fn(inputs): 49 | """tf.transform's callback function for preprocessing inputs. 50 | 51 | Args: 52 | inputs: map from feature keys to raw not-yet-transformed features. 53 | 54 | Returns: 55 | Map from string feature key to transformed feature operations. 56 | """ 57 | outputs = {} 58 | for key in features.DENSE_FLOAT_FEATURE_KEYS: 59 | # Preserve this feature as a dense float, setting nan's to the mean. 60 | outputs[features.transformed_name(key)] = tft.scale_to_z_score( 61 | _fill_in_missing(inputs[key])) 62 | 63 | for key in features.VOCAB_FEATURE_KEYS: 64 | # Build a vocabulary for this feature. 65 | outputs[features.transformed_name(key)] = tft.compute_and_apply_vocabulary( 66 | _fill_in_missing(inputs[key]), 67 | top_k=features.VOCAB_SIZE, 68 | num_oov_buckets=features.OOV_SIZE) 69 | 70 | for key, num_buckets in zip(features.BUCKET_FEATURE_KEYS, 71 | features.BUCKET_FEATURE_BUCKET_COUNT): 72 | outputs[features.transformed_name(key)] = tft.bucketize( 73 | _fill_in_missing(inputs[key]), 74 | num_buckets) 75 | 76 | for key in features.CATEGORICAL_FEATURE_KEYS: 77 | outputs[features.transformed_name(key)] = _fill_in_missing(inputs[key]) 78 | 79 | # Was this passenger a big tipper? 80 | taxi_fare = _fill_in_missing(inputs[features.FARE_KEY]) 81 | tips = _fill_in_missing(inputs[features.LABEL_KEY]) 82 | outputs[features.transformed_name(features.LABEL_KEY)] = tf.where( 83 | tf.math.is_nan(taxi_fare), 84 | tf.cast(tf.zeros_like(taxi_fare), tf.int64), 85 | # Test if the tip was > 20% of the fare. 86 | tf.cast( 87 | tf.greater(tips, tf.multiply(taxi_fare, tf.constant(0.2))), tf.int64)) 88 | 89 | return outputs 90 | -------------------------------------------------------------------------------- /tfx-pipeline/models/preprocessing_test.py: -------------------------------------------------------------------------------- 1 | # Lint as: python2, python3 2 | # Copyright 2020 Google LLC. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from __future__ import absolute_import 17 | from __future__ import division 18 | from __future__ import print_function 19 | 20 | import tensorflow as tf 21 | 22 | from models import preprocessing 23 | 24 | 25 | class PreprocessingTest(tf.test.TestCase): 26 | 27 | def testPreprocessingFn(self): 28 | self.assertTrue(callable(preprocessing.preprocessing_fn)) 29 | 30 | 31 | if __name__ == '__main__': 32 | tf.test.main() 33 | -------------------------------------------------------------------------------- /tfx-pipeline/pipeline/__init__.py: -------------------------------------------------------------------------------- 1 | # Lint as: python2, python3 2 | # Copyright 2020 Google LLC. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | -------------------------------------------------------------------------------- /tfx-pipeline/pipeline/configs.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """TFX taxi template configurations. 15 | 16 | This file defines environments for a TFX taxi pipeline. 17 | """ 18 | 19 | import os # pylint: disable=unused-import 20 | 21 | # TODO(b/149347293): Move more TFX CLI flags into python configuration. 22 | 23 | # Pipeline name will be used to identify this pipeline. 24 | PIPELINE_NAME = 'tfx-pipeline' 25 | 26 | # GCP related configs. 27 | 28 | # Following code will retrieve your GCP project. You can choose which project 29 | # to use by setting GOOGLE_CLOUD_PROJECT environment variable. 30 | try: 31 | import google.auth # pylint: disable=g-import-not-at-top # pytype: disable=import-error 32 | try: 33 | _, GOOGLE_CLOUD_PROJECT = google.auth.default() 34 | except google.auth.exceptions.DefaultCredentialsError: 35 | GOOGLE_CLOUD_PROJECT = '' 36 | except ImportError: 37 | GOOGLE_CLOUD_PROJECT = '' 38 | 39 | # Specify your GCS bucket name here. You have to use GCS to store output files 40 | # when running a pipeline with Kubeflow Pipeline on GCP or when running a job 41 | # using Dataflow. Default is '-kubeflowpipelines-default'. 42 | # This bucket is created automatically when you deploy KFP from marketplace. 43 | GCS_BUCKET_NAME = GOOGLE_CLOUD_PROJECT + '-kubeflowpipelines-default' 44 | 45 | # TODO(step 8,step 9): (Optional) Set your region to use GCP services including 46 | # BigQuery, Dataflow and Cloud AI Platform. 47 | GOOGLE_CLOUD_REGION = 'us-central1' # ex) 'us-central1' 48 | 49 | # Following image will be used to run pipeline components run if Kubeflow 50 | # Pipelines used. 51 | # This image will be automatically built by CLI if we use --build-image flag. 52 | PIPELINE_IMAGE = f'gcr.io/{GOOGLE_CLOUD_PROJECT}/{PIPELINE_NAME}' 53 | 54 | PREPROCESSING_FN = 'models.preprocessing.preprocessing_fn' 55 | RUN_FN = 'models.keras_model.model.run_fn' 56 | # NOTE: Uncomment below to use an estimator based model. 57 | # RUN_FN = 'models.estimator_model.model.run_fn' 58 | 59 | TRAIN_NUM_STEPS = 1000 60 | EVAL_NUM_STEPS = 150 61 | 62 | # Change this value according to your use cases. 63 | EVAL_ACCURACY_THRESHOLD = 0.6 64 | 65 | # Beam args to run data processing on DataflowRunner. 66 | # 67 | # TODO(b/151114974): Remove `disk_size_gb` flag after default is increased. 68 | # TODO(b/156874687): Remove `machine_type` after IP addresses are no longer a 69 | # scaling bottleneck. 70 | # TODO(b/171733562): Remove `use_runner_v2` once it is the default for Dataflow. 71 | # TODO(step 8): (Optional) Uncomment below to use Dataflow. 72 | # DATAFLOW_BEAM_PIPELINE_ARGS = [ 73 | # '--project=' + GOOGLE_CLOUD_PROJECT, 74 | # '--runner=DataflowRunner', 75 | # '--temp_location=' + os.path.join('gs://', GCS_BUCKET_NAME, 'tmp'), 76 | # '--region=' + GOOGLE_CLOUD_REGION, 77 | # 78 | # # Temporary overrides of defaults. 79 | # '--disk_size_gb=50', 80 | # '--machine_type=e2-standard-8', 81 | # '--experiments=use_runner_v2', 82 | # ] 83 | 84 | # A dict which contains the training job parameters to be passed to Google 85 | # Cloud AI Platform. For the full set of parameters supported by Google Cloud AI 86 | # Platform, refer to 87 | # https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#Job 88 | # TODO(step 9): (Optional) Uncomment below to use AI Platform training. 89 | GCP_AI_PLATFORM_TRAINING_ARGS = { 90 | 'project': GOOGLE_CLOUD_PROJECT, 91 | 'region': GOOGLE_CLOUD_REGION, 92 | 'scaleTier': 'BASIC_GPU', 93 | 'masterConfig': { 94 | 'imageUri': PIPELINE_IMAGE 95 | }, 96 | } 97 | 98 | # A dict which contains the serving job parameters to be passed to Google 99 | # Cloud AI Platform. For the full set of parameters supported by Google Cloud AI 100 | # Platform, refer to 101 | # https://cloud.google.com/ml-engine/reference/rest/v1/projects.models 102 | # TODO(step 9): (Optional) Uncomment below to use AI Platform serving. 103 | # GCP_AI_PLATFORM_SERVING_ARGS = { 104 | # 'model_name': PIPELINE_NAME.replace('-','_'), # '-' is not allowed. 105 | # 'project_id': GOOGLE_CLOUD_PROJECT, 106 | # # The region to use when serving the model. See available regions here: 107 | # # https://cloud.google.com/ml-engine/docs/regions 108 | # # Note that serving currently only supports a single region: 109 | # # https://cloud.google.com/ml-engine/reference/rest/v1/projects.models#Model # pylint: disable=line-too-long 110 | # 'regions': [GOOGLE_CLOUD_REGION], 111 | # } 112 | -------------------------------------------------------------------------------- /tfx-pipeline/pipeline/pipeline.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Google LLC. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """TFX taxi template pipeline definition. 15 | 16 | This file defines TFX pipeline and various components in the pipeline. 17 | """ 18 | 19 | from typing import Any, Dict, List, Optional, Text 20 | 21 | import tensorflow_model_analysis as tfma 22 | from tfx import v1 as tfx 23 | 24 | from ml_metadata.proto import metadata_store_pb2 25 | 26 | 27 | def create_pipeline( 28 | pipeline_name: Text, 29 | pipeline_root: Text, 30 | data_path: Text, 31 | # TODO(step 7): (Optional) Uncomment here to use BigQuery as a data source. 32 | # query: Text, 33 | preprocessing_fn: Text, 34 | run_fn: Text, 35 | train_args: tfx.proto.TrainArgs, 36 | eval_args: tfx.proto.EvalArgs, 37 | eval_accuracy_threshold: float, 38 | serving_model_dir: Text, 39 | metadata_connection_config: Optional[ 40 | metadata_store_pb2.ConnectionConfig] = None, 41 | beam_pipeline_args: Optional[List[Text]] = None, 42 | ai_platform_training_args: Optional[Dict[Text, Text]] = None, 43 | ai_platform_serving_args: Optional[Dict[Text, Any]] = None, 44 | ) -> tfx.dsl.Pipeline: 45 | """Implements the chicago taxi pipeline with TFX.""" 46 | 47 | components = [] 48 | 49 | # Brings data into the pipeline or otherwise joins/converts training data. 50 | example_gen = tfx.components.CsvExampleGen(input_base=data_path) 51 | components.append(example_gen) 52 | 53 | # Computes statistics over data for visualization and example validation. 54 | statistics_gen = tfx.components.StatisticsGen( 55 | examples=example_gen.outputs['examples']) 56 | components.append(statistics_gen) 57 | 58 | # Generates schema based on statistics files. 59 | schema_gen = tfx.components.SchemaGen( 60 | statistics=statistics_gen.outputs['statistics'], infer_feature_shape=True) 61 | components.append(schema_gen) 62 | 63 | # Performs anomaly detection based on statistics and data schema. 64 | example_validator = tfx.components.ExampleValidator( # pylint: disable=unused-variable 65 | statistics=statistics_gen.outputs['statistics'], 66 | schema=schema_gen.outputs['schema']) 67 | components.append(example_validator) 68 | 69 | # Performs transformations and feature engineering in training and serving. 70 | transform = tfx.components.Transform( 71 | examples=example_gen.outputs['examples'], 72 | schema=schema_gen.outputs['schema'], 73 | preprocessing_fn=preprocessing_fn) 74 | components.append(transform) 75 | 76 | # Uses user-provided Python function that implements a model using TF-Learn. 77 | trainer_args = { 78 | 'run_fn': run_fn, 79 | 'transformed_examples': transform.outputs['transformed_examples'], 80 | 'schema': schema_gen.outputs['schema'], 81 | 'transform_graph': transform.outputs['transform_graph'], 82 | 'train_args': train_args, 83 | 'eval_args': eval_args, 84 | } 85 | if ai_platform_training_args is not None: 86 | trainer_args['custom_config'] = { 87 | tfx.extensions.google_cloud_ai_platform.TRAINING_ARGS_KEY: 88 | ai_platform_training_args, 89 | } 90 | trainer = tfx.extensions.google_cloud_ai_platform.Trainer(**trainer_args) 91 | else: 92 | trainer = tfx.components.Trainer(**trainer_args) 93 | components.append(trainer) 94 | 95 | # Get the latest blessed model for model validation. 96 | model_resolver = tfx.dsl.Resolver( 97 | strategy_class=tfx.dsl.experimental.LatestBlessedModelStrategy, 98 | model=tfx.dsl.Channel(type=tfx.types.standard_artifacts.Model), 99 | model_blessing=tfx.dsl.Channel( 100 | type=tfx.types.standard_artifacts.ModelBlessing)).with_id( 101 | 'latest_blessed_model_resolver') 102 | components.append(model_resolver) 103 | 104 | # Uses TFMA to compute a evaluation statistics over features of a model and 105 | # perform quality validation of a candidate model (compared to a baseline). 106 | eval_config = tfma.EvalConfig( 107 | model_specs=[ 108 | tfma.ModelSpec( 109 | signature_name='serving_default', 110 | label_key='tips_xf', 111 | preprocessing_function_names=['transform_features']) 112 | ], 113 | slicing_specs=[tfma.SlicingSpec()], 114 | metrics_specs=[ 115 | tfma.MetricsSpec(metrics=[ 116 | tfma.MetricConfig( 117 | class_name='BinaryAccuracy', 118 | threshold=tfma.MetricThreshold( 119 | value_threshold=tfma.GenericValueThreshold( 120 | lower_bound={'value': eval_accuracy_threshold}), 121 | change_threshold=tfma.GenericChangeThreshold( 122 | direction=tfma.MetricDirection.HIGHER_IS_BETTER, 123 | absolute={'value': -1e-10}))) 124 | ]) 125 | ]) 126 | evaluator = tfx.components.Evaluator( 127 | examples=example_gen.outputs['examples'], 128 | model=trainer.outputs['model'], 129 | baseline_model=model_resolver.outputs['model'], 130 | # Change threshold will be ignored if there is no baseline (first run). 131 | eval_config=eval_config) 132 | components.append(evaluator) 133 | 134 | # Checks whether the model passed the validation steps and pushes the model 135 | # to a file destination if check passed. 136 | pusher_args = { 137 | 'model': 138 | trainer.outputs['model'], 139 | 'model_blessing': 140 | evaluator.outputs['blessing'], 141 | } 142 | if ai_platform_serving_args is not None: 143 | pusher_args['custom_config'] = { 144 | tfx.extensions.google_cloud_ai_platform.experimental 145 | .PUSHER_SERVING_ARGS_KEY: 146 | ai_platform_serving_args 147 | } 148 | pusher = tfx.extensions.google_cloud_ai_platform.Pusher(**pusher_args) # pylint: disable=unused-variable 149 | else: 150 | pusher_args['push_destination'] = tfx.proto.PushDestination( 151 | filesystem=tfx.proto.PushDestination.Filesystem( 152 | base_directory=serving_model_dir)) 153 | pusher = tfx.components.Pusher(**pusher_args) # pylint: disable=unused-variable 154 | components.append(pusher) 155 | 156 | return tfx.dsl.Pipeline( 157 | pipeline_name=pipeline_name, 158 | pipeline_root=pipeline_root, 159 | components=components, 160 | # Change this value to control caching of execution results. Default value 161 | # is `False`. 162 | # enable_cache=True, 163 | metadata_connection_config=metadata_connection_config, 164 | beam_pipeline_args=beam_pipeline_args, 165 | ) 166 | --------------------------------------------------------------------------------