コード例 #1
0
 def setUp(self):
     self.operator = BeamRunPythonPipelineOperator(
         task_id=TASK_ID,
         py_file=PY_FILE,
         py_options=PY_OPTIONS,
         default_pipeline_options=DEFAULT_OPTIONS_PYTHON,
         pipeline_options=ADDITIONAL_OPTIONS,
     )
コード例 #2
0
with models.DAG(
        "example_gcp_dataflow_native_python",
        default_args=default_args,
        start_date=days_ago(1),
        schedule_interval=None,  # Override to match your needs
        tags=['example'],
) as dag_native_python:

    # [START howto_operator_start_python_job]
    start_python_job = BeamRunPythonPipelineOperator(
        task_id="start-python-job",
        py_file=GCS_PYTHON,
        py_options=[],
        pipeline_options={
            'output': GCS_OUTPUT,
        },
        py_requirements=['apache-beam[gcp]==2.21.0'],
        py_interpreter='python3',
        py_system_site_packages=False,
        dataflow_config={'location': 'europe-west3'},
    )
    # [END howto_operator_start_python_job]

    start_python_job_local = BeamRunPythonPipelineOperator(
        task_id="start-python-job-local",
        py_file='apache_beam.examples.wordcount',
        py_options=['-m'],
        pipeline_options={
            'output': GCS_OUTPUT,
        },
        py_requirements=['apache-beam[gcp]==2.14.0'],
コード例 #3
0
def create_evaluate_ops(
    task_prefix: str,
    data_format: str,
    input_paths: List[str],
    prediction_path: str,
    metric_fn_and_keys: Tuple[T, Iterable[str]],
    validate_fn: T,
    batch_prediction_job_id: Optional[str] = None,
    region: Optional[str] = None,
    project_id: Optional[str] = None,
    dataflow_options: Optional[Dict] = None,
    model_uri: Optional[str] = None,
    model_name: Optional[str] = None,
    version_name: Optional[str] = None,
    dag: Optional[DAG] = None,
    py_interpreter="python3",
):
    """
    Creates Operators needed for model evaluation and returns.

    It gets prediction over inputs via Cloud ML Engine BatchPrediction API by
    calling MLEngineBatchPredictionOperator, then summarize and validate
    the result via Cloud Dataflow using DataFlowPythonOperator.

    For details and pricing about Batch prediction, please refer to the website
    https://cloud.google.com/ml-engine/docs/how-tos/batch-predict
    and for Cloud Dataflow, https://cloud.google.com/dataflow/docs/

    It returns three chained operators for prediction, summary, and validation,
    named as ``<prefix>-prediction``, ``<prefix>-summary``, and ``<prefix>-validation``,
    respectively.
    (``<prefix>`` should contain only alphanumeric characters or hyphen.)

    The upstream and downstream can be set accordingly like:

    .. code-block:: python

        pred, _, val = create_evaluate_ops(...)
        pred.set_upstream(upstream_op)
        ...
        downstream_op.set_upstream(val)

    Callers will provide two python callables, metric_fn and validate_fn, in
    order to customize the evaluation behavior as they wish.

    - metric_fn receives a dictionary per instance derived from json in the
      batch prediction result. The keys might vary depending on the model.
      It should return a tuple of metrics.
    - validation_fn receives a dictionary of the averaged metrics that metric_fn
      generated over all instances.
      The key/value of the dictionary matches to what's given by
      metric_fn_and_keys arg.
      The dictionary contains an additional metric, 'count' to represent the
      total number of instances received for evaluation.
      The function would raise an exception to mark the task as failed, in a
      case the validation result is not okay to proceed (i.e. to set the trained
      version as default).

    Typical examples are like this:

    .. code-block:: python

        def get_metric_fn_and_keys():
            import math  # imports should be outside of the metric_fn below.

            def error_and_squared_error(inst):
                label = float(inst["input_label"])
                classes = float(inst["classes"])  # 0 or 1
                err = abs(classes - label)
                squared_err = math.pow(classes - label, 2)
                return (err, squared_err)  # returns a tuple.

            return error_and_squared_error, ["err", "mse"]  # key order must match.


        def validate_err_and_count(summary):
            if summary["err"] > 0.2:
                raise ValueError("Too high err>0.2; summary=%s" % summary)
            if summary["mse"] > 0.05:
                raise ValueError("Too high mse>0.05; summary=%s" % summary)
            if summary["count"] < 1000:
                raise ValueError("Too few instances<1000; summary=%s" % summary)
            return summary

    For the details on the other BatchPrediction-related arguments (project_id,
    job_id, region, data_format, input_paths, prediction_path, model_uri),
    please refer to MLEngineBatchPredictionOperator too.

    :param task_prefix: a prefix for the tasks. Only alphanumeric characters and
        hyphen are allowed (no underscores), since this will be used as dataflow
        job name, which doesn't allow other characters.

    :param data_format: either of 'TEXT', 'TF_RECORD', 'TF_RECORD_GZIP'

    :param input_paths: a list of input paths to be sent to BatchPrediction.

    :param prediction_path: GCS path to put the prediction results in.

    :param metric_fn_and_keys: a tuple of metric_fn and metric_keys:

        - metric_fn is a function that accepts a dictionary (for an instance),
          and returns a tuple of metric(s) that it calculates.

        - metric_keys is a list of strings to denote the key of each metric.

    :param validate_fn: a function to validate whether the averaged metric(s) is
        good enough to push the model.

    :param batch_prediction_job_id: the id to use for the Cloud ML Batch
        prediction job. Passed directly to the MLEngineBatchPredictionOperator as
        the job_id argument.

    :param project_id: the Google Cloud project id in which to execute
        Cloud ML Batch Prediction and Dataflow jobs. If None, then the `dag`'s
        `default_args['project_id']` will be used.

    :param region: the Google Cloud region in which to execute Cloud ML
        Batch Prediction and Dataflow jobs. If None, then the `dag`'s
        `default_args['region']` will be used.

    :param dataflow_options: options to run Dataflow jobs. If None, then the
        `dag`'s `default_args['dataflow_default_options']` will be used.

    :param model_uri: GCS path of the model exported by Tensorflow using
        ``tensorflow.estimator.export_savedmodel()``. It cannot be used with
        model_name or version_name below. See MLEngineBatchPredictionOperator for
        more detail.

    :param model_name: Used to indicate a model to use for prediction. Can be
        used in combination with version_name, but cannot be used together with
        model_uri. See MLEngineBatchPredictionOperator for more detail. If None,
        then the `dag`'s `default_args['model_name']` will be used.

    :param version_name: Used to indicate a model version to use for prediction,
        in combination with model_name. Cannot be used together with model_uri.
        See MLEngineBatchPredictionOperator for more detail. If None, then the
        `dag`'s `default_args['version_name']` will be used.

    :param dag: The `DAG` to use for all Operators.

    :param py_interpreter: Python version of the beam pipeline.
        If None, this defaults to the python3.
        To track python versions supported by beam and related
        issues check: https://issues.apache.org/jira/browse/BEAM-1251

    :returns: a tuple of three operators, (prediction, summary, validation)
    :rtype: tuple(DataFlowPythonOperator, DataFlowPythonOperator,
                  PythonOperator)
    """
    batch_prediction_job_id = batch_prediction_job_id or ""
    dataflow_options = dataflow_options or {}
    region = region or ""

    # Verify that task_prefix doesn't have any special characters except hyphen
    # '-', which is the only allowed non-alphanumeric character by Dataflow.
    if not re.match(r"^[a-zA-Z][-A-Za-z0-9]*$", task_prefix):
        raise AirflowException(
            "Malformed task_id for DataFlowPythonOperator (only alphanumeric "
            "and hyphens are allowed but got: " + task_prefix)

    metric_fn, metric_keys = metric_fn_and_keys
    if not callable(metric_fn):
        raise AirflowException("`metric_fn` param must be callable.")
    if not callable(validate_fn):
        raise AirflowException("`validate_fn` param must be callable.")

    if dag is not None and dag.default_args is not None:
        default_args = dag.default_args
        project_id = project_id or default_args.get('project_id')
        region = region or default_args['region']
        model_name = model_name or default_args.get('model_name')
        version_name = version_name or default_args.get('version_name')
        dataflow_options = dataflow_options or default_args.get(
            'dataflow_default_options')

    evaluate_prediction = MLEngineStartBatchPredictionJobOperator(
        task_id=(task_prefix + "-prediction"),
        project_id=project_id,
        job_id=batch_prediction_job_id,
        region=region,
        data_format=data_format,
        input_paths=input_paths,
        output_path=prediction_path,
        uri=model_uri,
        model_name=model_name,
        version_name=version_name,
        dag=dag,
    )

    metric_fn_encoded = base64.b64encode(dill.dumps(metric_fn,
                                                    recurse=True)).decode()
    evaluate_summary = BeamRunPythonPipelineOperator(
        task_id=(task_prefix + "-summary"),
        py_file=os.path.join(os.path.dirname(__file__),
                             'mlengine_prediction_summary.py'),
        default_pipeline_options=dataflow_options,
        pipeline_options={
            "prediction_path": prediction_path,
            "metric_fn_encoded": metric_fn_encoded,
            "metric_keys": ','.join(metric_keys),
        },
        py_interpreter=py_interpreter,
        py_requirements=['apache-beam[gcp]>=2.14.0'],
        dag=dag,
    )
    evaluate_summary.set_upstream(evaluate_prediction)

    def apply_validate_fn(*args, templates_dict, **kwargs):
        prediction_path = templates_dict["prediction_path"]
        scheme, bucket, obj, _, _ = urlsplit(prediction_path)
        if scheme != "gs" or not bucket or not obj:
            raise ValueError(
                f"Wrong format prediction_path: {prediction_path}")
        summary = os.path.join(obj.strip("/"), "prediction.summary.json")
        gcs_hook = GCSHook()
        summary = json.loads(
            gcs_hook.download(bucket, summary).decode("utf-8"))
        return validate_fn(summary)

    evaluate_validation = PythonOperator(
        task_id=(task_prefix + "-validation"),
        python_callable=apply_validate_fn,
        templates_dict={"prediction_path": prediction_path},
        dag=dag,
    )
    evaluate_validation.set_upstream(evaluate_summary)

    return evaluate_prediction, evaluate_summary, evaluate_validation
コード例 #4
0
    jar_to_local_flink_runner >> start_java_pipeline_flink_runner

with models.DAG(
        "example_beam_native_python",
        default_args=default_args,
        start_date=days_ago(1),
        schedule_interval=None,  # Override to match your needs
        tags=['example'],
) as dag_native_python:

    # [START howto_operator_start_python_direct_runner_pipeline_local_file]
    start_python_pipeline_local_direct_runner = BeamRunPythonPipelineOperator(
        task_id="start_python_pipeline_local_direct_runner",
        py_file='apache_beam.examples.wordcount',
        py_options=['-m'],
        py_requirements=['apache-beam[gcp]==2.26.0'],
        py_interpreter='python3',
        py_system_site_packages=False,
    )
    # [END howto_operator_start_python_direct_runner_pipeline_local_file]

    # [START howto_operator_start_python_direct_runner_pipeline_gcs_file]
    start_python_pipeline_direct_runner = BeamRunPythonPipelineOperator(
        task_id="start_python_pipeline_direct_runner",
        py_file=GCS_PYTHON,
        py_options=[],
        pipeline_options={"output": GCS_OUTPUT},
        py_requirements=['apache-beam[gcp]==2.26.0'],
        py_interpreter='python3',
        py_system_site_packages=False,
    )
コード例 #5
0
class TestBeamRunPythonPipelineOperator(unittest.TestCase):
    def setUp(self):
        self.operator = BeamRunPythonPipelineOperator(
            task_id=TASK_ID,
            py_file=PY_FILE,
            py_options=PY_OPTIONS,
            default_pipeline_options=DEFAULT_OPTIONS_PYTHON,
            pipeline_options=ADDITIONAL_OPTIONS,
        )

    def test_init(self):
        """Test BeamRunPythonPipelineOperator instance is properly initialized."""
        self.assertEqual(self.operator.task_id, TASK_ID)
        self.assertEqual(self.operator.py_file, PY_FILE)
        self.assertEqual(self.operator.runner, DEFAULT_RUNNER)
        self.assertEqual(self.operator.py_options, PY_OPTIONS)
        self.assertEqual(self.operator.py_interpreter, PY_INTERPRETER)
        self.assertEqual(self.operator.default_pipeline_options,
                         DEFAULT_OPTIONS_PYTHON)
        self.assertEqual(self.operator.pipeline_options,
                         EXPECTED_ADDITIONAL_OPTIONS)

    @mock.patch('airflow.providers.apache.beam.operators.beam.BeamHook')
    @mock.patch('airflow.providers.apache.beam.operators.beam.GCSHook')
    def test_exec_direct_runner(self, gcs_hook, beam_hook_mock):
        """Test BeamHook is created and the right args are passed to
        start_python_workflow.
        """
        start_python_hook = beam_hook_mock.return_value.start_python_pipeline
        gcs_provide_file = gcs_hook.return_value.provide_file
        self.operator.execute(None)
        beam_hook_mock.assert_called_once_with(runner=DEFAULT_RUNNER)
        expected_options = {
            'project': 'test',
            'staging_location': 'gs://test/staging',
            'output': 'gs://test/output',
            'labels': {
                'foo': 'bar',
                'airflow-version': TEST_VERSION
            },
        }
        gcs_provide_file.assert_called_once_with(object_url=PY_FILE)
        start_python_hook.assert_called_once_with(
            variables=expected_options,
            py_file=gcs_provide_file.return_value.__enter__.return_value.name,
            py_options=PY_OPTIONS,
            py_interpreter=PY_INTERPRETER,
            py_requirements=None,
            py_system_site_packages=False,
            process_line_callback=None,
        )

    @mock.patch('airflow.providers.apache.beam.operators.beam.BeamHook')
    @mock.patch('airflow.providers.apache.beam.operators.beam.DataflowHook')
    @mock.patch('airflow.providers.apache.beam.operators.beam.GCSHook')
    def test_exec_dataflow_runner(self, gcs_hook, dataflow_hook_mock,
                                  beam_hook_mock):
        """Test DataflowHook is created and the right args are passed to
        start_python_dataflow.
        """
        dataflow_config = DataflowConfiguration()
        self.operator.runner = "DataflowRunner"
        self.operator.dataflow_config = dataflow_config
        gcs_provide_file = gcs_hook.return_value.provide_file
        self.operator.execute(None)
        job_name = dataflow_hook_mock.build_dataflow_job_name.return_value
        dataflow_hook_mock.assert_called_once_with(
            gcp_conn_id=dataflow_config.gcp_conn_id,
            delegate_to=dataflow_config.delegate_to,
            poll_sleep=dataflow_config.poll_sleep,
            impersonation_chain=dataflow_config.impersonation_chain,
            drain_pipeline=dataflow_config.drain_pipeline,
            cancel_timeout=dataflow_config.cancel_timeout,
            wait_until_finished=dataflow_config.wait_until_finished,
        )
        expected_options = {
            'project': dataflow_hook_mock.return_value.project_id,
            'job_name': job_name,
            'staging_location': 'gs://test/staging',
            'output': 'gs://test/output',
            'labels': {
                'foo': 'bar',
                'airflow-version': TEST_VERSION
            },
            'region': 'us-central1',
        }
        gcs_provide_file.assert_called_once_with(object_url=PY_FILE)
        beam_hook_mock.return_value.start_python_pipeline.assert_called_once_with(
            variables=expected_options,
            py_file=gcs_provide_file.return_value.__enter__.return_value.name,
            py_options=PY_OPTIONS,
            py_interpreter=PY_INTERPRETER,
            py_requirements=None,
            py_system_site_packages=False,
            process_line_callback=mock.ANY,
        )
        dataflow_hook_mock.return_value.wait_for_done.assert_called_once_with(
            job_id=self.operator.dataflow_job_id,
            job_name=job_name,
            location='us-central1',
            multiple_jobs=False,
        )

    @mock.patch('airflow.providers.apache.beam.operators.beam.BeamHook')
    @mock.patch('airflow.providers.apache.beam.operators.beam.GCSHook')
    @mock.patch('airflow.providers.apache.beam.operators.beam.DataflowHook')
    def test_on_kill_dataflow_runner(self, dataflow_hook_mock, _, __):
        self.operator.runner = "DataflowRunner"
        dataflow_cancel_job = dataflow_hook_mock.return_value.cancel_job
        self.operator.execute(None)
        self.operator.dataflow_job_id = JOB_ID
        self.operator.on_kill()
        dataflow_cancel_job.assert_called_once_with(
            job_id=JOB_ID, project_id=self.operator.dataflow_config.project_id)

    @mock.patch('airflow.providers.apache.beam.operators.beam.BeamHook')
    @mock.patch('airflow.providers.apache.beam.operators.beam.DataflowHook')
    @mock.patch('airflow.providers.apache.beam.operators.beam.GCSHook')
    def test_on_kill_direct_runner(self, _, dataflow_mock, __):
        dataflow_cancel_job = dataflow_mock.return_value.cancel_job
        self.operator.execute(None)
        self.operator.on_kill()
        dataflow_cancel_job.assert_not_called()