apache_beam.ml.inference.base module

An extensible run inference transform.

Users of this module can extend the ModelHandler class for any machine learning framework. A ModelHandler implementation is a required parameter of RunInference.

The transform handles standard inference functionality, like metric collection, sharing model between threads, and batching elements.

class apache_beam.ml.inference.base.PredictionResult[source]

Bases: apache_beam.ml.inference.base.PredictionResult

A NamedTuple containing both input and output from the inference.

class apache_beam.ml.inference.base.ModelMetadata(model_id, model_name)[source]

Bases: tuple

Create new instance of ModelMetadata(model_id, model_name)

model_id

Unique identifier for the model. This can be a file path or a URL where the model can be accessed. It is used to load the model for inference.

model_name

Human-readable name for the model. This can be used to identify the model in the metrics generated by the RunInference transform.

class apache_beam.ml.inference.base.RunInferenceDLQ(failed_inferences, failed_preprocessing, failed_postprocessing)[source]

Bases: tuple

Create new instance of RunInferenceDLQ(failed_inferences, failed_preprocessing, failed_postprocessing)

failed_inferences

Alias for field number 0

failed_preprocessing

Alias for field number 1

failed_postprocessing

Alias for field number 2

class apache_beam.ml.inference.base.ModelHandler[source]

Bases: typing.Generic

Has the ability to load and apply an ML model.

Environment variables are set using a dict named ‘env_vars’ before loading the model. Child classes can accept this dict as a kwarg.

load_model() → ModelT[source]

Loads and initializes a model for processing.

run_inference(batch: Sequence[ExampleT], model: ModelT, inference_args: Optional[Dict[str, Any]] = None) → Iterable[PredictionT][source]

Runs inferences on a batch of examples.

Parameters:
  • batch – A sequence of examples or features.
  • model – The model used to make inferences.
  • inference_args – Extra arguments for models whose inference call requires extra parameters.
Returns:

An Iterable of Predictions.

get_num_bytes(batch: Sequence[ExampleT]) → int[source]
Returns:The number of bytes of data for a batch.
get_metrics_namespace() → str[source]
Returns:A namespace for metrics collected by the RunInference transform.
get_resource_hints() → dict[source]
Returns:Resource hints for the transform.
batch_elements_kwargs() → Mapping[str, Any][source]
Returns:kwargs suitable for beam.BatchElements.
validate_inference_args(inference_args: Optional[Dict[str, Any]])[source]

Validates inference_args passed in the inference call.

Because most frameworks do not need extra arguments in their predict() call, the default behavior is to error out if inference_args are present.

update_model_path(model_path: Optional[str] = None)[source]

Update the model paths produced by side inputs.

get_preprocess_fns() → Iterable[Callable[[Any], Any]][source]

Gets all preprocessing functions to be run before batching/inference. Functions are in order that they should be applied.

get_postprocess_fns() → Iterable[Callable[[Any], Any]][source]

Gets all postprocessing functions to be run after inference. Functions are in order that they should be applied.

set_environment_vars()[source]

Sets environment variables using a dictionary provided via kwargs. Keys are the env variable name, and values are the env variable value. Child ModelHandler classes should set _env_vars via kwargs in __init__, or else call super().__init__().

with_preprocess_fn(fn: Callable[[PreProcessT], ExampleT]) → ModelHandler[PreProcessT, PredictionT, ModelT, PreProcessT][source]

Returns a new ModelHandler with a preprocessing function associated with it. The preprocessing function will be run before batching/inference and should map your input PCollection to the base ModelHandler’s input type. If you apply multiple preprocessing functions, they will be run on your original PCollection in order from last applied to first applied.

with_postprocess_fn(fn: Callable[[PredictionT], PostProcessT]) → ModelHandler[ExampleT, PostProcessT, ModelT, PostProcessT][source]

Returns a new ModelHandler with a postprocessing function associated with it. The postprocessing function will be run after inference and should map the base ModelHandler’s output type to your desired output type. If you apply multiple postprocessing functions, they will be run on your original inference result in order from first applied to last applied.

share_model_across_processes() → bool[source]

Returns a boolean representing whether or not a model should be shared across multiple processes instead of being loaded per process. This is primary useful for large models that can’t fit multiple copies in memory. Multi-process support may vary by runner, but this will fallback to loading per process as necessary. See https://beam.apache.org/releases/pydoc/current/apache_beam.utils.multi_process_shared.html

class apache_beam.ml.inference.base.KeyedModelHandler(unkeyed: apache_beam.ml.inference.base.ModelHandler[~ExampleT, ~PredictionT, ~ModelT][ExampleT, PredictionT, ModelT])[source]

Bases: apache_beam.ml.inference.base.ModelHandler

A ModelHandler that takes keyed examples and returns keyed predictions.

For example, if the original model is used with RunInference to take a PCollection[E] to a PCollection[P], this ModelHandler would take a PCollection[Tuple[K, E]] to a PCollection[Tuple[K, P]], making it possible to use the key to associate the outputs with the inputs.

Parameters:unkeyed – An implementation of ModelHandler that does not require keys.
load_model() → ModelT[source]
run_inference(batch: Sequence[Tuple[KeyT, ExampleT]], model: ModelT, inference_args: Optional[Dict[str, Any]] = None) → Iterable[Tuple[KeyT, PredictionT]][source]
get_num_bytes(batch: Sequence[Tuple[KeyT, ExampleT]]) → int[source]
get_metrics_namespace() → str[source]
get_resource_hints()[source]
batch_elements_kwargs()[source]
validate_inference_args(inference_args: Optional[Dict[str, Any]])[source]
update_model_path(model_path: Optional[str] = None)[source]
get_preprocess_fns() → Iterable[Callable[[Any], Any]][source]
get_postprocess_fns() → Iterable[Callable[[Any], Any]][source]
share_model_across_processes() → bool[source]
class apache_beam.ml.inference.base.MaybeKeyedModelHandler(unkeyed: apache_beam.ml.inference.base.ModelHandler[~ExampleT, ~PredictionT, ~ModelT][ExampleT, PredictionT, ModelT])[source]

Bases: apache_beam.ml.inference.base.ModelHandler

A ModelHandler that takes examples that might have keys and returns predictions that might have keys.

For example, if the original model is used with RunInference to take a PCollection[E] to a PCollection[P], this ModelHandler would take either PCollection[E] to a PCollection[P] or PCollection[Tuple[K, E]] to a PCollection[Tuple[K, P]], depending on the whether the elements are tuples. This pattern makes it possible to associate the outputs with the inputs based on the key.

Note that you cannot use this ModelHandler if E is a tuple type. In addition, either all examples should be keyed, or none of them.

Parameters:unkeyed – An implementation of ModelHandler that does not require keys.
load_model() → ModelT[source]
run_inference(batch: Sequence[Union[ExampleT, Tuple[KeyT, ExampleT]]], model: ModelT, inference_args: Optional[Dict[str, Any]] = None) → Union[Iterable[PredictionT], Iterable[Tuple[KeyT, PredictionT]]][source]
get_num_bytes(batch: Sequence[Union[ExampleT, Tuple[KeyT, ExampleT]]]) → int[source]
get_metrics_namespace() → str[source]
get_resource_hints()[source]
batch_elements_kwargs()[source]
validate_inference_args(inference_args: Optional[Dict[str, Any]])[source]
update_model_path(model_path: Optional[str] = None)[source]
get_preprocess_fns() → Iterable[Callable[[Any], Any]][source]
get_postprocess_fns() → Iterable[Callable[[Any], Any]][source]
share_model_across_processes() → bool[source]
class apache_beam.ml.inference.base.RunInference(model_handler: apache_beam.ml.inference.base.ModelHandler[~ExampleT, ~PredictionT, typing.Any][ExampleT, PredictionT, Any], clock=<module 'time' (built-in)>, inference_args: Optional[Dict[str, Any]] = None, metrics_namespace: Optional[str] = None, *, model_metadata_pcoll: apache_beam.pvalue.PCollection[apache_beam.ml.inference.base.ModelMetadata][apache_beam.ml.inference.base.ModelMetadata] = None, watch_model_pattern: Optional[str] = None, **kwargs)[source]

Bases: apache_beam.transforms.ptransform.PTransform

A transform that takes a PCollection of examples (or features) for use on an ML model. The transform then outputs inferences (or predictions) for those examples in a PCollection of PredictionResults that contains the input examples and the output inferences.

Models for supported frameworks can be loaded using a URI. Supported services can also be used.

This transform attempts to batch examples using the beam.BatchElements transform. Batching can be configured using the ModelHandler.

Parameters:
  • model_handler – An implementation of ModelHandler.
  • clock – A clock implementing time_ns. Used for unit testing.
  • inference_args – Extra arguments for models whose inference call requires extra parameters.
  • metrics_namespace – Namespace of the transform to collect metrics.
  • model_metadata_pcoll – PCollection that emits Singleton ModelMetadata containing model path and model name, that is used as a side input to the _RunInferenceDoFn.
  • watch_model_pattern – A glob pattern used to watch a directory for automatic model refresh.
classmethod from_callable(model_handler_provider, **kwargs)[source]

Multi-language friendly constructor.

Use this constructor with fully_qualified_named_transform to initialize the RunInference transform from PythonCallableSource provided by foreign SDKs.

Parameters:
  • model_handler_provider – A callable object that returns ModelHandler.
  • kwargs – Keyword arguments for model_handler_provider.
expand(pcoll: apache_beam.pvalue.PCollection[~ExampleT][ExampleT]) → apache_beam.pvalue.PCollection[~PredictionT][PredictionT][source]
with_exception_handling(*, exc_class=<class 'Exception'>, use_subprocess=False, threshold=1)[source]

Automatically provides a dead letter output for skipping bad records. This can allow a pipeline to continue successfully rather than fail or continuously throw errors on retry when bad elements are encountered.

This returns a tagged output with two PCollections, the first being the results of successfully processing the input PCollection, and the second being the set of bad batches of records (those which threw exceptions during processing) along with information about the errors raised.

For example, one would write:

main, other = RunInference(
  maybe_error_raising_model_handler
).with_exception_handling()

and main will be a PCollection of PredictionResults and other will contain a RunInferenceDLQ object with PCollections containing failed records for each failed inference, preprocess operation, or postprocess operation. To access each collection of failed records, one would write:

failed_inferences = other.failed_inferences failed_preprocessing = other.failed_preprocessing failed_postprocessing = other.failed_postprocessing

failed_inferences is in the form PCollection[Tuple[failed batch, exception]].

failed_preprocessing is in the form list[PCollection[Tuple[failed record, exception]]]], where each element of the list corresponds to a preprocess function. These PCollections are in the same order that the preprocess functions are applied.

failed_postprocessing is in the form List[PCollection[Tuple[failed record, exception]]]], where each element of the list corresponds to a postprocess function. These PCollections are in the same order that the postprocess functions are applied.

Parameters:
  • exc_class – An exception class, or tuple of exception classes, to catch. Optional, defaults to ‘Exception’.
  • use_subprocess – Whether to execute the DoFn logic in a subprocess. This allows one to recover from errors that can crash the calling process (e.g. from an underlying library causing a segfault), but is slower as elements and results must cross a process boundary. Note that this starts up a long-running process that is used to handle all the elements (until hard failure, which should be rare) rather than a new process per element, so the overhead should be minimal (and can be amortized if there’s any per-process or per-bundle initialization that needs to be done). Optional, defaults to False.
  • threshold – An upper bound on the ratio of records that can be bad before aborting the entire pipeline. Optional, defaults to 1.0 (meaning up to 100% of records can be bad and the pipeline will still succeed).