[
  {
    "path": ".gitignore",
    "content": "# build\n/target/\n/public\ncluster-manager/.m2/\n\n.ipynb_checkpoints\n\n# eclipse\n.classpath\n.settings/\n.project\n\n# Netbeans and IntelliJ files\n!.gitignore\n/nbproject\n/*.ipr\n/*.iws\n*.iml\n.idea\n\n/bin/\n*~\n*.pyc\n.m2\n\\#*\n_*.yaml\n_*.json\n\n\nmodels/tf_mnist/runtime/build/\nmodels/sk_mnist/runtime/build/\n\nmodels/sk_mnist/train/mnist-original.mat\nnotebooks/proto/prediction_pb2.py\nnotebooks/proto/prediction_pb2_grpc.py\nnotebooks/tensorflow\nscripts/kubeflow_src\nscripts/env.sh\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\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       http://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.\n"
  },
  {
    "path": "OWNERS",
    "content": "approvers:\n  - cliveseldon\n  - jinchihe\n  - ryandawsonuk\nreviewers:\n  - cliveseldon\n  - jinchihe\n"
  },
  {
    "path": "README.md",
    "content": "## :warning: **kubeflow/example-seldon is not maintained**\n\nThis repository has been deprecated and [archived](https://github.com/kubeflow/community/issues/479) on Nov 30th, 2021. \n\n\n# Train and Deploy Machine Learning Models on Kubernetes with Kubeflow and Seldon-Core\n\n![MNIST](notebooks/mnist.png \"MNIST Digits\")\n\nUsing:\n\n * [kubeflow](https://github.com/kubeflow/kubeflow)\n * [seldon-core](https://github.com/SeldonIO/seldon-core)\n\nThe example will be the MNIST handwritten digit classification task. We will train 3 different models to solve this task:\n\n * A TensorFlow neural network model.\n * A scikit-learn random forest model.\n * An R least squares model.\n\nWe will then show various rolling deployments\n\n 1. Deploy the single Tensorflow model.\n 2. Do a rolling update to an AB test of the Tensorflow model and the sklearn model.\n 3. Do a rolling update to a Multi-armed Bandit over all 3 models to direct traffic in real time to the best model.\n\n\nIn the follow we will:\n\n 1. [Install kubeflow and seldon-core on a kubernetes cluster](#setup)\n 1. [Train the models](#train-the-models)\n 1. [Serve the models](#serve-the-models)\n\n\n# Requirements\n\n * gcloud\n * kubectl\n * ksonnet\n * argo\n\n\n# Setup\n\n  There is a consolidated script to create the demo which can be found [here](./scripts/README.md). For a step by step guide do the following:\n\n  1. [Install kubeflow on GKE](https://www.kubeflow.org/docs/started/getting-started-gke/). This should create kubeflow in a namespace ```kubeflow```. We suggest you use the command line install so you can easily modify your Ksonnet installation. Ensure you have the environment variables `KUBEFLOW_SRC` and `KFAPP` set. OAUTH is preferred as with basic auth [port-forwarding to ambassador is insufficient](https://github.com/kubeflow/kubeflow/issues/3213)\n\n  1. Install seldon. Go to your Ksonnet application folder setup in the previous step and run\n      ```\n      cd ${KUBEFLOW_SRC}/${KFAPP}/ks_app\n\n      ks pkg install kubeflow/seldon\n      ks generate seldon seldon\n      ks apply default -c seldon\n      ```\n  1. Install Helm\n      ```\n      kubectl -n kube-system create sa tiller\n      kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller\n      helm init --service-account tiller\n      kubectl rollout status deploy/tiller-deploy -n kube-system\n      ```\n  1. Create an NFS disk and persistent volume claim called `nfs-1`. You can follow one guide on create an NFS volume using Google Filestore [here](https://cloud.google.com/community/tutorials/gke-filestore-dynamic-provisioning). A consolidated set of steps is shown [here](nfs.md)\n  1. Add Cluster Roles so Argo can start jobs successfully\n      ```\n      kubectl create clusterrolebinding my-cluster-admin-binding --clusterrole=cluster-admin --user=$(gcloud info --format=\"value(config.account)\")\n      kubectl create clusterrolebinding default-admin2 --clusterrole=cluster-admin --serviceaccount=kubeflow:default\n      ```\n  1. Install Seldon Analytics Dashboard\n      ```\n      helm install seldon-core-analytics --name seldon-core-analytics --set grafana_prom_admin_password=password --set persistence.enabled=false --repo https://storage.googleapis.com/seldon-charts --namespace kubeflow\n      ```\n  1. Port forward the dashboard when running\n      ```\n      kubectl port-forward $(kubectl get pods -n kubeflow -l app=grafana-prom-server -o jsonpath='{.items[0].metadata.name}') -n kubeflow 3000:3000\n      ```\n  1. Visit http://localhost:3000/dashboard/db/prediction-analytics?refresh=5s&orgId=1 and login using \"admin\" and the password you set above when launching with helm.\n\n# MNIST models\n\n## Tensorflow Model\n\n * [Python training code](models/tf_mnist/train/create_model.py)\n * [Python runtime prediction code](models/tf_mnist/runtime/DeepMnist.py)\n * [Dockerfile to wrap runtime prediction code to run under seldon-Core](models/tf_mnist/runtime/Dockerfile).\n\n## SKLearn Model\n\n * [Python training code](models/sk_mnist/train/create_model.py)\n * [Python runtime prediction code](models/sk_mnist/runtime/SkMnist.py)\n * [Dockerfile to wrap runtime prediction code to run under seldon-Core](models/sk_mnist/runtime/Dockerfile).\n\n## R Model\n\n * [R training code](models/r_mnist/train/train.R)\n * [R runtime prediction code](models/r_mnist/runtime/mnist.R)\n * [Dockerfile to wrap runtime prediction code to run under seldon-Core](models/r_mnist/runtime/Dockerfile).\n\n# Train the Models\n\n Follow the steps in [./notebooks/training.ipynb](./notebooks/training.ipynb) to:\n\n * Run Argo Jobs for each model to:\n   * Creating training images and push to repo\n   * Run training\n   * Create runtime prediction images and push to repo\n   * Deploy individual runtime model\n\n**To push to your own repo the Docker images you will need to setup your docker credentials as a Kubernetes secret containing a [config.json](https://www.projectatomic.io/blog/2016/03/docker-credentials-store/). To do this you can find your docker home (typically ~/.docker) and run `kubectl create secret generic docker-config --from-file=config.json=${DOCKERHOME}/config.json --type=kubernetes.io/config` to [create a secret](https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/#registry-secret-existing-credentials).**\n\n# Serve the Models\n\nFollow the steps in [./notebooks/serving.ipynb](./notebooks/serving.ipynb) to:\n\n 1. Deploy the single Tensorflow model.\n 2. Do a rolling update to an AB test of the Tensorflow model and the sklearn model.\n 3. Do a rolling update to a Multi-armed Bandit over all 3 models to direct traffic in real time to the best model.\n\nTo ensure the notebook can run successfully install the python dependencies:\n\n```\npip install -r notebooks/requirements.txt\n```\n\nIf you have [installed the Seldon-Core analytics](#setup) you can view them on the grafana dashboard:\n\n![Grafana](grafana.png \"Grafana Dashboard\")\n"
  },
  {
    "path": "VERSION",
    "content": "0.1"
  },
  {
    "path": "k8s_serving/ab_test_sklearn_tensorflow.json",
    "content": "{\n    \"apiVersion\": \"machinelearning.seldon.io/v1alpha2\",\n    \"kind\": \"SeldonDeployment\",\n    \"metadata\": {\n\t\"labels\": {\n\t    \"app\": \"seldon\"\n\t},\n\t\"name\": \"mnist-classifier\"\n    },\n    \"spec\": {\n\t\"annotations\": {\n\t    \"project_name\": \"kubeflow-seldon\",\n\t    \"deployment_version\": \"v1\",\n\t    \"seldon.io/rest-connection-timeout\": \"100\"\t    \n\t},\n\t\"name\": \"mnist-classifier\",\n\t\"predictors\": [\n\t    {\n\t\t\"componentSpecs\": [{\n\t\t    \"spec\": {\n\t\t\t\"containers\": [\n\t\t\t    {\n                                \"image\": \"seldonio/deepmnistclassifier_runtime:0.2\",\n\t\t\t\t\"name\": \"tf-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n\t\t\t    },\n\t\t\t    {\n                                \"image\": \"seldonio/skmnistclassifier_runtime:0.2\",\n\t\t\t\t\"name\": \"sk-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n\t\t\t    }\n\t\t\t],\n                        \"volumes\": [\n                            {\n                                \"name\": \"persistent-storage\",\n\t\t\t\t\"volumeSource\" : {\n                                    \"persistentVolumeClaim\": {\n\t\t\t\t\t\"claimName\": \"nfs-1\"\n                                    }\n\t\t\t\t}\n                            }\n                        ]\n\t\t    }\n\t\t}],\n\t\t\"name\": \"mnist-classifier\",\n\t\t\"replicas\": 1,\n\t\t\"annotations\": {\n\t\t    \"predictor_version\": \"v1\"\n\t\t},\n\t\t\"graph\": {\n\t\t    \"name\": \"random-ab-test\",\n\t\t    \"implementation\":\"RANDOM_ABTEST\",\n\t\t    \"parameters\": [\n\t\t\t{\n\t\t\t    \"name\":\"ratioA\",\n\t\t\t    \"value\":\"0.5\",\n\t\t\t    \"type\":\"FLOAT\"\n\t\t\t}\n\t\t    ],\n\t\t    \"children\": [\n\t\t\t{\n\t\t\t    \"name\": \"tf-model\",\n\t\t\t    \"endpoint\":{\n\t\t\t\t\"type\":\"REST\"\n\t\t\t    },\n\t\t\t    \"type\":\"MODEL\"\n\t\t\t},\n\t\t\t{\n\t\t\t    \"name\": \"sk-model\",\n\t\t\t    \"endpoint\":{\n\t\t\t\t\"type\":\"REST\"\n\t\t\t    },\n\t\t\t    \"type\":\"MODEL\"\n\t\t\t}   \n\t\t    ]\n\t\t}\n\t    }\n\t]\n    }\n}\n\t\t\n\t\t\n\n \n"
  },
  {
    "path": "k8s_serving/ambassador-auth-service-config.yaml",
    "content": "---\napiVersion: v1\nkind: Service\nmetadata:\n  name: example-auth\n  annotations:\n    getambassador.io/config: |\n      \n      ---\n      apiVersion: ambassador/v0\n      kind:  Module\n      name:  authentication\n      config:\n        auth_service: \"example-auth:3000\"\n        path_prefix: \"/extauth\"\nspec:\n  type: ClusterIP\n  selector:\n    app: example-auth\n  ports:\n  - port: 3000\n    name: http-example-auth\n    targetPort: http-api\n"
  },
  {
    "path": "k8s_serving/ambassador-auth-service-setup.yaml",
    "content": "---\napiVersion: v1\nkind: Service\nmetadata:\n  name: example-auth\nspec:\n  type: ClusterIP\n  selector:\n    app: example-auth\n  ports:\n  - port: 3000\n    name: http-example-auth\n    targetPort: http-api\n---\napiVersion: extensions/v1beta1\nkind: Deployment\nmetadata:\n  name: example-auth\nspec:\n  replicas: 1\n  strategy:\n    type: RollingUpdate\n  template:\n    metadata:\n      labels:\n        app: example-auth\n    spec:\n      containers:\n      - name: example-auth\n        image: seldonio/ambassador-auth-service:1.1.1\n        imagePullPolicy: IfNotPresent\n        ports:\n        - name: http-api\n          containerPort: 3000\n        resources:\n          limits:\n            cpu: \"0.1\"\n            memory: 100Mi\n"
  },
  {
    "path": "k8s_serving/epsilon_greedy.json",
    "content": "{\n    \"apiVersion\": \"machinelearning.seldon.io/v1alpha2\",\n    \"kind\": \"SeldonDeployment\",\n    \"metadata\": {\n\t\"labels\": {\n\t    \"app\": \"seldon\"\n\t},\n\t\"name\": \"mnist-classifier\"\n    },\n    \"spec\": {\n\t\"annotations\": {\n\t    \"project_name\": \"kubeflow-seldon\",\n\t    \"deployment_version\": \"v1\"\n\t},\n\t\"name\": \"mnist-classifier\",\n\t\"predictors\": [\n\t    {\n\t\t\"componentSpecs\": [{\n\t\t    \"spec\": {\n\t\t\t\"containers\": [\n\t\t\t    {\n                                \"image\": \"seldonio/deepmnistclassifier_runtime:0.2\",\n\t\t\t\t\"name\": \"tf-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n\t\t\t    },\n\t\t\t    {\n                                \"image\": \"seldonio/skmnistclassifier_runtime:0.2\",\n\t\t\t\t\"name\": \"sk-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n\t\t\t    },\n\t\t\t    {\n\t\t\t\t\"image\": \"seldonio/mab_epsilon_greedy:1.1\",\n\t\t\t\t\"name\": \"eg-router\"\n\t\t\t    }\n\t\t\t],\n                        \"volumes\": [\n                            {\n                                \"name\": \"persistent-storage\",\n\t\t\t\t\"volumeSource\" : {\n                                    \"persistentVolumeClaim\": {\n\t\t\t\t\t\"claimName\": \"nfs-1\"\n                                    }\n\t\t\t\t}\n                            }\n                        ]\n\t\t    }\n\t\t}],\n\t\t\"name\": \"mnist-classifier\",\n\t\t\"replicas\": 1,\n\t\t\"annotations\": {\n\t\t    \"predictor_version\": \"v1\"\n\t\t},\n\t\t\"graph\": {\n\t\t    \"name\": \"eg-router\",\n\t\t    \"type\":\"ROUTER\",\n\t\t    \"parameters\": [\n\t\t\t{\n\t\t\t    \"name\": \"n_branches\",\n\t\t\t    \"value\": \"2\",\n\t\t\t    \"type\": \"INT\"\n\t\t\t},\n\t\t\t{\n\t\t\t    \"name\": \"epsilon\",\n\t\t\t    \"value\": \"0.1\",\n\t\t\t    \"type\": \"FLOAT\"\n\t\t\t},\n\t\t\t{\n\t\t\t    \"name\": \"verbose\",\n\t\t\t    \"value\": \"1\",\n\t\t\t    \"type\": \"BOOL\"\n\t\t\t}\n\t\t    ],\n\t\t    \"children\": [\n\t\t\t{\n\t\t\t    \"name\": \"sk-model\",\n\t\t\t    \"type\": \"MODEL\",\n\t\t\t    \"endpoint\":{\n\t\t\t\t\"type\":\"REST\"\n\t\t\t    }\n\t\t\t},\n\t\t\t{\n\t\t\t    \"name\": \"tf-model\",\n\t\t\t    \"type\": \"MODEL\",\n\t\t\t    \"endpoint\":{\n\t\t\t\t\"type\":\"REST\"\n\t\t\t    }\n\t\t\t}\n\t\t    ]\n\t\t}\n\t    }\n\t]\n    }\n}\n"
  },
  {
    "path": "k8s_serving/epsilon_greedy_3way.json",
    "content": "{\n    \"apiVersion\": \"machinelearning.seldon.io/v1alpha2\",\n    \"kind\": \"SeldonDeployment\",\n    \"metadata\": {\n\t\"labels\": {\n\t    \"app\": \"seldon\"\n\t},\n\t\"name\": \"mnist-classifier\"\n    },\n    \"spec\": {\n\t\"annotations\": {\n\t    \"project_name\": \"kubeflow-seldon\",\n\t    \"deployment_version\": \"v1\"\n\t},\n\t\"name\": \"mnist-classifier\",\n\t\"predictors\": [\n\t    {\n\t\t\"componentSpecs\": [{\n\t\t    \"spec\": {\n\t\t\t\"containers\": [\n\t\t\t    {\n                                \"image\": \"seldonio/deepmnistclassifier_runtime:0.2\",\n\t\t\t\t\"name\": \"tf-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n\t\t\t    },\n\t\t\t    {\n                                \"image\": \"seldonio/skmnistclassifier_runtime:0.2\",\n\t\t\t\t\"name\": \"sk-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n\t\t\t    },\n\t\t\t    {\n                                \"image\": \"seldonio/rmnistclassifier_runtime:0.2\",\n\t\t\t\t\"name\": \"r-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n\t\t\t    },\n\t\t\t    {\n\t\t\t\t\"image\": \"seldonio/mab_epsilon_greedy:1.1\",\n\t\t\t\t\"name\": \"eg-router\"\n\t\t\t    }\n\t\t\t],\n                        \"volumes\": [\n                            {\n                                \"name\": \"persistent-storage\",\n\t\t\t\t\"volumeSource\" : {\n                                    \"persistentVolumeClaim\": {\n\t\t\t\t\t\"claimName\": \"nfs-1\"\n                                    }\n\t\t\t\t}\n                            }\n                        ]\n\t\t    }\n\t\t}],\n\t\t\"name\": \"mnist-classifier\",\n\t\t\"replicas\": 1,\n\t\t\"annotations\": {\n\t\t    \"predictor_version\": \"v1\"\n\t\t},\n\t\t\"graph\": {\n\t\t    \"name\": \"eg-router\",\n\t\t    \"type\":\"ROUTER\",\n\t\t    \"parameters\": [\n\t\t\t{\n\t\t\t    \"name\": \"n_branches\",\n\t\t\t    \"value\": \"3\",\n\t\t\t    \"type\": \"INT\"\n\t\t\t},\n\t\t\t{\n\t\t\t    \"name\": \"epsilon\",\n\t\t\t    \"value\": \"0.2\",\n\t\t\t    \"type\": \"FLOAT\"\n\t\t\t},\n\t\t\t{\n\t\t\t    \"name\": \"verbose\",\n\t\t\t    \"value\": \"1\",\n\t\t\t    \"type\": \"BOOL\"\n\t\t\t}\n\t\t    ],\n\t\t    \"children\": [\n\t\t\t{\n\t\t\t    \"name\": \"sk-model\",\n\t\t\t    \"type\": \"MODEL\",\n\t\t\t    \"endpoint\":{\n\t\t\t\t\"type\":\"REST\"\n\t\t\t    }\n\t\t\t},\n\t\t\t{\n\t\t\t    \"name\": \"tf-model\",\n\t\t\t    \"type\": \"MODEL\",\n\t\t\t    \"endpoint\":{\n\t\t\t\t\"type\":\"REST\"\n\t\t\t    }\n\t\t\t},\n\t\t\t{\n\t\t\t    \"name\": \"r-model\",\n\t\t\t    \"type\": \"MODEL\",\n\t\t\t    \"endpoint\":{\n\t\t\t\t\"type\":\"REST\"\n\t\t\t    }\n\t\t\t}\n\t\t    ]\n\t\t}\n\t    }\n\t]\n    }\n}\n"
  },
  {
    "path": "k8s_serving/serving_model.json",
    "content": "{\n    \"apiVersion\": \"machinelearning.seldon.io/v1alpha2\",\n    \"kind\": \"SeldonDeployment\",\n    \"metadata\": {\n        \"labels\": {\n            \"app\": \"seldon\"\n        },\n        \"name\": \"mnist-classifier\"\n    },\n    \"spec\": {\n        \"annotations\": {\n            \"deployment_version\": \"v1\",\n            \"project_name\": \"MNIST Example\",\n\t    \"seldon.io/engine-separate-pod\": \"false\",\n\t    \"seldon.io/rest-connection-timeout\": \"100\"\n        },\n        \"name\": \"mnist-classifier\",\n        \"predictors\": [\n            {\n                \"annotations\": {\n                    \"predictor_version\": \"v1\"\n                },\n                \"componentSpecs\": [{\n                    \"spec\": {\n                        \"containers\": [\n                            {\n                                \"image\": \"seldonio/deepmnistclassifier_runtime:0.2\",\n                                \"imagePullPolicy\": \"Always\",\n                                \"name\": \"tf-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n                            }\n                        ],\n                        \"terminationGracePeriodSeconds\": 1,\n                        \"volumes\": [\n                            {\n                                \"name\": \"persistent-storage\",\n\t\t\t\t\"volumeSource\" : {\n                                    \"persistentVolumeClaim\": {\n\t\t\t\t\t\"claimName\": \"nfs-1\"\n                                    }\n\t\t\t\t}\n                            }\n                        ]\n                     }\n                }],\n                \"graph\": {\n                    \"children\": [],\n                    \"endpoint\": {\n                        \"type\": \"REST\"\n                    },\n                    \"name\": \"tf-model\",\n                    \"type\": \"MODEL\"\n                },\n                \"name\": \"mnist-classifier\",\n                \"replicas\": 1\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "k8s_serving/serving_r_model.json",
    "content": "{\n    \"apiVersion\": \"machinelearning.seldon.io/v1alpha2\",\n    \"kind\": \"SeldonDeployment\",\n    \"metadata\": {\n        \"labels\": {\n            \"app\": \"seldon\"\n        },\n        \"name\": \"mnist-classifier\"\n    },\n    \"spec\": {\n        \"annotations\": {\n            \"deployment_version\": \"v1\",\n            \"project_name\": \"MNIST Example\"\n        },\n        \"name\": \"mnist-classifier\",\n        \"predictors\": [\n            {\n                \"annotations\": {\n                    \"predictor_version\": \"v1\"\n                },\n                \"componentSpecs\": [{\n                    \"spec\": {\n                        \"containers\": [\n                            {\n                                \"image\": \"seldonio/rmnistclassifier_runtime:0.2\",\n                                \"imagePullPolicy\": \"Always\",\n                                \"name\": \"r-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n                            }\n                        ],\n                        \"terminationGracePeriodSeconds\": 1,\n                        \"volumes\": [\n                            {\n                                \"name\": \"persistent-storage\",\n\t\t\t\t\"volumeSource\" : {\n                                    \"persistentVolumeClaim\": {\n\t\t\t\t\t\"claimName\": \"nfs-1\"\n                                    }\n\t\t\t\t}\n                            }\n                        ]\n                     }\n                }],\n                \"graph\": {\n                    \"children\": [],\n                    \"endpoint\": {\n                        \"type\": \"REST\"\n                    },\n                    \"name\": \"r-model\",\n                    \"type\": \"MODEL\"\n                },\n                \"name\": \"mnist-classifier\",\n                \"replicas\": 1\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "k8s_serving/serving_sk_model.json",
    "content": "{\n    \"apiVersion\": \"machinelearning.seldon.io/v1alpha2\",\n    \"kind\": \"SeldonDeployment\",\n    \"metadata\": {\n        \"labels\": {\n            \"app\": \"seldon\"\n        },\n        \"name\": \"mnist-classifier\"\n    },\n    \"spec\": {\n        \"annotations\": {\n            \"deployment_version\": \"v1\",\n            \"project_name\": \"MNIST Example\"\n        },\n        \"name\": \"mnist-classifier\",\n        \"predictors\": [\n            {\n                \"annotations\": {\n                    \"predictor_version\": \"v1\"\n                },\n                \"componentSpecs\": [{\n                    \"spec\": {\n                        \"containers\": [\n                            {\n                                \"image\": \"seldonio/skmnistclassifier_runtime:0.2\",\n                                \"imagePullPolicy\": \"Always\",\n                                \"name\": \"sk-model\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n                            }\n                        ],\n                        \"terminationGracePeriodSeconds\": 1,\n                        \"volumes\": [\n                            {\n                                \"name\": \"persistent-storage\",\n\t\t\t\t\"volumeSource\" : {\n                                    \"persistentVolumeClaim\": {\n\t\t\t\t\t\"claimName\": \"nfs-1\"\n                                    }\n\t\t\t\t}\n                            }\n                        ]\n                     }\n                }],\n                \"graph\": {\n                    \"children\": [],\n                    \"endpoint\": {\n                        \"type\": \"REST\"\n                    },\n                    \"name\": \"sk-model\",\n                    \"type\": \"MODEL\"\n                },\n                \"name\": \"mnist-classifier\",\n                \"replicas\": 1\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "k8s_train/sklearn_training_job.yaml",
    "content": "apiVersion: \"batch/v1\"\nkind: \"Job\"\nmetadata: \n  name: \"sk-train\"\n  namespace: \"default\"\nspec: \n  template: \n    metadata: \n      name: \"sk-train\"\n    spec: \n      containers: \n        - \n          image: \"seldonio/skmnistclassifier_trainer:0.1\"\n          name: \"sk-train\"\n          volumeMounts: \n            - \n              mountPath: \"/data\"\n              name: \"persistent-storage\"\n      restartPolicy: \"Never\"\n      volumes: \n        - \n          name: \"persistent-storage\"\n          persistentVolumeClaim: \n            claimName: \"ml-data\"\n"
  },
  {
    "path": "k8s_train/tfJob.json",
    "content": "{\n    \"apiVersion\": \"kubeflow.org/v1alpha1\",\n    \"kind\": \"TFJob\",\n    \"metadata\": {\n        \"name\": \"mnist-train\",\n        \"namespace\": \"kubeflow-seldon\"\n    },\n    \"spec\": {\n        \"replicaSpecs\": [\n            {\n                \"replicas\": 1,\n                \"template\": {\n                    \"spec\": {\n                        \"containers\": [\n                            {\n                                \"image\": \"seldonio/deepmnistclassifier_trainer:0.1\",\n                                \"name\": \"tensorflow\",\n                                \"volumeMounts\": [\n                                    {\n                                        \"mountPath\": \"/data\",\n                                        \"name\": \"persistent-storage\"\n                                    }\n                                ]\n                            }\n                        ],\n                        \"restartPolicy\": \"OnFailure\",\n                        \"volumes\": [\n                            {\n                                \"name\": \"persistent-storage\",\n                                \"persistentVolumeClaim\": {\n                                    \"claimName\": \"ml-data\"\n                                }\n                            }\n                        ]\n                    }\n                },\n                \"tfReplicaType\": \"MASTER\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "models/r_mnist/runtime/Dockerfile",
    "content": "FROM rocker/r-apt:bionic\n\nRUN apt-get update && \\\n    apt-get install -y -qq \\\n    \tr-cran-plumber \\\n    \tr-cran-jsonlite \\\n    \tr-cran-optparse \\\n    \tr-cran-stringr \\\n    \tr-cran-urltools \\\n    \tr-cran-caret \\\n    \tr-cran-pls \\\n    \tcurl\n\nENV MODEL_NAME mnist.R\nENV API_TYPE REST\nENV SERVICE_TYPE MODEL\nENV PERSISTENCE 0\n\nRUN mkdir microservice\nCOPY . /microservice\nWORKDIR /microservice\n\nRUN curl -OL https://raw.githubusercontent.com/SeldonIO/seldon-core/v0.2.7/wrappers/s2i/R/microservice.R > /microservice/microservice.R\n\nEXPOSE 5000\n\nCMD Rscript microservice.R --model $MODEL_NAME --api $API_TYPE --service $SERVICE_TYPE --persistence $PERSISTENCE"
  },
  {
    "path": "models/r_mnist/runtime/Makefile",
    "content": "\nseldon_build_image_local:\n\tdocker build . -t seldonio/rmnistclassifier_runtime:0.2\n\nseldon_push_docker_hub:\n\tdocker push seldonio/rmnistclassifier_runtime:0.2\n"
  },
  {
    "path": "models/r_mnist/runtime/install.R",
    "content": "install.packages('pls')\n\n"
  },
  {
    "path": "models/r_mnist/runtime/mnist.R",
    "content": "library(methods)\n\npredict.mnist <- function(mnist,newdata=list()) {\n  cn <- 1:784\n  for (i in seq_along(cn)){cn[i] <- paste(\"X\",cn[i],sep = \"\")}\n  colnames(newdata) <- cn\n  predict(mnist$model, newdata = newdata, type='prob')\n}\n\nsend_feedback.mnist <- function(mnist,request=list(),reward=1,truth=list()) {\n}\n\nnew_mnist <- function(filename) {\n  model <- readRDS(filename)\n  structure(list(model=model), class = \"mnist\")\n}\n\ninitialise_seldon <- function(params) {\n  new_mnist(\"/data/model.Rds\")\n}"
  },
  {
    "path": "models/r_mnist/train/Dockerfile",
    "content": "FROM rocker/r-apt:bionic\n\nRUN apt-get update && \\\n    apt-get install -y -qq \\\n    \tr-cran-caret \\\n    \tr-cran-pls \\\n    \tr-cran-e1071\n\nRUN R -e 'install.packages(\"doParallel\")'\n\nRUN mkdir training\nCOPY /train.R /training/train.R\nCOPY /get_data.sh /training/get_data.sh\nCOPY ./train.sh /training/train.sh\n\nRUN cd /training && \\\n    ./get_data.sh\n\nWORKDIR /training\n\nCMD [\"/training/train.sh\"]"
  },
  {
    "path": "models/r_mnist/train/Makefile",
    "content": "\n\nbuild_model:\n\tdocker build --force-rm=true -t seldonio/rmnistclassifier_trainer:0.1 .\n\npush_image:\n\tdocker push seldonio/rmnistclassifier_trainer:0.1 \n\n"
  },
  {
    "path": "models/r_mnist/train/get_data.sh",
    "content": "wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\nwget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\nwget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\nwget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\n\n\ngunzip train-images-idx3-ubyte.gz\ngunzip train-labels-idx1-ubyte.gz\ngunzip t10k-images-idx3-ubyte.gz\ngunzip t10k-labels-idx1-ubyte.gz\n"
  },
  {
    "path": "models/r_mnist/train/install.R",
    "content": "install.packages('caret')\ninstall.packages('doParallel')\ninstall.packages('pls')\ninstall.packages('e1071')\n\n"
  },
  {
    "path": "models/r_mnist/train/train.R",
    "content": "library(caret)\nlibrary(doParallel)\n\n# Enable parallel processing.\ncl <- makeCluster(detectCores())\nregisterDoParallel(cl)\n\n# Load the MNIST digit recognition dataset into R\n# http://yann.lecun.com/exdb/mnist/\n# assume you have all 4 files and gunzip'd them\n# creates train$n, train$x, train$y  and test$n, test$x, test$y\n# e.g. train$x is a 60000 x 784 matrix, each row is one digit (28x28)\n# call:  show_digit(train$x[5,])   to see a digit.\n# brendan o'connor - gist.github.com/39760 - anyall.org\nload_mnist <- function() {\n  load_image_file <- function(filename) {\n    ret = list()\n    f = file(filename,'rb')\n    readBin(f,'integer',n=1,size=4,endian='big')\n    ret$n = readBin(f,'integer',n=1,size=4,endian='big')\n    nrow = readBin(f,'integer',n=1,size=4,endian='big')\n    ncol = readBin(f,'integer',n=1,size=4,endian='big')\n    x = readBin(f,'integer',n=ret$n*nrow*ncol,size=1,signed=F)\n    ret$x = matrix(x, ncol=nrow*ncol, byrow=T)\n    close(f)\n    ret\n  }\n  load_label_file <- function(filename) {\n    f = file(filename,'rb')\n    readBin(f,'integer',n=1,size=4,endian='big')\n    n = readBin(f,'integer',n=1,size=4,endian='big')\n    y = readBin(f,'integer',n=n,size=1,signed=F)\n    close(f)\n    y\n  }\n  train <<- load_image_file('train-images-idx3-ubyte')\n  test <<- load_image_file('t10k-images-idx3-ubyte')\n  \n  train$y <<- load_label_file('train-labels-idx1-ubyte')\n  test$y <<- load_label_file('t10k-labels-idx1-ubyte')  \n}\n\nshow_digit <- function(arr784, col=gray(12:1/12), ...) {\n  image(matrix(arr784, nrow=28)[,28:1], col=col, ...)\n}\n\ntrain <- data.frame()\ntest <- data.frame()\n\n# Load data.\nload_mnist()\n\n# Normalize: X = (X - min) / (max - min) => X = (X - 0) / (255 - 0) => X = X / 255.\ntrain$x <- train$x / 255\n\n# Setup training data with digit and pixel values with 60/40 split for train/cv.\ninTrain = data.frame(y=train$y, train$x)\ninTrain$y <- as.factor(inTrain$y)\ntrainIndex = createDataPartition(inTrain$y, p = 0.60,list=FALSE)\ntraining = inTrain[trainIndex,]\ncv = inTrain[-trainIndex,]\n\n# SVM. 95/94.\n#fit <- train(y ~ ., data = head(training, 1000), method = 'svmRadial', tuneGrid = data.frame(sigma=0.0107249, C=1))\nfit <- train(y ~ ., data = head(training, 1000), method = 'pls')\nresults <- predict(fit, newdata = head(cv, 1000), type='prob')\n#confusionMatrix(results, head(cv$y, 1000))\nsaveRDS(fit, file = \"/data/model.Rds\", compress = TRUE)\n"
  },
  {
    "path": "models/r_mnist/train/train.sh",
    "content": "#!/usr/bin/env bash\n\n# exit when any command fails\nset -e\n\nuntil mountpoint -q /data; do\n    echo \"$(date) - waiting for /data to be mounted...\"\n    sleep 1\ndone       \n\nls -l /data\n\nRscript train.R\n\nls -l /data\n"
  },
  {
    "path": "models/sk_mnist/runtime/Dockerfile",
    "content": "FROM python:3.7-slim\nCOPY . /app\nWORKDIR /app\nRUN pip install -r requirements.txt\nEXPOSE 5000\n\n# Define environment variable\nENV MODEL_NAME SkMnist\nENV API_TYPE REST\nENV SERVICE_TYPE MODEL\nENV PERSISTENCE 0\n\nCMD exec seldon-core-microservice $MODEL_NAME $API_TYPE --service-type $SERVICE_TYPE --persistence $PERSISTENCE\n"
  },
  {
    "path": "models/sk_mnist/runtime/Makefile",
    "content": "\nseldon_build_image_local:\n\tdocker build . -t seldonio/skmnistclassifier_runtime:0.2\n\nseldon_push_docker_hub:\n\tdocker push seldonio/skmnistclassifier_runtime:0.2\n\n"
  },
  {
    "path": "models/sk_mnist/runtime/SkMnist.py",
    "content": "from sklearn.externals import joblib\n\nclass SkMnist(object):\n    def __init__(self):\n        self.class_names = [\"class:{}\".format(str(i)) for i in range(10)]\n        self.clf = joblib.load('/data/sk.pkl') \n\n    def predict(self,X,feature_names):\n        predictions = self.clf.predict_proba(X)\n        return predictions\n\n    \n"
  },
  {
    "path": "models/sk_mnist/runtime/contract.json",
    "content": "{\n    \"features\":[\n\t{\n\t    \"name\":\"x\",\n\t    \"dtype\":\"FLOAT\",\n\t    \"ftype\":\"continuous\",\n\t    \"range\":[0,1],\n\t    \"repeat\":784\n\t}\n    ],\n    \"targets\":[\n\t{\n\t    \"name\":\"class\",\n\t    \"dtype\":\"FLOAT\",\n\t    \"ftype\":\"continuous\",\n\t    \"range\":[0,1],\n\t    \"repeat\":10\n\t}\n    ]\n}\n\n    \n"
  },
  {
    "path": "models/sk_mnist/runtime/requirements.txt",
    "content": "scipy>= 0.13.3\nscikit-learn>=0.18\nseldon-core>=0.2.5"
  },
  {
    "path": "models/sk_mnist/train/Dockerfile",
    "content": "FROM python:3.7-slim\n\nRUN apt-get update -y\nRUN apt-get install -y python-pip python-dev build-essential\n\nCOPY /requirements.txt /tmp/\nRUN cd /tmp && \\\n    pip install --no-cache-dir -r requirements.txt\n\nRUN mkdir training\nCOPY ./create_model.py /training/create_model.py\nCOPY ./train.sh /training/train.sh\nWORKDIR /training\n\nCMD [\"/training/train.sh\"]\n"
  },
  {
    "path": "models/sk_mnist/train/Makefile",
    "content": "\n\nbuild_model:\n\tdocker build --force-rm=true -t seldonio/skmnistclassifier_trainer:0.2 .\n\npush_image:\n\tdocker push seldonio/skmnistclassifier_trainer:0.2\n\n"
  },
  {
    "path": "models/sk_mnist/train/create_model.py",
    "content": "from sklearn.ensemble import RandomForestClassifier\nfrom sklearn import datasets, metrics\nfrom sklearn.utils import shuffle\nfrom sklearn.datasets import fetch_mldata\nfrom sklearn.externals import joblib\nfrom six.moves import urllib\n\nif __name__ == '__main__':\n    try:\n        mnist = fetch_mldata('MNIST original')\n    except:\n        print(\"Could not download MNIST data from mldata.org, trying alternative...\")\n\n        # Alternative method to load MNIST, if mldata.org is down\n        from scipy.io import loadmat\n        mnist_alternative_url = \"https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat\"\n        mnist_path = \"./mnist-original.mat\"\n        response = urllib.request.urlopen(mnist_alternative_url)\n        with open(mnist_path, \"wb\") as f:\n            content = response.read()\n            f.write(content)\n        mnist_raw = loadmat(mnist_path)\n        mnist = {\n            \"data\": mnist_raw[\"data\"].T,\n            \"target\": mnist_raw[\"label\"][0],\n            \"COL_NAMES\": [\"label\", \"data\"],\n            \"DESCR\": \"mldata.org dataset: mnist-original\",\n        }\n        print(\"Success!\")\n\n    #mnist = fetch_mldata('MNIST original', data_home=\"./mnist_sklearn\")\n    # To apply a classifier on this data, we need to flatten the image, to\n    # turn the data in a (samples, feature) matrix:\n    n_samples = len(mnist['data'])\n    data = mnist['data'].reshape((n_samples, -1))\n    targets = mnist['target']\n\n    data,targets = shuffle(data,targets)\n    classifier = RandomForestClassifier(n_estimators=30)\n\n    # We learn the digits on the first half of the digits\n    classifier.fit(data[:n_samples // 2], targets[:n_samples // 2])\n\n    # Now predict the value of the digit on the second half:\n    expected = targets[n_samples // 2:]\n    test_data = data[n_samples // 2:]\n\n    print(classifier.score(test_data, expected))\n\n    predicted = classifier.predict(data[n_samples // 2:])\n\n    print(\"Classification report for classifier %s:\\n%s\\n\"\n          % (classifier, metrics.classification_report(expected, predicted)))\n    print(\"Confusion matrix:\\n%s\" % metrics.confusion_matrix(expected, predicted))\n\n    joblib.dump(classifier, '/data/sk.pkl') \n\n\n"
  },
  {
    "path": "models/sk_mnist/train/requirements.txt",
    "content": "scipy\nscikit-learn>=0.18\nsix\n"
  },
  {
    "path": "models/sk_mnist/train/train.sh",
    "content": "#!/usr/bin/env bash\n\n# exit when any command fails\nset -e\n\nuntil mountpoint -q /data; do\n    echo \"$(date) - wainting for /data to be mounted...\"\n    sleep 1\ndone       \n\nls -l /data\n\npython -u create_model.py\n\nls -l /data\n"
  },
  {
    "path": "models/tf_mnist/runtime/DeepMnist.py",
    "content": "import tensorflow as tf\nimport logging\nlogging.basicConfig(format='%(asctime)s.%(msecs)03d %(levelname)s {%(module)s} [%(funcName)s] %(message)s', datefmt='%Y-%m-%d,%H:%M:%S', level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nclass DeepMnist(object):\n    def __init__(self):\n        self.class_names = [\"class:{}\".format(str(i)) for i in range(10)]\n        self.sess = tf.Session()\n        saver = tf.train.import_meta_graph(\"/data/deep_mnist_model.meta\")\n        saver.restore(self.sess,tf.train.latest_checkpoint(\"/data/\"))\n\n        graph = tf.get_default_graph()\n        self.x = graph.get_tensor_by_name(\"x:0\")\n        self.y = graph.get_tensor_by_name(\"y:0\")\n\n    def predict(self,X,feature_names):\n        predictions = self.sess.run(self.y,feed_dict={self.x:X})\n        return predictions\n\n    \n"
  },
  {
    "path": "models/tf_mnist/runtime/Dockerfile",
    "content": "FROM python:3.7-slim\nCOPY . /app\nWORKDIR /app\nRUN pip install -r requirements.txt\nEXPOSE 5000\n\n# Define environment variable\nENV MODEL_NAME DeepMnist\nENV API_TYPE REST\nENV SERVICE_TYPE MODEL\nENV PERSISTENCE 0\n\nCMD exec seldon-core-microservice $MODEL_NAME $API_TYPE --service-type $SERVICE_TYPE --persistence $PERSISTENCE"
  },
  {
    "path": "models/tf_mnist/runtime/Makefile",
    "content": "\nseldon_build_image_local:\n\tdocker build . -t seldonio/deepmnistclassifier_runtime:0.2\n\nseldon_push_docker_hub:\n\tdocker push seldonio/deepmnistclassifier_runtime:0.2"
  },
  {
    "path": "models/tf_mnist/runtime/contract.json",
    "content": "{\n    \"features\":[\n\t{\n\t    \"name\":\"x\",\n\t    \"dtype\":\"FLOAT\",\n\t    \"ftype\":\"continuous\",\n\t    \"range\":[0,1],\n\t    \"repeat\":784\n\t}\n    ],\n    \"targets\":[\n\t{\n\t    \"name\":\"class\",\n\t    \"dtype\":\"FLOAT\",\n\t    \"ftype\":\"continuous\",\n\t    \"range\":[0,1],\n\t    \"repeat\":10\n\t}\n    ]\n}\n\n    \n"
  },
  {
    "path": "models/tf_mnist/runtime/requirements.txt",
    "content": "tensorflow==1.13.1\nseldon-core>=0.2.5"
  },
  {
    "path": "models/tf_mnist/train/Dockerfile",
    "content": "FROM tensorflow/tensorflow:1.3.0\n\nRUN mkdir training\nCOPY ./create_model.py /training/create_model.py\nWORKDIR /training\n\nCMD [\"python\",\"-u\",\"create_model.py\"]\n"
  },
  {
    "path": "models/tf_mnist/train/Makefile",
    "content": "\n\nbuild_model:\n\tdocker build --force-rm=true -t seldonio/deepmnistclassifier_trainer:0.1 .\n\npush_image:\n\tdocker push seldonio/deepmnistclassifier_trainer:0.1 \n\n"
  },
  {
    "path": "models/tf_mnist/train/create_model.py",
    "content": "from tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot = True)\nimport tensorflow as tf\n\nif __name__ == '__main__':\n    \n    x = tf.placeholder(tf.float32, [None,784], name=\"x\")\n\n    W = tf.Variable(tf.zeros([784,10]))\n    b = tf.Variable(tf.zeros([10]))\n\n    y = tf.nn.softmax(tf.matmul(x,W) + b, name=\"y\")\n\n    y_ = tf.placeholder(tf.float32, [None, 10])\n\n\n    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n\n    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n    init = tf.initialize_all_variables()\n\n    sess = tf.Session()\n    sess.run(init)\n\n    for i in range(1000):\n        batch_xs, batch_ys = mnist.train.next_batch(100)\n        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n\n    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n    print(sess.run(accuracy, feed_dict = {x: mnist.test.images, y_:mnist.test.labels}))\n\n    saver = tf.train.Saver()\n\n    saver.save(sess, \"/data/deep_mnist_model\")\n"
  },
  {
    "path": "nfs.md",
    "content": "# Example NFS Setup\n\nThe steps below are a consolidated set of steps following the guide [here](https://cloud.google.com/community/tutorials/gke-filestore-dynamic-provisioning).\n\nSet the following variables\n\n  * `FS` : the name of your filestore\n  * `PROJECT` : Your Google Project\n  * `ZONE` : Your GCP Zone\n\nCreate a Google Filestore and install the helm chart for nfs-client-provisioner to use it.\n```\n  PROJECT=seldon-demos\n  FS=mnist-data\n  ZONE=europe-west1-b    \n\n  gcloud beta filestore instances create ${FS}     --project=${PROJECT}     --location=${ZONE}     --tier=STANDARD     --file-share=name=\"volumes\",capacity=1TB     --network=name=\"default\",reserved-ip-range=\"10.0.0.0/29\"\n\n  FSADDR=$(gcloud beta filestore instances describe ${FS} --project=${PROJECT} --location=${ZONE} --format=\"value(networks.ipAddresses[0])\")\n\n  helm install stable/nfs-client-provisioner --name nfs-cp --set nfs.server=${FSADDR} --set nfs.path=/volumes\n  kubectl rollout status  deploy/nfs-cp-nfs-client-provisioner -n kubeflow\n```\n\nTo create the NFS claim save the following and apply to your kubernetes cluster\n\n```\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n  name: nfs-1\nspec:\n  accessModes:\n    - ReadWriteMany\n  storageClassName: nfs-client\n  resources:\n    requests:\n      storage: 30Gi\n```\n"
  },
  {
    "path": "notebooks/Makefile",
    "content": "SHELL=/bin/bash\n\ntensorflow/core/framework/tensor.proto:\n\t./create-protos.sh\n\n.PHONY: create_protos\ncreate_protos: tensorflow/core/framework/tensor.proto\n\n.PHONY: clean\nclean:\n\t@rm -rfv tensorflow\n"
  },
  {
    "path": "notebooks/__init__.py",
    "content": ""
  },
  {
    "path": "notebooks/create-protos.sh",
    "content": "#!/bin/bash\n\nrelease=${1:-\"master\"}\n\necho Downloading proto files for ${release}\n\nbase=https://raw.githubusercontent.com/tensorflow\ntensorflow_base=${base}/tensorflow/${release}\n\nbase_folder=tensorflow/core/framework/\nmkdir -p ${base_folder}\n\ncurl -s ${tensorflow_base}/tensorflow/core/framework/types.proto > ${base_folder}/types.proto\ncurl -s ${tensorflow_base}/tensorflow/core/framework/resource_handle.proto > ${base_folder}/resource_handle.proto\ncurl -s ${tensorflow_base}/tensorflow/core/framework/tensor_shape.proto > ${base_folder}/tensor_shape.proto\ncurl -s ${tensorflow_base}/tensorflow/core/framework/tensor.proto > ${base_folder}/tensor.proto\n\n"
  },
  {
    "path": "notebooks/proto/__init__.py",
    "content": ""
  },
  {
    "path": "notebooks/proto/prediction.proto",
    "content": "syntax = \"proto3\";\n\nimport \"google/protobuf/struct.proto\";\nimport \"tensorflow/core/framework/tensor.proto\";\n\npackage seldon.protos;\n\noption java_package = \"io.seldon.protos\";\noption java_outer_classname = \"PredictionProtos\";\noption go_package = \"github.com/seldonio/seldon-core/examples/wrappers/go/pkg/api\";\n\n// [START Messages]\n\nmessage SeldonMessage {\n\n  Status status = 1;\n  Meta meta = 2;\n  oneof data_oneof {\n    DefaultData data = 3;\n    bytes binData = 4;\n    string strData = 5;\n  }\n}\n\nmessage DefaultData {\n  repeated string names = 1;\n  oneof data_oneof {\n    Tensor tensor = 2;\n    google.protobuf.ListValue ndarray = 3;\n    tensorflow.TensorProto tftensor = 4;\n  }\n}\n\nmessage Tensor {\n  repeated int32 shape = 1 [packed=true];\n  repeated double values = 2 [packed=true];\n}\n\nmessage Meta {\n  string puid = 1; \n  map<string,google.protobuf.Value> tags = 2;\n  map<string,int32> routing = 3;\n  map<string,string> requestPath = 4;\n  repeated Metric metrics = 5;\n}\n\nmessage Metric {\n enum MetricType {\n     COUNTER = 0;\n     GAUGE = 1;\n     TIMER = 2;\n }\n string key = 1;\n MetricType type = 2;\n float value = 3;\n map<string,string> tags = 4;\n}\n\nmessage SeldonMessageList {\n  repeated SeldonMessage seldonMessages = 1;\n}\n\nmessage Status {\n\n    enum StatusFlag {\n        SUCCESS = 0;\n        FAILURE = 1;\n    }\n\n    int32 code = 1;\n    string info = 2;\n    string reason = 3;\n    StatusFlag status = 4;\n}\n\nmessage Feedback {\n  SeldonMessage request = 1;\n  SeldonMessage response = 2;\n  float reward = 3;\n  SeldonMessage truth = 4;\n}\n\nmessage RequestResponse {\n  SeldonMessage request = 1;\n  SeldonMessage response = 2;\n}\n\n// [END Messages]\n\n\n// [START Services]\n\nservice Generic {\n  rpc TransformInput(SeldonMessage) returns (SeldonMessage) {};\n  rpc TransformOutput(SeldonMessage) returns (SeldonMessage) {};\n  rpc Route(SeldonMessage) returns (SeldonMessage) {};\n  rpc Aggregate(SeldonMessageList) returns (SeldonMessage) {};\n  rpc SendFeedback(Feedback) returns (SeldonMessage) {};\n}\n\nservice Model {\n  rpc Predict(SeldonMessage) returns (SeldonMessage) {};\n  rpc SendFeedback(Feedback) returns (SeldonMessage) {};  \n }\n\nservice Router {\n  rpc Route(SeldonMessage) returns (SeldonMessage) {};\n  rpc SendFeedback(Feedback) returns (SeldonMessage) {};\n }\n\nservice Transformer {\n  rpc TransformInput(SeldonMessage) returns (SeldonMessage) {};\n}\n\nservice OutputTransformer {\n  rpc TransformOutput(SeldonMessage) returns (SeldonMessage) {};\n}\n\nservice Combiner {\n  rpc Aggregate(SeldonMessageList) returns (SeldonMessage) {};\n}\n\n\nservice Seldon {\n  rpc Predict(SeldonMessage) returns (SeldonMessage) {};\n  rpc SendFeedback(Feedback) returns (SeldonMessage) {};\n }\n\n// [END Services]"
  },
  {
    "path": "notebooks/requirements.txt",
    "content": "matplotlib==3.0.3\ngrpcio==1.20.1\ngrpcio-tools==1.20.1\ngraphviz==0.10.1\n"
  },
  {
    "path": "notebooks/serving.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Deploying Various MNIST Models on Kubernetes \\n\",\n    \"\\n\",\n    \"Using:\\n\",\n    \"\\n\",\n    \" * kubeflow\\n\",\n    \" * seldon-core\\n\",\n    \" \\n\",\n    \" \\n\",\n    \"Follow the main README to setup kubeflow and seldon-core. This notebook will show various rolling deployments of the trained models\\n\",\n    \"\\n\",\n    \" * Single model\\n\",\n    \" * AB Test between 2 models\\n\",\n    \" * Multi-Armed Bandit over 3 models\\n\",\n    \" \\n\",\n    \"### Dependencies\\n\",\n    \" \\n\",\n    \"  * Tensorflow\\n\",\n    \"  * grpcio package\\n\",\n    \" \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup\\n\",\n    \"\\n\",\n    \"Set kubectl to use the namespace where you installed kubeflow and seldon. In the README it is kubeflow.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl config set-context $(kubectl config current-context) --namespace=kubeflow\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!make create_protos\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!python -m grpc.tools.protoc -I. --python_out=. --grpc_python_out=. ./proto/prediction.proto\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"%matplotlib inline\\n\",\n    \"import utils\\n\",\n    \"from visualizer import get_graph\\n\",\n    \"mnist = utils.download_mnist()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"\\n\",\n    \"\\n\",\n    \"**Ensure you have port forwarded the ambassador reverse proxy**\\n\",\n    \"\\n\",\n    \"```bash\\n\",\n    \"kubectl port-forward $(kubectl get pods -n kubeflow -l service=ambassador -o jsonpath='{.items[0].metadata.name}') -n kubeflow 8002:80\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Deploy Single Tensorflow Model\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"get_graph(\\\"../k8s_serving/serving_model.json\\\",'r')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../k8s_serving/serving_model.json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl apply -f ../k8s_serving/serving_model.json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl get seldondeployments mnist-classifier -o jsonpath='{.status}'\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"utils.predict_rest_mnist(mnist)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"utils.predict_grpc_mnist(mnist)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Start load test\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl label nodes $(kubectl get nodes -o jsonpath='{.items[0].metadata.name}') role=locust\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!helm install seldon-core-loadtesting --name loadtest  \\\\\\n\",\n    \"    --namespace kubeflow \\\\\\n\",\n    \"    --repo https://storage.googleapis.com/seldon-charts \\\\\\n\",\n    \"    --set locust.script=mnist_rest_locust.py \\\\\\n\",\n    \"    --set locust.host=http://mnist-classifier:8000 \\\\\\n\",\n    \"    --set oauth.enabled=false \\\\\\n\",\n    \"    --set oauth.key=oauth-key \\\\\\n\",\n    \"    --set oauth.secret=oauth-secret \\\\\\n\",\n    \"    --set locust.hatchRate=1 \\\\\\n\",\n    \"    --set locust.clients=1 \\\\\\n\",\n    \"    --set loadtest.sendFeedback=1 \\\\\\n\",\n    \"    --set locust.minWait=0 \\\\\\n\",\n    \"    --set locust.maxWait=0 \\\\\\n\",\n    \"    --set replicaCount=1 \\\\\\n\",\n    \"    --set data.size=784\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Rolling update to AB Test\\n\",\n    \" Run an AB Test between 2 models:\\n\",\n    \"  * Tensorflow neural network model\\n\",\n    \"  * Scikit-learn random forest.\\n\",\n    \" \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"get_graph(\\\"../k8s_serving/ab_test_sklearn_tensorflow.json\\\",'r')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../k8s_serving/ab_test_sklearn_tensorflow.json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl apply -f ../k8s_serving/ab_test_sklearn_tensorflow.json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl get seldondeployments mnist-classifier -o jsonpath='{.status}'\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"utils.predict_rest_mnist(mnist)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"utils.evaluate_abtest(mnist,100)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Rolling Update to Multi-Armed Bandit\\n\",\n    \"Run a epsilon-greey multi-armed bandit over 3 models:\\n\",\n    \"  * Tensorflow neural network model\\n\",\n    \"  * Scikit-learn random forest model\\n\",\n    \"  * R least-squares model\\n\",\n    \"  \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"get_graph(\\\"../k8s_serving/epsilon_greedy_3way.json\\\",'r')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../k8s_serving/epsilon_greedy_3way.json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl apply -f ../k8s_serving/epsilon_greedy_3way.json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl get seldondeployments mnist-classifier -o jsonpath='{.status}'\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"utils.predict_rest_mnist(mnist)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"utils.evaluate_egreedy(mnist,100)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.4\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 1\n}\n"
  },
  {
    "path": "notebooks/training.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Train Various Models on MNIST using kubeflow and seldon-core\\n\",\n    \"\\n\",\n    \"Using:\\n\",\n    \"\\n\",\n    \" * kubeflow\\n\",\n    \" * seldon-core\\n\",\n    \" \\n\",\n    \"The example will be the MNIST handwriiten digit classification task.\\n\",\n    \"\\n\",\n    \"![MNIST](mnist.png \\\"MNIST Digits\\\")\\n\",\n    \"\\n\",\n    \"### Dependencies\\n\",\n    \"\\n\",\n    \"  * Argo\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!kubectl config set-context $(kubectl config current-context) --namespace=kubeflow\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Tensorflow Model\\n\",\n    \" A simple neural network in Tensorflow.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Training\\n\",\n    \" * Create image from source\\n\",\n    \" * Run training\\n\",\n    \" \\n\",\n    \"\\n\",\n    \"Run with:\\n\",\n    \"  * ``` -p build-push-image=true``` to build image and push to repo, needed extra params:\\n\",\n    \"    * ``` -p version=<version>``` create ```<version>``` of model\\n\",\n    \"    * ``` -p github-user=<github-user>``` to download example-seldon source from ```<github-user>``` account\\n\",\n    \"    * ``` -p github-revision=<revision>``` to use the github branch ```<revision>```\\n\",\n    \"    * ``` -p docker-org=<docker-org>``` to use Docker repo ```<docker-org>``` to push image to. Needs docker credentials in secret as described in README.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../workflows/training-tf-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo submit ../workflows/training-tf-mnist-workflow.yaml -p tfjob-version-hack=1\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo list\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Runtime Image\\n\",\n    \"\\n\",\n    \"Run with:\\n\",\n    \"  * ``` -p build-push-image=true``` to build image and push to repo, needed extra params:\\n\",\n    \"    * ``` -p version=<version>``` create ```<version>``` of model\\n\",\n    \"    * ``` -p github-user=<github-user>``` to download example-seldon source from ```<github-user>``` account\\n\",\n    \"    * ``` -p github-revision=<revision>``` to use the github branch ```<revision>```\\n\",\n    \"    * ``` -p docker-org=<docker-org>``` to use Docker user ```<docker-org>``` to push image to. Needs docker credentials in secret as described in README.\\n\",\n    \"  * ``` -p deploy-model=true``` to deploy model\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../workflows/serving-tf-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo submit ../workflows/serving-tf-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo list\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Sklearn Model\\n\",\n    \"A Random forest in sklearn.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Training\\n\",\n    \"\\n\",\n    \" * For options see above Tensorflow example\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../workflows/training-sk-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo submit ../workflows/training-sk-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo list\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Runtime Image\\n\",\n    \" * For options see above Tensorflow example\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../workflows/serving-sk-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo submit ../workflows/serving-sk-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo list\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# R Model\\n\",\n    \"A partial least squares model in R.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Training\\n\",\n    \"\\n\",\n    \" * For options see above Tensorflow example\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../workflows/training-r-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo submit ../workflows/training-r-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo list\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Runtime Image\\n\",\n    \" * For options see above Tensorflow example\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!pygmentize ../workflows/serving-r-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo submit ../workflows/serving-r-mnist-workflow.yaml\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!argo list\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.4\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 1\n}\n"
  },
  {
    "path": "notebooks/utils.py",
    "content": "import requests\nfrom requests.auth import HTTPBasicAuth\nfrom random import randint,random\nfrom proto import prediction_pb2\nfrom proto import prediction_pb2_grpc\nimport grpc\nimport json\nfrom visualizer import get_graph\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom google.protobuf.json_format import MessageToJson\n\nAMBASSADOR_API_IP=\"localhost:8002\"\n\ndef rest_request(deploymentName,request):\n    response = requests.post(\n                \"http://\"+AMBASSADOR_API_IP+\"/seldon/\"+deploymentName+\"/api/v0.1/predictions\",\n                json=request)\n    j = response.json()\n    return j\n    \ndef rest_request_auth(deploymentName,data,username,password):\n    payload = {\"data\":{\"ndarray\":data.tolist()}}\n    response = requests.post(\n                \"http://\"+AMBASSADOR_API_IP+\"/seldon/\"+deploymentName+\"/api/v0.1/predictions\",\n                json=payload,\n                auth=HTTPBasicAuth(username, password))\n    print(response.status_code)\n    return response.json()   \n\ndef grpc_request(deploymentName,data):\n    datadef = prediction_pb2.DefaultData(\n            names = [\"a\",\"b\"],\n            tensor = prediction_pb2.Tensor(\n                shape = [1,784],\n                values = data\n                )\n            )\n    request = prediction_pb2.SeldonMessage(data = datadef)\n    channel = grpc.insecure_channel(AMBASSADOR_API_IP)\n    stub = prediction_pb2_grpc.SeldonStub(channel)\n    metadata = [('seldon',deploymentName)]\n    response = stub.Predict(request=request,metadata=metadata)\n    return response\n\ndef send_feedback_rest(deploymentName,request,response,reward):\n    feedback = {\n        \"request\": request,\n        \"response\": response,\n        \"reward\": reward\n    }\n    ret = requests.post(\n         \"http://\"+AMBASSADOR_API_IP+\"/seldon/\"+deploymentName+\"/api/v0.1/feedback\",\n        json=feedback)\n    return ret.text\n\n\ndef gen_image(arr):\n    two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)\n    plt.imshow(two_d,cmap=plt.cm.gray_r, interpolation='nearest')\n    return plt\n\ndef download_mnist():\n    return input_data.read_data_sets(\"MNIST_data/\", one_hot = True)\n\n\ndef predict_rest_mnist(mnist):\n    batch_xs, batch_ys = mnist.train.next_batch(1)\n    chosen=0\n    gen_image(batch_xs[chosen]).show()\n    data = batch_xs[chosen].reshape((1,784))\n    features = [\"X\"+str(i+1) for i in range (0,784)]\n    request = {\"data\":{\"names\":features,\"ndarray\":data.tolist()}}\n    predictions = rest_request(\"mnist-classifier\",request)\n    print(json.dumps(predictions,indent=2))\n    #print(\"Route:\"+json.dumps(predictions[\"meta\"][\"routing\"],indent=2))\n    fpreds = [ '%.2f' % elem for elem in predictions[\"data\"][\"ndarray\"][0] ]\n    m = dict(zip(predictions[\"data\"][\"names\"],fpreds))\n    print(\"Returned probabilities\")\n    print(json.dumps(m,indent=2))\n\n\n\ndef predict_grpc_mnist(mnist):\n    batch_xs, batch_ys = mnist.train.next_batch(1)\n    chosen=0\n    gen_image(batch_xs[chosen]).show()\n    data = batch_xs[chosen].reshape((784))\n    resp = grpc_request(\"mnist-classifier\",data)\n    predictions = MessageToJson(resp)\n    predictions = json.loads(predictions)\n    print(json.dumps(predictions,indent=2))    \n    fpreds = [ '%.2f' % elem for elem in predictions[\"data\"][\"tensor\"][\"values\"] ]\n    m = dict(zip(predictions[\"data\"][\"names\"],fpreds))\n    print(\"Returned probabilities\")    \n    print(json.dumps(m,indent=2))\n\ndef evaluate_abtest(mnist,sz=100):\n    batch_xs, batch_ys = mnist.train.next_batch(sz)\n    routes_history = []\n    for idx in range(sz):\n        if idx % 10 == 0:\n            print(\"{}/{}\".format(idx,sz))\n        data = batch_xs[idx].reshape((1,784))\n        request = {\"data\":{\"ndarray\":data.tolist()}}\n        response = rest_request(\"mnist-classifier\",request)\n        route = response.get(\"meta\").get(\"routing\").get(\"random-ab-test\")\n        routes_history.append(route)\n\n    plt.figure(figsize=(15,6))\n    ax = plt.scatter(range(len(routes_history)),routes_history)\n    ax.axes.xaxis.set_label_text(\"Incoming Requests over Time\")\n    ax.axes.yaxis.set_label_text(\"Selected Branch\")\n    plt.yticks([0,1,2])\n    _ = plt.title(\"Branch Chosen for Incoming Requests\")\n\n\ndef evaluate_egreedy(mnist,sz=100):\n    score = [0.0,0.0,0.0]\n    sz = 100\n    batch_xs, batch_ys = mnist.train.next_batch(sz)\n    routes_history = []\n    for idx in range(sz):\n        if idx % 10 == 0:\n            print(\"{}/{}\".format(idx,sz))\n        data = batch_xs[idx].reshape((1,784))\n        request = {\"data\":{\"ndarray\":data.tolist()}}\n        response = rest_request(\"mnist-classifier\",request)\n        route = response.get(\"meta\").get(\"routing\").get(\"eg-router\")\n        proba = response[\"data\"][\"ndarray\"][0]\n        predicted = proba.index(max(proba))\n        correct = np.argmax(batch_ys[idx])\n        if predicted == correct:\n            score[route] = score[route] + 1\n            send_feedback_rest(\"mnist-classifier\",request,response,reward=1)\n        else:\n            send_feedback_rest(\"mnist-classifier\",request,response,reward=0)\n        routes_history.append(route)\n\n    plt.figure(figsize=(15,6))\n    ax = plt.scatter(range(len(routes_history)),routes_history)\n    ax.axes.xaxis.set_label_text(\"Incoming Requests over Time\")\n    ax.axes.yaxis.set_label_text(\"Selected Branch\")\n    plt.yticks([0,1,2])\n    _ = plt.title(\"Branch Chosen for Incoming Requests\")\n    print(score)    \n\n    \n"
  },
  {
    "path": "notebooks/visualizer.py",
    "content": "import graphviz\nimport json\n\ndef _populate_graph(dot, root, suffix=''):\n    name = root.get(\"name\")\n    id = name+suffix\n    if root.get(\"implementation\"):\n        dot.node(id, label=name, shape=\"box\", style=\"filled\", color=\"lightgrey\")\n    else:\n        dot.node(id, label=name, shape=\"box\")\n    endpoint_type = root.get(\"endpoint\",{}).get(\"type\")\n    if endpoint_type is not None:\n        dot.node(id+'endpoint', label=endpoint_type)\n        dot.edge(id,id+'endpoint')\n    for child in root.get(\"children\",[]):\n        child_id = _populate_graph(dot,child)\n        dot.edge(id, child_id)\n    return id\n\ndef get_graph(filename,predictor=0):\n    deployment = json.load(open(filename,'r'))\n    predictors = deployment.get(\"spec\").get(\"predictors\")\n    dot = graphviz.Digraph()\n    \n    with dot.subgraph(name=\"cluster_0\") as pdot:\n        graph = predictors[0].get(\"graph\")\n        _populate_graph(pdot, graph, suffix='0')\n        pdot.attr(label=\"predictor\")\n        \n    if len(predictors)>1:\n        with dot.subgraph(name=\"cluster_1\") as cdot:\n            graph = predictors[1].get(\"graph\")\n            _populate_graph(cdot, graph, suffix='1')\n            cdot.attr(label=\"canary\")\n        \n    return dot\n"
  },
  {
    "path": "scripts/README.md",
    "content": "# Create MNIST Demo\n\n 1. You will need all prerequisites (gcloud, kubectl, ks) in your path.\n 1. Copy `env-example.sh` to `env.sh` and edit with your own settings\n 1. run `create_demo.sh`\n \n# Delete Demo\n\n 1. run `delete-demo.sh` - this will delete the GCP resources except the Filestore disk. You will need to delete this manually at present.\n\n\n\n"
  },
  {
    "path": "scripts/create_demo.sh",
    "content": "#!/usr/bin/env bash\n\nset -o nounset\nset -o errexit\nset -o pipefail\n\ncreate_src() {\n    mkdir -p ${KUBEFLOW_SRC}\n    cd ${KUBEFLOW_SRC}\n    curl https://raw.githubusercontent.com/kubeflow/kubeflow/${KUBEFLOW_TAG}/scripts/download.sh | bash\n}\n\n\nlaunch_kubeflow() {\n    \n    KUBEFLOW_REPO=${KUBEFLOW_SRC} ${KUBEFLOW_SRC}/scripts/kfctl.sh init ${KFAPP} --platform gcp --project ${PROJECT}\n    \n    cd ${KFAPP}\n    ${KUBEFLOW_SRC}/scripts/kfctl.sh generate platform\n    ${KUBEFLOW_SRC}/scripts/kfctl.sh apply platform\n    ${KUBEFLOW_SRC}/scripts/kfctl.sh generate k8s\n    ${KUBEFLOW_SRC}/scripts/kfctl.sh apply k8s\n\n}\n\nlaunch_seldon() {\n    cd ${KUBEFLOW_SRC}/${KFAPP}/ks_app\n\n    ks pkg install kubeflow/seldon\n    ks generate seldon seldon\n    ks apply default -c seldon\n}\n\nadd_helm() {\n    kubectl -n kube-system create sa tiller\n    kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller\n    helm init --service-account tiller\n    kubectl rollout status deploy/tiller-deploy -n kube-system\n}\n\nadd_nfs_disk() {\n\n    set +e\n    FSADDR=$(gcloud beta filestore instances describe ${FS} --project=${PROJECT} --location=${ZONE} --format=\"value(networks.ipAddresses[0])\")\n    if [ -z \"$FSADDR\" ]; then\n\techo \"Creating filestore NFS volume\"\n\tgcloud beta filestore instances create ${FS}     --project=${PROJECT}     --location=${ZONE}     --tier=STANDARD     --file-share=name=\"volumes\",capacity=1TB     --network=name=\"default\",reserved-ip-range=\"10.0.0.0/29\"\n    fi\n    set -e\n\n    FSADDR=$(gcloud beta filestore instances describe ${FS} --project=${PROJECT} --location=${ZONE} --format=\"value(networks.ipAddresses[0])\")\n\n    helm install stable/nfs-client-provisioner --name nfs-cp --set nfs.server=${FSADDR} --set nfs.path=/volumes\n    kubectl rollout status  deploy/nfs-cp-nfs-client-provisioner -n kubeflow\n\n    kubectl apply -f ${STARTUP_DIR}/nfs-pvc.yaml -n kubeflow\n}\n\nadd_argo_clusterrole() {\n    kubectl create clusterrolebinding my-cluster-admin-binding --clusterrole=cluster-admin --user=$(gcloud info --format=\"value(config.account)\")\n    kubectl create clusterrolebinding default-admin2 --clusterrole=cluster-admin --serviceaccount=kubeflow:default\n\n}\n\nadd_seldon_analytics() {\n    helm install seldon-core-analytics --name seldon-core-analytics --set grafana_prom_admin_password=password --set persistence.enabled=false --repo https://storage.googleapis.com/seldon-charts --namespace kubeflow\n}\n\nif [ ! -f env.sh ]; then\n    echo \"Create env.sh by copying env-example.sh\"\nfi\nsource env.sh\ncreate_src\nlaunch_kubeflow\nlaunch_seldon\nadd_helm\nadd_nfs_disk\nadd_argo_clusterrole\nadd_seldon_analytics\n"
  },
  {
    "path": "scripts/delete-demo.sh",
    "content": "#!/usr/bin/env bash\n\nset -o nounset\nset -o errexit\nset -o pipefail\n\n\nif [ ! -f env.sh ]; then\n    echo \"Create env.sh by copying env-example.sh\"\nfi\nsource env.sh\n\ncd ${KUBEFLOW_SRC}/${KFAPP}\n${KUBEFLOW_SRC}/scripts/kfctl.sh  delete all\n"
  },
  {
    "path": "scripts/env-example.sh",
    "content": "STARTUP_DIR=\"$( cd \"$( dirname \"$0\" )\" && pwd )\"\nKFAPP=my-kubeflow    \nPROJECT=seldon-demos\nKUBEFLOW_SRC=${STARTUP_DIR}/kubeflow_src\nFS=mnist-data\nZONE=europe-west1-b\n# Next two lines are set from values created as discussed in https://www.kubeflow.org/docs/started/getting-started-gke/\nexport CLIENT_ID=<your-client-id>\nexport CLIENT_SECRET=<your-secret>\nexport KUBEFLOW_TAG=v0.5.1\n"
  },
  {
    "path": "scripts/nfs-pvc.yaml",
    "content": "apiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n  name: nfs-1\nspec:\n  accessModes:\n    - ReadWriteMany\n  storageClassName: nfs-client\n  resources:\n    requests:\n      storage: 30Gi\n"
  },
  {
    "path": "scripts/port-forwards.sh",
    "content": "\n#Argo\nkubectl port-forward $(kubectl get pods -n kubeflow -l app=argo-ui -o jsonpath='{.items[0].metadata.name}') -n kubeflow 8001:8001 &\n\n#Seldon Grafana\nkubectl port-forward $(kubectl get pods -n kubeflow -l app=grafana-prom-server -o jsonpath='{.items[0].metadata.name}') -n kubeflow 3000:3000 &\n\n#Ambassador reverse proxy\nkubectl port-forward $(kubectl get pods -n kubeflow -l service=ambassador -o jsonpath='{.items[0].metadata.name}') -n kubeflow 8002:80 &\n\n#Ambassador admin\nkubectl port-forward $(kubectl get pods -n kubeflow -l service=ambassador -o jsonpath='{.items[0].metadata.name}') -n kubeflow 8877:8877 &\n\n\n"
  },
  {
    "path": "scripts/watch-mnist.sh",
    "content": "watch kubectl get pods -l seldon-app=mnist-classifier\n"
  },
  {
    "path": "workflows/serving-r-mnist-workflow.yaml",
    "content": "# This example demonstrates the use of a git repo as a hard-wired\n# input artifact. The argo repo is cloned to its target destination\n# at '/src' for the main container to consume.\napiVersion: argoproj.io/v1alpha1\nkind: Workflow\nmetadata:\n  generateName: seldon-r-deploy-\nspec:\n  entrypoint: workflow\n  arguments:\n    parameters:\n    - name: version\n      value: 0.1\n    - name: github-user\n      value: kubeflow\n    - name: github-revision\n      value: master\n    - name: docker-org\n      value: index.docker.io/seldonio\n    - name: build-push-image\n      value: false\n    - name: deploy-model\n      value: false\n  volumes:\n  - name: docker-config\n    secret:\n      secretName: docker-config     # name of an existing k8s secret\n  volumeClaimTemplates:\n  - metadata:\n      name: workspace\n    spec:\n      accessModes: [ \"ReadWriteOnce\" ]\n      resources:\n        requests:\n          storage: 0.5Gi\n  templates:\n  - name: workflow\n    steps:\n    - - name: get-source\n        template: get-source-code\n    - - name: build-push\n        template: build-and-push\n        when: \"{{workflow.parameters.build-push-image}} == true\"\n    - - name: serve\n        template: seldon\n        when: \"{{workflow.parameters.deploy-model}} == true\"\n  - name: get-source-code\n    inputs:\n      artifacts:\n      - name: argo-source\n        path: /src/example-seldon\n        git:\n          repo: https://github.com/{{workflow.parameters.github-user}}/example-seldon.git\n          revision: \"{{workflow.parameters.github-revision}}\"\n    container:\n      image: alpine:latest\n      command: [sh, -c]\n      args: [\"cp /src/example-seldon/models/r_mnist/runtime/* /workspace/; ls /workspace/\"]\n      volumeMounts:\n      - name: workspace\n        mountPath: /workspace\n  - name: build-and-push\n    container:\n      image: gcr.io/kaniko-project/executor:latest\n      args: [\"--dockerfile\",\"Dockerfile\",\"--destination\",\"{{workflow.parameters.docker-org}}/rmnistclassifier_runtime:{{workflow.parameters.version}}\"]\n      workingDir: /src/example-seldon/models/r_mnist/runtime/\n      volumeMounts:\n      - name: docker-config\n        mountPath: \"/root/.docker/\"\n      - name: workspace\n        mountPath: /workspace\n  - name: seldon\n    resource:                   #indicates that this is a resource template\n      action: apply             #can be any kubectl action (e.g. create, delete, apply, patch)\n      #successCondition: ?\n      manifest: |   #put your kubernetes spec here\n       apiVersion: \"machinelearning.seldon.io/v1alpha2\"\n       kind: \"SeldonDeployment\"\n       metadata:\n         labels:\n           app: \"seldon\"\n         name: \"mnist-classifier\"\n       spec:\n         annotations:\n           deployment_version: \"v1\"\n           project_name: \"MNIST Example\"\n         name: \"mnist-classifier\"\n         predictors:\n           -\n             annotations:\n               predictor_version: \"v1\"\n             componentSpecs:\n               -\n                 spec:\n                   containers:\n                     -\n                       image: \"{{workflow.parameters.docker-org}}/rmnistclassifier_runtime:{{workflow.parameters.version}}\"\n                       imagePullPolicy: \"Always\"\n                       name: \"mnist-classifier\"\n                       volumeMounts:\n                         -\n                           mountPath: \"/data\"\n                           name: \"persistent-storage\"\n                   terminationGracePeriodSeconds: 1\n                   volumes:\n                     -\n                       name: \"persistent-storage\"\n                       volumeSource:\n                         persistentVolumeClaim:\n                           claimName: \"nfs-1\"\n             graph:\n               children: []\n               endpoint:\n                 type: \"REST\"\n               name: \"mnist-classifier\"\n               type: \"MODEL\"\n             name: \"mnist-classifier\"\n             replicas: 1\n"
  },
  {
    "path": "workflows/serving-sk-mnist-workflow.yaml",
    "content": "# This example demonstrates the use of a git repo as a hard-wired\n# input artifact. The argo repo is cloned to its target destination\n# at '/src' for the main container to consume.\napiVersion: argoproj.io/v1alpha1\nkind: Workflow\nmetadata:\n  generateName: seldon-sk-deploy-\nspec:\n  entrypoint: workflow\n  arguments:\n    parameters:\n    - name: version\n      value: 0.1\n    - name: github-user\n      value: kubeflow\n    - name: github-revision\n      value: master\n    - name: docker-org\n      value: index.docker.io/seldonio\n    - name: build-push-image\n      value: false\n    - name: deploy-model\n      value: false\n  volumes:\n  - name: docker-config\n    secret:\n      secretName: docker-config     # name of an existing k8s secret\n  volumeClaimTemplates:\n  - metadata:\n      name: workspace\n    spec:\n      accessModes: [ \"ReadWriteOnce\" ]\n      resources:\n        requests:\n          storage: 0.5Gi\n  templates:\n  - name: workflow\n    steps:\n    - - name: get-source\n        template: get-source-code\n    - - name: build-push\n        template: build-and-push\n        when: \"{{workflow.parameters.build-push-image}} == true\"\n    - - name: serve\n        template: seldon\n        when: \"{{workflow.parameters.deploy-model}} == true\"\n  - name: get-source-code\n    inputs:\n      artifacts:\n      - name: argo-source\n        path: /src/example-seldon\n        git:\n          repo: https://github.com/{{workflow.parameters.github-user}}/example-seldon.git\n          revision: \"{{workflow.parameters.github-revision}}\"\n    container:\n      image: alpine:latest\n      command: [sh, -c]\n      args: [\"cp /src/example-seldon/models/sk_mnist/runtime/* /workspace/; ls /workspace/\"]\n      volumeMounts:\n      - name: workspace\n        mountPath: /workspace\n  - name: build-and-push\n    container:\n      image: gcr.io/kaniko-project/executor:latest\n      args: [\"--dockerfile\",\"Dockerfile\",\"--destination\",\"{{workflow.parameters.docker-org}}/skmnistclassifier_runtime:{{workflow.parameters.version}}\"]\n      workingDir: /src/example-seldon/models/sk_mnist/runtime/\n      volumeMounts:\n      - name: docker-config\n        mountPath: \"/root/.docker/\"\n      - name: workspace\n        mountPath: /workspace\n  - name: seldon\n    resource:                   #indicates that this is a resource template\n      action: apply             #can be any kubectl action (e.g. create, delete, apply, patch)\n      #successCondition: ?\n      manifest: |   #put your kubernetes spec here\n       apiVersion: \"machinelearning.seldon.io/v1alpha2\"\n       kind: \"SeldonDeployment\"\n       metadata:\n         labels:\n           app: \"seldon\"\n         name: \"mnist-classifier\"\n       spec:\n         annotations:\n           deployment_version: \"v1\"\n           project_name: \"MNIST Example\"\n         name: \"mnist-classifier\"\n         predictors:\n           -\n             annotations:\n               predictor_version: \"v1\"\n             componentSpecs:\n               -\n                 spec:\n                   containers:\n                     -\n                       image: \"{{workflow.parameters.docker-org}}/skmnistclassifier_runtime:{{workflow.parameters.version}}\"\n                       imagePullPolicy: \"Always\"\n                       name: \"mnist-classifier\"\n                       volumeMounts:\n                         -\n                           mountPath: \"/data\"\n                           name: \"persistent-storage\"\n                   terminationGracePeriodSeconds: 1\n                   volumes:\n                     -\n                       name: \"persistent-storage\"\n                       volumeSource:\n                         persistentVolumeClaim:\n                           claimName: \"nfs-1\"\n             graph:\n               children: []\n               endpoint:\n                 type: \"REST\"\n               name: \"mnist-classifier\"\n               type: \"MODEL\"\n             name: \"mnist-classifier\"\n             replicas: 1\n"
  },
  {
    "path": "workflows/serving-tf-mnist-workflow.md",
    "content": "# Example Argo Workflow to dockerize runtime model and deploy it for serving\n\nComments on the [serving-tf-mnist-workflow.yaml](serving-tf-mnist-workflow.yaml)\n\n## Workflow Summary\n\nTo serve our runtime model we create:\n\n * [```models/tf_mnist/runtime/Dockerfile```](../models/tf_mnist/runtime/Dockerfile) to wrap model using the seldon-core python wrapper.\n * An Argo workflow to:\n    * Wrap the runtime model, builds a docker container for it and optionally push it to your repo\n    * Optionally starts a seldon deployment that will run and expose your model\n\n\n## Workflow parameters\n\n * version\n   * The version tag for the Docker image\n * github-user\n   * The github user to use to clone this repo/fork\n * github-revision\n   * The github revision to use for cloning the repo (can be a branch name)\n * docker-org\n   * The Docker host and org/user/project to use when pushing an image to the registry\n * build-push-image\n   * Whether to build and push the image to docker registry (true/false)\n * deploy-model\n   * Whether to start a seldon deployment to run and expose your model (true/false)\n"
  },
  {
    "path": "workflows/serving-tf-mnist-workflow.yaml",
    "content": "apiVersion: argoproj.io/v1alpha1\nkind: Workflow\nmetadata:\n  generateName: seldon-tf-deploy-\nspec:\n  entrypoint: workflow\n  arguments:\n    parameters:\n    - name: version\n      value: 0.1\n    - name: github-user\n      value: kubeflow\n    - name: github-revision\n      value: master\n    - name: docker-org\n      value: index.docker.io/seldonio\n    - name: build-push-image\n      value: false\n    - name: deploy-model\n      value: false\n  volumes:\n  - name: docker-config\n    secret:\n      secretName: docker-config     # name of an existing k8s secret\n  volumeClaimTemplates:\n  - metadata:\n      name: workspace\n    spec:\n      accessModes: [ \"ReadWriteOnce\" ]\n      resources:\n        requests:\n          storage: 0.5Gi\n  templates:\n  - name: workflow\n    steps:\n    - - name: get-source\n        template: get-source-code\n    - - name: build-push\n        template: build-and-push\n        when: \"{{workflow.parameters.build-push-image}} == true\"\n    - - name: serve\n        template: seldon\n        when: \"{{workflow.parameters.deploy-model}} == true\"\n  - name: get-source-code\n    inputs:\n      artifacts:\n      - name: argo-source\n        path: /src/example-seldon\n        git:\n          repo: https://github.com/{{workflow.parameters.github-user}}/example-seldon.git\n          revision: \"{{workflow.parameters.github-revision}}\"\n    container:\n      image: alpine:latest\n      command: [sh, -c]\n      args: [\"cp /src/example-seldon/models/tf_mnist/runtime/* /workspace/; ls /workspace/\"]\n      volumeMounts:\n      - name: workspace\n        mountPath: /workspace\n  - name: build-and-push\n    container:\n      image: gcr.io/kaniko-project/executor:latest\n      args: [\"--dockerfile\",\"Dockerfile\",\"--destination\",\"{{workflow.parameters.docker-org}}/deepmnistclassifier_runtime:{{workflow.parameters.version}}\"]\n      workingDir: /src/example-seldon/models/tf_mnist/runtime/\n      volumeMounts:\n      - name: docker-config\n        mountPath: \"/root/.docker/\"\n      - name: workspace\n        mountPath: /workspace\n  - name: seldon\n    resource:                   #indicates that this is a resource template\n      action: apply             #can be any kubectl action (e.g. create, delete, apply, patch)\n      #successCondition: ?\n      manifest: |   #put your kubernetes spec here\n       apiVersion: \"machinelearning.seldon.io/v1alpha2\"\n       kind: \"SeldonDeployment\"\n       metadata:\n         labels:\n           app: \"seldon\"\n         name: \"mnist-classifier\"\n       spec:\n         annotations:\n           deployment_version: \"v1\"\n           project_name: \"MNIST Example\"\n         name: \"mnist-classifier\"\n         predictors:\n           -\n             annotations:\n               predictor_version: \"v1\"\n             componentSpecs:\n               -\n                 spec:\n                   containers:\n                     -\n                       image: \"{{workflow.parameters.docker-org}}/deepmnistclassifier_runtime:{{workflow.parameters.version}}\"\n                       imagePullPolicy: \"Always\"\n                       name: \"mnist-classifier\"\n                       volumeMounts:\n                         -\n                           mountPath: \"/data\"\n                           name: \"persistent-storage\"\n                   terminationGracePeriodSeconds: 1\n                   volumes:\n                     -\n                       name: \"persistent-storage\"\n                       volumeSource:\n                         persistentVolumeClaim:\n                           claimName: \"nfs-1\"\n             graph:\n               children: []\n               endpoint:\n                 type: \"REST\"\n               name: \"mnist-classifier\"\n               type: \"MODEL\"\n             name: \"mnist-classifier\"\n             replicas: 1\n"
  },
  {
    "path": "workflows/training-r-mnist-workflow.yaml",
    "content": "apiVersion: argoproj.io/v1alpha1\nkind: Workflow\nmetadata:\n  generateName: kubeflow-r-train-\nspec:\n  entrypoint: workflow\n  arguments:\n    parameters:\n    - name: version\n      value: 0.1\n    - name: github-user\n      value: kubeflow\n    - name: github-revision\n      value: master\n    - name: docker-org\n      value: seldonio\n    - name: build-push-image\n      value: false\n  volumes:\n  - name: docker-config\n    secret:\n      secretName: docker-config     # name of an existing k8s secret\n  volumeClaimTemplates:\n  - metadata:\n      name: workspace\n    spec:\n      accessModes: [ \"ReadWriteOnce\" ]\n      resources:\n        requests:\n          storage: 0.5Gi\n  templates:\n  - name: workflow\n    steps:\n    - - name: get-source\n        template: get-source-code\n    - - name: build-push\n        template: build-and-push\n        when: \"{{workflow.parameters.build-push-image}} == true\"\n    - - name: train\n        template: tfjob\n  - name: get-source-code\n    inputs:\n      artifacts:\n      - name: argo-source\n        path: /src/example-seldon\n        git:\n          repo: https://github.com/{{workflow.parameters.github-user}}/example-seldon.git\n          revision: \"{{workflow.parameters.github-revision}}\"\n    container:\n      image: alpine:latest\n      command: [sh, -c]\n      args: [\"cp /src/example-seldon/models/r_mnist/train/* /workspace/; ls /workspace/\"]\n      volumeMounts:\n      - name: workspace\n        mountPath: /workspace\n  - name: build-and-push\n    container:\n      image: gcr.io/kaniko-project/executor:latest\n      args: [\"--dockerfile\",\"Dockerfile\",\"--destination\",\"{{workflow.parameters.docker-org}}/rmnistclassifier_trainer:{{workflow.parameters.version}}\"]\n      workingDir: /src/example-seldon/models/r_mnist/train/\n      volumeMounts:\n      - name: docker-config\n        mountPath: \"/root/.docker/\"\n      - name: workspace\n        mountPath: /workspace\n  - name: tfjob\n    resource:                   #indicates that this is a resource template\n      action: create             #can be any kubectl action (e.g. create, delete, apply, patch)\n      successCondition: status.succeeded == 1\n      manifest: |   #put your kubernetes spec here\n       apiVersion: \"batch/v1\"\n       kind: \"Job\"\n       metadata:\n         name: \"r-train\"\n         ownerReferences:\n         - apiVersion: argoproj.io/v1alpha1\n           kind: Workflow\n           controller: true\n           name: {{workflow.name}}\n           uid: {{workflow.uid}}\n       spec:\n         template:\n           metadata:\n             name: \"r-train\"\n           spec:\n             containers:\n               -\n                 image: \"{{workflow.parameters.docker-org}}/rmnistclassifier_trainer:{{workflow.parameters.version}}\"\n                 name: \"r-train\"\n                 volumeMounts:\n                   -\n                     mountPath: \"/data\"\n                     name: \"persistent-storage\"\n             restartPolicy: \"Never\"\n             volumes:\n               -\n                 name: \"persistent-storage\"\n                 persistentVolumeClaim:\n                   claimName: \"nfs-1\"\n"
  },
  {
    "path": "workflows/training-sk-mnist-workflow.yaml",
    "content": "apiVersion: argoproj.io/v1alpha1\nkind: Workflow\nmetadata:\n  generateName: kubeflow-sk-train-\nspec:\n  entrypoint: workflow\n  arguments:\n    parameters:\n    - name: version\n      value: 0.2\n    - name: github-user\n      value: kubeflow\n    - name: github-revision\n      value: master\n    - name: docker-org\n      value: index.docker.io/seldonio\n    - name: build-push-image\n      value: false\n  volumes:\n  - name: docker-config\n    secret:\n      secretName: docker-config     # name of an existing k8s secret\n  volumeClaimTemplates:\n  - metadata:\n      name: workspace\n    spec:\n      accessModes: [ \"ReadWriteOnce\" ]\n      resources:\n        requests:\n          storage: 0.5Gi\n  templates:\n  - name: workflow\n    steps:\n    - - name: get-source\n        template: get-source-code\n    - - name: build-push\n        template: build-and-push\n        when: \"{{workflow.parameters.build-push-image}} == true\"\n    - - name: train\n        template: tfjob\n  - name: get-source-code\n    inputs:\n      artifacts:\n      - name: argo-source\n        path: /src/example-seldon\n        git:\n          repo: https://github.com/{{workflow.parameters.github-user}}/example-seldon.git\n          revision: \"{{workflow.parameters.github-revision}}\"\n    container:\n      image: alpine:latest\n      command: [sh, -c]\n      args: [\"cp /src/example-seldon/models/sk_mnist/train/* /workspace/; ls /workspace/\"]\n      volumeMounts:\n      - name: workspace\n        mountPath: /workspace\n  - name: build-and-push\n    container:\n      image: gcr.io/kaniko-project/executor:latest\n      args: [\"--dockerfile\",\"Dockerfile\",\"--destination\",\"{{workflow.parameters.docker-org}}/skmnistclassifier_trainer:{{workflow.parameters.version}}\"]\n      workingDir: /src/example-seldon/models/sk_mnist/train/\n      volumeMounts:\n      - name: docker-config\n        mountPath: \"/root/.docker/\"\n      - name: workspace\n        mountPath: /workspace\n  - name: tfjob\n    resource:                   #indicates that this is a resource template\n      action: create             #can be any kubectl action (e.g. create, delete, apply, patch)\n      successCondition: status.succeeded == 1\n      manifest: |   #put your kubernetes spec here\n       apiVersion: \"batch/v1\"\n       kind: \"Job\"\n       metadata:\n         name: \"sk-train\"\n         ownerReferences:\n         - apiVersion: argoproj.io/v1alpha1\n           kind: Workflow\n           controller: true\n           name: {{workflow.name}}\n           uid: {{workflow.uid}}\n       spec:\n         template:\n           metadata:\n             name: \"sk-train\"\n           spec:\n             containers:\n               -\n                 image: \"{{workflow.parameters.docker-org}}/skmnistclassifier_trainer:{{workflow.parameters.version}}\"\n                 name: \"sk-train\"\n                 imagePullPolicy: Always\n                 volumeMounts:\n                   -\n                     mountPath: \"/data\"\n                     name: \"persistent-storage\"\n             restartPolicy: \"Never\"\n             volumes:\n               -\n                 name: \"persistent-storage\"\n                 persistentVolumeClaim:\n                   claimName: \"nfs-1\"\n"
  },
  {
    "path": "workflows/training-tf-mnist-workflow.md",
    "content": "# Example Argo Workflow to dockerize and Train Model\n\nComments on the [training-tf-mnist-workflow.yaml](training-tf-mnist-workflow.yaml)\n\n## Workflow summary\n\nTo dockerize our model training and run it we create:\n\n  * [```models/tf_mnist/train/build_and_push.sh```](../models/tf_mnist/train/build_and_push.sh) that will build an image for our Tensorflow training and push to our repo.\n  * An Argo workflow [```workflows/training-tf-mnist-workflow.yaml```](training-tf-mnist-workflow.yaml) is created which:\n    * Clones the project from github\n    * Runs the build and push script (using DockerInDocker)\n    * Starts a kubeflow TfJob to train the model and save the results to the persistent volume\n\n\n## Workflow parameters\n\n * version\n   * The version tag for the Docker image\n * github-user\n   * The github user/org for which to clone this repo/fork\n * github-revision\n   * The github revision to use for cloning the repo (can be a branch name)\n * docker-org\n   * The Docker host and org/user/project to use when pushing an image to the registry\n * tfjob-version-hack\n   * A temporary random integer for the tfjob ID\n * build-push-image\n   * Whether to build and push the image to docker registry (true/false)\n\n## Setup For Pushing Images\n\n**To push to your own repo the Docker images you will need to setup your docker credentials as a Kubernetes secret containing a [config.json](https://www.projectatomic.io/blog/2016/03/docker-credentials-store/). To do this you can find your docker home (typically ~/.docker) and run `kubectl create secret generic docker-config --from-file=config.json=${DOCKERHOME}/config.json --type=kubernetes.io/config` to [create a secret](https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/#registry-secret-existing-credentials).**\n"
  },
  {
    "path": "workflows/training-tf-mnist-workflow.yaml",
    "content": "apiVersion: argoproj.io/v1alpha1\nkind: Workflow\nmetadata:\n  generateName: kubeflow-tf-train-\nspec:\n  entrypoint: workflow\n  arguments:\n    parameters:\n    - name: version\n      value: 0.1\n    - name: github-user\n      value: kubeflow\n    - name: github-revision\n      value: master\n    - name: docker-org\n      value: index.docker.io/seldonio\n    - name: tfjob-version-hack\n      value: 1\n    - name: build-push-image\n      value: false\n  volumes:\n  - name: docker-config\n    secret:\n      secretName: docker-config     # name of an existing k8s secret\n  volumeClaimTemplates:\n  - metadata:\n      name: workspace\n    spec:\n      accessModes: [ \"ReadWriteOnce\" ]\n      resources:\n        requests:\n          storage: 0.5Gi\n  templates:\n  - name: workflow\n    steps:\n    - - name: get-source\n        template: get-source-code\n    - - name: build-push\n        template: build-and-push\n        when: \"{{workflow.parameters.build-push-image}} == true\"\n    - - name: train\n        template: tfjob\n  - name: get-source-code\n    inputs:\n      artifacts:\n      - name: argo-source\n        path: /src/example-seldon\n        git:\n          repo: https://github.com/{{workflow.parameters.github-user}}/example-seldon.git\n          revision: \"{{workflow.parameters.github-revision}}\"\n    container:\n      image: alpine:latest\n      command: [sh, -c]\n      args: [\"cp /src/example-seldon/models/tf_mnist/train/* /workspace/; ls /workspace/\"]\n      volumeMounts:\n      - name: workspace\n        mountPath: /workspace\n  - name: build-and-push\n    container:\n      image: gcr.io/kaniko-project/executor:latest\n      args: [\"--dockerfile\",\"Dockerfile\",\"--destination\",\"{{workflow.parameters.docker-org}}/deepmnistclassifier_trainer:{{workflow.parameters.version}}\"]\n      workingDir: /src/example-seldon/models/tf_mnist/train/\n      volumeMounts:\n      - name: docker-config\n        mountPath: \"/root/.docker/\"\n      - name: workspace\n        mountPath: /workspace\n  - name: tfjob\n    resource:                   #indicates that this is a resource template\n      action: create             #can be any kubectl action (e.g. create, delete, apply, patch)\n      #successCondition: status.tfReplicaStatuses.Worker.succeeded == 1\n      #successCondition: status.conditions.type == Succeeded\n      successCondition: status.replicaStatuses.Worker.succeeded == 1\n      manifest: |   #put your kubernetes spec here\n       apiVersion: \"kubeflow.org/v1beta1\"\n       kind: \"TFJob\"\n       metadata:\n         name: mnist-train-{{workflow.parameters.tfjob-version-hack}}\n         ownerReferences:\n         - apiVersion: argoproj.io/v1alpha1\n           kind: Workflow\n           controller: true\n           name: {{workflow.name}}\n           uid: {{workflow.uid}}\n       spec:\n         tfReplicaSpecs:\n           Worker:\n             replicas: 1\n             template:\n               spec:\n                 containers:\n                   -\n                     image: \"{{workflow.parameters.docker-org}}/deepmnistclassifier_trainer:{{workflow.parameters.version}}\"\n                     name: \"tensorflow\"\n                     volumeMounts:\n                       -\n                         mountPath: \"/data\"\n                         name: \"persistent-storage\"\n                 restartPolicy: \"OnFailure\"\n                 volumes:\n                   -\n                     name: \"persistent-storage\"\n                     persistentVolumeClaim:\n                       claimName: \"nfs-1\"\n             tfReplicaType: \"MASTER\"\n"
  }
]