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/06/02 03:50:45 UTC

[GitHub] [beam] AnandInguva commented on a diff in pull request #17462: [BEAM-14068]Add Pytorch inference test and example

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


##########
sdks/python/apache_beam/examples/inference/pytorch_image_classification.py:
##########
@@ -0,0 +1,122 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import argparse
+import io
+import os
+from functools import partial
+
+import apache_beam as beam
+import torch
+import torchvision
+from apache_beam.io.filesystems import FileSystems
+from apache_beam.ml.inference.api import RunInference
+from apache_beam.ml.inference.pytorch import PytorchModelLoader
+from apache_beam.options.pipeline_options import PipelineOptions
+from apache_beam.options.pipeline_options import SetupOptions
+from PIL import Image
+from torchvision import transforms
+
+
+def read_image(image_file_name: str, path_to_dir: str):
+  image_file_name = os.path.join(path_to_dir, image_file_name)
+  with FileSystems().open(image_file_name, 'r') as file:
+    data = Image.open(io.BytesIO(file.read())).convert('RGB')
+    return image_file_name, data
+
+
+def preprocess_data(data):
+  image_size = (224, 224)
+  normalize = transforms.Normalize(
+      mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
+  transform = transforms.Compose([
+      transforms.Resize(image_size),
+      transforms.ToTensor(),
+      normalize,
+  ])
+  return transform(data)
+
+
+class PostProcessor(beam.DoFn):
+  """Post process PredictionResult to output filename and
+  prediction using torch."""
+  def process(self, element):
+    filename, prediction_result = element
+    prediction = torch.argmax(prediction_result.inference, dim=0)
+    yield filename + ',' + str(int(prediction))
+
+
+def run_pipeline(options: PipelineOptions, args=None):
+  """Sets up PyTorch RunInference pipeline"""
+  model_class = torchvision.models.mobilenet_v2
+  model_params = {'pretrained': False}

Review Comment:
   In torch, it is not recommended to load the whole model. The conventional way is to save the model weights in dictionary and save it to remote path. 
   During Inference,  the model object will be instantiated with random weights using the model class definition. After this, the model weights are loaded in model object. 
   
   In our RunInference, if we instantiate model object, and if the model object is too large in size, the time it takes to pickle would be longer and also, the pipeline fails as we hit the size per request limit on Dataflow. 
   So, we pass the reference to the model class definition and the input parameters needed to instantiate the model. class to the RunInference transform so that the model class object would be instantiated on the worker rather than user's machine



-- 
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