You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "riteshghorse (via GitHub)" <gi...@apache.org> on 2023/05/10 13:34:35 UTC

[GitHub] [beam] riteshghorse opened a new pull request, #26632: [WIP] Hugging Face Model Handler with AutoModel

riteshghorse opened a new pull request, #26632:
URL: https://github.com/apache/beam/pull/26632

   **Please** add a meaningful description for your change here
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://beam.apache.org/contribute/get-started-contributing/#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/workflows/Build%20python%20source%20distribution%20and%20wheels/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/workflows/Python%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/workflows/Java%20Tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/workflows/Go%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI.
   


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


[GitHub] [beam] riteshghorse commented on a diff in pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
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-unsubscribe@beam.apache.org

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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1648360672

   Python 3.8 PC passed for `huggingface_inference_it_test`
   ![image](https://github.com/apache/beam/assets/25881114/375a9ede-f996-4034-91ce-8aaed8e4d841)
   
   


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


[GitHub] [beam] AnandInguva commented on a diff in pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "AnandInguva (via GitHub)" <gi...@apache.org>.
AnandInguva commented on code in PR #26632:
URL: https://github.com/apache/beam/pull/26632#discussion_r1244461264


##########
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:
   Can we follow a pattern where we create a class `HuggingFaceModelHandler`, which would have common method across `HuggingFaceModelHandlerTensor/KeyedTensor` such as `load_model` so that we wouldn't edit the twice? For the types we can use generic types for `HuggingFaceModelHandler`
   
   XGBoostModelHandler was implemented this way https://github.com/apache/beam/blob/5f1eae622932bc3362731bcc8cf464bf678877d4/sdks/python/apache_beam/ml/inference/xgboost_inference.py#L185



##########
sdks/python/apache_beam/examples/inference/huggingface_language_modeling.py:
##########
@@ -0,0 +1,180 @@
+#
+# 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.
+#
+
+""""A pipeline that uses RunInference to perform Language Modeling with
+model from Hugging Face.
+
+This pipeline takes sentences from a custom text file, converts the last word
+of the sentence into a <mask> token, and then uses the AutoModelForMaskedLM from
+Hugging Face to predict the best word for the masked token given all the words
+already in the sentence. The pipeline then writes the prediction to an output
+file in which users can then compare against the original sentence.
+"""
+
+import argparse
+import logging
+from typing import Dict
+from typing import Iterable
+from typing import Iterator
+from typing import Tuple
+
+import apache_beam as beam
+import torch
+from apache_beam.ml.inference.base import KeyedModelHandler
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import RunInference
+from apache_beam.ml.inference.huggingface_inference import HuggingFaceModelHandlerKeyedTensor
+from apache_beam.options.pipeline_options import PipelineOptions
+from apache_beam.options.pipeline_options import SetupOptions
+from apache_beam.runners.runner import PipelineResult
+from transformers import AutoModelForMaskedLM
+from transformers import AutoTokenizer
+
+
+def add_mask_to_last_word(text: str) -> Tuple[str, str]:
+  text_list = text.split()
+  return text, ' '.join(text_list[:-2] + ['<mask>', text_list[-1]])
+
+
+def tokenize_sentence(
+    text_and_mask: Tuple[str, str],
+    tokenizer: AutoTokenizer) -> Tuple[str, Dict[str, torch.Tensor]]:
+  text, masked_text = text_and_mask
+  tokenized_sentence = tokenizer.encode_plus(masked_text, return_tensors="pt")
+
+  # Workaround to manually remove batch dim until we have the feature to
+  # add optional batching flag.
+  # TODO(https://github.com/apache/beam/issues/21863): Remove once optional
+  # batching flag added
+  return text, {
+      k: torch.squeeze(v)
+      for k, v in dict(tokenized_sentence).items()
+  }
+
+
+def filter_empty_lines(text: str) -> Iterator[str]:
+  if len(text.strip()) > 0:
+    yield text
+
+
+class PostProcessor(beam.DoFn):
+  """Processes the PredictionResult to get the predicted word.
+
+  The logits are the output of the Model. After applying a softmax
+  activation function to the logits, we get probabilistic distributions for each
+  of the words in the model's vocabulary. We can get the word with the highest
+  probability of being a candidate replacement word by taking the argmax.
+  """
+  def __init__(self, tokenizer: AutoTokenizer):
+    super().__init__()
+    self.tokenizer = tokenizer
+
+  def process(self, element: Tuple[str, PredictionResult]) -> Iterable[str]:
+    text, prediction_result = element
+    inputs = prediction_result.example
+    logits = prediction_result.inference['logits']
+    mask_token_index = torch.where(
+        inputs["input_ids"] == self.tokenizer.mask_token_id)[0]
+    predicted_token_id = logits[mask_token_index].argmax(axis=-1)
+    decoded_word = self.tokenizer.decode(predicted_token_id)
+    yield text + ';' + decoded_word
+
+
+def parse_known_args(argv):
+  """Parses args for the workflow."""
+  parser = argparse.ArgumentParser()
+  parser.add_argument(
+      '--input',
+      dest='input',
+      help='Path to the text file containing sentences.')
+  parser.add_argument(
+      '--output',
+      dest='output',
+      required=True,
+      help='Path of file in which to save the output predictions.')
+  parser.add_argument(
+      '--model_name',
+      dest='model_name',
+      required=True,
+      help='bert uncased model. This can be base model or large model')
+  parser.add_argument(
+      '--model_class',
+      dest='model_class',
+      default=AutoModelForMaskedLM,
+      help="Name of the model from Hugging Face")
+  return parser.parse_known_args(argv)
+
+
+def run(
+    argv=None, save_main_session=True, test_pipeline=None) -> PipelineResult:
+  """
+  Args:
+    argv: Command line arguments defined for this example.
+    model_class: Reference to the class definition of the model.
+    model_name: Name of the pretrained model to be loaded.
+    save_main_session: Used for internal testing.
+    test_pipeline: Used for internal testing.
+  """
+  known_args, pipeline_args = parse_known_args(argv)
+  pipeline_options = PipelineOptions(pipeline_args)
+  pipeline_options.view_as(SetupOptions).save_main_session = save_main_session
+
+  pipeline = test_pipeline
+  if not test_pipeline:
+    pipeline = beam.Pipeline(options=pipeline_options)
+
+  tokenizer = AutoTokenizer.from_pretrained(known_args.model_name)
+
+  model_handler = HuggingFaceModelHandlerKeyedTensor(
+      model_uri=known_args.model_name,
+      model_class=known_args.model_class,
+      max_batch_size=1)
+  if not known_args.input:
+    text = (
+        pipeline | 'CreateSentences' >> beam.Create([
+            'The capital of France is Paris .',
+            'It is raining cats and dogs .',
+            'Today is Monday and tomorrow is Tuesday .',
+            'There are 5 coconuts on this palm tree .',
+            'The strongest person in the world is not famous .',
+            'The secret ingredient to his wonderful life was gratitude .',
+            'The biggest animal in the world is the whale .',
+        ]))
+  else:
+    text = (
+        pipeline | 'ReadSentences' >> beam.io.ReadFromText(known_args.input))
+  text_and_tokenized_text_tuple = (
+      text
+      | 'FilterEmptyLines' >> beam.ParDo(filter_empty_lines)
+      | 'AddMask' >> beam.Map(add_mask_to_last_word)
+      |
+      'TokenizeSentence' >> beam.Map(lambda x: tokenize_sentence(x, tokenizer)))
+  output = (
+      text_and_tokenized_text_tuple
+      | 'RunInference' >> RunInference(KeyedModelHandler(model_handler))
+      | 'ProcessOutput' >> beam.ParDo(PostProcessor(tokenizer=tokenizer)))
+  output | "WriteOutput" >> beam.io.WriteToText( # pylint: disable=expression-not-assigned

Review Comment:
   ```suggestion
     _ = output | "WriteOutput" >> beam.io.WriteToText( # pylint: disable=expression-not-assigned
   ```
   
   we can remove the pylint warning by assigning the expression to `_`



##########
sdks/python/tox.ini:
##########
@@ -400,3 +401,21 @@ commands =
   # Run all XGBoost unit tests
   # Allow exit code 5 (no tests run) so that we can run this command safely on arbitrary subdirectories.
   /bin/sh -c 'pytest -o junit_suite_name={envname} --junitxml=pytest_{envname}.xml -n 6 -m uses_xgboost {posargs}; ret=$?; [ $ret = 5 ] && exit 0 || exit $ret'
+
+[testenv:py{38,39,310}-transformers-{428,429,430}]

Review Comment:
   311?



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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1645652356

   Run Python 3.8 PostCommit


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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1648487977

   Python 3.11 failure is because of https://github.com/apache/beam/issues/27643


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


[GitHub] [beam] AnandInguva commented on a diff in pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "AnandInguva (via GitHub)" <gi...@apache.org>.
AnandInguva commented on code in PR #26632:
URL: https://github.com/apache/beam/pull/26632#discussion_r1246641050


##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,439 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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, 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
+    predictions = model(**key_to_batched_tensors, **inference_args)
+    return utils._convert_to_result(batch, predictions, model_id)
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, tf.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 = tf.stack(key_to_tensor_list[key], axis=0)
+    key_to_batched_tensors[key] = batched_tensors
+  predictions = model(**key_to_batched_tensors, **inference_args)
+  return utils._convert_to_result(batch, predictions, model_id)
+
+
+class HuggingFaceModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_uri: str,
+      model_class: Union[AutoModel, TFAutoModel],
+      device: str = 'CPU',
+      *,
+      inference_fn: Union[
+          KeyedTensorInferenceFn,
+          TensorInferenceFn] = _run_inference_torch_keyed_tensor,
+      load_model_args: Optional[Dict[str, Any]] = None,
+      inference_args: Optional[Dict[str, Any]] = None,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      large_model: bool = False,
+      **kwargs):
+    """Implementation of the abstract base class of ModelHandler interface
+    for Hugging Face. This class shouldn't be instantiated directly.
+    Use HuggingFaceModelHandlerKeyedTensor or HuggingFaceModelHandlerTensor.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+    Args:
+      model_uri (str): path to the pretrained model on the hugging face
+        models hub.
+      model_class: model class to load the repository from model_uri.
+      device: For torch tensors, specify device on which you wish to
+        run the model. Defaults to CPU.
+      inference_fn: the inference function to use during RunInference.
+        Default is _run_inference_torch_keyed_tensor or
+        _run_inference_tensorflow_keyed_tensor depending on the input type.
+      load_model_args (Dict[str, Any]): keyword arguments to provide load
+        options while loading from Hugging Face Hub. Defaults to None.
+      inference_args [Dict[str, Any]]: Non-batchable arguments
+        required as inputs to the model's forward() function. Unlike Tensors in
+        `batch`, these parameters will not be dynamically batched.
+        Defaults to None.
+      min_batch_size: the minimum batch size to use when batching inputs.
+      max_batch_size: the maximum batch size to use when batching inputs.
+      large_model: set to true if your model is large enough to run into
+        memory pressure if you load multiple copies. Given a model that
+        consumes N memory and a machine with W cores and M memory, you should
+        set this to True if N*W > M.
+      kwargs: 'env_vars' can be used to set environment variables
+        before loading the model.
+
+    **Supported Versions:** RunInference APIs in Apache Beam

Review Comment:
   ```suggestion
       **Supported Versions:** HuggingFaceModelHandler 
   ```



##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,439 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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, 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
+    predictions = model(**key_to_batched_tensors, **inference_args)
+    return utils._convert_to_result(batch, predictions, model_id)
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, tf.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 = tf.stack(key_to_tensor_list[key], axis=0)
+    key_to_batched_tensors[key] = batched_tensors
+  predictions = model(**key_to_batched_tensors, **inference_args)
+  return utils._convert_to_result(batch, predictions, model_id)
+
+
+class HuggingFaceModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_uri: str,
+      model_class: Union[AutoModel, TFAutoModel],
+      device: str = 'CPU',
+      *,
+      inference_fn: Union[
+          KeyedTensorInferenceFn,
+          TensorInferenceFn] = _run_inference_torch_keyed_tensor,
+      load_model_args: Optional[Dict[str, Any]] = None,
+      inference_args: Optional[Dict[str, Any]] = None,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      large_model: bool = False,
+      **kwargs):
+    """Implementation of the abstract base class of ModelHandler interface
+    for Hugging Face. This class shouldn't be instantiated directly.
+    Use HuggingFaceModelHandlerKeyedTensor or HuggingFaceModelHandlerTensor.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+    Args:
+      model_uri (str): path to the pretrained model on the hugging face
+        models hub.
+      model_class: model class to load the repository from model_uri.
+      device: For torch tensors, specify device on which you wish to
+        run the model. Defaults to CPU.
+      inference_fn: the inference function to use during RunInference.
+        Default is _run_inference_torch_keyed_tensor or
+        _run_inference_tensorflow_keyed_tensor depending on the input type.
+      load_model_args (Dict[str, Any]): keyword arguments to provide load
+        options while loading from Hugging Face Hub. Defaults to None.

Review Comment:
   loading models from Hugging Face hub?



##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,439 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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, 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
+    predictions = model(**key_to_batched_tensors, **inference_args)
+    return utils._convert_to_result(batch, predictions, model_id)
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, tf.Tensor]],
+    model: TFAutoModel,
+    device,

Review Comment:
   Can we confirm if GPU is provided, tensorflow is indeed using GPU? TF implicitly chooses a device but it would be good to warn if device is GPU and we run inference on CPU



##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,439 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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, 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
+    predictions = model(**key_to_batched_tensors, **inference_args)
+    return utils._convert_to_result(batch, predictions, model_id)
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, tf.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 = tf.stack(key_to_tensor_list[key], axis=0)
+    key_to_batched_tensors[key] = batched_tensors
+  predictions = model(**key_to_batched_tensors, **inference_args)
+  return utils._convert_to_result(batch, predictions, model_id)
+
+
+class HuggingFaceModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_uri: str,
+      model_class: Union[AutoModel, TFAutoModel],
+      device: str = 'CPU',
+      *,
+      inference_fn: Union[
+          KeyedTensorInferenceFn,
+          TensorInferenceFn] = _run_inference_torch_keyed_tensor,
+      load_model_args: Optional[Dict[str, Any]] = None,
+      inference_args: Optional[Dict[str, Any]] = None,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      large_model: bool = False,
+      **kwargs):
+    """Implementation of the abstract base class of ModelHandler interface
+    for Hugging Face. This class shouldn't be instantiated directly.
+    Use HuggingFaceModelHandlerKeyedTensor or HuggingFaceModelHandlerTensor.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+    Args:
+      model_uri (str): path to the pretrained model on the hugging face
+        models hub.
+      model_class: model class to load the repository from model_uri.
+      device: For torch tensors, specify device on which you wish to
+        run the model. Defaults to CPU.
+      inference_fn: the inference function to use during RunInference.
+        Default is _run_inference_torch_keyed_tensor or
+        _run_inference_tensorflow_keyed_tensor depending on the input type.
+      load_model_args (Dict[str, Any]): keyword arguments to provide load
+        options while loading from Hugging Face Hub. Defaults to None.
+      inference_args [Dict[str, Any]]: Non-batchable arguments
+        required as inputs to the model's forward() function. Unlike Tensors in

Review Comment:
   forward is specific to `torch` framework. Can we make it more general like Arguments required to pass to the model's inference call.



##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,439 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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, 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
+    predictions = model(**key_to_batched_tensors, **inference_args)
+    return utils._convert_to_result(batch, predictions, model_id)
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, tf.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 = tf.stack(key_to_tensor_list[key], axis=0)
+    key_to_batched_tensors[key] = batched_tensors
+  predictions = model(**key_to_batched_tensors, **inference_args)
+  return utils._convert_to_result(batch, predictions, model_id)
+
+
+class HuggingFaceModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_uri: str,
+      model_class: Union[AutoModel, TFAutoModel],
+      device: str = 'CPU',
+      *,
+      inference_fn: Union[
+          KeyedTensorInferenceFn,
+          TensorInferenceFn] = _run_inference_torch_keyed_tensor,
+      load_model_args: Optional[Dict[str, Any]] = None,
+      inference_args: Optional[Dict[str, Any]] = None,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      large_model: bool = False,
+      **kwargs):
+    """Implementation of the abstract base class of ModelHandler interface
+    for Hugging Face. This class shouldn't be instantiated directly.
+    Use HuggingFaceModelHandlerKeyedTensor or HuggingFaceModelHandlerTensor.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+    Args:
+      model_uri (str): path to the pretrained model on the hugging face
+        models hub.
+      model_class: model class to load the repository from model_uri.
+      device: For torch tensors, specify device on which you wish to
+        run the model. Defaults to CPU.
+      inference_fn: the inference function to use during RunInference.
+        Default is _run_inference_torch_keyed_tensor or
+        _run_inference_tensorflow_keyed_tensor depending on the input type.
+      load_model_args (Dict[str, Any]): keyword arguments to provide load
+        options while loading from Hugging Face Hub. Defaults to None.
+      inference_args [Dict[str, Any]]: Non-batchable arguments
+        required as inputs to the model's forward() function. Unlike Tensors in
+        `batch`, these parameters will not be dynamically batched.
+        Defaults to None.
+      min_batch_size: the minimum batch size to use when batching inputs.
+      max_batch_size: the maximum batch size to use when batching inputs.
+      large_model: set to true if your model is large enough to run into
+        memory pressure if you load multiple copies. Given a model that
+        consumes N memory and a machine with W cores and M memory, you should
+        set this to True if N*W > M.
+      kwargs: 'env_vars' can be used to set environment variables
+        before loading the model.
+
+    **Supported Versions:** RunInference APIs in Apache Beam
+    supports transformers>=4.18.0.
+    """
+    self._model_uri = model_uri
+    self._model_class = model_class
+    if device == 'GPU':
+      self._device = torch.device('cuda')
+    else:
+      self._device = torch.device('cpu')
+    self._inference_fn = inference_fn
+    self._model_config_args = load_model_args if load_model_args else {}
+    self._inference_args = inference_args if inference_args else {}
+    self._batching_kwargs = {}
+    self._env_vars = kwargs.get('env_vars', {})
+    if min_batch_size is not None:
+      self._batching_kwargs['min_batch_size'] = min_batch_size
+    if max_batch_size is not None:
+      self._batching_kwargs['max_batch_size'] = max_batch_size
+    self._large_model = large_model
+    self._framework = ""
+
+    _validate_constructor_args(
+        model_uri=self._model_uri, model_class=self._model_class)
+
+  def load_model(self):
+    """Loads and initializes the model for processing."""
+    model = self._model_class.from_pretrained(
+        self._model_uri, **self._model_config_args)
+    if self._device == torch.device('cuda'):
+      if not torch.cuda.is_available():
+        logging.warning(
+            "Model handler specified a 'GPU' device, "
+            "but GPUs are not available. Switching to CPU.")
+        self._device = torch.device('cpu')
+      model.to(self._device)
+    return model
+
+  def update_model_path(self, model_path: Optional[str] = None):
+    self._model_uri = model_path if model_path else self._model_uri
+
+  def get_num_bytes(
+      self, batch: Sequence[Union[tf.Tensor, torch.Tensor]]) -> int:
+    """
+    Returns:
+      The number of bytes of data for the Tensors batch.
+    """
+    if self._framework == "tf":
+      return sum(sys.getsizeof(element) for element in batch)
+    else:
+      return sum(
+          (el.element_size() for tensor in batch for el in tensor.values()))
+
+  def batch_elements_kwargs(self):
+    return self._batching_kwargs
+
+  def share_model_across_processes(self) -> bool:
+    return self._large_model
+
+
+class HuggingFaceModelHandlerKeyedTensor(
+    HuggingFaceModelHandler[Dict[str, Union[tf.Tensor, torch.Tensor]],
+                            PredictionResult,
+                            Union[AutoModel, TFAutoModel]]):
+  """Implementation of the ModelHandler interface for HuggingFace with
+    Keyed Tensors for PyTorch/Tensorflow backend.
+
+    Depending on the type of tensors,
+    the model framework is determined automatically.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+  Args:
+    model_uri (str): path to the pretrained model on the hugging face
+      models hub.
+    model_class: model class to load the repository from model_uri.
+    device: For torch tensors, specify device on which you wish to
+      run the model. Defaults to CPU.
+    inference_fn: the inference function to use during RunInference.
+      Default is _run_inference_torch_keyed_tensor or
+      _run_inference_tensorflow_keyed_tensor depending on the input type.
+    load_model_args (Dict[str, Any]): keyword arguments to provide load
+      options while loading from Hugging Face Hub. Defaults to None.
+    inference_args ([Dict[str, Any]]): Non-batchable arguments
+      required as inputs to the model's forward() function. Unlike Tensors in
+      `batch`, these parameters will not be dynamically batched.
+      Defaults to None.
+    min_batch_size: the minimum batch size to use when batching inputs.
+    max_batch_size: the maximum batch size to use when batching inputs.
+    large_model: set to true if your model is large enough to run into
+      memory pressure if you load multiple copies. Given a model that
+      consumes N memory and a machine with W cores and M memory, you should
+      set this to True if N*W > M.
+    kwargs: 'env_vars' can be used to set environment variables
+      before loading the model.
+
+  **Supported Versions:** RunInference APIs in Apache Beam
+  supports transformers>=4.18.0.
+  """
+  def run_inference(
+      self,
+      batch: Sequence[Dict[str, Union[tf.Tensor, torch.Tensor]]],
+      model: Union[AutoModel, TFAutoModel],
+      inference_args: Optional[Dict[str, Any]] = None
+  ) -> Iterable[PredictionResult]:
+    """
+    Runs inferences on a batch of Keyed Tensors and returns an Iterable of
+    Tensors Predictions.
+
+    This method stacks the list of Tensors in a vectorized format to optimize
+    the inference call.
+
+    Args:
+      batch: A sequence of Keyed Tensors. These Tensors should be batchable,
+        as this method will call `tf.stack()`/`torch.stack()` and pass in
+        batched Tensors with dimensions (batch_size, n_features, etc.) into the
+        model's predict() function.
+      model: A Tensorflow/PyTorch model.
+      inference_args: Non-batchable arguments required as inputs to the model's
+        forward() function. Unlike Tensors in `batch`, these parameters will
+        not be dynamically batched
+    Returns:
+      An Iterable of type PredictionResult.
+    """
+    inference_args = {} if not inference_args else inference_args
+    if not self._framework:
+      self._framework = "tf" if isinstance(batch[0], tf.Tensor) else "torch"
+
+    # default is always torch keyed tensor. We check if user has provided their
+    # own or we move to infer it with input type.
+    if self._inference_fn != _run_inference_torch_keyed_tensor:

Review Comment:
   we can make the default as None and type to be `Optional[Callable[...]]`.
   
   Let's check if it is not None, then run the custom inference_fn else choose depending on the framework.



##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,439 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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, 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
+    predictions = model(**key_to_batched_tensors, **inference_args)
+    return utils._convert_to_result(batch, predictions, model_id)
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, tf.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 = tf.stack(key_to_tensor_list[key], axis=0)
+    key_to_batched_tensors[key] = batched_tensors
+  predictions = model(**key_to_batched_tensors, **inference_args)
+  return utils._convert_to_result(batch, predictions, model_id)
+
+
+class HuggingFaceModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_uri: str,
+      model_class: Union[AutoModel, TFAutoModel],
+      device: str = 'CPU',
+      *,
+      inference_fn: Union[
+          KeyedTensorInferenceFn,
+          TensorInferenceFn] = _run_inference_torch_keyed_tensor,
+      load_model_args: Optional[Dict[str, Any]] = None,
+      inference_args: Optional[Dict[str, Any]] = None,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      large_model: bool = False,
+      **kwargs):
+    """Implementation of the abstract base class of ModelHandler interface
+    for Hugging Face. This class shouldn't be instantiated directly.
+    Use HuggingFaceModelHandlerKeyedTensor or HuggingFaceModelHandlerTensor.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+    Args:
+      model_uri (str): path to the pretrained model on the hugging face
+        models hub.
+      model_class: model class to load the repository from model_uri.
+      device: For torch tensors, specify device on which you wish to
+        run the model. Defaults to CPU.
+      inference_fn: the inference function to use during RunInference.
+        Default is _run_inference_torch_keyed_tensor or
+        _run_inference_tensorflow_keyed_tensor depending on the input type.
+      load_model_args (Dict[str, Any]): keyword arguments to provide load
+        options while loading from Hugging Face Hub. Defaults to None.
+      inference_args [Dict[str, Any]]: Non-batchable arguments
+        required as inputs to the model's forward() function. Unlike Tensors in
+        `batch`, these parameters will not be dynamically batched.
+        Defaults to None.
+      min_batch_size: the minimum batch size to use when batching inputs.
+      max_batch_size: the maximum batch size to use when batching inputs.
+      large_model: set to true if your model is large enough to run into
+        memory pressure if you load multiple copies. Given a model that
+        consumes N memory and a machine with W cores and M memory, you should
+        set this to True if N*W > M.
+      kwargs: 'env_vars' can be used to set environment variables
+        before loading the model.
+
+    **Supported Versions:** RunInference APIs in Apache Beam
+    supports transformers>=4.18.0.
+    """
+    self._model_uri = model_uri
+    self._model_class = model_class
+    if device == 'GPU':
+      self._device = torch.device('cuda')
+    else:
+      self._device = torch.device('cpu')

Review Comment:
   move this logic to torch related if case?



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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1648117828

   Run Python 3.11 PostCommit


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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1640675199

   @AnandInguva Robert approved the design. Can you take a final look before merging this?


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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1648117589

   Run Python 3.8 PostCommit


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


[GitHub] [beam] AnandInguva commented on a diff in pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "AnandInguva (via GitHub)" <gi...@apache.org>.
AnandInguva commented on code in PR #26632:
URL: https://github.com/apache/beam/pull/26632#discussion_r1246844939


##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -82,12 +82,35 @@ def _validate_constructor_args(model_uri, model_class):
         message.format(model_uri=model_uri, model_class=model_class))
 
 
+def no_gpu_available_warning():
+  logging.warning(

Review Comment:
   Let's use logging related to this file.
   
   For example, https://github.com/apache/beam/blob/04fdf0818c2147576ebbd51bc0d5b6d575ed905f/sdks/python/apache_beam/utils/retry.py#L59



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


[GitHub] [beam] AnandInguva commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "AnandInguva (via GitHub)" <gi...@apache.org>.
AnandInguva commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1625364801

   waiting on author


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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1645652767

   Run Python 3.11 PostCommit


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


[GitHub] [beam] riteshghorse commented on pull request #26632: Hugging Face Model Handler with AutoModel

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1609935163

   Run Python 3.11 PostCommit


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


[GitHub] [beam] github-actions[bot] commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1609992912

   Assigning reviewers. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @AnandInguva for label python.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1648361033

   Run Python 3.11 PostCommit


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


[GitHub] [beam] riteshghorse merged pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse merged PR #26632:
URL: https://github.com/apache/beam/pull/26632


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


[GitHub] [beam] AnandInguva commented on a diff in pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "AnandInguva (via GitHub)" <gi...@apache.org>.
AnandInguva commented on code in PR #26632:
URL: https://github.com/apache/beam/pull/26632#discussion_r1255769224


##########
sdks/python/apache_beam/ml/inference/huggingface_inference_it_test.py:
##########
@@ -0,0 +1,80 @@
+#
+# 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.
+#
+
+"""End-to-End test for Hugging Face Inference"""
+
+import logging
+import unittest
+import uuid
+
+import pytest
+
+from apache_beam.io.filesystems import FileSystems
+from apache_beam.testing.test_pipeline import TestPipeline
+
+try:
+  from apache_beam.examples.inference import huggingface_language_modeling
+  from apache_beam.ml.inference import pytorch_inference_it_test
+except ImportError:
+  raise unittest.SkipTest(
+      "transformers dependencies are not installed. "
+      "Check if transformers, torch, and tensorflow "
+      "is installed.")
+
+
+@pytest.mark.uses_transformers
+@pytest.mark.it_postcommit
+class HuggingFaceInference(unittest.TestCase):
+  @pytest.mark.timeout(1800)
+  def test_hf_language_modeling(self):
+    test_pipeline = TestPipeline(is_integration_test=True)
+    # Path to text file containing some sentences
+    file_of_sentences = 'gs://apache-beam-ml/datasets/custom/hf_sentences.txt'  # pylint: disable=line-too-long

Review Comment:
   Use parentheses to break up the line. avoid pylint if possible. Same comment for some other long lines as well.



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


[GitHub] [beam] github-actions[bot] commented on pull request #26632: Hugging Face Model Handler with AutoModel

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1609823955

   Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment `assign set of reviewers`


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


[GitHub] [beam] codecov[bot] commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1609965950

   ## [Codecov](https://app.codecov.io/gh/apache/beam/pull/26632?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   > Merging [#26632](https://app.codecov.io/gh/apache/beam/pull/26632?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) (4177c09) into [master](https://app.codecov.io/gh/apache/beam/commit/a4281d8f35cf26bc62444f06b48d0019085e8e64?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) (a4281d8) will **decrease** coverage by `0.15%`.
   > The diff coverage is `3.94%`.
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #26632      +/-   ##
   ==========================================
   - Coverage   71.49%   71.34%   -0.15%     
   ==========================================
     Files         858      860       +2     
     Lines      104715   104943     +228     
   ==========================================
   + Hits        74865    74875      +10     
   - Misses      28302    28520     +218     
     Partials     1548     1548              
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | python | `80.55% <3.94%> (-0.26%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://app.codecov.io/gh/apache/beam/pull/26632?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [.../apache\_beam/ml/inference/huggingface\_inference.py](https://app.codecov.io/gh/apache/beam/pull/26632?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vbWwvaW5mZXJlbmNlL2h1Z2dpbmdmYWNlX2luZmVyZW5jZS5weQ==) | `0.00% <0.00%> (ø)` | |
   | [...xamples/inference/huggingface\_language\_modeling.py](https://app.codecov.io/gh/apache/beam/pull/26632?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vZXhhbXBsZXMvaW5mZXJlbmNlL2h1Z2dpbmdmYWNlX2xhbmd1YWdlX21vZGVsaW5nLnB5) | `13.23% <13.23%> (ø)` | |
   
   ... and [4 files with indirect coverage changes](https://app.codecov.io/gh/apache/beam/pull/26632/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   


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


[GitHub] [beam] github-actions[bot] commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1625325905

   Reminder, please take a look at this pr: @AnandInguva 


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


[GitHub] [beam] riteshghorse commented on pull request #26632: Hugging Face Model Handler with AutoModel

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1609935029

   Run Python 3.8 PostCommit


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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1611632816

   Run Python 3.11 PostCommit


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


[GitHub] [beam] AnandInguva commented on a diff in pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "AnandInguva (via GitHub)" <gi...@apache.org>.
AnandInguva commented on code in PR #26632:
URL: https://github.com/apache/beam/pull/26632#discussion_r1247188195


##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,449 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    'HuggingFaceModelHandlerTensor',
+    'HuggingFaceModelHandlerKeyedTensor',
+]
+
+TensorInferenceFn = Callable[[
+    Sequence[Union[torch.Tensor, tf.Tensor]],
+    Union[AutoModel, TFAutoModel],
+    torch.device,

Review Comment:
   I think the type would be string now



##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,449 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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 no_gpu_available_warning():
+  logging.warning(
+      "Model handler specified a 'GPU' device, but GPUs are not available. "

Review Comment:
   Can we specify the name of the ModelHandler instead of `Model Handler`?



##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,449 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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 no_gpu_available_warning():
+  logging.warning(
+      "Model handler specified a 'GPU' device, but GPUs are not available. "
+      "Switching to CPU.")
+
+
+def is_gpu_available_torch(device):
+  if device == 'GPU' and torch.cuda.is_available():
+    return True
+  no_gpu_available_warning()
+  return False
+
+
+def is_gpu_available_tensorflow(device):
+  gpu_devices = tf.config.list_physical_devices(device)
+  if len(gpu_devices) == 0:
+    no_gpu_available_warning()
+    return False
+  return True
+
+
+def _run_inference_torch_keyed_tensor(
+    batch: Sequence[Dict[str, torch.Tensor]],
+    model: AutoModel,
+    device,
+    inference_args: Dict[str, Any],
+    model_id: Optional[str] = None) -> Iterable[PredictionResult]:
+  device = torch.device('cuda') if is_gpu_available_torch(
+      device) else torch.device('cpu')
+  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
+    predictions = model(**key_to_batched_tensors, **inference_args)
+    return utils._convert_to_result(batch, predictions, model_id)
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, tf.Tensor]],
+    model: TFAutoModel,
+    device,
+    inference_args: Dict[str, Any],
+    model_id: Optional[str] = None) -> Iterable[PredictionResult]:
+  is_gpu_available_tensorflow()
+  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 = tf.stack(key_to_tensor_list[key], axis=0)
+    key_to_batched_tensors[key] = batched_tensors
+  predictions = model(**key_to_batched_tensors, **inference_args)
+  return utils._convert_to_result(batch, predictions, model_id)
+
+
+class HuggingFaceModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_uri: str,
+      model_class: Union[AutoModel, TFAutoModel],
+      device: str = 'CPU',
+      *,
+      inference_fn: Optional[Callable[..., PredictionT]] = None,
+      load_model_args: Optional[Dict[str, Any]] = None,
+      inference_args: Optional[Dict[str, Any]] = None,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      large_model: bool = False,
+      **kwargs):
+    """Implementation of the abstract base class of ModelHandler interface
+    for Hugging Face. This class shouldn't be instantiated directly.
+    Use HuggingFaceModelHandlerKeyedTensor or HuggingFaceModelHandlerTensor.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+    Args:
+      model_uri (str): path to the pretrained model on the hugging face
+        models hub.
+      model_class: model class to load the repository from model_uri.
+      device: For torch tensors, specify device on which you wish to
+        run the model. Defaults to CPU.
+      inference_fn: the inference function to use during RunInference.
+        Default is _run_inference_torch_keyed_tensor or
+        _run_inference_tensorflow_keyed_tensor depending on the input type.
+      load_model_args (Dict[str, Any]): keyword arguments to provide load
+        options while loading models from Hugging Face Hub. Defaults to None.
+      inference_args [Dict[str, Any]]: Non-batchable arguments
+        required as inputs to the model's inference function. Unlike Tensors in
+        `batch`, these parameters will not be dynamically batched.
+        Defaults to None.
+      min_batch_size: the minimum batch size to use when batching inputs.
+      max_batch_size: the maximum batch size to use when batching inputs.
+      large_model: set to true if your model is large enough to run into
+        memory pressure if you load multiple copies. Given a model that
+        consumes N memory and a machine with W cores and M memory, you should
+        set this to True if N*W > M.
+      kwargs: 'env_vars' can be used to set environment variables
+        before loading the model.
+
+    **Supported Versions:** HuggingFaceModelHandler supports
+    transformers>=4.18.0.
+    """
+    self._model_uri = model_uri
+    self._model_class = model_class
+    self._device = device
+    self._inference_fn = inference_fn
+    self._model_config_args = load_model_args if load_model_args else {}
+    self._inference_args = inference_args if inference_args else {}
+    self._batching_kwargs = {}
+    self._env_vars = kwargs.get('env_vars', {})
+    if min_batch_size is not None:
+      self._batching_kwargs['min_batch_size'] = min_batch_size
+    if max_batch_size is not None:
+      self._batching_kwargs['max_batch_size'] = max_batch_size
+    self._large_model = large_model
+    self._framework = ""
+
+    _validate_constructor_args(
+        model_uri=self._model_uri, model_class=self._model_class)
+
+  def load_model(self):
+    """Loads and initializes the model for processing."""
+    model = self._model_class.from_pretrained(
+        self._model_uri, **self._model_config_args)
+    if is_gpu_available_torch(self._device):
+      model.to(torch.device('cuda'))
+    return model
+
+  def update_model_path(self, model_path: Optional[str] = None):
+    self._model_uri = model_path if model_path else self._model_uri
+
+  def get_num_bytes(
+      self, batch: Sequence[Union[tf.Tensor, torch.Tensor]]) -> int:
+    """
+    Returns:
+      The number of bytes of data for the Tensors batch.
+    """
+    if self._framework == "tf":
+      return sum(sys.getsizeof(element) for element in batch)
+    else:
+      return sum(
+          (el.element_size() for tensor in batch for el in tensor.values()))
+
+  def batch_elements_kwargs(self):
+    return self._batching_kwargs
+
+  def share_model_across_processes(self) -> bool:
+    return self._large_model
+
+
+class HuggingFaceModelHandlerKeyedTensor(
+    HuggingFaceModelHandler[Dict[str, Union[tf.Tensor, torch.Tensor]],
+                            PredictionResult,
+                            Union[AutoModel, TFAutoModel]]):
+  """Implementation of the ModelHandler interface for HuggingFace with
+    Keyed Tensors for PyTorch/Tensorflow backend.
+
+    Depending on the type of tensors,
+    the model framework is determined automatically.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+  Args:
+    model_uri (str): path to the pretrained model on the hugging face
+      models hub.
+    model_class: model class to load the repository from model_uri.
+    device: For torch tensors, specify device on which you wish to
+      run the model. Defaults to CPU.
+    inference_fn: the inference function to use during RunInference.
+      Default is _run_inference_torch_keyed_tensor or
+      _run_inference_tensorflow_keyed_tensor depending on the input type.
+    load_model_args (Dict[str, Any]): keyword arguments to provide load
+      options while loading models from Hugging Face Hub. Defaults to None.
+    inference_args ([Dict[str, Any]]): Non-batchable arguments
+      required as inputs to the model's inference function. Unlike Tensors in
+      `batch`, these parameters will not be dynamically batched.
+      Defaults to None.
+    min_batch_size: the minimum batch size to use when batching inputs.
+    max_batch_size: the maximum batch size to use when batching inputs.
+    large_model: set to true if your model is large enough to run into
+      memory pressure if you load multiple copies. Given a model that
+      consumes N memory and a machine with W cores and M memory, you should
+      set this to True if N*W > M.
+    kwargs: 'env_vars' can be used to set environment variables
+      before loading the model.
+

Review Comment:
   Just an idea. I am fine with having the doc string here as well.



##########
sdks/python/apache_beam/ml/inference/huggingface_inference.py:
##########
@@ -0,0 +1,449 @@
+#
+# 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
+
+from abc import ABC
+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 ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+from apache_beam.ml.inference.pytorch_inference import _convert_to_device
+from transformers import AutoModel
+from transformers import TFAutoModel
+
+__all__ = [
+    'HuggingFaceModelHandler',
+    '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 no_gpu_available_warning():
+  logging.warning(
+      "Model handler specified a 'GPU' device, but GPUs are not available. "
+      "Switching to CPU.")
+
+
+def is_gpu_available_torch(device):
+  if device == 'GPU' and torch.cuda.is_available():
+    return True
+  no_gpu_available_warning()
+  return False
+
+
+def is_gpu_available_tensorflow(device):
+  gpu_devices = tf.config.list_physical_devices(device)
+  if len(gpu_devices) == 0:
+    no_gpu_available_warning()
+    return False
+  return True
+
+
+def _run_inference_torch_keyed_tensor(
+    batch: Sequence[Dict[str, torch.Tensor]],
+    model: AutoModel,
+    device,
+    inference_args: Dict[str, Any],
+    model_id: Optional[str] = None) -> Iterable[PredictionResult]:
+  device = torch.device('cuda') if is_gpu_available_torch(
+      device) else torch.device('cpu')
+  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
+    predictions = model(**key_to_batched_tensors, **inference_args)
+    return utils._convert_to_result(batch, predictions, model_id)
+
+
+def _run_inference_tensorflow_keyed_tensor(
+    batch: Sequence[Dict[str, tf.Tensor]],
+    model: TFAutoModel,
+    device,
+    inference_args: Dict[str, Any],
+    model_id: Optional[str] = None) -> Iterable[PredictionResult]:
+  is_gpu_available_tensorflow()
+  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 = tf.stack(key_to_tensor_list[key], axis=0)
+    key_to_batched_tensors[key] = batched_tensors
+  predictions = model(**key_to_batched_tensors, **inference_args)
+  return utils._convert_to_result(batch, predictions, model_id)
+
+
+class HuggingFaceModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_uri: str,
+      model_class: Union[AutoModel, TFAutoModel],
+      device: str = 'CPU',
+      *,
+      inference_fn: Optional[Callable[..., PredictionT]] = None,
+      load_model_args: Optional[Dict[str, Any]] = None,
+      inference_args: Optional[Dict[str, Any]] = None,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      large_model: bool = False,
+      **kwargs):
+    """Implementation of the abstract base class of ModelHandler interface
+    for Hugging Face. This class shouldn't be instantiated directly.
+    Use HuggingFaceModelHandlerKeyedTensor or HuggingFaceModelHandlerTensor.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+    Args:
+      model_uri (str): path to the pretrained model on the hugging face
+        models hub.
+      model_class: model class to load the repository from model_uri.
+      device: For torch tensors, specify device on which you wish to
+        run the model. Defaults to CPU.
+      inference_fn: the inference function to use during RunInference.
+        Default is _run_inference_torch_keyed_tensor or
+        _run_inference_tensorflow_keyed_tensor depending on the input type.
+      load_model_args (Dict[str, Any]): keyword arguments to provide load
+        options while loading models from Hugging Face Hub. Defaults to None.
+      inference_args [Dict[str, Any]]: Non-batchable arguments
+        required as inputs to the model's inference function. Unlike Tensors in
+        `batch`, these parameters will not be dynamically batched.
+        Defaults to None.
+      min_batch_size: the minimum batch size to use when batching inputs.
+      max_batch_size: the maximum batch size to use when batching inputs.
+      large_model: set to true if your model is large enough to run into
+        memory pressure if you load multiple copies. Given a model that
+        consumes N memory and a machine with W cores and M memory, you should
+        set this to True if N*W > M.
+      kwargs: 'env_vars' can be used to set environment variables
+        before loading the model.
+
+    **Supported Versions:** HuggingFaceModelHandler supports
+    transformers>=4.18.0.
+    """
+    self._model_uri = model_uri
+    self._model_class = model_class
+    self._device = device
+    self._inference_fn = inference_fn
+    self._model_config_args = load_model_args if load_model_args else {}
+    self._inference_args = inference_args if inference_args else {}
+    self._batching_kwargs = {}
+    self._env_vars = kwargs.get('env_vars', {})
+    if min_batch_size is not None:
+      self._batching_kwargs['min_batch_size'] = min_batch_size
+    if max_batch_size is not None:
+      self._batching_kwargs['max_batch_size'] = max_batch_size
+    self._large_model = large_model
+    self._framework = ""
+
+    _validate_constructor_args(
+        model_uri=self._model_uri, model_class=self._model_class)
+
+  def load_model(self):
+    """Loads and initializes the model for processing."""
+    model = self._model_class.from_pretrained(
+        self._model_uri, **self._model_config_args)
+    if is_gpu_available_torch(self._device):
+      model.to(torch.device('cuda'))
+    return model
+
+  def update_model_path(self, model_path: Optional[str] = None):
+    self._model_uri = model_path if model_path else self._model_uri
+
+  def get_num_bytes(
+      self, batch: Sequence[Union[tf.Tensor, torch.Tensor]]) -> int:
+    """
+    Returns:
+      The number of bytes of data for the Tensors batch.
+    """
+    if self._framework == "tf":
+      return sum(sys.getsizeof(element) for element in batch)
+    else:
+      return sum(
+          (el.element_size() for tensor in batch for el in tensor.values()))
+
+  def batch_elements_kwargs(self):
+    return self._batching_kwargs
+
+  def share_model_across_processes(self) -> bool:
+    return self._large_model
+
+
+class HuggingFaceModelHandlerKeyedTensor(
+    HuggingFaceModelHandler[Dict[str, Union[tf.Tensor, torch.Tensor]],
+                            PredictionResult,
+                            Union[AutoModel, TFAutoModel]]):
+  """Implementation of the ModelHandler interface for HuggingFace with
+    Keyed Tensors for PyTorch/Tensorflow backend.
+
+    Depending on the type of tensors,
+    the model framework is determined automatically.
+
+    Example Usage model::
+    pcoll | RunInference(HuggingFaceModelHandlerKeyedTensor(
+      model_uri="bert-base-uncased", model_class=AutoModelForMaskedLM))
+
+  Args:
+    model_uri (str): path to the pretrained model on the hugging face
+      models hub.
+    model_class: model class to load the repository from model_uri.
+    device: For torch tensors, specify device on which you wish to
+      run the model. Defaults to CPU.
+    inference_fn: the inference function to use during RunInference.
+      Default is _run_inference_torch_keyed_tensor or
+      _run_inference_tensorflow_keyed_tensor depending on the input type.
+    load_model_args (Dict[str, Any]): keyword arguments to provide load
+      options while loading models from Hugging Face Hub. Defaults to None.
+    inference_args ([Dict[str, Any]]): Non-batchable arguments
+      required as inputs to the model's inference function. Unlike Tensors in
+      `batch`, these parameters will not be dynamically batched.
+      Defaults to None.
+    min_batch_size: the minimum batch size to use when batching inputs.
+    max_batch_size: the maximum batch size to use when batching inputs.
+    large_model: set to true if your model is large enough to run into
+      memory pressure if you load multiple copies. Given a model that
+      consumes N memory and a machine with W cores and M memory, you should
+      set this to True if N*W > M.
+    kwargs: 'env_vars' can be used to set environment variables
+      before loading the model.
+

Review Comment:
   Do we need to mention the documentation again here? Instead can we address the difference between base class and the current one?



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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1611632547

   Run Python 3.8 PostCommit


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


[GitHub] [beam] riteshghorse commented on pull request #26632: [Python] Implemented Hugging Face Model Handler

Posted by "riteshghorse (via GitHub)" <gi...@apache.org>.
riteshghorse commented on PR #26632:
URL: https://github.com/apache/beam/pull/26632#issuecomment-1648488250

   Merging this!


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