code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def test_markdown_source_missing_key(viz_params, markdown_key): #pylint: disable=redefined-outer-name """Test with markdown source missing keys.""" del viz_params["markdown"][markdown_key] expected_exception_msg = r"Missing mandatory key - {}".format(markdown_key) with pytest.raises(ValueError, match=e...
Test with markdown source missing keys.
test_markdown_source_missing_key
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
Apache-2.0
def test_different_storage_value(viz_params): #pylint: disable=redefined-outer-name """Test for different storgae values for markdown.""" viz_params["markdown"]["storage"] = "inline" output_dict = generate_visualization(viz_params) assert output_dict is not None assert "mlpipeline_ui_metadata" in o...
Test for different storgae values for markdown.
test_different_storage_value
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
Apache-2.0
def test_confusion_matrix_invalid_types( viz_params, #pylint: disable=redefined-outer-name confusion_matrix_params, #pylint: disable=redefined-outer-name cm_key): """Test for invalid type keys for confusion matrix.""" confusion_matrix_params[cm_key] = {"test": "dummy"} viz_params["...
Test for invalid type keys for confusion matrix.
test_confusion_matrix_invalid_types
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
Apache-2.0
def test_confusion_matrix_optional_check( viz_params, #pylint: disable=redefined-outer-name confusion_matrix_params, #pylint: disable=redefined-outer-name cm_key): """Tests for passing confusion matrix keys as optional.""" confusion_matrix_params[cm_key] = {} viz_params["confusion_...
Tests for passing confusion matrix keys as optional.
test_confusion_matrix_optional_check
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
Apache-2.0
def test_confusion_matrix_missing_check( viz_params, #pylint: disable=redefined-outer-name confusion_matrix_params, #pylint: disable=redefined-outer-name cm_key): """Tests for missing confusion matrix keys.""" del confusion_matrix_params[cm_key] viz_params["confusion_matrix_dict"] ...
Tests for missing confusion matrix keys.
test_confusion_matrix_missing_check
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
Apache-2.0
def test_confusion_matrix_success(viz_params, confusion_matrix_params): #pylint: disable=redefined-outer-name """Test for successful confusion matrix generation.""" if os.path.exists(viz_params["mlpipeline_ui_metadata"]): os.remove(viz_params["mlpipeline_ui_metadata"]) viz_params["confusion_matrix_...
Test for successful confusion matrix generation.
test_confusion_matrix_success
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/test_visualization.py
Apache-2.0
def add_model_specific_args(parent_parser): """ Add model specific arguments like learning rate :param parent_parser: Application specific parser :return: Returns the augmented arugument parser """ parser = ArgumentParser(parents=[parent_parser], add_help=False) ...
Add model specific arguments like learning rate :param parent_parser: Application specific parser :return: Returns the augmented arugument parser
add_model_specific_args
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/iris/iris_classification.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/iris/iris_classification.py
Apache-2.0
def add_model_specific_args(parent_parser): """ Adds model specific arguments batch size and num workers :param parent_parser: Application specific parser :return: Returns the augmented arugument parser """ parser = ArgumentParser(parents=[parent_parser], add_help=False...
Adds model specific arguments batch size and num workers :param parent_parser: Application specific parser :return: Returns the augmented arugument parser
add_model_specific_args
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/iris/iris_data_module.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/iris/iris_data_module.py
Apache-2.0
def create_data_loader(self, dataset): """ Generic data loader function :param data_set: Input data set :return: Returns the constructed dataloader """ return DataLoader( dataset, batch_size=self.args.get("batch_size", 16), num_worke...
Generic data loader function :param data_set: Input data set :return: Returns the constructed dataloader
create_data_loader
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/iris/iris_data_module.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/iris/iris_data_module.py
Apache-2.0
def preprocess(self, data): """ preprocessing step - Reads the input array and converts it to tensor :param data: Input to be passed through the layers for prediction :return: output - Preprocessed input """ input_data_str = data[0].get("data") if input_data_st...
preprocessing step - Reads the input array and converts it to tensor :param data: Input to be passed through the layers for prediction :return: output - Preprocessed input
preprocess
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/iris/iris_handler.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/iris/iris_handler.py
Apache-2.0
def postprocess(self, inference_output): """ Does postprocess after inference to be returned to user :param inference_output: Output of inference :return: output - Output after post processing """ predicted_idx = str(np.argmax(inference_output.cpu().detach().numpy())) ...
Does postprocess after inference to be returned to user :param inference_output: Output of inference :return: output - Output after post processing
postprocess
python
kubeflow/pipelines
components/PyTorch/pytorch-kfp-components/tests/iris/iris_handler.py
https://github.com/kubeflow/pipelines/blob/master/components/PyTorch/pytorch-kfp-components/tests/iris/iris_handler.py
Apache-2.0
def snowflake_unload_op( output_gcs_path: str, sf_storage_integration: str, query: str, sf_user: str, sf_password: str, sf_account: str, sf_warehouse: str, sf_database: str ) -> str: """ Run COPY in snowflake to unload data to GCS bucket. output_gcs_path: the location to...
Run COPY in snowflake to unload data to GCS bucket. output_gcs_path: the location to land the data sf_storage_integration: the Snowflake Storage Integration name query: the query to execute in the COPY command sf_user: the snowflake username sf_password: the snowflake password sf_warehouse...
snowflake_unload_op
python
kubeflow/pipelines
components/snowflake/snowflake_unload_data.py
https://github.com/kubeflow/pipelines/blob/master/components/snowflake/snowflake_unload_data.py
Apache-2.0
def use_config_map_as_env( task: PipelineTask, config_map_name: Union[pipeline_channel.PipelineParameterChannel, str], config_map_key_to_env: Dict[str, str], ) -> PipelineTask: """Use a Kubernetes ConfigMap as an environment variable as described by the `Kubernetes documentation https://kubernetes.i...
Use a Kubernetes ConfigMap as an environment variable as described by the `Kubernetes documentation https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#define-container-environment-variables-using-configmap-data` _. Args: task: Pipeline task. config_map_name: Name ...
use_config_map_as_env
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/config_map.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/config_map.py
Apache-2.0
def use_config_map_as_volume( task: PipelineTask, config_map_name: Union[pipeline_channel.PipelineParameterChannel, str], mount_path: str, optional: bool = False, ) -> PipelineTask: """Use a Kubernetes ConfigMap by mounting its data to the task's container as described by the `Kubernetes documen...
Use a Kubernetes ConfigMap by mounting its data to the task's container as described by the `Kubernetes documentation <https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#add-configmap-data-to-a-volume>`_. Args: task: Pipeline task. config_map_name: Name of the Con...
use_config_map_as_volume
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/config_map.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/config_map.py
Apache-2.0
def use_field_path_as_env( task: PipelineTask, env_name: str, field_path: str, ) -> PipelineTask: """Use a Kubernetes Field Path as an environment variable as described in https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information Args: task: Pi...
Use a Kubernetes Field Path as an environment variable as described in https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information Args: task: Pipeline task. env_name: Name of the enviornment variable. field_path: Kubernetes field path to expose ...
use_field_path_as_env
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/field.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/field.py
Apache-2.0
def set_image_pull_secrets( task: PipelineTask, secret_names: Union[List[str], List[pipeline_channel.PipelineParameterChannel]], ) -> PipelineTask: """Set image pull secrets for a Kubernetes task. Args: task: Pipeline task. secret_names: List of image pull secret names. Ret...
Set image pull secrets for a Kubernetes task. Args: task: Pipeline task. secret_names: List of image pull secret names. Returns: Task object with updated image pull secret configuration.
set_image_pull_secrets
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/image.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/image.py
Apache-2.0
def set_image_pull_policy(task: PipelineTask, policy: str) -> PipelineTask: """Set image pull policy for the container. Args: task: Pipeline task. policy: One of `Always`, `Never`, `IfNotPresent`. Returns: Task object with an added ImagePullPolicy specification. """ if poli...
Set image pull policy for the container. Args: task: Pipeline task. policy: One of `Always`, `Never`, `IfNotPresent`. Returns: Task object with an added ImagePullPolicy specification.
set_image_pull_policy
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/image.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/image.py
Apache-2.0
def add_node_selector( task: PipelineTask, label_key: str, label_value: str, ) -> PipelineTask: """Add a constraint to the task Pod's `nodeSelector <https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodeselector>`_. Each constraint is a key-value pair, corresp...
Add a constraint to the task Pod's `nodeSelector <https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodeselector>`_. Each constraint is a key-value pair, corresponding to the PodSpec's `nodeSelector <https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#schedulin...
add_node_selector
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/node_selector.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/node_selector.py
Apache-2.0
def add_node_selector_json( task: PipelineTask, node_selector_json: Union[pipeline_channel.PipelineParameterChannel, dict], ) -> PipelineTask: """Add a pod nodeSelector constraint to the task Pod's `nodeSelector' Args: task: Pipeline task. node_selector_json: node se...
Add a pod nodeSelector constraint to the task Pod's `nodeSelector' Args: task: Pipeline task. node_selector_json: node selector provided as dict or input parameter. Takes precedence over label_key and label_value. Only one node_selector_json is applicable to a ta...
add_node_selector_json
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/node_selector.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/node_selector.py
Apache-2.0
def add_pod_label( task: PipelineTask, label_key: str, label_value: str, ) -> PipelineTask: """Add a label to the task Pod's `metadata <https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#Pod>`_. Each label is a key-value pair, corresponding to the metadata's `ObjectM...
Add a label to the task Pod's `metadata <https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#Pod>`_. Each label is a key-value pair, corresponding to the metadata's `ObjectMeta <https://kubernetes.io/docs/reference/kubernetes-api/common-definitions/object-meta/#ObjectMeta`_ field. ...
add_pod_label
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/pod_metadata.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/pod_metadata.py
Apache-2.0
def add_pod_annotation( task: PipelineTask, annotation_key: str, annotation_value: str, ) -> PipelineTask: """Add an annotation to the task Pod's `metadata <https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#Pod>`_. Each annotation is a key-value pair, corresponding ...
Add an annotation to the task Pod's `metadata <https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#Pod>`_. Each annotation is a key-value pair, corresponding to the metadata's `ObjectMeta <https://kubernetes.io/docs/reference/kubernetes-api/common-definitions/object-meta/#ObjectMeta`...
add_pod_annotation
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/pod_metadata.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/pod_metadata.py
Apache-2.0
def use_secret_as_env( task: PipelineTask, secret_name: Union[pipeline_channel.PipelineParameterChannel, str], secret_key_to_env: Dict[str, str], ) -> PipelineTask: """Use a Kubernetes Secret as an environment variable as described by the `Kubernetes documentation https://kubernetes.io/docs/concepts...
Use a Kubernetes Secret as an environment variable as described by the `Kubernetes documentation https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-environment-variables `_. Args: task: Pipeline task. secret_name: Name of the Secret. secret_key_to_env: Dictionary...
use_secret_as_env
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/secret.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/secret.py
Apache-2.0
def use_secret_as_volume( task: PipelineTask, secret_name: Union[pipeline_channel.PipelineParameterChannel, str], mount_path: str, optional: bool = False, ) -> PipelineTask: """Use a Kubernetes Secret by mounting its data to the task's container as described by the `Kubernetes documentation <htt...
Use a Kubernetes Secret by mounting its data to the task's container as described by the `Kubernetes documentation <https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod>`_. Args: task: Pipeline task. secret_name: Name of the Secret. mount_path: Pat...
use_secret_as_volume
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/secret.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/secret.py
Apache-2.0
def set_timeout( task: PipelineTask, seconds: int, ) -> PipelineTask: """Add timeout to the task Pod's `active_deadline_seconds <https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.26/#podspec-v1-core>`_. Timeout an integer greater than 0, corresponding to the podspec active_deadline_s...
Add timeout to the task Pod's `active_deadline_seconds <https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.26/#podspec-v1-core>`_. Timeout an integer greater than 0, corresponding to the podspec active_deadline_seconds <https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.26/#podspec-...
set_timeout
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/timeout.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/timeout.py
Apache-2.0
def add_toleration( task: PipelineTask, key: Optional[str] = None, operator: Optional[Literal["Equal", "Exists"]] = None, value: Optional[str] = None, effect: Optional[Literal["NoExecute", "NoSchedule", "PreferNoSchedule"]] = None, toleration_seconds: Optional[int] = None, ): """Add a `toler...
Add a `toleration<https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/>`_. to a task. Args: task: Pipeline task. key: key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator mus...
add_toleration
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/toleration.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/toleration.py
Apache-2.0
def add_toleration_json(task: PipelineTask, toleration_json: Union[pipeline_channel.PipelineParameterChannel, list, dict] ): """Add a Pod Toleration in the form of a Pipeline Input JSON to a task. Args: task: Pipeline task. toleration_...
Add a Pod Toleration in the form of a Pipeline Input JSON to a task. Args: task: Pipeline task. toleration_json: a toleration that is a pipeline input parameter, dict, or list. The input parameter must be of type dict or list. If it is an input para...
add_toleration_json
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/toleration.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/toleration.py
Apache-2.0
def CreatePVC( name: dsl.OutputPath(str), access_modes: List[str], size: str, pvc_name: Optional[str] = None, pvc_name_suffix: Optional[str] = None, storage_class_name: Optional[str] = '', volume_name: Optional[str] = None, annotations: Optional[Dict[str, str]] = None, ): """Create a...
Create a PersistentVolumeClaim, which can be used by downstream tasks. See `PersistentVolume <https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistent-volumes>`_ and `PersistentVolumeClaim <https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistentvolumeclaims>`_ documentation for ...
CreatePVC
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/volume.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/volume.py
Apache-2.0
def mount_pvc( task: PipelineTask, pvc_name: Union[str, 'PipelineChannel'], mount_path: str, ) -> PipelineTask: """Mount a PersistentVolumeClaim to the task's container. Args: task: Pipeline task. pvc_name: Name of the PVC to mount. Supports passing a runtime-generated name, such as...
Mount a PersistentVolumeClaim to the task's container. Args: task: Pipeline task. pvc_name: Name of the PVC to mount. Supports passing a runtime-generated name, such as a name provided by ``kubernetes.CreatePvcOp().outputs['name']``. mount_path: Path to which the PVC should be mounted as a ...
mount_pvc
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/volume.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/volume.py
Apache-2.0
def _assign_pvc_name_to_msg( msg: message.Message, pvc_name: Union[str, 'PipelineChannel'], ) -> bool: """Assigns pvc_name to the msg's pvc_reference oneof. Returns True if pvc_name is an upstream task output. Else, returns False.""" if isinstance(pvc_name, str): msg.constant = pvc_name ...
Assigns pvc_name to the msg's pvc_reference oneof. Returns True if pvc_name is an upstream task output. Else, returns False.
_assign_pvc_name_to_msg
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/volume.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/volume.py
Apache-2.0
def add_ephemeral_volume( task: PipelineTask, volume_name: str, mount_path: str, access_modes: List[str], size: str, storage_class_name: Optional[str] = None, labels: Dict[str, str] = None, annotations: Dict[str, str] = None, ): """Add a `generic ephemeral volume <https://kuberne...
Add a `generic ephemeral volume <https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes>`_. to a task. Args: task: Pipeline task. volume_name: name to be given to the created ephemeral volume. Corresponds to Pod.spec.volumes[*].name ...
add_ephemeral_volume
python
kubeflow/pipelines
kubernetes_platform/python/kfp/kubernetes/volume.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/kfp/kubernetes/volume.py
Apache-2.0
def ignore_kfp_version_helper(spec: Dict[str, Any]) -> Dict[str, Any]: """Ignores kfp sdk versioning in command. Takes in a YAML input and ignores the kfp sdk versioning in command for comparison between compiled file and goldens. """ pipeline_spec = spec.get('pipelineSpec', spec) if 'executor...
Ignores kfp sdk versioning in command. Takes in a YAML input and ignores the kfp sdk versioning in command for comparison between compiled file and goldens.
ignore_kfp_version_helper
python
kubeflow/pipelines
kubernetes_platform/python/test/snapshot/read_write_test.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/test/snapshot/read_write_test.py
Apache-2.0
def handle_expected_diffs( component_spec: 'structures.ComponentSpec' ) -> 'structures.ComponentSpec': """Strips some component spec fields that should be ignored when comparing with golden result.""" # Ignore description when comparing components specs read in from v1 component YAML and from IR YAM...
Strips some component spec fields that should be ignored when comparing with golden result.
handle_expected_diffs
python
kubeflow/pipelines
kubernetes_platform/python/test/snapshot/read_write_test.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/test/snapshot/read_write_test.py
Apache-2.0
def test( self, test_case: str, function: str, ): """Tests serialization and deserialization consistency and correctness. Args: name (str): '{test_group_name}-{test_case_name}'. Useful for print statements/debugging. test_case (str): Test case name (w...
Tests serialization and deserialization consistency and correctness. Args: name (str): '{test_group_name}-{test_case_name}'. Useful for print statements/debugging. test_case (str): Test case name (without file extension). test_data_dir (str): The directory containing the tes...
test
python
kubeflow/pipelines
kubernetes_platform/python/test/snapshot/read_write_test.py
https://github.com/kubeflow/pipelines/blob/master/kubernetes_platform/python/test/snapshot/read_write_test.py
Apache-2.0
def get_settings_from_env(controller_port=None, visualization_server_image=None, frontend_image=None, visualization_server_tag=None, frontend_tag=None, disable_istio_sidecar=None, minio_access_key=None, minio_secret_key=None, kfp_default_pipe...
Returns a dict of settings from environment variables relevant to the controller Environment settings can be overridden by passing them here as arguments. Settings are pulled from the all-caps version of the setting name. The following defaults are used if those environment variables are not set ...
get_settings_from_env
python
kubeflow/pipelines
manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/sync.py
https://github.com/kubeflow/pipelines/blob/master/manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/sync.py
Apache-2.0
def server_factory(visualization_server_image, visualization_server_tag, frontend_image, frontend_tag, disable_istio_sidecar, minio_access_key, minio_secret_key, kfp_default_pipeline_root=None, url="", controller_port=8080): """ Returns...
Returns an HTTPServer populated with Handler with customized settings
server_factory
python
kubeflow/pipelines
manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/sync.py
https://github.com/kubeflow/pipelines/blob/master/manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/sync.py
Apache-2.0
def sync_server(request): """ Starts the sync HTTP server for a given set of environment variables on a separate thread Yields: * the server (useful to interrogate for the server address) * environment variables (useful to interrogate for correct responses) """ environ = request.param w...
Starts the sync HTTP server for a given set of environment variables on a separate thread Yields: * the server (useful to interrogate for the server address) * environment variables (useful to interrogate for correct responses)
sync_server
python
kubeflow/pipelines
manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
https://github.com/kubeflow/pipelines/blob/master/manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
Apache-2.0
def sync_server_from_arguments(request): """ Starts the sync HTTP server for a given set of parameters passed as arguments, with server on a separate thread Yields: * the server (useful to interrogate for the server address) * environment variables (useful to interrogate for correct responses) ...
Starts the sync HTTP server for a given set of parameters passed as arguments, with server on a separate thread Yields: * the server (useful to interrogate for the server address) * environment variables (useful to interrogate for correct responses)
sync_server_from_arguments
python
kubeflow/pipelines
manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
https://github.com/kubeflow/pipelines/blob/master/manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
Apache-2.0
def test_sync_server_with_pipeline_enabled(sync_server, data, expected_status, expected_visualization_server_image, expected_frontend_server_image): """ Nearly end-to-end test of how Controller serves .sync as a POST Tests case where metadata.labels.pipelines.kube...
Nearly end-to-end test of how Controller serves .sync as a POST Tests case where metadata.labels.pipelines.kubeflow.org/enabled exists, and thus we should produce children Only does spot checks on children to see if key properties are correct
test_sync_server_with_pipeline_enabled
python
kubeflow/pipelines
manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
https://github.com/kubeflow/pipelines/blob/master/manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
Apache-2.0
def test_sync_server_with_direct_passing_of_settings( sync_server_from_arguments, data, expected_status, expected_visualization_server_image, expected_frontend_server_image): """ Nearly end-to-end test of how Controller serves .sync as a POST, taking variables as arguments Only does spot ch...
Nearly end-to-end test of how Controller serves .sync as a POST, taking variables as arguments Only does spot checks on children to see if key properties are correct
test_sync_server_with_direct_passing_of_settings
python
kubeflow/pipelines
manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
https://github.com/kubeflow/pipelines/blob/master/manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
Apache-2.0
def test_sync_server_without_pipeline_enabled(sync_server, data, expected_status, expected_children): """ Nearly end-to-end test of how Controller serves .sync as a POST Tests case where metadata.labels.pipelines.kubeflow.org/enabled does not exist and thus...
Nearly end-to-end test of how Controller serves .sync as a POST Tests case where metadata.labels.pipelines.kubeflow.org/enabled does not exist and thus server returns an empty reply
test_sync_server_without_pipeline_enabled
python
kubeflow/pipelines
manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
https://github.com/kubeflow/pipelines/blob/master/manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/test_sync.py
Apache-2.0
def mpirun_pipeline(image="uber/horovod:0.13.11-tf1.10.0-torch0.4.0-py3.5", batch_size="64", optimizer='momentum', sync_source='https://github.com/tensorflow/benchmarks.git', git_sync_branch='cnn_tf_v1.9_compatible', data='user-susan:/training', ...
A pipeline for end to end machine learning workflow.
mpirun_pipeline
python
kubeflow/pipelines
samples/contrib/arena-samples/mpi/mpi_run.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/arena-samples/mpi/mpi_run.py
Apache-2.0
def compile( path ): """ Compile a Kubeflow pipeline. Args: path: Path to the pipeline (e.g. databricks_run_pipeline.py) """ logging.info("Compiling '%s'...", path) compiled_path = f"{path}.tar.gz" result = os.system(f"dsl-compile --p...
Compile a Kubeflow pipeline. Args: path: Path to the pipeline (e.g. databricks_run_pipeline.py)
compile
python
kubeflow/pipelines
samples/contrib/azure-samples/databricks-pipelines/pipeline_cli.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/azure-samples/databricks-pipelines/pipeline_cli.py
Apache-2.0
def run( path, host, params={} ): """ Run a compiled pipeline in Kubeflow. Args: path: Path to the compiled pipeline (e.g. databricks_run_pipeline.py.tar.gz) host: Host name to use to talk to Kubeflow Pipelines (e.g. http://localho...
Run a compiled pipeline in Kubeflow. Args: path: Path to the compiled pipeline (e.g. databricks_run_pipeline.py.tar.gz) host: Host name to use to talk to Kubeflow Pipelines (e.g. http://localhost:8080/pipeline) params: Pipeline parameters (e.g. '{"run_name":"test-ru...
run
python
kubeflow/pipelines
samples/contrib/azure-samples/databricks-pipelines/pipeline_cli.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/azure-samples/databricks-pipelines/pipeline_cli.py
Apache-2.0
def compile_run( path, host, params={} ): """ Compile and run a Kubeflow pipeline. Args: path: Path to the pipeline (e.g. databricks_run_pipeline.py) host: Host name to use to talk to Kubeflow Pipelines (e.g. http://localhost:8080/...
Compile and run a Kubeflow pipeline. Args: path: Path to the pipeline (e.g. databricks_run_pipeline.py) host: Host name to use to talk to Kubeflow Pipelines (e.g. http://localhost:8080/pipeline) params: Pipeline parameters (e.g. '{"run_name":"test-run","parameter":"...
compile_run
python
kubeflow/pipelines
samples/contrib/azure-samples/databricks-pipelines/pipeline_cli.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/azure-samples/databricks-pipelines/pipeline_cli.py
Apache-2.0
def aiosPipeline( BUCKET_NAME='', TRAINING_DATA_LINK='https://raw.githubusercontent.com/emartensibm/german-credit/master/german_credit_data_biased_training.csv', POSTGRES_SCHEMA_NAME='data_mart_credit', LABEL_NAME='Risk', PROBLEM_TYPE='BINARY_CLASSIFICATION', THRESHOLD='0.7', AIOS_MANIFEST_P...
A pipeline for Spark machine learning workflow with OpenScale.
aiosPipeline
python
kubeflow/pipelines
samples/contrib/ibm-samples/openscale/openscale.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/ibm-samples/openscale/openscale.py
Apache-2.0
def load_data( data_url: str, data_size: int, credit_risk_dataset: Output[Dataset]): ''' Downloads credit_risk_dataset.csv file and generates additional synthetic data for benchmarking and testing purposes. Input Parameters ---------------- data_url : str url where ...
Downloads credit_risk_dataset.csv file and generates additional synthetic data for benchmarking and testing purposes. Input Parameters ---------------- data_url : str url where the dataset is hosted data_size : int size of final dataset desired, default 1M rows O...
load_data
python
kubeflow/pipelines
samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
Apache-2.0
def create_train_test_set( data: Input[Dataset], x_train_data: Output[Dataset], y_train_data: Output[Dataset], x_test_data: Output[Dataset], y_test_data: Output[Dataset]): ''' Creates 75:25 split of input dataset for model evaluation. Input Artifacts --------------- data :...
Creates 75:25 split of input dataset for model evaluation. Input Artifacts --------------- data : Dataset dataset that has been synthetically augmented by the load_data() function Output Artifacts ---------------- x_train_data : Dataset training features, 75% of or...
create_train_test_set
python
kubeflow/pipelines
samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
Apache-2.0
def preprocess_features( x_train: Input[Dataset], x_test: Input[Dataset], x_train_processed: Output[Dataset], x_test_processed: Output[Dataset]): ''' Performs data preprocessing of training and test features. Input Artifacts --------------- x_train : Dataset original u...
Performs data preprocessing of training and test features. Input Artifacts --------------- x_train : Dataset original unprocessed training features x_test : Dataset original unprocessed test features Output Artifacts ---------------- x_train_processed : Datase...
preprocess_features
python
kubeflow/pipelines
samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
Apache-2.0
def train_xgboost_model( x_train: Input[Dataset], y_train: Input[Dataset], xgb_model: Output[Model]): ''' Trains an XGBoost classification model. Input Artifacts --------------- x_train : Dataset processed and scaled training features y_train : Dataset trainin...
Trains an XGBoost classification model. Input Artifacts --------------- x_train : Dataset processed and scaled training features y_train : Dataset training labels of target variable, loan_status Output Artifacts ---------------- xgb_model : Model train...
train_xgboost_model
python
kubeflow/pipelines
samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
Apache-2.0
def convert_xgboost_to_daal4py( xgb_model: Input[Model], daal4py_model: Output[Model]): ''' Converts XGBoost model to inference-optimized daal4py classifier. Input Artifacts --------------- xgb_model : Model trained XGBoost classifier Output Artifacts ------------...
Converts XGBoost model to inference-optimized daal4py classifier. Input Artifacts --------------- xgb_model : Model trained XGBoost classifier Output Artifacts ---------------- daal4py_model : Model inference-optimized daal4py classifier
convert_xgboost_to_daal4py
python
kubeflow/pipelines
samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
Apache-2.0
def daal4py_inference( x_test: Input[Dataset], y_test: Input[Dataset], daal4py_model: Input[Model], prediction_data: Output[Dataset], report: Output[Dataset], metrics: Output[Metrics] ): ''' Computes predictions using the inference-optimized daal4py classifier and evaluates mod...
Computes predictions using the inference-optimized daal4py classifier and evaluates model performance. Input Artifacts --------------- x_test : Dataset processed and scaled test features y_test : Dataset test labels of target variable, loan_status daal4py_model : Mod...
daal4py_inference
python
kubeflow/pipelines
samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
Apache-2.0
def plot_roc_curve( predictions: Input[Dataset], class_metrics: Output[ClassificationMetrics] ): ''' Function to plot Receiver Operating Characteristic (ROC) curve. Input Artifacts --------------- predictions : Dataset dataset containing true test labels and predicted proba...
Function to plot Receiver Operating Characteristic (ROC) curve. Input Artifacts --------------- predictions : Dataset dataset containing true test labels and predicted probabilities Output Artifacts ---------------- class_metrics : ClassificationMetrics classificat...
plot_roc_curve
python
kubeflow/pipelines
samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/intel-oneapi-samples/intel_xgboost_daal4py_pipeline.py
Apache-2.0
def lr_schedule(epoch): """Learning Rate Schedule Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs. Called automatically every epoch as part of callbacks during training. # Arguments epoch (int): The number of epochs # Returns lr ...
Learning Rate Schedule Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs. Called automatically every epoch as part of callbacks during training. # Arguments epoch (int): The number of epochs # Returns lr (float32): learning rate
lr_schedule
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/train/src/train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/train/src/train.py
Apache-2.0
def resnet_layer(inputs, num_filters=16, kernel_size=3, strides=1, activation='relu', batch_normalization=True, conv_first=True): """2D Convolution-Batch Normalization-Activation stack b...
2D Convolution-Batch Normalization-Activation stack builder # Arguments inputs (tensor): input tensor from input image or previous layer num_filters (int): Conv2D number of filters kernel_size (int): Conv2D square kernel dimensions strides (int): Conv2D square st...
resnet_layer
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/train/src/train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/train/src/train.py
Apache-2.0
def resnet_v1(input_shape, depth, num_classes=10): """ResNet Version 1 Model builder [a] Stacks of 2 x (3 x 3) Conv2D-BN-ReLU Last ReLU is after the shortcut connection. At the beginning of each stage, the feature map size is halved (downsampled) by a convolutional layer with st...
ResNet Version 1 Model builder [a] Stacks of 2 x (3 x 3) Conv2D-BN-ReLU Last ReLU is after the shortcut connection. At the beginning of each stage, the feature map size is halved (downsampled) by a convolutional layer with strides=2, while the number of filters is doubled. Withi...
resnet_v1
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/train/src/train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/train/src/train.py
Apache-2.0
def resnet_v2(input_shape, depth, num_classes=10): """ResNet Version 2 Model builder [b] Stacks of (1 x 1)-(3 x 3)-(1 x 1) BN-ReLU-Conv2D or also known as bottleneck layer First shortcut connection per layer is 1 x 1 Conv2D. Second and onwards shortcut connection is identity. ...
ResNet Version 2 Model builder [b] Stacks of (1 x 1)-(3 x 3)-(1 x 1) BN-ReLU-Conv2D or also known as bottleneck layer First shortcut connection per layer is 1 x 1 Conv2D. Second and onwards shortcut connection is identity. At the beginning of each stage, the feature map size is ...
resnet_v2
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/train/src/train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/train/src/train.py
Apache-2.0
def remove_resource(path): """ attempt to delete file from path. Used to clean up MNIST testing images :param path: the path of the file to delete """ try: os.remove(path) print("removed " + path) except OSError: print("no file at " + path)
attempt to delete file from path. Used to clean up MNIST testing images :param path: the path of the file to delete
remove_resource
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/webapp/src/flask_server.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/webapp/src/flask_server.py
Apache-2.0
def parse_model(status, model_name, batch_size, verbose=False): """ Check the configuration of a model to make sure it meets the requirements for an image classification network (as expected by this client) """ server_status = status.server_status if model_name not in server_status.model_status.keys(): ...
Check the configuration of a model to make sure it meets the requirements for an image classification network (as expected by this client)
parse_model
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
Apache-2.0
def preprocess(img, format, dtype, c, h, w): """ Pre-process an image to meet the size, type and format requirements specified by the parameters. """ # np.set_printoptions(threshold='nan') if c == 1: sample_img = img.convert('L') else: sample_img = img.convert('RGB') resized_img = sample_img.r...
Pre-process an image to meet the size, type and format requirements specified by the parameters.
preprocess
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
Apache-2.0
def postprocess(results, filenames, batch_size): """ Post-process results to show classifications. """ if len(results) != 1: raise Exception("expected 1 result, got {}".format(len(results))) batched_result = results[0].batch_classes if len(batched_result) != batch_size: raise Exception("expected {}...
Post-process results to show classifications.
postprocess
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
Apache-2.0
def get_prediction(image_filename, server_host='localhost', server_port=8001, model_name="end2end-demo", model_version=None): """ Retrieve a prediction from a TensorFlow model server :param image: a end2end-demo image :param server_host: the address of the TensorRT inference server :...
Retrieve a prediction from a TensorFlow model server :param image: a end2end-demo image :param server_host: the address of the TensorRT inference server :param server_port: the port used by the server :param model_name: the name of the model :param timeout: the amount of time to wait for a predi...
get_prediction
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
Apache-2.0
def random_image(img_path='/workspace/web_server/static/images'): """ Pull a random image out of the small end2end-demo dataset :param savePath: the path to save the file to. If None, file is not saved :return 0: file selected :return 1: label selelcted """ random_dir = random.choice(os.listdir(img_path)...
Pull a random image out of the small end2end-demo dataset :param savePath: the path to save the file to. If None, file is not saved :return 0: file selected :return 1: label selelcted
random_image
python
kubeflow/pipelines
samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/nvidia-resnet/components/webapp/src/trtis_client.py
Apache-2.0
def __init__(self, **kwargs): """Initialization of inherited lightning data module.""" super(BertDataModule, self).__init__() # pylint: disable=super-with-arguments self.pre_trained_model_name = "bert-base-uncased" self.df_train = None self.df_val = None self.df_test = N...
Initialization of inherited lightning data module.
__init__
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_datamodule.py
Apache-2.0
def setup(self, stage=None): """Downloads the data, parse it and split the data into train, test, validation data. Args: stage: Stage - training or testing """ num_samples = self.args.get("num_samples", 1000) data_path = self.args["train_glob"] pri...
Downloads the data, parse it and split the data into train, test, validation data. Args: stage: Stage - training or testing
setup
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_datamodule.py
Apache-2.0
def create_data_loader(self, dataframe, tokenizer, max_len, batch_size): # pylint: disable=unused-argument """Generic data loader function. Args: dataframe: Input dataframe tokenizer: bert tokenizer max_len: Max length of the news datapoint batch_size: Batch size fo...
Generic data loader function. Args: dataframe: Input dataframe tokenizer: bert tokenizer max_len: Max length of the news datapoint batch_size: Batch size for training Returns: Returns the constructed dataloader
create_data_loader
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_datamodule.py
Apache-2.0
def train_dataloader(self): """Train data loader Returns: output - Train data loader for the given input """ self.train_data_loader = self.create_data_loader( self.df_train, self.tokenizer, self.max_length, self.args.get("batch...
Train data loader Returns: output - Train data loader for the given input
train_dataloader
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_datamodule.py
Apache-2.0
def val_dataloader(self): """Validation data loader. Returns: output - Validation data loader for the given input """ self.val_data_loader = self.create_data_loader( self.df_val, self.tokenizer, self.max_length, self.args.get("b...
Validation data loader. Returns: output - Validation data loader for the given input
val_dataloader
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_datamodule.py
Apache-2.0
def test_dataloader(self): """Test data loader. Return: output - Test data loader for the given input """ self.test_data_loader = self.create_data_loader( self.df_test, self.tokenizer, self.max_length, self.args.get("batch_size...
Test data loader. Return: output - Test data loader for the given input
test_dataloader
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_datamodule.py
Apache-2.0
def initialize(self, ctx): """ First try to load torchscript else load eager mode state_dict based model :param ctx: System properties """ properties = ctx.system_properties self.device = torch.device("cuda") if torch.cuda.is_available() else "cpu" model_dir = pr...
First try to load torchscript else load eager mode state_dict based model :param ctx: System properties
initialize
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_handler.py
Apache-2.0
def preprocess(self, data): """ Receives text in form of json and converts it into an encoding for the inference stage :param data: Input to be passed through the layers for prediction :return: output - preprocessed encoding """ text = data[0].get("data") if text...
Receives text in form of json and converts it into an encoding for the inference stage :param data: Input to be passed through the layers for prediction :return: output - preprocessed encoding
preprocess
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_handler.py
Apache-2.0
def inference(self, input_ids): """ Predict the class for a review / sentence whether it is belong to world / sports / business /sci-tech :param encoding: Input encoding to be passed through the layers for prediction :return: output - predicted output """ inputs ...
Predict the class for a review / sentence whether it is belong to world / sports / business /sci-tech :param encoding: Input encoding to be passed through the layers for prediction :return: output - predicted output
inference
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_handler.py
Apache-2.0
def postprocess(self, inference_output): """ Does postprocess after inference to be returned to user :param inference_output: Output of inference :return: output - Output after post processing """ if os.path.exists(self.class_mapping_file): with open(self.clas...
Does postprocess after inference to be returned to user :param inference_output: Output of inference :return: output - Output after post processing
postprocess
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_handler.py
Apache-2.0
def summarize_attributions(self, attributions): """Summarises the attribution across multiple runs Args: attributions ([list): attributions from the Integrated Gradients Returns: list : Returns the attributions after normalizing them. """ attributions = at...
Summarises the attribution across multiple runs Args: attributions ([list): attributions from the Integrated Gradients Returns: list : Returns the attributions after normalizing them.
summarize_attributions
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_handler.py
Apache-2.0
def explain_handle(self, model_wraper, text, target=1): """Captum explanations handler Args: data_preprocess (Torch Tensor): Preprocessed data to be used for captum raw_data (list): The unprocessed data to get target from the request Returns: dict ...
Captum explanations handler Args: data_preprocess (Torch Tensor): Preprocessed data to be used for captum raw_data (list): The unprocessed data to get target from the request Returns: dict : A dictionary response with the explanations response.
explain_handle
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_handler.py
Apache-2.0
def __init__(self, **kwargs): """Initializes the network, optimizer and scheduler.""" super(BertNewsClassifier, self).__init__() #pylint: disable=super-with-arguments self.pre_trained_model_name = "bert-base-uncased" #pylint: disable=invalid-name self.bert_model = BertModel.from_pretra...
Initializes the network, optimizer and scheduler.
__init__
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_train.py
Apache-2.0
def compute_bert_outputs( #pylint: disable=no-self-use self, model_bert, embedding_input, attention_mask=None, head_mask=None ): """Computes Bert Outputs. Args: model_bert : the bert model embedding_input : input for bert embeddings. attention_mask : att...
Computes Bert Outputs. Args: model_bert : the bert model embedding_input : input for bert embeddings. attention_mask : attention mask head_mask : head mask Returns: output : the bert output
compute_bert_outputs
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_train.py
Apache-2.0
def forward(self, input_ids, attention_mask=None): """ Forward function. Args: input_ids: Input data attention_maks: Attention mask value Returns: output - Type of news for the given news snippet """ embedding_input = self.bert_model.embeddin...
Forward function. Args: input_ids: Input data attention_maks: Attention mask value Returns: output - Type of news for the given news snippet
forward
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_train.py
Apache-2.0
def training_step(self, train_batch, batch_idx): """Training the data as batches and returns training loss on each batch. Args: train_batch Batch data batch_idx: Batch indices Returns: output - Training loss """ input_ids = train_batc...
Training the data as batches and returns training loss on each batch. Args: train_batch Batch data batch_idx: Batch indices Returns: output - Training loss
training_step
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_train.py
Apache-2.0
def test_step(self, test_batch, batch_idx): """Performs test and computes the accuracy of the model. Args: test_batch: Batch data batch_idx: Batch indices Returns: output - Testing accuracy """ input_ids = test_batch["input_ids"].to(self.d...
Performs test and computes the accuracy of the model. Args: test_batch: Batch data batch_idx: Batch indices Returns: output - Testing accuracy
test_step
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_train.py
Apache-2.0
def validation_step(self, val_batch, batch_idx): """Performs validation of data in batches. Args: val_batch: Batch data batch_idx: Batch indices Returns: output - valid step loss """ input_ids = val_batch["input_ids"].to(self.device) ...
Performs validation of data in batches. Args: val_batch: Batch data batch_idx: Batch indices Returns: output - valid step loss
validation_step
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_train.py
Apache-2.0
def configure_optimizers(self): """Initializes the optimizer and learning rate scheduler. Returns: output - Initialized optimizer and scheduler """ self.optimizer = AdamW(self.parameters(), lr=self.args.get("lr", 0.001)) self.scheduler = { "scheduler": ...
Initializes the optimizer and learning rate scheduler. Returns: output - Initialized optimizer and scheduler
configure_optimizers
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/bert_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/bert_train.py
Apache-2.0
def __init__(self, reviews, targets, tokenizer, max_length): """Performs initialization of tokenizer. Args: reviews: AG news text targets: labels tokenizer: bert tokenizer max_length: maximum length of the news text """ self.reviews = ...
Performs initialization of tokenizer. Args: reviews: AG news text targets: labels tokenizer: bert tokenizer max_length: maximum length of the news text
__init__
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/news_dataset.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/news_dataset.py
Apache-2.0
def __getitem__(self, item): """Returns the review text and the targets of the specified item. Args: item: Index of sample review Returns: Returns the dictionary of review text, input ids, attention mask, targets """ review = str(self.revi...
Returns the review text and the targets of the specified item. Args: item: Index of sample review Returns: Returns the dictionary of review text, input ids, attention mask, targets
__getitem__
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/news_dataset.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/news_dataset.py
Apache-2.0
def pytorch_bert( # pylint: disable=too-many-arguments minio_endpoint=MINIO_ENDPOINT, log_bucket=LOG_BUCKET, log_dir=f"tensorboard/logs/{dsl.RUN_ID_PLACEHOLDER}", mar_path=f"mar/{dsl.RUN_ID_PLACEHOLDER}/model-store", config_prop_path=f"mar/{dsl.RUN_ID_PLACEHOLDER}/config", model_uri=f"s3://mlpip...
Thid method defines the pipeline tasks and operations
pytorch_bert
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/pipeline.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/pipeline.py
Apache-2.0
def forward(self, embeddings, attention_mask=None): """Forward function. Args: embeddings : bert embeddings. attention_mask: Attention mask value """ outputs = self.compute_bert_outputs( self.model.bert_model, embeddings, attention_mask ) ...
Forward function. Args: embeddings : bert embeddings. attention_mask: Attention mask value
forward
python
kubeflow/pipelines
samples/contrib/pytorch-samples/bert/wrapper.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/bert/wrapper.py
Apache-2.0
def train_dataloader(self): """Train Data loader. Returns: output - Train data loader for the given input """ self.train_data_loader = self.create_data_loader( self.train_dataset, self.args.get("train_batch_size", None), self.args.get("tra...
Train Data loader. Returns: output - Train data loader for the given input
train_dataloader
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_datamodule.py
Apache-2.0
def val_dataloader(self): """Validation Data Loader. Returns: output - Validation data loader for the given input """ self.val_data_loader = self.create_data_loader( self.valid_dataset, self.args.get("val_batch_size", None), self.args.get(...
Validation Data Loader. Returns: output - Validation data loader for the given input
val_dataloader
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_datamodule.py
Apache-2.0
def test_dataloader(self): """Test Data Loader. Returns: output - Test data loader for the given input """ self.test_data_loader = self.create_data_loader( self.test_dataset, self.args.get("val_batch_size", None), self.args.get("val_num_wo...
Test Data Loader. Returns: output - Test data loader for the given input
test_dataloader
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_datamodule.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_datamodule.py
Apache-2.0
def initialize(self, ctx): # pylint: disable=arguments-differ """In this initialize function, the CIFAR10 trained model is loaded and the Integrated Gradients,occlusion and layer_gradcam Algorithm for Captum Explanations is initialized here. Args: ctx (context): It is a JSON ...
In this initialize function, the CIFAR10 trained model is loaded and the Integrated Gradients,occlusion and layer_gradcam Algorithm for Captum Explanations is initialized here. Args: ctx (context): It is a JSON Object containing information pertaining to the model artifac...
initialize
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_handler.py
Apache-2.0
def _get_img(self, row): """Compat layer: normally the envelope should just return the data directly, but older version of KFServing envelope and Torchserve in general didn't have things set up right """ if isinstance(row, dict): image = row.get("data") or row.get("b...
Compat layer: normally the envelope should just return the data directly, but older version of KFServing envelope and Torchserve in general didn't have things set up right
_get_img
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_handler.py
Apache-2.0
def preprocess(self, data): """The preprocess function of cifar10 program converts the input data to a float tensor Args: data (List): Input data from the request is in the form of a Tensor Returns: list : The preprocess function returns the input imag...
The preprocess function of cifar10 program converts the input data to a float tensor Args: data (List): Input data from the request is in the form of a Tensor Returns: list : The preprocess function returns the input image as a list of float tensors.
preprocess
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_handler.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_handler.py
Apache-2.0
def training_step(self, train_batch, batch_idx): """Training Step Args: train_batch : training batch batch_idx : batch id number Returns: train accuracy """ if batch_idx == 0: self.reference_image = (train_batch[0][0]).unsqueeze(0...
Training Step Args: train_batch : training batch batch_idx : batch id number Returns: train accuracy
training_step
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_train.py
Apache-2.0
def test_step(self, test_batch, batch_idx): """Testing step Args: test_batch : test batch data batch_idx : tests batch id Returns: test accuracy """ x_var, y_var = test_batch output = self.forward(x_var) _, y_hat = torch.max...
Testing step Args: test_batch : test batch data batch_idx : tests batch id Returns: test accuracy
test_step
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_train.py
Apache-2.0
def validation_step(self, val_batch, batch_idx): """Testing step. Args: val_batch : val batch data batch_idx : val batch id Returns: validation accuracy """ x_var, y_var = val_batch output = self.forward(x_var) _, y_hat = t...
Testing step. Args: val_batch : val batch data batch_idx : val batch id Returns: validation accuracy
validation_step
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_train.py
Apache-2.0
def makegrid(self, output, numrows): #pylint: disable=no-self-use """Makes grids. Args: output : Tensor output numrows : num of rows. Returns: c_array : gird array """ outer = torch.Tensor.cpu(output).detach() plt.figure(figsize=(2...
Makes grids. Args: output : Tensor output numrows : num of rows. Returns: c_array : gird array
makegrid
python
kubeflow/pipelines
samples/contrib/pytorch-samples/cifar10/cifar10_train.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/cifar10/cifar10_train.py
Apache-2.0
def get_templates_list(): """Get the list of template files from `templates` directory""" assert os.path.exists(TEMPLATE_PATH) templates_list = os.listdir(TEMPLATE_PATH) return templates_list
Get the list of template files from `templates` directory
get_templates_list
python
kubeflow/pipelines
samples/contrib/pytorch-samples/utils/generate_templates.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/utils/generate_templates.py
Apache-2.0
def replace_keys_in_template(template_dict: dict, mapping: dict): """Replace the keys, values in `component.yaml` based on `mapping` dict""" # Sample mapping will be as below # { "implementation.container.image" : "image_name" } for nested_key, value in mapping.items(): # parse through each ne...
Replace the keys, values in `component.yaml` based on `mapping` dict
replace_keys_in_template
python
kubeflow/pipelines
samples/contrib/pytorch-samples/utils/generate_templates.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/utils/generate_templates.py
Apache-2.0
def generate_component_yaml(mapping_template_path: str): """Method to generate component.yaml based on the template""" mapping: dict = {} if os.path.exists(mapping_template_path): with open(mapping_template_path) as pointer: mapping = json.load(pointer) create_output_folder() tem...
Method to generate component.yaml based on the template
generate_component_yaml
python
kubeflow/pipelines
samples/contrib/pytorch-samples/utils/generate_templates.py
https://github.com/kubeflow/pipelines/blob/master/samples/contrib/pytorch-samples/utils/generate_templates.py
Apache-2.0
def flip_coin(force_flip_result: str = '') -> str: """Flip a coin and output heads or tails randomly.""" if force_flip_result: return force_flip_result import random result = 'heads' if random.randint(0, 1) == 0 else 'tails' return result
Flip a coin and output heads or tails randomly.
flip_coin
python
kubeflow/pipelines
samples/core/condition/condition_v2.py
https://github.com/kubeflow/pipelines/blob/master/samples/core/condition/condition_v2.py
Apache-2.0
def execution_order_pipeline(text1: str='message 1', text2: str='message 2'): """A two step pipeline with an explicitly defined execution order.""" step1_task = echo1_op(text1=text1) step2_task = echo2_op(text2=text2) step2_task.after(step1_task)
A two step pipeline with an explicitly defined execution order.
execution_order_pipeline
python
kubeflow/pipelines
samples/core/execution_order/execution_order.py
https://github.com/kubeflow/pipelines/blob/master/samples/core/execution_order/execution_order.py
Apache-2.0