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 _download_wheels(cls, pip_requirements_path, dst_path): """ Downloads all the wheels of the dependencies specified in the requirements.txt file. The pip wheel download_command defaults to downloading only binary packages using the `--only-binary=:all:` option. This behavior can be ov...
Downloads all the wheels of the dependencies specified in the requirements.txt file. The pip wheel download_command defaults to downloading only binary packages using the `--only-binary=:all:` option. This behavior can be overridden using an environment variable `MLFLOW_WHEELED_MODEL_PI...
_download_wheels
python
mlflow/mlflow
mlflow/models/wheeled_model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/wheeled_model.py
Apache-2.0
def _overwrite_pip_requirements_with_wheels(self, pip_requirements_path, wheels_dir): """ Overwrites the requirements.txt with the wheels of the required dependencies. Args: pip_requirements_path: Path to requirements.txt in the model directory. wheels_dir: Path to direc...
Overwrites the requirements.txt with the wheels of the required dependencies. Args: pip_requirements_path: Path to requirements.txt in the model directory. wheels_dir: Path to directory where wheels are stored.
_overwrite_pip_requirements_with_wheels
python
mlflow/mlflow
mlflow/models/wheeled_model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/wheeled_model.py
Apache-2.0
def _create_pip_requirement(self, conda_env_path, pip_requirements_path): """ This method creates a requirements.txt file for the model dependencies if the file does not already exist. It uses the pip dependencies found in the conda.yaml env file. Args: conda_env_path: Path ...
This method creates a requirements.txt file for the model dependencies if the file does not already exist. It uses the pip dependencies found in the conda.yaml env file. Args: conda_env_path: Path to conda.yaml env file which contains the required pip dependencies ...
_create_pip_requirement
python
mlflow/mlflow
mlflow/models/wheeled_model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/wheeled_model.py
Apache-2.0
def _init(cmd, env_manager): # noqa: D417 """ Initialize the container and execute command. Args: cmd: Command param passed by Sagemaker. Can be "serve" or "train" (unimplemented). """ if cmd == "serve": _serve(env_manager) elif cmd == "train": _train() else: ...
Initialize the container and execute command. Args: cmd: Command param passed by Sagemaker. Can be "serve" or "train" (unimplemented).
_init
python
mlflow/mlflow
mlflow/models/container/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/container/__init__.py
Apache-2.0
def _serve(env_manager): """ Serve the model. Read the MLmodel config, initialize the Conda environment if needed and start python server. """ model_config_path = os.path.join(MODEL_PATH, MLMODEL_FILE_NAME) m = Model.load(model_config_path) if pyfunc.FLAVOR_NAME in m.flavors: _serv...
Serve the model. Read the MLmodel config, initialize the Conda environment if needed and start python server.
_serve
python
mlflow/mlflow
mlflow/models/container/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/container/__init__.py
Apache-2.0
def _install_pyfunc_deps( model_path=None, install_mlflow=False, enable_mlserver=False, env_manager=em.VIRTUALENV ): """ Creates a conda env for serving the model at the specified path and installs almost all serving dependencies into the environment - MLflow is not installed as it's not available via c...
Creates a conda env for serving the model at the specified path and installs almost all serving dependencies into the environment - MLflow is not installed as it's not available via conda.
_install_pyfunc_deps
python
mlflow/mlflow
mlflow/models/container/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/container/__init__.py
Apache-2.0
def _install_model_dependencies_to_env(model_path, env_manager) -> list[str]: """: Installs model dependencies to the specified environment, which can be either a local environment, a conda environment, or a virtualenv. Returns: Empty list if local environment, otherwise a list of bash commands...
: Installs model dependencies to the specified environment, which can be either a local environment, a conda environment, or a virtualenv. Returns: Empty list if local environment, otherwise a list of bash commands to activate the virtualenv or conda environment.
_install_model_dependencies_to_env
python
mlflow/mlflow
mlflow/models/container/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/container/__init__.py
Apache-2.0
def _sigterm_handler(pids): """ Cleanup when terminating. Attempt to kill all launched processes and exit. """ _logger.info("Got sigterm signal, exiting.") for pid in pids: try: os.kill(pid, signal.SIGTERM) except OSError: pass sys.exit(0)
Cleanup when terminating. Attempt to kill all launched processes and exit.
_sigterm_handler
python
mlflow/mlflow
mlflow/models/container/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/container/__init__.py
Apache-2.0
def _infer_artifact_type_and_ext(artifact_name, raw_artifact, custom_metric_tuple): """ This function performs type and file extension inference on the provided artifact Args: artifact_name: The name of the provided artifact raw_artifact: The artifact object custom_metric_tuple: Con...
This function performs type and file extension inference on the provided artifact Args: artifact_name: The name of the provided artifact raw_artifact: The artifact object custom_metric_tuple: Containing a user provided function and its index in the ``custom_metrics`` parame...
_infer_artifact_type_and_ext
python
mlflow/mlflow
mlflow/models/evaluation/artifacts.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/artifacts.py
Apache-2.0
def _generate_eval_metric_class(eval_fn, require_strict_signature=False): """ Dynamically generate a GenAIEvaluationMetric class that can be used to evaluate the metric on the given input data. The generated class is callable with a __call__ method that takes the arguments specified in the signature of ...
Dynamically generate a GenAIEvaluationMetric class that can be used to evaluate the metric on the given input data. The generated class is callable with a __call__ method that takes the arguments specified in the signature of the eval_fn function. Args: eval_fn: the evaluation function of the ...
_generate_eval_metric_class
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def make_metric( *, eval_fn, greater_is_better, name=None, long_name=None, version=None, metric_details=None, metric_metadata=None, genai_metric_args=None, ): ''' A factory function to create an :py:class:`EvaluationMetric` object. Args: eval_fn: A function that ...
A factory function to create an :py:class:`EvaluationMetric` object. Args: eval_fn: A function that computes the metric with the following signature: .. code-block:: python def eval_fn( predictions: pandas.Series, targets: pandas.Se...
make_metric
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def _make_metric( *, eval_fn, greater_is_better, name=None, long_name=None, version=None, metric_details=None, metric_metadata=None, genai_metric_args=None, require_strict_signature=False, ): ''' A factory function to create an :py:class:`EvaluationMetric` object. Ar...
A factory function to create an :py:class:`EvaluationMetric` object. Args: eval_fn: A function that computes the metric with the following signature: .. code-block:: python def eval_fn( predictions: pandas.Series, targets: pandas.Se...
_make_metric
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def _load_content_from_file(self, local_artifact_path): """ Abstract interface to load the content from local artifact file path, and return the loaded content. """
Abstract interface to load the content from local artifact file path, and return the loaded content.
_load_content_from_file
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def _load(self, local_artifact_path=None): """ If ``local_artifact_path`` is ``None``, download artifact from the artifact uri. Otherwise, load artifact content from the specified path. Assign the loaded content to ``self._content``, and return the loaded content. """ if ...
If ``local_artifact_path`` is ``None``, download artifact from the artifact uri. Otherwise, load artifact content from the specified path. Assign the loaded content to ``self._content``, and return the loaded content.
_load
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def content(self): """ The content of the artifact (representation varies) """ if self._content is None: self._load() return self._content
The content of the artifact (representation varies)
content
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def load(cls, path): """Load the evaluation results from the specified local filesystem path""" with open(os.path.join(path, "metrics.json")) as fp: metrics = json.load(fp) with open(os.path.join(path, "artifacts_metadata.json")) as fp: artifacts_metadata = json.load(fp)...
Load the evaluation results from the specified local filesystem path
load
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def save(self, path): """Write the evaluation results to the specified local filesystem path""" os.makedirs(path, exist_ok=True) with open(os.path.join(path, "metrics.json"), "w") as fp: json.dump(self.metrics, fp, cls=NumpyEncoder) artifacts_metadata = { artifac...
Write the evaluation results to the specified local filesystem path
save
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def tables(self) -> dict[str, "pd.DataFrame"]: """ A dictionary mapping standardized artifact names (e.g. "eval_results_table") to corresponding table content as pandas DataFrame. """ eval_tables = {} if self._run_id is None: _logger.warning("Cannot load eval_...
A dictionary mapping standardized artifact names (e.g. "eval_results_table") to corresponding table content as pandas DataFrame.
tables
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def list_evaluators(): """ Return a name list for all available Evaluators. """ # import _model_evaluation_registry inside function to avoid circuit importing from mlflow.models.evaluation.evaluator_registry import _model_evaluation_registry return list(_model_evaluation_registry._registry.keys...
Return a name list for all available Evaluators.
list_evaluators
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def _start_run_or_reuse_active_run(): """ A manager context return: - If there's an active run, return the active run id. - otherwise start a mflow run with the specified run_id, if specified run_id is None, start a new run. """ active_run = mlflow.active_run() if not active_run: ...
A manager context return: - If there's an active run, return the active run id. - otherwise start a mflow run with the specified run_id, if specified run_id is None, start a new run.
_start_run_or_reuse_active_run
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def _model_validation_contains_model_comparison(validation_thresholds): """ Helper function for determining if validation_thresholds contains thresholds for model comparison: either min_relative_change or min_absolute_change """ if not validation_thresholds: return False thresholds = val...
Helper function for determining if validation_thresholds contains thresholds for model comparison: either min_relative_change or min_absolute_change
_model_validation_contains_model_comparison
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def _evaluate( *, model, model_type, model_id, dataset, run_id, # The `evaluator_name_list` and `evaluator_name_to_conf_map` are not used by MLflow at all, # but we need to keep these for backward compatibility. evaluator_name_list, evaluator_name_to_conf_map, extra_metrics, ...
The public API "evaluate" will verify argument first, and then pass normalized arguments to the _evaluate method.
_evaluate
python
mlflow/mlflow
mlflow/models/evaluation/base.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/base.py
Apache-2.0
def make_multi_class_calibration_plot( n_classes, y_true, y_probs, calibration_config, label_list ) -> Figure: """Generate one calibration plot for all classes of a multi-class classifier Args: n_classes (int): number of classes in multi-class prediction y_true (array-like, shape (n_samples...
Generate one calibration plot for all classes of a multi-class classifier Args: n_classes (int): number of classes in multi-class prediction y_true (array-like, shape (n_samples)): Ground truth (correct) target values. y_probs (array-like, shape (n_samples, n_classes)): ...
make_multi_class_calibration_plot
python
mlflow/mlflow
mlflow/models/evaluation/calibration_curve.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/calibration_curve.py
Apache-2.0
def plot_calibration_curve(y_true, y_probs, pos_label, calibration_config, label_list) -> Figure: """Generate a calibration curve for a trained classifier Args: y_true (array-like, shape (n_samples)): Ground truth (correct) target values. y_probs (array-like, shape (n_samples, n_cl...
Generate a calibration curve for a trained classifier Args: y_true (array-like, shape (n_samples)): Ground truth (correct) target values. y_probs (array-like, shape (n_samples, n_classes)): Prediction probabilities for each class returned by a classifier. pos_label...
plot_calibration_curve
python
mlflow/mlflow
mlflow/models/evaluation/calibration_curve.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/calibration_curve.py
Apache-2.0
def _extract_predict_fn(model: Any) -> Optional[Callable]: """ Extracts the predict function from the given model or raw_model. Precedence order: 1. If raw_model is specified, its predict function is used. 2. If model is specified, its predict function is used. 3. If none of the above, predict ...
Extracts the predict function from the given model or raw_model. Precedence order: 1. If raw_model is specified, its predict function is used. 2. If model is specified, its predict function is used. 3. If none of the above, predict function is None. Args: model: A model object that ha...
_extract_predict_fn
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def _get_dataframe_with_renamed_columns(x, new_column_names): """ Downstream inference functions may expect a pd.DataFrame to be created from x. However, if x is already a pd.DataFrame, and new_column_names != x.columns, we cannot simply call pd.DataFrame(x, columns=new_column_names) because the resulti...
Downstream inference functions may expect a pd.DataFrame to be created from x. However, if x is already a pd.DataFrame, and new_column_names != x.columns, we cannot simply call pd.DataFrame(x, columns=new_column_names) because the resulting pd.DataFrame will contain NaNs for every column in new_column_...
_get_dataframe_with_renamed_columns
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def _evaluate_custom_artifacts(custom_artifact_tuple, eval_df, builtin_metrics): """ This function calls the `custom_artifact` function and performs validations on the returned result to ensure that they are in the expected format. It will raise a MlflowException if the result is not in the expected for...
This function calls the `custom_artifact` function and performs validations on the returned result to ensure that they are in the expected format. It will raise a MlflowException if the result is not in the expected format. Args: custom_artifact_tuple: Containing a user provided function and i...
_evaluate_custom_artifacts
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def _evaluate( self, model: Optional["mlflow.pyfunc.PyFuncModel"], extra_metrics: list[EvaluationMetric], custom_artifacts=None, **kwargs, ) -> Optional[EvaluationResult]: """Implement the evaluation logic for each evaluator."""
Implement the evaluation logic for each evaluator.
_evaluate
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def log_metrics(self): """ Helper method to log metrics into specified run. """ self._add_prefix_to_metrics() timestamp = get_current_time_millis() self.client.log_batch( self.run_id, metrics=[ Metric( key=key, ...
Helper method to log metrics into specified run.
log_metrics
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def _log_custom_metric_artifact(self, artifact_name, raw_artifact, custom_metric_tuple): """ This function logs and returns a custom metric artifact. Two cases: - The provided artifact is a path to a file, the function will make a copy of it with a formatted name in a temporary...
This function logs and returns a custom metric artifact. Two cases: - The provided artifact is a path to a file, the function will make a copy of it with a formatted name in a temporary directory and call mlflow.log_artifact. - Otherwise: will attempt to save the artifact ...
_log_custom_metric_artifact
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def _get_args_for_metrics( self, metric: MetricDefinition, eval_df: pd.DataFrame, input_df: pd.DataFrame, other_output_df: Optional[pd.DataFrame], ) -> tuple[bool, list[Union[str, pd.DataFrame]]]: """ Given a metric_tuple, read the signature of the metric func...
Given a metric_tuple, read the signature of the metric function and get the appropriate arguments from the input/output columns, other calculated metrics, and evaluator_config. Args: metric: The metric definition containing a user provided function and its index in ...
_get_args_for_metrics
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def evaluate_and_log_custom_artifacts( self, custom_artifacts: list[_CustomArtifact], prediction: pd.Series, target: Optional[np.array] = None, ): """Evaluate custom artifacts provided by users.""" if not custom_artifacts: return eval_df = self._g...
Evaluate custom artifacts provided by users.
evaluate_and_log_custom_artifacts
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def _get_eval_df(self, prediction: pd.Series, target: Optional[np.array] = None): """ Create a DataFrame with "prediction" and "target" columns. This is a standard format that can be passed to the metric functions. """ eval_df = pd.DataFrame({"prediction": copy.deepcopy(predicti...
Create a DataFrame with "prediction" and "target" columns. This is a standard format that can be passed to the metric functions.
_get_eval_df
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def _order_metrics( self, metrics: list[EvaluationMetric], eval_df: pd.DataFrame, other_output_df: Optional[pd.DataFrame], ): """ Order the list metrics so they can be computed in sequence. Some metrics might use the results of other metrics to compute their ...
Order the list metrics so they can be computed in sequence. Some metrics might use the results of other metrics to compute their own results. This function iteratively resolve this dependency, by checking if each metric can be computed with the current available columns and metrics val...
_order_metrics
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def evaluate_metrics( self, metrics: list[EvaluationMetric], prediction: pd.Series, target: Optional[np.array] = None, other_output_df: Optional[pd.DataFrame] = None, ): """ Evaluate the metrics on the given prediction and target data. Args: ...
Evaluate the metrics on the given prediction and target data. Args: metrics: A list of metrics to evaluate. prediction: A Pandas Series containing the predictions. target: A numpy array containing the target values. other_output_df: A Pandas DataFrame co...
evaluate_metrics
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def X(self) -> pd.DataFrame: """ The features (`X`) portion of the dataset, guarded against accidental mutations. """ return BuiltInEvaluator._MutationGuardedData( _get_dataframe_with_renamed_columns( self.dataset.features_data, self.dataset.feature_names ...
The features (`X`) portion of the dataset, guarded against accidental mutations.
X
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def copy_to_avoid_mutation(self): """ Obtain a copy of the data. This method should be called every time the data needs to be used in a context where it may be subsequently mutated, guarding against accidental reuse after mutation. Returns: A ...
Obtain a copy of the data. This method should be called every time the data needs to be used in a context where it may be subsequently mutated, guarding against accidental reuse after mutation. Returns: A copy of the data object.
copy_to_avoid_mutation
python
mlflow/mlflow
mlflow/models/evaluation/default_evaluator.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/default_evaluator.py
Apache-2.0
def get_evaluator(self, evaluator_name): """ Get an evaluator instance from the registry based on the name of evaluator """ evaluator_cls = self._registry.get(evaluator_name) if evaluator_cls is None: raise MlflowException( f"Could not find a registere...
Get an evaluator instance from the registry based on the name of evaluator
get_evaluator
python
mlflow/mlflow
mlflow/models/evaluation/evaluator_registry.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluator_registry.py
Apache-2.0
def _cumulative_gain_curve(y_true, y_score, pos_label=None): """ This method is copied from scikit-plot package. See https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/helpers.py#L157 This function generates the points necessary to plot the Cumulative Gai...
This method is copied from scikit-plot package. See https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/helpers.py#L157 This function generates the points necessary to plot the Cumulative Gain Note: This implementation is restricted to the binary classif...
_cumulative_gain_curve
python
mlflow/mlflow
mlflow/models/evaluation/lift_curve.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/lift_curve.py
Apache-2.0
def plot_lift_curve( y_true, y_probas, title="Lift Curve", ax=None, figsize=None, title_fontsize="large", text_fontsize="medium", pos_label=None, ): """ This method is copied from scikit-plot package. See https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4d...
This method is copied from scikit-plot package. See https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/metrics.py#L1133 Generates the Lift Curve from labels and scores/probabilities The lift curve is used to determine the effectiveness of a binary c...
plot_lift_curve
python
mlflow/mlflow
mlflow/models/evaluation/lift_curve.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/lift_curve.py
Apache-2.0
def __str__(self): """ Returns a human-readable string consisting of all specified thresholds. """ threshold_strs = [] if self._threshold is not None: threshold_strs.append(f"Threshold: {self._threshold}.") if self._min_absolute_change is not None: ...
Returns a human-readable string consisting of all specified thresholds.
__str__
python
mlflow/mlflow
mlflow/models/evaluation/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/validation.py
Apache-2.0
def __str__(self): """ Returns a human-readable string representing the validation result for the metric. """ if self.is_success(): return f"Metric {self.metric_name} passed the validation." if self.missing_candidate: return ( f"Metric val...
Returns a human-readable string representing the validation result for the metric.
__str__
python
mlflow/mlflow
mlflow/models/evaluation/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/validation.py
Apache-2.0
def validate_evaluation_results( validation_thresholds: dict[str, MetricThreshold], candidate_result: EvaluationResult, baseline_result: Optional[EvaluationResult] = None, ): """ Validate the evaluation result from one model (candidate) against another model (baseline). If the candidate results ...
Validate the evaluation result from one model (candidate) against another model (baseline). If the candidate results do not meet the validation thresholds, an ModelValidationFailedException will be raised. .. note:: This API is a replacement for the deprecated model validation functio...
validate_evaluation_results
python
mlflow/mlflow
mlflow/models/evaluation/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/validation.py
Apache-2.0
def _validate( validation_thresholds: dict[str, MetricThreshold], candidate_metrics: dict[str, float], baseline_metrics: dict[str, float], ): """ Validate the model based on validation_thresholds by metrics value and metrics comparison between candidate model's metrics (candidate_metrics) and ...
Validate the model based on validation_thresholds by metrics value and metrics comparison between candidate model's metrics (candidate_metrics) and baseline model's metrics (baseline_metrics). Args: validation_thresholds: A dictionary from metric_name to MetricThreshold. candidate_metr...
_validate
python
mlflow/mlflow
mlflow/models/evaluation/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/validation.py
Apache-2.0
def save(self, out_file, model_saver=None, masker_saver=None): """ This patched `save` method fix `KernelExplainer.save`. Issues in original `KernelExplainer.save`: - It saves model by calling model.save, but shap.utils._legacy.Model has no save method - It tries to save "maske...
This patched `save` method fix `KernelExplainer.save`. Issues in original `KernelExplainer.save`: - It saves model by calling model.save, but shap.utils._legacy.Model has no save method - It tries to save "masker", but there's no "masker" in KernelExplainer - It does not save...
save
python
mlflow/mlflow
mlflow/models/evaluation/_shap_patch.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/_shap_patch.py
Apache-2.0
def load(cls, in_file, model_loader=None, masker_loader=None, instantiate=True): """ This patched `load` method fix `KernelExplainer.load`. Issues in original KernelExplainer.load: - Use mismatched model loader to load model - Try to load non-existent "masker" attribute ...
This patched `load` method fix `KernelExplainer.load`. Issues in original KernelExplainer.load: - Use mismatched model loader to load model - Try to load non-existent "masker" attribute - Does not load "data" attribute and then cause calling " KernelExplainer" cons...
load
python
mlflow/mlflow
mlflow/models/evaluation/_shap_patch.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/_shap_patch.py
Apache-2.0
def _log_confusion_matrix(self): """ Helper method for logging confusion matrix """ # normalize the confusion matrix, keep consistent with sklearn autologging. confusion_matrix = sk_metrics.confusion_matrix( self.y_true, self.y_pred, labels=sel...
Helper method for logging confusion matrix
_log_confusion_matrix
python
mlflow/mlflow
mlflow/models/evaluation/evaluators/classifier.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluators/classifier.py
Apache-2.0
def _is_categorical(values): """ Infer whether input values are categorical on best effort. Return True represent they are categorical, return False represent we cannot determine result. """ dtype_name = pd.Series(values).convert_dtypes().dtype.name.lower() return dtype_name in ["category", "str...
Infer whether input values are categorical on best effort. Return True represent they are categorical, return False represent we cannot determine result.
_is_categorical
python
mlflow/mlflow
mlflow/models/evaluation/evaluators/classifier.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluators/classifier.py
Apache-2.0
def _infer_model_type_by_labels(labels): """ Infer model type by target values. """ if _is_categorical(labels): return _ModelType.CLASSIFIER elif _is_continuous(labels): return _ModelType.REGRESSOR else: return None # Unknown
Infer model type by target values.
_infer_model_type_by_labels
python
mlflow/mlflow
mlflow/models/evaluation/evaluators/classifier.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluators/classifier.py
Apache-2.0
def _suppress_class_imbalance_errors(exception_type=Exception, log_warning=True): """ Exception handler context manager to suppress Exceptions if the private environment variable `_MLFLOW_EVALUATE_SUPPRESS_CLASSIFICATION_ERRORS` is set to `True`. The purpose of this handler is to prevent an evaluation c...
Exception handler context manager to suppress Exceptions if the private environment variable `_MLFLOW_EVALUATE_SUPPRESS_CLASSIFICATION_ERRORS` is set to `True`. The purpose of this handler is to prevent an evaluation call for a binary or multiclass classification automl run from aborting due to an extr...
_suppress_class_imbalance_errors
python
mlflow/mlflow
mlflow/models/evaluation/evaluators/classifier.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluators/classifier.py
Apache-2.0
def _gen_classifier_curve( is_binomial, y, y_probs, labels, pos_label, curve_type, sample_weights, ): """ Generate precision-recall curve or ROC curve for classifier. Args: is_binomial: True if it is binary classifier otherwise False y: True label values ...
Generate precision-recall curve or ROC curve for classifier. Args: is_binomial: True if it is binary classifier otherwise False y: True label values y_probs: if binary classifier, the predicted probability for positive class. if multiclass classifier, the predicted pr...
_gen_classifier_curve
python
mlflow/mlflow
mlflow/models/evaluation/evaluators/classifier.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluators/classifier.py
Apache-2.0
def _builtin_metrics(self) -> list[Metric]: """ Get a list of builtin metrics for the model type. """ text_metrics = [ token_count(), toxicity(), flesch_kincaid_grade_level(), ari_grade_level(), ] builtin_metrics = [] ...
Get a list of builtin metrics for the model type.
_builtin_metrics
python
mlflow/mlflow
mlflow/models/evaluation/evaluators/default.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluators/default.py
Apache-2.0
def _generate_model_predictions( self, model: Optional["mlflow.pyfunc.PyFuncModel"], input_df: pd.DataFrame, compute_latency=False, ): """ Helper method for generating model predictions """ predict_fn = _extract_predict_fn(model) def predict_w...
Helper method for generating model predictions
_generate_model_predictions
python
mlflow/mlflow
mlflow/models/evaluation/evaluators/default.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluators/default.py
Apache-2.0
def _compute_df_mode_or_mean(df): """ Compute mean (for continuous columns) and compute mode (for other columns) for the input dataframe, return a dict, key is column name, value is the corresponding mode or mean value, this function calls `_is_continuous` to determine whether the column is continuo...
Compute mean (for continuous columns) and compute mode (for other columns) for the input dataframe, return a dict, key is column name, value is the corresponding mode or mean value, this function calls `_is_continuous` to determine whether the column is continuous column.
_compute_df_mode_or_mean
python
mlflow/mlflow
mlflow/models/evaluation/evaluators/shap.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/evaluators/shap.py
Apache-2.0
def evaluate(self, eval_fn_args) -> Optional[MetricValue]: """ This function calls the metric function and performs validations on the returned result to ensure that they are in the expected format. It will warn and will not log metrics that are in the wrong format. Args: ...
This function calls the metric function and performs validations on the returned result to ensure that they are in the expected format. It will warn and will not log metrics that are in the wrong format. Args: eval_fn_args: A dictionary of args needed to compute the eval me...
evaluate
python
mlflow/mlflow
mlflow/models/evaluation/utils/metric.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/utils/metric.py
Apache-2.0
def configure_autologging_for_evaluation(enable_tracing: bool = True): """ Temporarily override the autologging configuration for all flavors during the model evaluation. For example, model auto-logging must be disabled during the evaluation. After the evaluation is done, the original autologging config...
Temporarily override the autologging configuration for all flavors during the model evaluation. For example, model auto-logging must be disabled during the evaluation. After the evaluation is done, the original autologging configurations are restored. Args: enable_tracing (bool): Whether to en...
configure_autologging_for_evaluation
python
mlflow/mlflow
mlflow/models/evaluation/utils/trace.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/utils/trace.py
Apache-2.0
def _should_enable_tracing(flavor: str, autologging_config: dict[str, Any]) -> bool: """ Check if tracing should be enabled for the given flavor during the model evaluation. """ # 1. Check if the autologging or tracing is globally disabled # TODO: This check should not take precedence over the flavo...
Check if tracing should be enabled for the given flavor during the model evaluation.
_should_enable_tracing
python
mlflow/mlflow
mlflow/models/evaluation/utils/trace.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/utils/trace.py
Apache-2.0
def _kwargs_safe_invoke(func: Callable[..., Any], kwargs: dict[str, Any]): """ Invoke the function with the given dictionary as keyword arguments, but only include the arguments that are present in the function's signature. This is particularly used for calling autolog() function with the configuration...
Invoke the function with the given dictionary as keyword arguments, but only include the arguments that are present in the function's signature. This is particularly used for calling autolog() function with the configuration dictionary stored in AUTOLOGGING_INTEGRATIONS. While the config keys mostly a...
_kwargs_safe_invoke
python
mlflow/mlflow
mlflow/models/evaluation/utils/trace.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/utils/trace.py
Apache-2.0
def _is_trace_autologging_supported(flavor_name: str) -> bool: """Check if the given flavor supports trace autologging.""" if autolog_func := get_autolog_function(flavor_name): return "log_traces" in inspect.signature(autolog_func).parameters return False
Check if the given flavor supports trace autologging.
_is_trace_autologging_supported
python
mlflow/mlflow
mlflow/models/evaluation/utils/trace.py
https://github.com/mlflow/mlflow/blob/master/mlflow/models/evaluation/utils/trace.py
Apache-2.0
def predict(self, data, params: Optional[dict[str, Any]] = None): """ Args: data: Either a pandas DataFrame, numpy.ndarray or a dictionary. Dictionary input is expected to be a valid ONNX model feed dictionary. Numpy array input is supported iff the model has...
Args: data: Either a pandas DataFrame, numpy.ndarray or a dictionary. Dictionary input is expected to be a valid ONNX model feed dictionary. Numpy array input is supported iff the model has a single tensor input and is converted into an ONNX feed dic...
predict
python
mlflow/mlflow
mlflow/onnx/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/onnx/__init__.py
Apache-2.0
def load_model(model_uri, dst_path=None): """ Load an ONNX model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model, for example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket...
Load an ONNX model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model, for example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs:/<mlflow_ru...
load_model
python
mlflow/mlflow
mlflow/onnx/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/onnx/__init__.py
Apache-2.0
def autolog( disable=False, exclusive=False, disable_for_unsupported_versions=False, silent=False, log_traces=True, ): """ Enables (or disables) and configures autologging from OpenAI to MLflow. Raises :py:class:`MlflowException <mlflow.exceptions.MlflowException>` if the OpenAI vers...
Enables (or disables) and configures autologging from OpenAI to MLflow. Raises :py:class:`MlflowException <mlflow.exceptions.MlflowException>` if the OpenAI version < 1.0. Args: disable: If ``True``, disables the OpenAI autologging integration. If ``False``, enables the OpenAI auto...
autolog
python
mlflow/mlflow
mlflow/openai/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/autolog.py
Apache-2.0
def _try_parse_raw_response(response: Any) -> Any: """ As documented at https://github.com/openai/openai-python/tree/52357cff50bee57ef442e94d78a0de38b4173fc2?tab=readme-ov-file#accessing-raw-response-data-eg-headers, a `LegacyAPIResponse` (https://github.com/openai/openai-python/blob/52357cff50bee57ef442e94...
As documented at https://github.com/openai/openai-python/tree/52357cff50bee57ef442e94d78a0de38b4173fc2?tab=readme-ov-file#accessing-raw-response-data-eg-headers, a `LegacyAPIResponse` (https://github.com/openai/openai-python/blob/52357cff50bee57ef442e94d78a0de38b4173fc2/src/openai/_legacy_response.py#L45) ...
_try_parse_raw_response
python
mlflow/mlflow
mlflow/openai/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/autolog.py
Apache-2.0
def _process_chunk(span: LiveSpan, index: int, chunk: Any) -> str: """Parse the chunk and log it as a span event in the trace.""" from openai.types.chat.chat_completion_chunk import ChatCompletionChunk from openai.types.completion import Completion # `chunk.choices` can be empty: https://github.com/mlf...
Parse the chunk and log it as a span event in the trace.
_process_chunk
python
mlflow/mlflow
mlflow/openai/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/autolog.py
Apache-2.0
def patched_agent_get_chat_completion(original, self, *args, **kwargs): """ Patch the `get_chat_completion` method of the ChatCompletion object. OpenAI autolog already handles the raw completion request, but tracing the swarm's method is useful to track other parameters like agent name. """ agen...
Patch the `get_chat_completion` method of the ChatCompletion object. OpenAI autolog already handles the raw completion request, but tracing the swarm's method is useful to track other parameters like agent name.
patched_agent_get_chat_completion
python
mlflow/mlflow
mlflow/openai/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/autolog.py
Apache-2.0
def patched_swarm_run(original, self, *args, **kwargs): """ Patched version of `run` method of the Swarm object. """ traced_fn = mlflow.trace(original, span_type=SpanType.AGENT) return traced_fn(self, *args, **kwargs)
Patched version of `run` method of the Swarm object.
patched_swarm_run
python
mlflow/mlflow
mlflow/openai/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/autolog.py
Apache-2.0
def _get_api_config() -> _OpenAIApiConfig: """Gets the parameters and configuration of the OpenAI API connected to.""" import openai api_type = os.getenv(_OpenAIEnvVar.OPENAI_API_TYPE.value, openai.api_type) api_version = os.getenv(_OpenAIEnvVar.OPENAI_API_VERSION.value, openai.api_version) api_bas...
Gets the parameters and configuration of the OpenAI API connected to.
_get_api_config
python
mlflow/mlflow
mlflow/openai/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/model.py
Apache-2.0
def load_model(model_uri, dst_path=None): """ Load an OpenAI model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_buck...
Load an OpenAI model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs:/<mlflow_...
load_model
python
mlflow/mlflow
mlflow/openai/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/model.py
Apache-2.0
def _is_responses_output(output: Any) -> bool: """ Check whether the output is OpenAI Responses API output, or a response from the MLflow ResponsesAgent instance. """ try: from openai.types.responses import Response if isinstance(output, Response): return True except...
Check whether the output is OpenAI Responses API output, or a response from the MLflow ResponsesAgent instance.
_is_responses_output
python
mlflow/mlflow
mlflow/openai/utils/chat_schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/utils/chat_schema.py
Apache-2.0
def _parse_response_item( item: Union[dict[str, Any], BaseModel], past_messages: list[ChatMessage], ) -> list[ChatMessage]: """Parse Response API output into MLflow standard chat messages""" if isinstance(item, BaseModel): item = item.model_dump() item_type = item.get("type", "message") ...
Parse Response API output into MLflow standard chat messages
_parse_response_item
python
mlflow/mlflow
mlflow/openai/utils/chat_schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/utils/chat_schema.py
Apache-2.0
def _populate_tool_result_message( annotations: dict[str, Any], messages: list[ChatMessage] ) -> ChatMessage: """ Parses annotations from the Response API output into MLflow standard chat spec. In OpenAI spec, annotations are used for populating information from file/web search tools in the Respons...
Parses annotations from the Response API output into MLflow standard chat spec. In OpenAI spec, annotations are used for populating information from file/web search tools in the Responses API response. When converting to MLflow standard chat spec, it should be presented as a tool result message.
_populate_tool_result_message
python
mlflow/mlflow
mlflow/openai/utils/chat_schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/utils/chat_schema.py
Apache-2.0
def _parse_usage(output: Any) -> Optional[dict]: """ Parse token usage information from OpenAI response objects. Args: output: The response object from OpenAI API calls Returns: A dictionary containing token usage information. """ if output is None: return None # H...
Parse token usage information from OpenAI response objects. Args: output: The response object from OpenAI API calls Returns: A dictionary containing token usage information.
_parse_usage
python
mlflow/mlflow
mlflow/openai/utils/chat_schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/openai/utils/chat_schema.py
Apache-2.0
def __init__( self, experiment_id: str, name: Optional[str] = None, batch_flush_interval: float = 1.0, batch_size_threshold: int = 100, ): """ Initialize MLFlowStorage with batching capabilities. Parameters ---------- experiment_id : s...
Initialize MLFlowStorage with batching capabilities. Parameters ---------- experiment_id : str MLflow experiment ID name : Optional[str] Optional name for the storage batch_flush_interval : float Time in seconds between automatic batc...
__init__
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def __getstate__(self): """ Prepare the object for serialization by removing non-picklable components. This is called when the object is being pickled. """ state = self.__dict__.copy() # Remove thread-related attributes that can't be pickled state.pop("_batch_loc...
Prepare the object for serialization by removing non-picklable components. This is called when the object is being pickled.
__getstate__
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def __setstate__(self, state): """ Restore the object after deserialization by recreating non-picklable components. This is called when the object is being unpickled. """ # First, update the instance with the pickled state self.__dict__.update(state) # Recreate t...
Restore the object after deserialization by recreating non-picklable components. This is called when the object is being unpickled.
__setstate__
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def __del__(self): """Ensure all queued data is flushed before destroying the object.""" # Set the stop flag if hasattr(self, "_stop_worker"): self._stop_worker = True # Join the thread if it exists and is alive if hasattr(self, "_flush_thread") and self._flush_threa...
Ensure all queued data is flushed before destroying the object.
__del__
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def _periodic_flush_worker(self): """Background worker that periodically flushes batched data.""" while not self._stop_worker: try: time.sleep(min(0.1, self._batch_flush_interval / 10)) # Sleep in small increments # Check if it's time to flush ...
Background worker that periodically flushes batched data.
_periodic_flush_worker
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def _queue_batch_operation( self, run_id: str, metrics: Optional[list[Metric]] = None, params: Optional[list[Param]] = None, tags: Optional[list[RunTag]] = None, ): """Queue metrics, parameters, or tags for batched processing.""" with self._batch_lock: ...
Queue metrics, parameters, or tags for batched processing.
_queue_batch_operation
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def _flush_batch(self, run_id: str): """Flush the batch for a specific run_id to MLflow.""" with self._batch_lock: if run_id not in self._batch_queue: return batch = self._batch_queue[run_id] # Only make the API call if there's something to flush ...
Flush the batch for a specific run_id to MLflow.
_flush_batch
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def flush_all_batches(self): """Flush all pending batches to MLflow.""" with self._batch_lock: run_ids = list(self._batch_queue.keys()) # Flush each run's batch for run_id in run_ids: self._flush_batch(run_id)
Flush all pending batches to MLflow.
flush_all_batches
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def create_new_study( self, directions: Sequence[StudyDirection], study_name: Optional[str] = None ) -> int: """Create a new study as a mlflow run.""" study_name = study_name or DEFAULT_STUDY_NAME_PREFIX + str(uuid.uuid4()) tags = { "mlflow.runName": study_name, ...
Create a new study as a mlflow run.
create_new_study
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def set_study_user_attr(self, study_id, key: str, value: JSONSerializable) -> None: """Register a user-defined attribute as mlflow run tags to a study run.""" # Verify the run exists first to fail fast if it doesn't self._mlflow_client.get_run(study_id) # Queue the tag if the run exists...
Register a user-defined attribute as mlflow run tags to a study run.
set_study_user_attr
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def set_study_system_attr(self, study_id, key: str, value: JSONSerializable) -> None: """Register a optuna-internal attribute as mlflow run tags to a study run.""" # Verify the run exists first to fail fast if it doesn't self._mlflow_client.get_run(study_id) # Queue the tag if the run e...
Register a optuna-internal attribute as mlflow run tags to a study run.
set_study_system_attr
python
mlflow/mlflow
mlflow/optuna/storage.py
https://github.com/mlflow/mlflow/blob/master/mlflow/optuna/storage.py
Apache-2.0
def _log_early_stop_params(early_stop_callback, client, run_id): """ Logs early stopping configuration parameters to MLflow. Args: early_stop_callback: The early stopping callback instance used during training. client: An `MlflowAutologgingQueueingClient` instance used for MLflow logging. ...
Logs early stopping configuration parameters to MLflow. Args: early_stop_callback: The early stopping callback instance used during training. client: An `MlflowAutologgingQueueingClient` instance used for MLflow logging. run_id: The ID of the MLflow Run to which to log configuration pa...
_log_early_stop_params
python
mlflow/mlflow
mlflow/paddle/_paddle_autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/paddle/_paddle_autolog.py
Apache-2.0
def _log_early_stop_metrics(early_stop_callback, client, run_id, model_id=None): """ Logs early stopping behavior results (e.g. stopped epoch) as metrics to MLflow. Args: early_stop_callback: The early stopping callback instance used during training. client: An `MlflowAutologgingQueueingCli...
Logs early stopping behavior results (e.g. stopped epoch) as metrics to MLflow. Args: early_stop_callback: The early stopping callback instance used during training. client: An `MlflowAutologgingQueueingClient` instance used for MLflow logging. run_id: The ID of the MLflow Run to which...
_log_early_stop_metrics
python
mlflow/mlflow
mlflow/paddle/_paddle_autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/paddle/_paddle_autolog.py
Apache-2.0
def save_model( pd_model, path, training=False, conda_env=None, code_paths=None, mlflow_model=None, signature: ModelSignature = None, input_example: ModelInputExample = None, pip_requirements=None, extra_pip_requirements=None, metadata=None, ): """ Save a paddle model...
Save a paddle model to a path on the local file system. Produces an MLflow Model containing the following flavors: - :py:mod:`mlflow.paddle` - :py:mod:`mlflow.pyfunc`. NOTE: This flavor is only included for paddle models that define `predict()`, since `predict()` is required for pyfu...
save_model
python
mlflow/mlflow
mlflow/paddle/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/paddle/__init__.py
Apache-2.0
def load_model(model_uri, model=None, dst_path=None, **kwargs): """ Load a paddle model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model, for example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` ...
Load a paddle model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model, for example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs:/<mlflow_ru...
load_model
python
mlflow/mlflow
mlflow/paddle/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/paddle/__init__.py
Apache-2.0
def log_model( pd_model, artifact_path: Optional[str] = None, training=False, conda_env=None, code_paths=None, registered_model_name=None, signature: ModelSignature = None, input_example: ModelInputExample = None, await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS, pip_requir...
Log a paddle model as an MLflow artifact for the current run. Produces an MLflow Model containing the following flavors: - :py:mod:`mlflow.paddle` - :py:mod:`mlflow.pyfunc`. NOTE: This flavor is only included for paddle models that define `predict()`, since `predict()` is required fo...
log_model
python
mlflow/mlflow
mlflow/paddle/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/paddle/__init__.py
Apache-2.0
def autolog( log_every_n_epoch=1, log_models=True, disable=False, exclusive=False, silent=False, registered_model_name=None, extra_tags=None, ): """ Enables (or disables) and configures autologging from PaddlePaddle to MLflow. Autologging is performed when the `fit` method of `p...
Enables (or disables) and configures autologging from PaddlePaddle to MLflow. Autologging is performed when the `fit` method of `paddle.Model`_ is called. .. _paddle.Model: https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/Model_en.html Args: log_every_n_epoch: If spec...
autolog
python
mlflow/mlflow
mlflow/paddle/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/paddle/__init__.py
Apache-2.0
def load_model(model_uri, dst_path=None): """ Load a ``pmdarima`` ``ARIMA`` model or ``Pipeline`` object from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/loca...
Load a ``pmdarima`` ``ARIMA`` model or ``Pipeline`` object from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/...
load_model
python
mlflow/mlflow
mlflow/pmdarima/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/pmdarima/__init__.py
Apache-2.0
def before_run_validations(tracking_uri, backend_config): """Validations to perform before running a project on Databricks.""" if backend_config is None: raise ExecutionException( "Backend spec must be provided when launching MLflow project runs on Databricks." ) elif "existing_c...
Validations to perform before running a project on Databricks.
before_run_validations
python
mlflow/mlflow
mlflow/projects/databricks.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/databricks.py
Apache-2.0
def _upload_to_dbfs(self, src_path, dbfs_fuse_uri): """ Upload the file at `src_path` to the specified DBFS URI within the Databricks workspace corresponding to the default Databricks CLI profile. """ _logger.info("=== Uploading project to DBFS path %s ===", dbfs_fuse_uri) ...
Upload the file at `src_path` to the specified DBFS URI within the Databricks workspace corresponding to the default Databricks CLI profile.
_upload_to_dbfs
python
mlflow/mlflow
mlflow/projects/databricks.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/databricks.py
Apache-2.0
def _dbfs_path_exists(self, dbfs_path): """ Return True if the passed-in path exists in DBFS for the workspace corresponding to the default Databricks CLI profile. The path is expected to be a relative path to the DBFS root directory, e.g. 'path/to/file'. """ host_creds =...
Return True if the passed-in path exists in DBFS for the workspace corresponding to the default Databricks CLI profile. The path is expected to be a relative path to the DBFS root directory, e.g. 'path/to/file'.
_dbfs_path_exists
python
mlflow/mlflow
mlflow/projects/databricks.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/databricks.py
Apache-2.0
def _upload_project_to_dbfs(self, project_dir, experiment_id): # noqa: D417 """ Tars a project directory into an archive in a temp dir and uploads it to DBFS, returning the HDFS-style URI of the tarball in DBFS (e.g. dbfs:/path/to/tar). Args: project_dir: Path to a director...
Tars a project directory into an archive in a temp dir and uploads it to DBFS, returning the HDFS-style URI of the tarball in DBFS (e.g. dbfs:/path/to/tar). Args: project_dir: Path to a directory containing an MLflow project to upload to DBFS (e.g. a directory conta...
_upload_project_to_dbfs
python
mlflow/mlflow
mlflow/projects/databricks.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/databricks.py
Apache-2.0
def _run_shell_command_job(self, project_uri, command, env_vars, cluster_spec): """ Run the specified shell command on a Databricks cluster. Args: project_uri: URI of the project from which the shell command originates. command: Shell command to run. env_vars...
Run the specified shell command on a Databricks cluster. Args: project_uri: URI of the project from which the shell command originates. command: Shell command to run. env_vars: Environment variables to set in the process running ``command``. cluster_spec...
_run_shell_command_job
python
mlflow/mlflow
mlflow/projects/databricks.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/databricks.py
Apache-2.0
def get_run_result_state(self, databricks_run_id): """ Get the run result state (string) of a Databricks job run. Args: databricks_run_id: Integer Databricks job run ID. Returns: `RunResultState <https://docs.databricks.com/api/latest/jobs.html#runresultstate>`_...
Get the run result state (string) of a Databricks job run. Args: databricks_run_id: Integer Databricks job run ID. Returns: `RunResultState <https://docs.databricks.com/api/latest/jobs.html#runresultstate>`_ or None if the run is still active.
get_run_result_state
python
mlflow/mlflow
mlflow/projects/databricks.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/databricks.py
Apache-2.0
def _get_databricks_run_cmd(dbfs_fuse_tar_uri, run_id, entry_point, parameters, env_manager): """ Generate MLflow CLI command to run on Databricks cluster in order to launch a run on Databricks. """ project_dir, extracting_tar_command = _get_project_dir_and_extracting_tar_command( dbfs_fuse_tar_...
Generate MLflow CLI command to run on Databricks cluster in order to launch a run on Databricks.
_get_databricks_run_cmd
python
mlflow/mlflow
mlflow/projects/databricks.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/databricks.py
Apache-2.0
def validate_docker_installation(): """ Verify if Docker is installed and running on host machine. """ if shutil.which("docker") is None: raise ExecutionException( "Could not find Docker executable. " "Ensure Docker is installed as per the instructions " "at h...
Verify if Docker is installed and running on host machine.
validate_docker_installation
python
mlflow/mlflow
mlflow/projects/docker.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/docker.py
Apache-2.0
def build_docker_image(work_dir, repository_uri, base_image, run_id, build_image, docker_auth): """ Build a docker image containing the project in `work_dir`, using the base image. """ image_uri = _get_docker_image_uri(repository_uri=repository_uri, work_dir=work_dir) client = docker.from_env() ...
Build a docker image containing the project in `work_dir`, using the base image.
build_docker_image
python
mlflow/mlflow
mlflow/projects/docker.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/docker.py
Apache-2.0
def _create_docker_build_ctx(work_dir, dockerfile_contents): """ Creates build context tarfile containing Dockerfile and project code, returning path to tarfile """ directory = tempfile.mkdtemp() try: dst_path = os.path.join(directory, "mlflow-project-contents") shutil.copytree(src=w...
Creates build context tarfile containing Dockerfile and project code, returning path to tarfile
_create_docker_build_ctx
python
mlflow/mlflow
mlflow/projects/docker.py
https://github.com/mlflow/mlflow/blob/master/mlflow/projects/docker.py
Apache-2.0