You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@beam.apache.org by bh...@apache.org on 2022/04/29 20:09:28 UTC

[beam] branch master updated: [BEAM-14368][BEAM-13984]Change model loading from constructor to load_model method in PyTorch… (#17494)

This is an automated email from the ASF dual-hosted git repository.

bhulette pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/beam.git


The following commit(s) were added to refs/heads/master by this push:
     new 4e148858e62 [BEAM-14368][BEAM-13984]Change model loading from constructor to load_model method in PyTorch… (#17494)
4e148858e62 is described below

commit 4e148858e6274ca36cd290804ff157884da0eb9b
Author: Anand Inguva <34...@users.noreply.github.com>
AuthorDate: Fri Apr 29 20:09:20 2022 +0000

    [BEAM-14368][BEAM-13984]Change model loading from constructor to load_model method in PyTorch… (#17494)
    
    * Change model loading from constructor to load_model method in PyTorchModelLoader
    
    * Update typehint for model_class argument
    
    Co-authored-by: Brian Hulette <hu...@gmail.com>
    
    * fixup lint
    
    * Callable typehint for model_class in PytorchModelLoader constructor
    
    Co-authored-by: Brian Hulette <hu...@gmail.com>
---
 sdks/python/apache_beam/ml/inference/pytorch.py      | 13 +++++++++----
 sdks/python/apache_beam/ml/inference/pytorch_test.py | 15 ++++++++++++---
 2 files changed, 21 insertions(+), 7 deletions(-)

diff --git a/sdks/python/apache_beam/ml/inference/pytorch.py b/sdks/python/apache_beam/ml/inference/pytorch.py
index 438582d73dc..cb0935e3a3a 100644
--- a/sdks/python/apache_beam/ml/inference/pytorch.py
+++ b/sdks/python/apache_beam/ml/inference/pytorch.py
@@ -17,6 +17,9 @@
 
 # pytype: skip-file
 
+from typing import Any
+from typing import Callable
+from typing import Dict
 from typing import Iterable
 from typing import List
 
@@ -68,13 +71,14 @@ class PytorchModelLoader(ModelLoader):
   def __init__(
       self,
       state_dict_path: str,
-      model_class: torch.nn.Module,
+      model_class: Callable[..., torch.nn.Module],
+      model_params: Dict[str, Any],
       device: str = 'CPU'):
     """
     state_dict_path: path to the saved dictionary of the model state.
     model_class: class of the Pytorch model that defines the model structure.
     device: the device on which you wish to run the model. If ``device = GPU``
-        then device will be cuda if it is avaiable. Otherwise, it will be cpu.
+        then device will be cuda if it is available. Otherwise, it will be cpu.
 
     See https://pytorch.org/tutorials/beginner/saving_loading_models.html
     for details
@@ -85,12 +89,13 @@ class PytorchModelLoader(ModelLoader):
     else:
       self._device = torch.device('cpu')
     self._model_class = model_class
-    self._model_class.to(self._device)
+    self.model_params = model_params
     self._inference_runner = PytorchInferenceRunner(device=self._device)
 
   def load_model(self) -> torch.nn.Module:
     """Loads and initializes a Pytorch model for processing."""
-    model = self._model_class
+    model = self._model_class(**self.model_params)
+    model.to(self._device)
     file = FileSystems.open(self._state_dict_path, 'rb')
     model.load_state_dict(torch.load(file))
     model.eval()
diff --git a/sdks/python/apache_beam/ml/inference/pytorch_test.py b/sdks/python/apache_beam/ml/inference/pytorch_test.py
index 9a8d3871c09..6c374dbf183 100644
--- a/sdks/python/apache_beam/ml/inference/pytorch_test.py
+++ b/sdks/python/apache_beam/ml/inference/pytorch_test.py
@@ -155,7 +155,10 @@ class PytorchRunInferenceTest(unittest.TestCase):
 
       model_loader = PytorchModelLoader(
           state_dict_path=path,
-          model_class=PytorchLinearRegression(input_dim=2, output_dim=1))
+          model_class=PytorchLinearRegression,
+          model_params={
+              'input_dim': 2, 'output_dim': 1
+          })
 
       pcoll = pipeline | 'start' >> beam.Create(examples)
       predictions = pcoll | RunInference(model_loader)
@@ -178,7 +181,10 @@ class PytorchRunInferenceTest(unittest.TestCase):
       gs_pth = 'gs://apache-beam-ml/pytorch_lin_reg_model_2x+0.5_state_dict.pth'
       model_loader = PytorchModelLoader(
           state_dict_path=gs_pth,
-          model_class=PytorchLinearRegression(input_dim=1, output_dim=1))
+          model_class=PytorchLinearRegression,
+          model_params={
+              'input_dim': 1, 'output_dim': 1
+          })
 
       pcoll = pipeline | 'start' >> beam.Create(examples)
       predictions = pcoll | RunInference(model_loader)
@@ -198,7 +204,10 @@ class PytorchRunInferenceTest(unittest.TestCase):
 
         model_loader = PytorchModelLoader(
             state_dict_path=path,
-            model_class=PytorchLinearRegression(input_dim=1, output_dim=1))
+            model_class=PytorchLinearRegression,
+            model_params={
+                'input_dim': 1, 'output_dim': 1
+            })
 
         pcoll = pipeline | 'start' >> beam.Create(examples)
         # pylint: disable=expression-not-assigned