You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by GitBox <gi...@apache.org> on 2022/08/02 15:21:11 UTC

[GitHub] [beam] AnandInguva commented on a diff in pull request #22510: Beam ml notebooks

AnandInguva commented on code in PR #22510:
URL: https://github.com/apache/beam/pull/22510#discussion_r935729440


##########
examples/notebooks/beam-ml/run_inference_basic.ipynb:
##########
@@ -0,0 +1,1127 @@
+{
+  "nbformat": 4,
+  "nbformat_minor": 2,
+  "metadata": {
+    "colab": {
+      "name": "Beam ML RunInference",
+      "provenance": [],
+      "collapsed_sections": [],
+      "toc_visible": true
+    },
+    "kernelspec": {
+      "name": "python3",
+      "display_name": "Python 3"
+    },
+    "language_info": {
+      "name": "python"
+    }
+  },
+  "cells": [
+    {
+      "cell_type": "code",
+      "source": [
+        "#@title ###### Licensed to the Apache Software Foundation (ASF), Version 2.0 (the \"License\")\n",
+        "\n",
+        "# Licensed to the Apache Software Foundation (ASF) under one\n",
+        "# or more contributor license agreements. See the NOTICE file\n",
+        "# distributed with this work for additional information\n",
+        "# regarding copyright ownership. The ASF licenses this file\n",
+        "# to you under the Apache License, Version 2.0 (the\n",
+        "# \"License\"); you may not use this file except in compliance\n",
+        "# with the License. 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,\n",
+        "# software distributed under the License is distributed on an\n",
+        "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n",
+        "# KIND, either express or implied. See the License for the\n",
+        "# specific language governing permissions and limitations\n",
+        "# under the License."
+      ],
+      "metadata": {
+        "id": "C1rAsD2L-hSO",
+        "cellView": "form"
+      },
+      "id": "C1rAsD2L-hSO",
+      "execution_count": null,
+      "outputs": []
+    },
+    {
+      "cell_type": "markdown",
+      "id": "b6f8f3af-744e-4eaa-8a30-6d03e8e4d21e",
+      "metadata": {
+        "id": "b6f8f3af-744e-4eaa-8a30-6d03e8e4d21e"
+      },
+      "source": [
+        "# RunInference\n",
+        "\n",
+        "<button>\n",
+        "  <a href=\"https://beam.apache.org/documentation/sdks/python-machine-learning/\">\n",
+        "    <img src=\"https://beam.apache.org/images/favicon.ico\" alt=\"Open the docs\" height=\"16\"/>\n",
+        "    Beam RunInference\n",
+        "  </a>\n",
+        "</button>\n",
+        "\n",
+        "In this notebook, we walk through the use of the RunInference transform.\n",
+        "The transform and its accompanying [ModelHandler](https://beam.apache.org/releases/pydoc/current/apache_beam.ml.inference.base.html#apache_beam.ml.inference.base.ModelHandler) classes handle the following tasks:\n",
+        "\n",
+        "\n",
+        "*   Optimizing loading models from popular frameworks.\n",
+        "*   Batching examples in a scalable fashion.\n",
+        "\n",
+        "\n",
+        "This notebook illustrates common RunInference patterns such as the following:\n",
+        "*   Generating predictions using both Pytorch and Scikit-learn.\n",
+        "*   Post processing results after RunInference.\n",
+        "*   Inference with multiple models in the same pipeline.\n",
+        "\n",
+        "The linear regression models used in these samples are trained on data that correspondes to the 5 and 10 times table; that is,`y = 5x` and `y = 10x` respectively."
+      ]
+    },
+    {
+      "cell_type": "markdown",
+      "id": "299af9bb-b2fc-405c-96e7-ee0a6ae24bdd",
+      "metadata": {
+        "id": "299af9bb-b2fc-405c-96e7-ee0a6ae24bdd"
+      },
+      "source": [
+        "### Dependencies\n",
+        "\n",
+        "The RunInference library is available in Apache Beam version <b>2.40</b> or later.\n",
+        "\n",
+        "Pytorch module is needed to use Pytorch RunInference API. use `pip` to install Pytorch."
+      ]
+    },
+    {
+      "cell_type": "code",
+      "source": [
+        "%pip install apache_beam[gcp,dataframe]>=2.40.0"
+      ],
+      "metadata": {
+        "id": "loxD-rOVchRn"
+      },
+      "id": "loxD-rOVchRn",
+      "execution_count": null,
+      "outputs": []
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "id": "7f841596-f217-46d2-b64e-1952db4de4cb",
+      "metadata": {
+        "id": "7f841596-f217-46d2-b64e-1952db4de4cb"
+      },
+      "outputs": [],
+      "source": [
+        "%pip install torch"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "id": "9a92e3a7-beb6-46ae-a5b0-53c15487de38",
+      "metadata": {
+        "id": "9a92e3a7-beb6-46ae-a5b0-53c15487de38"
+      },
+      "outputs": [],
+      "source": [
+        "import argparse\n",
+        "import csv\n",
+        "import json\n",
+        "import os\n",
+        "import torch\n",
+        "from typing import Tuple\n",
+        "\n",
+        "import apache_beam as beam\n",
+        "import numpy\n",
+        "from apache_beam.io.gcp.bigquery import ReadFromBigQuery\n",
+        "from apache_beam.ml.inference.base import KeyedModelHandler\n",
+        "from apache_beam.ml.inference.base import PredictionResult\n",
+        "from apache_beam.ml.inference.base import RunInference\n",
+        "from apache_beam.dataframe.convert import to_pcollection\n",
+        "from apache_beam.ml.inference.pytorch_inference import PytorchModelHandlerTensor\n",
+        "from apache_beam.ml.inference.pytorch_inference import PytorchModelHandlerKeyedTensor\n",
+        "from apache_beam.options.pipeline_options import PipelineOptions"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "source": [
+        "from google.colab import auth\n",
+        "auth.authenticate_user()"
+      ],
+      "metadata": {
+        "id": "V0E35R5Ka2cE"
+      },
+      "id": "V0E35R5Ka2cE",
+      "execution_count": null,
+      "outputs": []
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "id": "248458a6-cfd8-474d-ad0e-f37f7ae981ae",
+      "metadata": {
+        "id": "248458a6-cfd8-474d-ad0e-f37f7ae981ae"
+      },
+      "outputs": [],
+      "source": [
+        "# Constants\n",
+        "project = \"<your-project>\"\n",
+        "bucket = \"<your-bucket>\"\n",
+        "\n",
+        "save_model_dir_multiply_five = 'five_times_table_torch.pt'\n",
+        "save_model_dir_multiply_ten = 'ten_times_table_torch.pt'"
+      ]
+    },
+    {
+      "cell_type": "markdown",
+      "id": "b2b7cedc-79f5-4599-8178-e5da35dba032",
+      "metadata": {
+        "tags": [],
+        "id": "b2b7cedc-79f5-4599-8178-e5da35dba032"
+      },
+      "source": [
+        "## Create data and Pytorch models for RunInference transform"
+      ]
+    },
+    {
+      "cell_type": "markdown",
+      "id": "202e5a3e-4ccd-4ae3-9852-e47de0721839",
+      "metadata": {
+        "id": "202e5a3e-4ccd-4ae3-9852-e47de0721839"
+      },
+      "source": [
+        "### Linear regression model in Pytorch."
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "id": "68bf8bf0-f735-45ee-8ebb-a2d8bb8a6bc7",
+      "metadata": {
+        "id": "68bf8bf0-f735-45ee-8ebb-a2d8bb8a6bc7"
+      },
+      "outputs": [],
+      "source": [
+        "class LinearRegression(torch.nn.Module):\n",
+        "    def __init__(self, input_dim=1, output_dim=1):\n",
+        "        super().__init__()\n",
+        "        self.linear = torch.nn.Linear(input_dim, output_dim)  \n",
+        "    def forward(self, x):\n",
+        "        out = self.linear(x)\n",
+        "        return out"
+      ]
+    },
+    {
+      "cell_type": "markdown",
+      "id": "1918435c-0029-4eb6-8eee-bda5470eb2ff",
+      "metadata": {
+        "id": "1918435c-0029-4eb6-8eee-bda5470eb2ff"
+      },
+      "source": [
+        "### Prepare train and test data to train a 5 times model.\n",
+        "* `x` contains values in the range from 0 to 99.\n",
+        "* `y` is a list of 5 * `x`. \n",
+        "* `value_to_predict` includes values outside of the training data."
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "id": "9302917f-6200-4af4-a410-4bd6f2a070b8",
+      "metadata": {
+        "id": "9302917f-6200-4af4-a410-4bd6f2a070b8"
+      },
+      "outputs": [],
+      "source": [
+        "x = numpy.arange(0, 100, dtype=numpy.float32).reshape(-1, 1)\n",
+        "y = (x * 5).reshape(-1, 1)\n",
+        "value_to_predict = numpy.array([20, 40, 60, 90], dtype=numpy.float32).reshape(-1, 1)"
+      ]
+    },
+    {
+      "cell_type": "markdown",
+      "id": "9dc22aec-08c3-43ab-a5ce-451cb63c485a",
+      "metadata": {
+        "id": "9dc22aec-08c3-43ab-a5ce-451cb63c485a"
+      },
+      "source": [
+        "### Train the linear regression mode on 5 times data."
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "id": "0a8b7924-ff06-4584-8f41-079268387a67",
+      "metadata": {
+        "id": "0a8b7924-ff06-4584-8f41-079268387a67"
+      },
+      "outputs": [],
+      "source": [
+        "five_times_model = LinearRegression()\n",
+        "optimizer = torch.optim.Adam(five_times_model.parameters())\n",
+        "loss_fn = torch.nn.L1Loss()\n",
+        "\n",
+        "\"\"\"\n",
+        "Train the five_times_model\n",
+        "\"\"\"\n",
+        "epochs = 10000\n",
+        "tensor_x = torch.from_numpy(x)\n",
+        "tensor_y = torch.from_numpy(y)\n",
+        "for epoch in range(epochs):\n",
+        "    y_pred = five_times_model(tensor_x)\n",
+        "    loss = loss_fn(y_pred, tensor_y)\n",
+        "    five_times_model.zero_grad()\n",
+        "    loss.backward()\n",
+        "    optimizer.step()"
+      ]
+    },
+    {
+      "cell_type": "markdown",
+      "id": "bd106b29-6187-42c1-9743-1666c147b5e3",
+      "metadata": {
+        "id": "bd106b29-6187-42c1-9743-1666c147b5e3"
+      },
+      "source": [
+        "Save the model using `torch.save()` and verify if the saved model file exists."
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "id": "882bbada-4f6d-4370-a047-c5961e564ee8",
+      "metadata": {
+        "id": "882bbada-4f6d-4370-a047-c5961e564ee8"
+      },
+      "outputs": [],
+      "source": [
+        "torch.save(five_times_model.state_dict(), save_model_dir_multiply_five)\n",
+        "print(os.path.exists(save_model_dir_multiply_five)) # verify if the model is saved"
+      ]

Review Comment:
   Added the outputs



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org