riteshghorse commented on code in PR #26632:
URL: https://github.com/apache/beam/pull/26632#discussion_r1245388722


##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,462 @@
+#
+# 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.
+#
+
+# pytype: skip-file
+
+import logging
+import sys
+from collections import defaultdict
+from typing import Any
+from typing import Callable
+from typing import Dict
+from typing import Iterable
+from typing import Optional
+from typing import Sequence
+from typing import Union
+
+import tensorflow as tf
+import torch
+from apache_beam.ml.inference import utils
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandlerTensor',
+    'HuggingFaceModelHandlerKeyedTensor',
+]
+
+TensorInferenceFn = Callable[[
+    Sequence[Union[torch.Tensor, tf.Tensor]],
+    Union[AutoModel, TFAutoModel],
+    torch.device,
+    Optional[Dict[str, Any]],
+    Optional[str]
+],
+                             Iterable[PredictionResult]]
+
+KeyedTensorInferenceFn = Callable[[
+    Sequence[Dict[str, Union[torch.Tensor, tf.Tensor]]],
+    Union[AutoModel, TFAutoModel],
+    torch.device,
+    Optional[Dict[str, Any]],
+    Optional[str]
+],
+                                  Iterable[PredictionResult]]
+
+
+def _validate_constructor_args(model_uri, model_class):
+  message = (
+      "Please provide both model class and model uri to load the model."
+      "Got params as model_uri={model_uri} and "
+      "model_class={model_class}.")
+  if not model_uri and not model_class:
+    raise RuntimeError(
+        message.format(model_uri=model_uri, model_class=model_class))
+  elif not model_uri:
+    raise RuntimeError(
+        message.format(model_uri=model_uri, model_class=model_class))
+  elif not model_class:
+    raise RuntimeError(
+        message.format(model_uri=model_uri, model_class=model_class))
+
+
+def _run_inference_torch_keyed_tensor(
+    batch: Sequence[Dict[str, Union[tf.Tensor, torch.Tensor]]],
+    model: AutoModel,
+    device,
+    inference_args: Dict[str, Any],
+    model_id: Optional[str] = None) -> Iterable[PredictionResult]:
+  key_to_tensor_list = defaultdict(list)
+  # torch.no_grad() mitigates GPU memory issues
+  # https://github.com/apache/beam/issues/22811
+  with torch.no_grad():
+    for example in batch:
+      for key, tensor in example.items():
+        key_to_tensor_list[key].append(tensor)
+    key_to_batched_tensors = {}
+    for key in key_to_tensor_list:
+      batched_tensors = torch.stack(key_to_tensor_list[key])
+      batched_tensors = _convert_to_device(batched_tensors, device)
+      key_to_batched_tensors[key] = batched_tensors
+    return utils._convert_to_result(
+        batch, model(**key_to_batched_tensors, **inference_args))
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, Union[tf.Tensor, torch.Tensor]]],
+    model: TFAutoModel,
+    device,
+    inference_args: Dict[str, Any],
+    model_id: Optional[str] = None) -> Iterable[PredictionResult]:
+  key_to_tensor_list = defaultdict(list)
+  for example in batch:
+    for key, tensor in example.items():
+      key_to_tensor_list[key].append(tensor)
+  key_to_batched_tensors = {}
+  for key in key_to_tensor_list:
+    batched_tensors = torch.stack(key_to_tensor_list[key])
+    batched_tensors = key_to_tensor_list[key]
+    key_to_batched_tensors[key] = batched_tensors
+  return utils._convert_to_result(
+      batch, model(**key_to_batched_tensors, **inference_args))
+
+
+class HuggingFaceModelHandlerKeyedTensor(ModelHandler[Dict[str,

Review Comment:
   done



-- 
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-unsubscr...@beam.apache.org

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

Reply via email to