genesis-flow 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- genesis_flow-1.0.0.dist-info/METADATA +822 -0
- genesis_flow-1.0.0.dist-info/RECORD +645 -0
- genesis_flow-1.0.0.dist-info/WHEEL +5 -0
- genesis_flow-1.0.0.dist-info/entry_points.txt +19 -0
- genesis_flow-1.0.0.dist-info/licenses/LICENSE.txt +202 -0
- genesis_flow-1.0.0.dist-info/top_level.txt +1 -0
- mlflow/__init__.py +367 -0
- mlflow/__main__.py +3 -0
- mlflow/ag2/__init__.py +56 -0
- mlflow/ag2/ag2_logger.py +294 -0
- mlflow/anthropic/__init__.py +40 -0
- mlflow/anthropic/autolog.py +129 -0
- mlflow/anthropic/chat.py +144 -0
- mlflow/artifacts/__init__.py +268 -0
- mlflow/autogen/__init__.py +144 -0
- mlflow/autogen/chat.py +142 -0
- mlflow/azure/__init__.py +26 -0
- mlflow/azure/auth_handler.py +257 -0
- mlflow/azure/client.py +319 -0
- mlflow/azure/config.py +120 -0
- mlflow/azure/connection_factory.py +340 -0
- mlflow/azure/exceptions.py +27 -0
- mlflow/azure/stores.py +327 -0
- mlflow/azure/utils.py +183 -0
- mlflow/bedrock/__init__.py +45 -0
- mlflow/bedrock/_autolog.py +202 -0
- mlflow/bedrock/chat.py +122 -0
- mlflow/bedrock/stream.py +160 -0
- mlflow/bedrock/utils.py +43 -0
- mlflow/cli.py +707 -0
- mlflow/client.py +12 -0
- mlflow/config/__init__.py +56 -0
- mlflow/crewai/__init__.py +79 -0
- mlflow/crewai/autolog.py +253 -0
- mlflow/crewai/chat.py +29 -0
- mlflow/data/__init__.py +75 -0
- mlflow/data/artifact_dataset_sources.py +170 -0
- mlflow/data/code_dataset_source.py +40 -0
- mlflow/data/dataset.py +123 -0
- mlflow/data/dataset_registry.py +168 -0
- mlflow/data/dataset_source.py +110 -0
- mlflow/data/dataset_source_registry.py +219 -0
- mlflow/data/delta_dataset_source.py +167 -0
- mlflow/data/digest_utils.py +108 -0
- mlflow/data/evaluation_dataset.py +562 -0
- mlflow/data/filesystem_dataset_source.py +81 -0
- mlflow/data/http_dataset_source.py +145 -0
- mlflow/data/huggingface_dataset.py +258 -0
- mlflow/data/huggingface_dataset_source.py +118 -0
- mlflow/data/meta_dataset.py +104 -0
- mlflow/data/numpy_dataset.py +223 -0
- mlflow/data/pandas_dataset.py +231 -0
- mlflow/data/polars_dataset.py +352 -0
- mlflow/data/pyfunc_dataset_mixin.py +31 -0
- mlflow/data/schema.py +76 -0
- mlflow/data/sources.py +1 -0
- mlflow/data/spark_dataset.py +406 -0
- mlflow/data/spark_dataset_source.py +74 -0
- mlflow/data/spark_delta_utils.py +118 -0
- mlflow/data/tensorflow_dataset.py +350 -0
- mlflow/data/uc_volume_dataset_source.py +81 -0
- mlflow/db.py +27 -0
- mlflow/dspy/__init__.py +17 -0
- mlflow/dspy/autolog.py +197 -0
- mlflow/dspy/callback.py +398 -0
- mlflow/dspy/constant.py +1 -0
- mlflow/dspy/load.py +93 -0
- mlflow/dspy/save.py +393 -0
- mlflow/dspy/util.py +109 -0
- mlflow/dspy/wrapper.py +226 -0
- mlflow/entities/__init__.py +104 -0
- mlflow/entities/_mlflow_object.py +52 -0
- mlflow/entities/assessment.py +545 -0
- mlflow/entities/assessment_error.py +80 -0
- mlflow/entities/assessment_source.py +141 -0
- mlflow/entities/dataset.py +92 -0
- mlflow/entities/dataset_input.py +51 -0
- mlflow/entities/dataset_summary.py +62 -0
- mlflow/entities/document.py +48 -0
- mlflow/entities/experiment.py +109 -0
- mlflow/entities/experiment_tag.py +35 -0
- mlflow/entities/file_info.py +45 -0
- mlflow/entities/input_tag.py +35 -0
- mlflow/entities/lifecycle_stage.py +35 -0
- mlflow/entities/logged_model.py +228 -0
- mlflow/entities/logged_model_input.py +26 -0
- mlflow/entities/logged_model_output.py +32 -0
- mlflow/entities/logged_model_parameter.py +46 -0
- mlflow/entities/logged_model_status.py +74 -0
- mlflow/entities/logged_model_tag.py +33 -0
- mlflow/entities/metric.py +200 -0
- mlflow/entities/model_registry/__init__.py +29 -0
- mlflow/entities/model_registry/_model_registry_entity.py +13 -0
- mlflow/entities/model_registry/model_version.py +243 -0
- mlflow/entities/model_registry/model_version_deployment_job_run_state.py +44 -0
- mlflow/entities/model_registry/model_version_deployment_job_state.py +70 -0
- mlflow/entities/model_registry/model_version_search.py +25 -0
- mlflow/entities/model_registry/model_version_stages.py +25 -0
- mlflow/entities/model_registry/model_version_status.py +35 -0
- mlflow/entities/model_registry/model_version_tag.py +35 -0
- mlflow/entities/model_registry/prompt.py +73 -0
- mlflow/entities/model_registry/prompt_version.py +244 -0
- mlflow/entities/model_registry/registered_model.py +175 -0
- mlflow/entities/model_registry/registered_model_alias.py +35 -0
- mlflow/entities/model_registry/registered_model_deployment_job_state.py +39 -0
- mlflow/entities/model_registry/registered_model_search.py +25 -0
- mlflow/entities/model_registry/registered_model_tag.py +35 -0
- mlflow/entities/multipart_upload.py +74 -0
- mlflow/entities/param.py +49 -0
- mlflow/entities/run.py +97 -0
- mlflow/entities/run_data.py +84 -0
- mlflow/entities/run_info.py +188 -0
- mlflow/entities/run_inputs.py +59 -0
- mlflow/entities/run_outputs.py +43 -0
- mlflow/entities/run_status.py +41 -0
- mlflow/entities/run_tag.py +36 -0
- mlflow/entities/source_type.py +31 -0
- mlflow/entities/span.py +774 -0
- mlflow/entities/span_event.py +96 -0
- mlflow/entities/span_status.py +102 -0
- mlflow/entities/trace.py +317 -0
- mlflow/entities/trace_data.py +71 -0
- mlflow/entities/trace_info.py +220 -0
- mlflow/entities/trace_info_v2.py +162 -0
- mlflow/entities/trace_location.py +173 -0
- mlflow/entities/trace_state.py +39 -0
- mlflow/entities/trace_status.py +68 -0
- mlflow/entities/view_type.py +51 -0
- mlflow/environment_variables.py +866 -0
- mlflow/evaluation/__init__.py +16 -0
- mlflow/evaluation/assessment.py +369 -0
- mlflow/evaluation/evaluation.py +411 -0
- mlflow/evaluation/evaluation_tag.py +61 -0
- mlflow/evaluation/fluent.py +48 -0
- mlflow/evaluation/utils.py +201 -0
- mlflow/exceptions.py +213 -0
- mlflow/experiments.py +140 -0
- mlflow/gemini/__init__.py +81 -0
- mlflow/gemini/autolog.py +186 -0
- mlflow/gemini/chat.py +261 -0
- mlflow/genai/__init__.py +71 -0
- mlflow/genai/datasets/__init__.py +67 -0
- mlflow/genai/datasets/evaluation_dataset.py +131 -0
- mlflow/genai/evaluation/__init__.py +3 -0
- mlflow/genai/evaluation/base.py +411 -0
- mlflow/genai/evaluation/constant.py +23 -0
- mlflow/genai/evaluation/utils.py +244 -0
- mlflow/genai/judges/__init__.py +21 -0
- mlflow/genai/judges/databricks.py +404 -0
- mlflow/genai/label_schemas/__init__.py +153 -0
- mlflow/genai/label_schemas/label_schemas.py +209 -0
- mlflow/genai/labeling/__init__.py +159 -0
- mlflow/genai/labeling/labeling.py +250 -0
- mlflow/genai/optimize/__init__.py +13 -0
- mlflow/genai/optimize/base.py +198 -0
- mlflow/genai/optimize/optimizers/__init__.py +4 -0
- mlflow/genai/optimize/optimizers/base_optimizer.py +38 -0
- mlflow/genai/optimize/optimizers/dspy_mipro_optimizer.py +221 -0
- mlflow/genai/optimize/optimizers/dspy_optimizer.py +91 -0
- mlflow/genai/optimize/optimizers/utils/dspy_mipro_callback.py +76 -0
- mlflow/genai/optimize/optimizers/utils/dspy_mipro_utils.py +18 -0
- mlflow/genai/optimize/types.py +75 -0
- mlflow/genai/optimize/util.py +30 -0
- mlflow/genai/prompts/__init__.py +206 -0
- mlflow/genai/scheduled_scorers.py +431 -0
- mlflow/genai/scorers/__init__.py +26 -0
- mlflow/genai/scorers/base.py +492 -0
- mlflow/genai/scorers/builtin_scorers.py +765 -0
- mlflow/genai/scorers/scorer_utils.py +138 -0
- mlflow/genai/scorers/validation.py +165 -0
- mlflow/genai/utils/data_validation.py +146 -0
- mlflow/genai/utils/enum_utils.py +23 -0
- mlflow/genai/utils/trace_utils.py +211 -0
- mlflow/groq/__init__.py +42 -0
- mlflow/groq/_groq_autolog.py +74 -0
- mlflow/johnsnowlabs/__init__.py +888 -0
- mlflow/langchain/__init__.py +24 -0
- mlflow/langchain/api_request_parallel_processor.py +330 -0
- mlflow/langchain/autolog.py +147 -0
- mlflow/langchain/chat_agent_langgraph.py +340 -0
- mlflow/langchain/constant.py +1 -0
- mlflow/langchain/constants.py +1 -0
- mlflow/langchain/databricks_dependencies.py +444 -0
- mlflow/langchain/langchain_tracer.py +597 -0
- mlflow/langchain/model.py +919 -0
- mlflow/langchain/output_parsers.py +142 -0
- mlflow/langchain/retriever_chain.py +153 -0
- mlflow/langchain/runnables.py +527 -0
- mlflow/langchain/utils/chat.py +402 -0
- mlflow/langchain/utils/logging.py +671 -0
- mlflow/langchain/utils/serialization.py +36 -0
- mlflow/legacy_databricks_cli/__init__.py +0 -0
- mlflow/legacy_databricks_cli/configure/__init__.py +0 -0
- mlflow/legacy_databricks_cli/configure/provider.py +482 -0
- mlflow/litellm/__init__.py +175 -0
- mlflow/llama_index/__init__.py +22 -0
- mlflow/llama_index/autolog.py +55 -0
- mlflow/llama_index/chat.py +43 -0
- mlflow/llama_index/constant.py +1 -0
- mlflow/llama_index/model.py +577 -0
- mlflow/llama_index/pyfunc_wrapper.py +332 -0
- mlflow/llama_index/serialize_objects.py +188 -0
- mlflow/llama_index/tracer.py +561 -0
- mlflow/metrics/__init__.py +479 -0
- mlflow/metrics/base.py +39 -0
- mlflow/metrics/genai/__init__.py +25 -0
- mlflow/metrics/genai/base.py +101 -0
- mlflow/metrics/genai/genai_metric.py +771 -0
- mlflow/metrics/genai/metric_definitions.py +450 -0
- mlflow/metrics/genai/model_utils.py +371 -0
- mlflow/metrics/genai/prompt_template.py +68 -0
- mlflow/metrics/genai/prompts/__init__.py +0 -0
- mlflow/metrics/genai/prompts/v1.py +422 -0
- mlflow/metrics/genai/utils.py +6 -0
- mlflow/metrics/metric_definitions.py +619 -0
- mlflow/mismatch.py +34 -0
- mlflow/mistral/__init__.py +34 -0
- mlflow/mistral/autolog.py +71 -0
- mlflow/mistral/chat.py +135 -0
- mlflow/ml_package_versions.py +452 -0
- mlflow/models/__init__.py +97 -0
- mlflow/models/auth_policy.py +83 -0
- mlflow/models/cli.py +354 -0
- mlflow/models/container/__init__.py +294 -0
- mlflow/models/container/scoring_server/__init__.py +0 -0
- mlflow/models/container/scoring_server/nginx.conf +39 -0
- mlflow/models/dependencies_schemas.py +287 -0
- mlflow/models/display_utils.py +158 -0
- mlflow/models/docker_utils.py +211 -0
- mlflow/models/evaluation/__init__.py +23 -0
- mlflow/models/evaluation/_shap_patch.py +64 -0
- mlflow/models/evaluation/artifacts.py +194 -0
- mlflow/models/evaluation/base.py +1811 -0
- mlflow/models/evaluation/calibration_curve.py +109 -0
- mlflow/models/evaluation/default_evaluator.py +996 -0
- mlflow/models/evaluation/deprecated.py +23 -0
- mlflow/models/evaluation/evaluator_registry.py +80 -0
- mlflow/models/evaluation/evaluators/classifier.py +704 -0
- mlflow/models/evaluation/evaluators/default.py +233 -0
- mlflow/models/evaluation/evaluators/regressor.py +96 -0
- mlflow/models/evaluation/evaluators/shap.py +296 -0
- mlflow/models/evaluation/lift_curve.py +178 -0
- mlflow/models/evaluation/utils/metric.py +123 -0
- mlflow/models/evaluation/utils/trace.py +179 -0
- mlflow/models/evaluation/validation.py +434 -0
- mlflow/models/flavor_backend.py +93 -0
- mlflow/models/flavor_backend_registry.py +53 -0
- mlflow/models/model.py +1639 -0
- mlflow/models/model_config.py +150 -0
- mlflow/models/notebook_resources/agent_evaluation_template.html +235 -0
- mlflow/models/notebook_resources/eval_with_dataset_example.py +22 -0
- mlflow/models/notebook_resources/eval_with_synthetic_example.py +22 -0
- mlflow/models/python_api.py +369 -0
- mlflow/models/rag_signatures.py +128 -0
- mlflow/models/resources.py +321 -0
- mlflow/models/signature.py +662 -0
- mlflow/models/utils.py +2054 -0
- mlflow/models/wheeled_model.py +280 -0
- mlflow/openai/__init__.py +57 -0
- mlflow/openai/_agent_tracer.py +364 -0
- mlflow/openai/api_request_parallel_processor.py +131 -0
- mlflow/openai/autolog.py +509 -0
- mlflow/openai/constant.py +1 -0
- mlflow/openai/model.py +824 -0
- mlflow/openai/utils/chat_schema.py +367 -0
- mlflow/optuna/__init__.py +3 -0
- mlflow/optuna/storage.py +646 -0
- mlflow/plugins/__init__.py +72 -0
- mlflow/plugins/base.py +358 -0
- mlflow/plugins/builtin/__init__.py +24 -0
- mlflow/plugins/builtin/pytorch_plugin.py +150 -0
- mlflow/plugins/builtin/sklearn_plugin.py +158 -0
- mlflow/plugins/builtin/transformers_plugin.py +187 -0
- mlflow/plugins/cli.py +321 -0
- mlflow/plugins/discovery.py +340 -0
- mlflow/plugins/manager.py +465 -0
- mlflow/plugins/registry.py +316 -0
- mlflow/plugins/templates/framework_plugin_template.py +329 -0
- mlflow/prompt/constants.py +20 -0
- mlflow/prompt/promptlab_model.py +197 -0
- mlflow/prompt/registry_utils.py +248 -0
- mlflow/promptflow/__init__.py +495 -0
- mlflow/protos/__init__.py +0 -0
- mlflow/protos/assessments_pb2.py +174 -0
- mlflow/protos/databricks_artifacts_pb2.py +489 -0
- mlflow/protos/databricks_filesystem_service_pb2.py +196 -0
- mlflow/protos/databricks_managed_catalog_messages_pb2.py +95 -0
- mlflow/protos/databricks_managed_catalog_service_pb2.py +86 -0
- mlflow/protos/databricks_pb2.py +267 -0
- mlflow/protos/databricks_trace_server_pb2.py +374 -0
- mlflow/protos/databricks_uc_registry_messages_pb2.py +1249 -0
- mlflow/protos/databricks_uc_registry_service_pb2.py +170 -0
- mlflow/protos/facet_feature_statistics_pb2.py +296 -0
- mlflow/protos/internal_pb2.py +77 -0
- mlflow/protos/mlflow_artifacts_pb2.py +336 -0
- mlflow/protos/model_registry_pb2.py +1073 -0
- mlflow/protos/scalapb/__init__.py +0 -0
- mlflow/protos/scalapb/scalapb_pb2.py +104 -0
- mlflow/protos/service_pb2.py +2600 -0
- mlflow/protos/unity_catalog_oss_messages_pb2.py +457 -0
- mlflow/protos/unity_catalog_oss_service_pb2.py +130 -0
- mlflow/protos/unity_catalog_prompt_messages_pb2.py +447 -0
- mlflow/protos/unity_catalog_prompt_messages_pb2_grpc.py +24 -0
- mlflow/protos/unity_catalog_prompt_service_pb2.py +164 -0
- mlflow/protos/unity_catalog_prompt_service_pb2_grpc.py +785 -0
- mlflow/py.typed +0 -0
- mlflow/pydantic_ai/__init__.py +57 -0
- mlflow/pydantic_ai/autolog.py +173 -0
- mlflow/pyfunc/__init__.py +3844 -0
- mlflow/pyfunc/_mlflow_pyfunc_backend_predict.py +61 -0
- mlflow/pyfunc/backend.py +523 -0
- mlflow/pyfunc/context.py +78 -0
- mlflow/pyfunc/dbconnect_artifact_cache.py +144 -0
- mlflow/pyfunc/loaders/__init__.py +7 -0
- mlflow/pyfunc/loaders/chat_agent.py +117 -0
- mlflow/pyfunc/loaders/chat_model.py +125 -0
- mlflow/pyfunc/loaders/code_model.py +31 -0
- mlflow/pyfunc/loaders/responses_agent.py +112 -0
- mlflow/pyfunc/mlserver.py +46 -0
- mlflow/pyfunc/model.py +1473 -0
- mlflow/pyfunc/scoring_server/__init__.py +604 -0
- mlflow/pyfunc/scoring_server/app.py +7 -0
- mlflow/pyfunc/scoring_server/client.py +146 -0
- mlflow/pyfunc/spark_model_cache.py +48 -0
- mlflow/pyfunc/stdin_server.py +44 -0
- mlflow/pyfunc/utils/__init__.py +3 -0
- mlflow/pyfunc/utils/data_validation.py +224 -0
- mlflow/pyfunc/utils/environment.py +22 -0
- mlflow/pyfunc/utils/input_converter.py +47 -0
- mlflow/pyfunc/utils/serving_data_parser.py +11 -0
- mlflow/pytorch/__init__.py +1171 -0
- mlflow/pytorch/_lightning_autolog.py +580 -0
- mlflow/pytorch/_pytorch_autolog.py +50 -0
- mlflow/pytorch/pickle_module.py +35 -0
- mlflow/rfunc/__init__.py +42 -0
- mlflow/rfunc/backend.py +134 -0
- mlflow/runs.py +89 -0
- mlflow/server/__init__.py +302 -0
- mlflow/server/auth/__init__.py +1224 -0
- mlflow/server/auth/__main__.py +4 -0
- mlflow/server/auth/basic_auth.ini +6 -0
- mlflow/server/auth/cli.py +11 -0
- mlflow/server/auth/client.py +537 -0
- mlflow/server/auth/config.py +34 -0
- mlflow/server/auth/db/__init__.py +0 -0
- mlflow/server/auth/db/cli.py +18 -0
- mlflow/server/auth/db/migrations/__init__.py +0 -0
- mlflow/server/auth/db/migrations/alembic.ini +110 -0
- mlflow/server/auth/db/migrations/env.py +76 -0
- mlflow/server/auth/db/migrations/versions/8606fa83a998_initial_migration.py +51 -0
- mlflow/server/auth/db/migrations/versions/__init__.py +0 -0
- mlflow/server/auth/db/models.py +67 -0
- mlflow/server/auth/db/utils.py +37 -0
- mlflow/server/auth/entities.py +165 -0
- mlflow/server/auth/logo.py +14 -0
- mlflow/server/auth/permissions.py +65 -0
- mlflow/server/auth/routes.py +18 -0
- mlflow/server/auth/sqlalchemy_store.py +263 -0
- mlflow/server/graphql/__init__.py +0 -0
- mlflow/server/graphql/autogenerated_graphql_schema.py +353 -0
- mlflow/server/graphql/graphql_custom_scalars.py +24 -0
- mlflow/server/graphql/graphql_errors.py +15 -0
- mlflow/server/graphql/graphql_no_batching.py +89 -0
- mlflow/server/graphql/graphql_schema_extensions.py +74 -0
- mlflow/server/handlers.py +3217 -0
- mlflow/server/prometheus_exporter.py +17 -0
- mlflow/server/validation.py +30 -0
- mlflow/shap/__init__.py +691 -0
- mlflow/sklearn/__init__.py +1994 -0
- mlflow/sklearn/utils.py +1041 -0
- mlflow/smolagents/__init__.py +66 -0
- mlflow/smolagents/autolog.py +139 -0
- mlflow/smolagents/chat.py +29 -0
- mlflow/store/__init__.py +10 -0
- mlflow/store/_unity_catalog/__init__.py +1 -0
- mlflow/store/_unity_catalog/lineage/__init__.py +1 -0
- mlflow/store/_unity_catalog/lineage/constants.py +2 -0
- mlflow/store/_unity_catalog/registry/__init__.py +6 -0
- mlflow/store/_unity_catalog/registry/prompt_info.py +75 -0
- mlflow/store/_unity_catalog/registry/rest_store.py +1740 -0
- mlflow/store/_unity_catalog/registry/uc_oss_rest_store.py +507 -0
- mlflow/store/_unity_catalog/registry/utils.py +121 -0
- mlflow/store/artifact/__init__.py +0 -0
- mlflow/store/artifact/artifact_repo.py +472 -0
- mlflow/store/artifact/artifact_repository_registry.py +154 -0
- mlflow/store/artifact/azure_blob_artifact_repo.py +275 -0
- mlflow/store/artifact/azure_data_lake_artifact_repo.py +295 -0
- mlflow/store/artifact/cli.py +141 -0
- mlflow/store/artifact/cloud_artifact_repo.py +332 -0
- mlflow/store/artifact/databricks_artifact_repo.py +729 -0
- mlflow/store/artifact/databricks_artifact_repo_resources.py +301 -0
- mlflow/store/artifact/databricks_logged_model_artifact_repo.py +93 -0
- mlflow/store/artifact/databricks_models_artifact_repo.py +216 -0
- mlflow/store/artifact/databricks_sdk_artifact_repo.py +134 -0
- mlflow/store/artifact/databricks_sdk_models_artifact_repo.py +97 -0
- mlflow/store/artifact/dbfs_artifact_repo.py +240 -0
- mlflow/store/artifact/ftp_artifact_repo.py +132 -0
- mlflow/store/artifact/gcs_artifact_repo.py +296 -0
- mlflow/store/artifact/hdfs_artifact_repo.py +209 -0
- mlflow/store/artifact/http_artifact_repo.py +218 -0
- mlflow/store/artifact/local_artifact_repo.py +142 -0
- mlflow/store/artifact/mlflow_artifacts_repo.py +94 -0
- mlflow/store/artifact/models_artifact_repo.py +259 -0
- mlflow/store/artifact/optimized_s3_artifact_repo.py +356 -0
- mlflow/store/artifact/presigned_url_artifact_repo.py +173 -0
- mlflow/store/artifact/r2_artifact_repo.py +70 -0
- mlflow/store/artifact/runs_artifact_repo.py +265 -0
- mlflow/store/artifact/s3_artifact_repo.py +330 -0
- mlflow/store/artifact/sftp_artifact_repo.py +141 -0
- mlflow/store/artifact/uc_volume_artifact_repo.py +76 -0
- mlflow/store/artifact/unity_catalog_models_artifact_repo.py +168 -0
- mlflow/store/artifact/unity_catalog_oss_models_artifact_repo.py +168 -0
- mlflow/store/artifact/utils/__init__.py +0 -0
- mlflow/store/artifact/utils/models.py +148 -0
- mlflow/store/db/__init__.py +0 -0
- mlflow/store/db/base_sql_model.py +3 -0
- mlflow/store/db/db_types.py +10 -0
- mlflow/store/db/utils.py +314 -0
- mlflow/store/db_migrations/__init__.py +0 -0
- mlflow/store/db_migrations/alembic.ini +74 -0
- mlflow/store/db_migrations/env.py +84 -0
- mlflow/store/db_migrations/versions/0584bdc529eb_add_cascading_deletion_to_datasets_from_experiments.py +88 -0
- mlflow/store/db_migrations/versions/0a8213491aaa_drop_duplicate_killed_constraint.py +49 -0
- mlflow/store/db_migrations/versions/0c779009ac13_add_deleted_time_field_to_runs_table.py +24 -0
- mlflow/store/db_migrations/versions/181f10493468_allow_nulls_for_metric_values.py +35 -0
- mlflow/store/db_migrations/versions/27a6a02d2cf1_add_model_version_tags_table.py +38 -0
- mlflow/store/db_migrations/versions/2b4d017a5e9b_add_model_registry_tables_to_db.py +77 -0
- mlflow/store/db_migrations/versions/2d6e25af4d3e_increase_max_param_val_length.py +33 -0
- mlflow/store/db_migrations/versions/3500859a5d39_add_model_aliases_table.py +50 -0
- mlflow/store/db_migrations/versions/39d1c3be5f05_add_is_nan_constraint_for_metrics_tables_if_necessary.py +41 -0
- mlflow/store/db_migrations/versions/400f98739977_add_logged_model_tables.py +123 -0
- mlflow/store/db_migrations/versions/4465047574b1_increase_max_dataset_schema_size.py +38 -0
- mlflow/store/db_migrations/versions/451aebb31d03_add_metric_step.py +35 -0
- mlflow/store/db_migrations/versions/5b0e9adcef9c_add_cascade_deletion_to_trace_tables_fk.py +40 -0
- mlflow/store/db_migrations/versions/6953534de441_add_step_to_inputs_table.py +25 -0
- mlflow/store/db_migrations/versions/728d730b5ebd_add_registered_model_tags_table.py +38 -0
- mlflow/store/db_migrations/versions/7ac759974ad8_update_run_tags_with_larger_limit.py +36 -0
- mlflow/store/db_migrations/versions/7f2a7d5fae7d_add_datasets_inputs_input_tags_tables.py +82 -0
- mlflow/store/db_migrations/versions/84291f40a231_add_run_link_to_model_version.py +26 -0
- mlflow/store/db_migrations/versions/867495a8f9d4_add_trace_tables.py +90 -0
- mlflow/store/db_migrations/versions/89d4b8295536_create_latest_metrics_table.py +169 -0
- mlflow/store/db_migrations/versions/90e64c465722_migrate_user_column_to_tags.py +64 -0
- mlflow/store/db_migrations/versions/97727af70f4d_creation_time_last_update_time_experiments.py +25 -0
- mlflow/store/db_migrations/versions/__init__.py +0 -0
- mlflow/store/db_migrations/versions/a8c4a736bde6_allow_nulls_for_run_id.py +27 -0
- mlflow/store/db_migrations/versions/acf3f17fdcc7_add_storage_location_field_to_model_.py +29 -0
- mlflow/store/db_migrations/versions/bd07f7e963c5_create_index_on_run_uuid.py +26 -0
- mlflow/store/db_migrations/versions/bda7b8c39065_increase_model_version_tag_value_limit.py +38 -0
- mlflow/store/db_migrations/versions/c48cb773bb87_reset_default_value_for_is_nan_in_metrics_table_for_mysql.py +41 -0
- mlflow/store/db_migrations/versions/cbc13b556ace_add_v3_trace_schema_columns.py +31 -0
- mlflow/store/db_migrations/versions/cc1f77228345_change_param_value_length_to_500.py +34 -0
- mlflow/store/db_migrations/versions/cfd24bdc0731_update_run_status_constraint_with_killed.py +78 -0
- mlflow/store/db_migrations/versions/df50e92ffc5e_add_experiment_tags_table.py +38 -0
- mlflow/store/db_migrations/versions/f5a4f2784254_increase_run_tag_value_limit.py +36 -0
- mlflow/store/entities/__init__.py +3 -0
- mlflow/store/entities/paged_list.py +18 -0
- mlflow/store/model_registry/__init__.py +10 -0
- mlflow/store/model_registry/abstract_store.py +1081 -0
- mlflow/store/model_registry/base_rest_store.py +44 -0
- mlflow/store/model_registry/databricks_workspace_model_registry_rest_store.py +37 -0
- mlflow/store/model_registry/dbmodels/__init__.py +0 -0
- mlflow/store/model_registry/dbmodels/models.py +206 -0
- mlflow/store/model_registry/file_store.py +1091 -0
- mlflow/store/model_registry/rest_store.py +481 -0
- mlflow/store/model_registry/sqlalchemy_store.py +1286 -0
- mlflow/store/tracking/__init__.py +23 -0
- mlflow/store/tracking/abstract_store.py +816 -0
- mlflow/store/tracking/dbmodels/__init__.py +0 -0
- mlflow/store/tracking/dbmodels/initial_models.py +243 -0
- mlflow/store/tracking/dbmodels/models.py +1073 -0
- mlflow/store/tracking/file_store.py +2438 -0
- mlflow/store/tracking/postgres_managed_identity.py +146 -0
- mlflow/store/tracking/rest_store.py +1131 -0
- mlflow/store/tracking/sqlalchemy_store.py +2785 -0
- mlflow/system_metrics/__init__.py +61 -0
- mlflow/system_metrics/metrics/__init__.py +0 -0
- mlflow/system_metrics/metrics/base_metrics_monitor.py +32 -0
- mlflow/system_metrics/metrics/cpu_monitor.py +23 -0
- mlflow/system_metrics/metrics/disk_monitor.py +21 -0
- mlflow/system_metrics/metrics/gpu_monitor.py +71 -0
- mlflow/system_metrics/metrics/network_monitor.py +34 -0
- mlflow/system_metrics/metrics/rocm_monitor.py +123 -0
- mlflow/system_metrics/system_metrics_monitor.py +198 -0
- mlflow/tracing/__init__.py +16 -0
- mlflow/tracing/assessment.py +356 -0
- mlflow/tracing/client.py +531 -0
- mlflow/tracing/config.py +125 -0
- mlflow/tracing/constant.py +105 -0
- mlflow/tracing/destination.py +81 -0
- mlflow/tracing/display/__init__.py +40 -0
- mlflow/tracing/display/display_handler.py +196 -0
- mlflow/tracing/export/async_export_queue.py +186 -0
- mlflow/tracing/export/inference_table.py +138 -0
- mlflow/tracing/export/mlflow_v3.py +137 -0
- mlflow/tracing/export/utils.py +70 -0
- mlflow/tracing/fluent.py +1417 -0
- mlflow/tracing/processor/base_mlflow.py +199 -0
- mlflow/tracing/processor/inference_table.py +175 -0
- mlflow/tracing/processor/mlflow_v3.py +47 -0
- mlflow/tracing/processor/otel.py +73 -0
- mlflow/tracing/provider.py +487 -0
- mlflow/tracing/trace_manager.py +200 -0
- mlflow/tracing/utils/__init__.py +616 -0
- mlflow/tracing/utils/artifact_utils.py +28 -0
- mlflow/tracing/utils/copy.py +55 -0
- mlflow/tracing/utils/environment.py +55 -0
- mlflow/tracing/utils/exception.py +21 -0
- mlflow/tracing/utils/once.py +35 -0
- mlflow/tracing/utils/otlp.py +63 -0
- mlflow/tracing/utils/processor.py +54 -0
- mlflow/tracing/utils/search.py +292 -0
- mlflow/tracing/utils/timeout.py +250 -0
- mlflow/tracing/utils/token.py +19 -0
- mlflow/tracing/utils/truncation.py +124 -0
- mlflow/tracing/utils/warning.py +76 -0
- mlflow/tracking/__init__.py +39 -0
- mlflow/tracking/_model_registry/__init__.py +1 -0
- mlflow/tracking/_model_registry/client.py +764 -0
- mlflow/tracking/_model_registry/fluent.py +853 -0
- mlflow/tracking/_model_registry/registry.py +67 -0
- mlflow/tracking/_model_registry/utils.py +251 -0
- mlflow/tracking/_tracking_service/__init__.py +0 -0
- mlflow/tracking/_tracking_service/client.py +883 -0
- mlflow/tracking/_tracking_service/registry.py +56 -0
- mlflow/tracking/_tracking_service/utils.py +275 -0
- mlflow/tracking/artifact_utils.py +179 -0
- mlflow/tracking/client.py +5900 -0
- mlflow/tracking/context/__init__.py +0 -0
- mlflow/tracking/context/abstract_context.py +35 -0
- mlflow/tracking/context/databricks_cluster_context.py +15 -0
- mlflow/tracking/context/databricks_command_context.py +15 -0
- mlflow/tracking/context/databricks_job_context.py +49 -0
- mlflow/tracking/context/databricks_notebook_context.py +41 -0
- mlflow/tracking/context/databricks_repo_context.py +43 -0
- mlflow/tracking/context/default_context.py +51 -0
- mlflow/tracking/context/git_context.py +32 -0
- mlflow/tracking/context/registry.py +98 -0
- mlflow/tracking/context/system_environment_context.py +15 -0
- mlflow/tracking/default_experiment/__init__.py +1 -0
- mlflow/tracking/default_experiment/abstract_context.py +43 -0
- mlflow/tracking/default_experiment/databricks_notebook_experiment_provider.py +44 -0
- mlflow/tracking/default_experiment/registry.py +75 -0
- mlflow/tracking/fluent.py +3595 -0
- mlflow/tracking/metric_value_conversion_utils.py +93 -0
- mlflow/tracking/multimedia.py +206 -0
- mlflow/tracking/registry.py +86 -0
- mlflow/tracking/request_auth/__init__.py +0 -0
- mlflow/tracking/request_auth/abstract_request_auth_provider.py +34 -0
- mlflow/tracking/request_auth/registry.py +60 -0
- mlflow/tracking/request_header/__init__.py +0 -0
- mlflow/tracking/request_header/abstract_request_header_provider.py +36 -0
- mlflow/tracking/request_header/databricks_request_header_provider.py +38 -0
- mlflow/tracking/request_header/default_request_header_provider.py +17 -0
- mlflow/tracking/request_header/registry.py +79 -0
- mlflow/transformers/__init__.py +2982 -0
- mlflow/transformers/flavor_config.py +258 -0
- mlflow/transformers/hub_utils.py +83 -0
- mlflow/transformers/llm_inference_utils.py +468 -0
- mlflow/transformers/model_io.py +301 -0
- mlflow/transformers/peft.py +51 -0
- mlflow/transformers/signature.py +183 -0
- mlflow/transformers/torch_utils.py +55 -0
- mlflow/types/__init__.py +21 -0
- mlflow/types/agent.py +270 -0
- mlflow/types/chat.py +240 -0
- mlflow/types/llm.py +935 -0
- mlflow/types/responses.py +139 -0
- mlflow/types/responses_helpers.py +416 -0
- mlflow/types/schema.py +1505 -0
- mlflow/types/type_hints.py +647 -0
- mlflow/types/utils.py +753 -0
- mlflow/utils/__init__.py +283 -0
- mlflow/utils/_capture_modules.py +256 -0
- mlflow/utils/_capture_transformers_modules.py +75 -0
- mlflow/utils/_spark_utils.py +201 -0
- mlflow/utils/_unity_catalog_oss_utils.py +97 -0
- mlflow/utils/_unity_catalog_utils.py +479 -0
- mlflow/utils/annotations.py +218 -0
- mlflow/utils/arguments_utils.py +16 -0
- mlflow/utils/async_logging/__init__.py +1 -0
- mlflow/utils/async_logging/async_artifacts_logging_queue.py +258 -0
- mlflow/utils/async_logging/async_logging_queue.py +366 -0
- mlflow/utils/async_logging/run_artifact.py +38 -0
- mlflow/utils/async_logging/run_batch.py +58 -0
- mlflow/utils/async_logging/run_operations.py +49 -0
- mlflow/utils/autologging_utils/__init__.py +737 -0
- mlflow/utils/autologging_utils/client.py +432 -0
- mlflow/utils/autologging_utils/config.py +33 -0
- mlflow/utils/autologging_utils/events.py +294 -0
- mlflow/utils/autologging_utils/logging_and_warnings.py +328 -0
- mlflow/utils/autologging_utils/metrics_queue.py +71 -0
- mlflow/utils/autologging_utils/safety.py +1104 -0
- mlflow/utils/autologging_utils/versioning.py +95 -0
- mlflow/utils/checkpoint_utils.py +206 -0
- mlflow/utils/class_utils.py +6 -0
- mlflow/utils/cli_args.py +257 -0
- mlflow/utils/conda.py +354 -0
- mlflow/utils/credentials.py +231 -0
- mlflow/utils/data_utils.py +17 -0
- mlflow/utils/databricks_utils.py +1436 -0
- mlflow/utils/docstring_utils.py +477 -0
- mlflow/utils/doctor.py +133 -0
- mlflow/utils/download_cloud_file_chunk.py +43 -0
- mlflow/utils/env_manager.py +16 -0
- mlflow/utils/env_pack.py +131 -0
- mlflow/utils/environment.py +1009 -0
- mlflow/utils/exception_utils.py +14 -0
- mlflow/utils/file_utils.py +978 -0
- mlflow/utils/git_utils.py +77 -0
- mlflow/utils/gorilla.py +797 -0
- mlflow/utils/import_hooks/__init__.py +363 -0
- mlflow/utils/lazy_load.py +51 -0
- mlflow/utils/logging_utils.py +168 -0
- mlflow/utils/mime_type_utils.py +58 -0
- mlflow/utils/mlflow_tags.py +103 -0
- mlflow/utils/model_utils.py +486 -0
- mlflow/utils/name_utils.py +346 -0
- mlflow/utils/nfs_on_spark.py +62 -0
- mlflow/utils/openai_utils.py +164 -0
- mlflow/utils/os.py +12 -0
- mlflow/utils/oss_registry_utils.py +29 -0
- mlflow/utils/plugins.py +17 -0
- mlflow/utils/process.py +182 -0
- mlflow/utils/promptlab_utils.py +146 -0
- mlflow/utils/proto_json_utils.py +743 -0
- mlflow/utils/pydantic_utils.py +54 -0
- mlflow/utils/request_utils.py +279 -0
- mlflow/utils/requirements_utils.py +704 -0
- mlflow/utils/rest_utils.py +673 -0
- mlflow/utils/search_logged_model_utils.py +127 -0
- mlflow/utils/search_utils.py +2111 -0
- mlflow/utils/secure_loading.py +221 -0
- mlflow/utils/security_validation.py +384 -0
- mlflow/utils/server_cli_utils.py +61 -0
- mlflow/utils/spark_utils.py +15 -0
- mlflow/utils/string_utils.py +138 -0
- mlflow/utils/thread_utils.py +63 -0
- mlflow/utils/time.py +54 -0
- mlflow/utils/timeout.py +42 -0
- mlflow/utils/uri.py +572 -0
- mlflow/utils/validation.py +662 -0
- mlflow/utils/virtualenv.py +458 -0
- mlflow/utils/warnings_utils.py +25 -0
- mlflow/utils/yaml_utils.py +179 -0
- mlflow/version.py +24 -0
@@ -0,0 +1,1171 @@
|
|
1
|
+
"""
|
2
|
+
The ``mlflow.pytorch`` module provides an API for logging and loading PyTorch models. This module
|
3
|
+
exports PyTorch models with the following flavors:
|
4
|
+
|
5
|
+
PyTorch (native) format
|
6
|
+
This is the main flavor that can be loaded back into PyTorch.
|
7
|
+
:py:mod:`mlflow.pyfunc`
|
8
|
+
Produced for use by generic pyfunc-based deployment tools and batch inference.
|
9
|
+
"""
|
10
|
+
|
11
|
+
import atexit
|
12
|
+
import importlib
|
13
|
+
import logging
|
14
|
+
import os
|
15
|
+
import posixpath
|
16
|
+
import shutil
|
17
|
+
from functools import partial
|
18
|
+
from typing import Any, Optional
|
19
|
+
|
20
|
+
import numpy as np
|
21
|
+
import pandas as pd
|
22
|
+
import yaml
|
23
|
+
from packaging.version import Version
|
24
|
+
|
25
|
+
import mlflow
|
26
|
+
from mlflow import pyfunc
|
27
|
+
from mlflow.environment_variables import MLFLOW_DEFAULT_PREDICTION_DEVICE
|
28
|
+
from mlflow.exceptions import MlflowException
|
29
|
+
from mlflow.ml_package_versions import _ML_PACKAGE_VERSIONS
|
30
|
+
from mlflow.models import Model, ModelSignature
|
31
|
+
from mlflow.models.model import MLMODEL_FILE_NAME
|
32
|
+
from mlflow.models.signature import _infer_signature_from_input_example
|
33
|
+
from mlflow.models.utils import ModelInputExample, _save_example
|
34
|
+
from mlflow.protos.databricks_pb2 import RESOURCE_DOES_NOT_EXIST
|
35
|
+
from mlflow.pytorch import pickle_module as mlflow_pytorch_pickle_module
|
36
|
+
from mlflow.tracking._model_registry import DEFAULT_AWAIT_MAX_SLEEP_SECONDS
|
37
|
+
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
|
38
|
+
from mlflow.utils.autologging_utils import autologging_integration, safe_patch
|
39
|
+
from mlflow.utils.checkpoint_utils import download_checkpoint_artifact
|
40
|
+
from mlflow.utils.docstring_utils import LOG_MODEL_PARAM_DOCS, format_docstring
|
41
|
+
from mlflow.utils.environment import (
|
42
|
+
_CONDA_ENV_FILE_NAME,
|
43
|
+
_CONSTRAINTS_FILE_NAME,
|
44
|
+
_PYTHON_ENV_FILE_NAME,
|
45
|
+
_REQUIREMENTS_FILE_NAME,
|
46
|
+
_mlflow_conda_env,
|
47
|
+
_process_conda_env,
|
48
|
+
_process_pip_requirements,
|
49
|
+
_PythonEnv,
|
50
|
+
_validate_env_arguments,
|
51
|
+
)
|
52
|
+
from mlflow.utils.file_utils import (
|
53
|
+
TempDir,
|
54
|
+
get_total_file_size,
|
55
|
+
write_to,
|
56
|
+
)
|
57
|
+
from mlflow.utils.model_utils import (
|
58
|
+
_add_code_from_conf_to_system_path,
|
59
|
+
_get_flavor_configuration,
|
60
|
+
_validate_and_copy_code_paths,
|
61
|
+
_validate_and_prepare_target_save_path,
|
62
|
+
)
|
63
|
+
from mlflow.utils.requirements_utils import _get_pinned_requirement
|
64
|
+
|
65
|
+
FLAVOR_NAME = "pytorch"
|
66
|
+
|
67
|
+
_SERIALIZED_TORCH_MODEL_FILE_NAME = "model.pth"
|
68
|
+
_TORCH_STATE_DICT_FILE_NAME = "state_dict.pth"
|
69
|
+
_PICKLE_MODULE_INFO_FILE_NAME = "pickle_module_info.txt"
|
70
|
+
_EXTRA_FILES_KEY = "extra_files"
|
71
|
+
_TORCH_CPU_DEVICE_NAME = "cpu"
|
72
|
+
_TORCH_DEFAULT_GPU_DEVICE_NAME = "cuda"
|
73
|
+
|
74
|
+
_logger = logging.getLogger(__name__)
|
75
|
+
|
76
|
+
MIN_REQ_VERSION = Version(_ML_PACKAGE_VERSIONS["pytorch-lightning"]["autologging"]["minimum"])
|
77
|
+
MAX_REQ_VERSION = Version(_ML_PACKAGE_VERSIONS["pytorch-lightning"]["autologging"]["maximum"])
|
78
|
+
|
79
|
+
|
80
|
+
_MODEL_DATA_SUBPATH = "data"
|
81
|
+
|
82
|
+
|
83
|
+
def get_default_pip_requirements():
|
84
|
+
"""
|
85
|
+
Returns:
|
86
|
+
A list of default pip requirements for MLflow Models produced by this flavor. Calls to
|
87
|
+
:func:`save_model()` and :func:`log_model()` produce a pip environment that, at minimum,
|
88
|
+
contains these requirements.
|
89
|
+
"""
|
90
|
+
return list(
|
91
|
+
map(
|
92
|
+
_get_pinned_requirement,
|
93
|
+
[
|
94
|
+
"torch",
|
95
|
+
# We include CloudPickle in the default environment because
|
96
|
+
# it's required by the default pickle module used by `save_model()`
|
97
|
+
# and `log_model()`: `mlflow.pytorch.pickle_module`.
|
98
|
+
"cloudpickle",
|
99
|
+
],
|
100
|
+
)
|
101
|
+
)
|
102
|
+
|
103
|
+
|
104
|
+
def get_default_conda_env():
|
105
|
+
"""
|
106
|
+
Returns:
|
107
|
+
The default Conda environment as a dictionary for MLflow Models produced by calls to
|
108
|
+
:func:`save_model()` and :func:`log_model()`.
|
109
|
+
|
110
|
+
.. code-block:: python
|
111
|
+
:caption: Example
|
112
|
+
|
113
|
+
import mlflow
|
114
|
+
|
115
|
+
# Log PyTorch model
|
116
|
+
with mlflow.start_run() as run:
|
117
|
+
mlflow.pytorch.log_model(model, name="model", signature=signature)
|
118
|
+
|
119
|
+
# Fetch the associated conda environment
|
120
|
+
env = mlflow.pytorch.get_default_conda_env()
|
121
|
+
print(f"conda env: {env}")
|
122
|
+
|
123
|
+
.. code-block:: text
|
124
|
+
:caption: Output
|
125
|
+
|
126
|
+
conda env {'name': 'mlflow-env',
|
127
|
+
'channels': ['conda-forge'],
|
128
|
+
'dependencies': ['python=3.8.15',
|
129
|
+
{'pip': ['torch==1.5.1',
|
130
|
+
'mlflow',
|
131
|
+
'cloudpickle==1.6.0']}]}
|
132
|
+
"""
|
133
|
+
return _mlflow_conda_env(additional_pip_deps=get_default_pip_requirements())
|
134
|
+
|
135
|
+
|
136
|
+
@format_docstring(LOG_MODEL_PARAM_DOCS.format(package_name="torch"))
|
137
|
+
def log_model(
|
138
|
+
pytorch_model,
|
139
|
+
artifact_path: Optional[str] = None,
|
140
|
+
conda_env=None,
|
141
|
+
code_paths=None,
|
142
|
+
pickle_module=None,
|
143
|
+
registered_model_name=None,
|
144
|
+
signature: ModelSignature = None,
|
145
|
+
input_example: ModelInputExample = None,
|
146
|
+
await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS,
|
147
|
+
extra_files=None,
|
148
|
+
pip_requirements=None,
|
149
|
+
extra_pip_requirements=None,
|
150
|
+
metadata=None,
|
151
|
+
name: Optional[str] = None,
|
152
|
+
params: Optional[dict[str, Any]] = None,
|
153
|
+
tags: Optional[dict[str, Any]] = None,
|
154
|
+
model_type: Optional[str] = None,
|
155
|
+
step: int = 0,
|
156
|
+
model_id: Optional[str] = None,
|
157
|
+
**kwargs,
|
158
|
+
):
|
159
|
+
"""
|
160
|
+
Log a PyTorch model as an MLflow artifact for the current run.
|
161
|
+
|
162
|
+
.. warning:: Log the model with a signature to avoid inference errors.
|
163
|
+
If the model is logged without a signature, the MLflow Model Server relies on the
|
164
|
+
default inferred data type from NumPy. However, PyTorch often expects different
|
165
|
+
defaults, particularly when parsing floats. You must include the signature to ensure
|
166
|
+
that the model is logged with the correct data type so that the MLflow model server
|
167
|
+
can correctly provide valid input.
|
168
|
+
|
169
|
+
Args:
|
170
|
+
pytorch_model: PyTorch model to be saved. Can be either an eager model (subclass of
|
171
|
+
``torch.nn.Module``) or scripted model prepared via ``torch.jit.script`` or
|
172
|
+
``torch.jit.trace``.
|
173
|
+
|
174
|
+
The model accept a single ``torch.FloatTensor`` as input and produce a single output
|
175
|
+
tensor.
|
176
|
+
|
177
|
+
If saving an eager model, any code dependencies of the model's class, including the
|
178
|
+
class definition itself, should be included in one of the following locations:
|
179
|
+
|
180
|
+
- The package(s) listed in the model's Conda environment, specified by the
|
181
|
+
``conda_env`` parameter.
|
182
|
+
- One or more of the files specified by the ``code_paths`` parameter.
|
183
|
+
artifact_path: Deprecated. Use `name` instead.
|
184
|
+
conda_env: {{ conda_env }}
|
185
|
+
code_paths: {{ code_paths }}
|
186
|
+
pickle_module: The module that PyTorch should use to serialize ("pickle") the specified
|
187
|
+
``pytorch_model``. This is passed as the ``pickle_module`` parameter to
|
188
|
+
``torch.save()``. By default, this module is also used to deserialize ("unpickle") the
|
189
|
+
PyTorch model at load time.
|
190
|
+
registered_model_name: If given, create a model version under ``registered_model_name``,
|
191
|
+
also create a registered model if one with the given name does not exist.
|
192
|
+
signature: {{ signature }}
|
193
|
+
input_example: {{ input_example }}
|
194
|
+
await_registration_for: Number of seconds to wait for the model version to finish
|
195
|
+
being created and is in ``READY`` status. By default, the function waits for five
|
196
|
+
minutes. Specify 0 or None to skip waiting.
|
197
|
+
|
198
|
+
extra_files: A list containing the paths to corresponding extra files, if ``None``, no
|
199
|
+
extra files are added to the model. Remote URIs are resolved to absolute filesystem
|
200
|
+
paths. For example, consider the following ``extra_files`` list:
|
201
|
+
|
202
|
+
.. code-block:: python
|
203
|
+
|
204
|
+
extra_files = ["s3://my-bucket/path/to/my_file1", "s3://my-bucket/path/to/my_file2"]
|
205
|
+
|
206
|
+
In this case, the ``"my_file1 & my_file2"`` extra file is downloaded from S3.
|
207
|
+
|
208
|
+
pip_requirements: {{ pip_requirements }}
|
209
|
+
extra_pip_requirements: {{ extra_pip_requirements }}
|
210
|
+
metadata: {{ metadata }}
|
211
|
+
name: {{ name }}
|
212
|
+
params: {{ params }}
|
213
|
+
tags: {{ tags }}
|
214
|
+
model_type: {{ model_type }}
|
215
|
+
step: {{ step }}
|
216
|
+
model_id: {{ model_id }}
|
217
|
+
kwargs: kwargs to pass to ``torch.save`` method.
|
218
|
+
|
219
|
+
Returns:
|
220
|
+
A :py:class:`ModelInfo <mlflow.models.model.ModelInfo>` instance that contains the
|
221
|
+
metadata of the logged model.
|
222
|
+
|
223
|
+
.. code-block:: python
|
224
|
+
:caption: Example
|
225
|
+
|
226
|
+
import numpy as np
|
227
|
+
import torch
|
228
|
+
import mlflow
|
229
|
+
from mlflow import MlflowClient
|
230
|
+
from mlflow.models import infer_signature
|
231
|
+
|
232
|
+
# Define model, loss, and optimizer
|
233
|
+
model = nn.Linear(1, 1)
|
234
|
+
criterion = torch.nn.MSELoss()
|
235
|
+
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
|
236
|
+
|
237
|
+
# Create training data with relationship y = 2X
|
238
|
+
X = torch.arange(1.0, 26.0).reshape(-1, 1)
|
239
|
+
y = X * 2
|
240
|
+
|
241
|
+
# Training loop
|
242
|
+
epochs = 250
|
243
|
+
for epoch in range(epochs):
|
244
|
+
# Forward pass: Compute predicted y by passing X to the model
|
245
|
+
y_pred = model(X)
|
246
|
+
|
247
|
+
# Compute the loss
|
248
|
+
loss = criterion(y_pred, y)
|
249
|
+
|
250
|
+
# Zero gradients, perform a backward pass, and update the weights.
|
251
|
+
optimizer.zero_grad()
|
252
|
+
loss.backward()
|
253
|
+
optimizer.step()
|
254
|
+
|
255
|
+
# Create model signature
|
256
|
+
signature = infer_signature(X.numpy(), model(X).detach().numpy())
|
257
|
+
|
258
|
+
# Log the model
|
259
|
+
with mlflow.start_run() as run:
|
260
|
+
mlflow.pytorch.log_model(model, name="model")
|
261
|
+
|
262
|
+
# convert to scripted model and log the model
|
263
|
+
scripted_pytorch_model = torch.jit.script(model)
|
264
|
+
mlflow.pytorch.log_model(scripted_pytorch_model, name="scripted_model")
|
265
|
+
|
266
|
+
# Fetch the logged model artifacts
|
267
|
+
print(f"run_id: {run.info.run_id}")
|
268
|
+
for artifact_path in ["model/data", "scripted_model/data"]:
|
269
|
+
artifacts = [
|
270
|
+
f.path for f in MlflowClient().list_artifacts(run.info.run_id, artifact_path)
|
271
|
+
]
|
272
|
+
print(f"artifacts: {artifacts}")
|
273
|
+
|
274
|
+
.. code-block:: text
|
275
|
+
:caption: Output
|
276
|
+
|
277
|
+
run_id: 1a1ec9e413ce48e9abf9aec20efd6f71
|
278
|
+
artifacts: ['model/data/model.pth',
|
279
|
+
'model/data/pickle_module_info.txt']
|
280
|
+
artifacts: ['scripted_model/data/model.pth',
|
281
|
+
'scripted_model/data/pickle_module_info.txt']
|
282
|
+
|
283
|
+
.. figure:: ../_static/images/pytorch_logged_models.png
|
284
|
+
|
285
|
+
PyTorch logged models
|
286
|
+
"""
|
287
|
+
pickle_module = pickle_module or mlflow_pytorch_pickle_module
|
288
|
+
return Model.log(
|
289
|
+
artifact_path=artifact_path,
|
290
|
+
name=name,
|
291
|
+
flavor=mlflow.pytorch,
|
292
|
+
pytorch_model=pytorch_model,
|
293
|
+
conda_env=conda_env,
|
294
|
+
code_paths=code_paths,
|
295
|
+
pickle_module=pickle_module,
|
296
|
+
registered_model_name=registered_model_name,
|
297
|
+
signature=signature,
|
298
|
+
input_example=input_example,
|
299
|
+
await_registration_for=await_registration_for,
|
300
|
+
extra_files=extra_files,
|
301
|
+
pip_requirements=pip_requirements,
|
302
|
+
extra_pip_requirements=extra_pip_requirements,
|
303
|
+
metadata=metadata,
|
304
|
+
params=params,
|
305
|
+
tags=tags,
|
306
|
+
model_type=model_type,
|
307
|
+
step=step,
|
308
|
+
model_id=model_id,
|
309
|
+
**kwargs,
|
310
|
+
)
|
311
|
+
|
312
|
+
|
313
|
+
@format_docstring(LOG_MODEL_PARAM_DOCS.format(package_name="torch"))
|
314
|
+
def save_model(
|
315
|
+
pytorch_model,
|
316
|
+
path,
|
317
|
+
conda_env=None,
|
318
|
+
mlflow_model=None,
|
319
|
+
code_paths=None,
|
320
|
+
pickle_module=None,
|
321
|
+
signature: ModelSignature = None,
|
322
|
+
input_example: ModelInputExample = None,
|
323
|
+
extra_files=None,
|
324
|
+
pip_requirements=None,
|
325
|
+
extra_pip_requirements=None,
|
326
|
+
metadata=None,
|
327
|
+
**kwargs,
|
328
|
+
):
|
329
|
+
"""
|
330
|
+
Save a PyTorch model to a path on the local file system.
|
331
|
+
|
332
|
+
Args:
|
333
|
+
pytorch_model: PyTorch model to be saved. Can be either an eager model (subclass of
|
334
|
+
``torch.nn.Module``) or a scripted model prepared via ``torch.jit.script`` or
|
335
|
+
``torch.jit.trace``.
|
336
|
+
|
337
|
+
To save an eager model, any code dependencies of the model's class, including the class
|
338
|
+
definition itself, should be included in one of the following locations:
|
339
|
+
|
340
|
+
- The package(s) listed in the model's Conda environment, specified by the
|
341
|
+
``conda_env`` parameter.
|
342
|
+
- One or more of the files specified by the ``code_paths`` parameter.
|
343
|
+
|
344
|
+
path: Local path where the model is to be saved.
|
345
|
+
conda_env: {{ conda_env }}
|
346
|
+
mlflow_model: :py:mod:`mlflow.models.Model` this flavor is being added to.
|
347
|
+
code_paths: {{ code_paths }}
|
348
|
+
pickle_module: The module that PyTorch should use to serialize ("pickle") the specified
|
349
|
+
``pytorch_model``. This is passed as the ``pickle_module`` parameter to
|
350
|
+
``torch.save()``. By default, this module is also used to deserialize ("unpickle") the
|
351
|
+
model at loading time.
|
352
|
+
signature: {{ signature }}
|
353
|
+
input_example: {{ input_example }}
|
354
|
+
|
355
|
+
extra_files: A list containing the paths to corresponding extra files. Remote URIs
|
356
|
+
are resolved to absolute filesystem paths.
|
357
|
+
For example, consider the following ``extra_files`` list -
|
358
|
+
|
359
|
+
extra_files = ["s3://my-bucket/path/to/my_file1", "s3://my-bucket/path/to/my_file2"]
|
360
|
+
|
361
|
+
In this case, the ``"my_file1 & my_file2"`` extra file is downloaded from S3.
|
362
|
+
|
363
|
+
If ``None``, no extra files are added to the model.
|
364
|
+
pip_requirements: {{ pip_requirements }}
|
365
|
+
extra_pip_requirements: {{ extra_pip_requirements }}
|
366
|
+
metadata:{{ metadata }}
|
367
|
+
kwargs: kwargs to pass to ``torch.save`` method.
|
368
|
+
|
369
|
+
.. code-block:: python
|
370
|
+
:caption: Example
|
371
|
+
|
372
|
+
import os
|
373
|
+
import mlflow
|
374
|
+
import torch
|
375
|
+
|
376
|
+
|
377
|
+
model = nn.Linear(1, 1)
|
378
|
+
|
379
|
+
# Save PyTorch models to current working directory
|
380
|
+
with mlflow.start_run() as run:
|
381
|
+
mlflow.pytorch.save_model(model, "model")
|
382
|
+
|
383
|
+
# Convert to a scripted model and save it
|
384
|
+
scripted_pytorch_model = torch.jit.script(model)
|
385
|
+
mlflow.pytorch.save_model(scripted_pytorch_model, "scripted_model")
|
386
|
+
|
387
|
+
# Load each saved model for inference
|
388
|
+
for model_path in ["model", "scripted_model"]:
|
389
|
+
model_uri = f"{os.getcwd()}/{model_path}"
|
390
|
+
loaded_model = mlflow.pytorch.load_model(model_uri)
|
391
|
+
print(f"Loaded {model_path}:")
|
392
|
+
for x in [6.0, 8.0, 12.0, 30.0]:
|
393
|
+
X = torch.Tensor([[x]])
|
394
|
+
y_pred = loaded_model(X)
|
395
|
+
print(f"predict X: {x}, y_pred: {y_pred.data.item():.2f}")
|
396
|
+
print("--")
|
397
|
+
|
398
|
+
.. code-block:: text
|
399
|
+
:caption: Output
|
400
|
+
|
401
|
+
Loaded model:
|
402
|
+
predict X: 6.0, y_pred: 11.90
|
403
|
+
predict X: 8.0, y_pred: 15.92
|
404
|
+
predict X: 12.0, y_pred: 23.96
|
405
|
+
predict X: 30.0, y_pred: 60.13
|
406
|
+
--
|
407
|
+
Loaded scripted_model:
|
408
|
+
predict X: 6.0, y_pred: 11.90
|
409
|
+
predict X: 8.0, y_pred: 15.92
|
410
|
+
predict X: 12.0, y_pred: 23.96
|
411
|
+
predict X: 30.0, y_pred: 60.13
|
412
|
+
|
413
|
+
"""
|
414
|
+
import torch
|
415
|
+
|
416
|
+
_validate_env_arguments(conda_env, pip_requirements, extra_pip_requirements)
|
417
|
+
|
418
|
+
pickle_module = pickle_module or mlflow_pytorch_pickle_module
|
419
|
+
|
420
|
+
if not isinstance(pytorch_model, torch.nn.Module):
|
421
|
+
raise TypeError("Argument 'pytorch_model' should be a torch.nn.Module")
|
422
|
+
path = os.path.abspath(path)
|
423
|
+
_validate_and_prepare_target_save_path(path)
|
424
|
+
|
425
|
+
if mlflow_model is None:
|
426
|
+
mlflow_model = Model()
|
427
|
+
saved_example = _save_example(mlflow_model, input_example, path)
|
428
|
+
|
429
|
+
if signature is None and saved_example is not None:
|
430
|
+
wrapped_model = _PyTorchWrapper(pytorch_model, device="cpu")
|
431
|
+
signature = _infer_signature_from_input_example(saved_example, wrapped_model)
|
432
|
+
elif signature is False:
|
433
|
+
signature = None
|
434
|
+
|
435
|
+
if signature is not None:
|
436
|
+
mlflow_model.signature = signature
|
437
|
+
if metadata is not None:
|
438
|
+
mlflow_model.metadata = metadata
|
439
|
+
|
440
|
+
code_dir_subpath = _validate_and_copy_code_paths(code_paths, path)
|
441
|
+
|
442
|
+
model_data_subpath = _MODEL_DATA_SUBPATH
|
443
|
+
model_data_path = os.path.join(path, model_data_subpath)
|
444
|
+
os.makedirs(model_data_path)
|
445
|
+
|
446
|
+
# Persist the pickle module name as a file in the model's `data` directory. This is necessary
|
447
|
+
# because the `data` directory is the only available parameter to `_load_pyfunc`, and it
|
448
|
+
# does not contain the MLmodel configuration; therefore, it is not sufficient to place
|
449
|
+
# the module name in the MLmodel
|
450
|
+
#
|
451
|
+
# TODO: Stop persisting this information to the filesystem once we have a mechanism for
|
452
|
+
# supplying the MLmodel configuration to `mlflow.pytorch._load_pyfunc`
|
453
|
+
pickle_module_path = os.path.join(model_data_path, _PICKLE_MODULE_INFO_FILE_NAME)
|
454
|
+
with open(pickle_module_path, "w") as f:
|
455
|
+
f.write(pickle_module.__name__)
|
456
|
+
# Save pytorch model
|
457
|
+
model_path = os.path.join(model_data_path, _SERIALIZED_TORCH_MODEL_FILE_NAME)
|
458
|
+
if isinstance(pytorch_model, torch.jit.ScriptModule):
|
459
|
+
torch.jit.ScriptModule.save(pytorch_model, model_path)
|
460
|
+
else:
|
461
|
+
torch.save(pytorch_model, model_path, pickle_module=pickle_module, **kwargs)
|
462
|
+
|
463
|
+
torchserve_artifacts_config = {}
|
464
|
+
|
465
|
+
if extra_files:
|
466
|
+
torchserve_artifacts_config[_EXTRA_FILES_KEY] = []
|
467
|
+
if not isinstance(extra_files, list):
|
468
|
+
raise TypeError("Extra files argument should be a list")
|
469
|
+
|
470
|
+
with TempDir() as tmp_extra_files_dir:
|
471
|
+
for extra_file in extra_files:
|
472
|
+
_download_artifact_from_uri(
|
473
|
+
artifact_uri=extra_file, output_path=tmp_extra_files_dir.path()
|
474
|
+
)
|
475
|
+
rel_path = posixpath.join(_EXTRA_FILES_KEY, os.path.basename(extra_file))
|
476
|
+
torchserve_artifacts_config[_EXTRA_FILES_KEY].append({"path": rel_path})
|
477
|
+
shutil.move(
|
478
|
+
tmp_extra_files_dir.path(),
|
479
|
+
posixpath.join(path, _EXTRA_FILES_KEY),
|
480
|
+
)
|
481
|
+
|
482
|
+
mlflow_model.add_flavor(
|
483
|
+
FLAVOR_NAME,
|
484
|
+
model_data=model_data_subpath,
|
485
|
+
pytorch_version=str(torch.__version__),
|
486
|
+
code=code_dir_subpath,
|
487
|
+
**torchserve_artifacts_config,
|
488
|
+
)
|
489
|
+
pyfunc.add_to_model(
|
490
|
+
mlflow_model,
|
491
|
+
loader_module="mlflow.pytorch",
|
492
|
+
data=model_data_subpath,
|
493
|
+
pickle_module_name=pickle_module.__name__,
|
494
|
+
code=code_dir_subpath,
|
495
|
+
conda_env=_CONDA_ENV_FILE_NAME,
|
496
|
+
python_env=_PYTHON_ENV_FILE_NAME,
|
497
|
+
model_config={"device": None},
|
498
|
+
)
|
499
|
+
if size := get_total_file_size(path):
|
500
|
+
mlflow_model.model_size_bytes = size
|
501
|
+
mlflow_model.save(os.path.join(path, MLMODEL_FILE_NAME))
|
502
|
+
|
503
|
+
if conda_env is None:
|
504
|
+
if pip_requirements is None:
|
505
|
+
default_reqs = get_default_pip_requirements()
|
506
|
+
# To ensure `_load_pyfunc` can successfully load the model during the dependency
|
507
|
+
# inference, `mlflow_model.save` must be called beforehand to save an MLmodel file.
|
508
|
+
inferred_reqs = mlflow.models.infer_pip_requirements(
|
509
|
+
model_data_path,
|
510
|
+
FLAVOR_NAME,
|
511
|
+
fallback=default_reqs,
|
512
|
+
)
|
513
|
+
default_reqs = sorted(set(inferred_reqs).union(default_reqs))
|
514
|
+
else:
|
515
|
+
default_reqs = None
|
516
|
+
conda_env, pip_requirements, pip_constraints = _process_pip_requirements(
|
517
|
+
default_reqs,
|
518
|
+
pip_requirements,
|
519
|
+
extra_pip_requirements,
|
520
|
+
)
|
521
|
+
else:
|
522
|
+
conda_env, pip_requirements, pip_constraints = _process_conda_env(conda_env)
|
523
|
+
|
524
|
+
with open(os.path.join(path, _CONDA_ENV_FILE_NAME), "w") as f:
|
525
|
+
yaml.safe_dump(conda_env, stream=f, default_flow_style=False)
|
526
|
+
|
527
|
+
# Save `constraints.txt` if necessary
|
528
|
+
if pip_constraints:
|
529
|
+
write_to(os.path.join(path, _CONSTRAINTS_FILE_NAME), "\n".join(pip_constraints))
|
530
|
+
|
531
|
+
# Save `requirements.txt`
|
532
|
+
write_to(os.path.join(path, _REQUIREMENTS_FILE_NAME), "\n".join(pip_requirements))
|
533
|
+
|
534
|
+
_PythonEnv.current().to_yaml(os.path.join(path, _PYTHON_ENV_FILE_NAME))
|
535
|
+
|
536
|
+
|
537
|
+
def _load_model(path, device=None, **kwargs):
|
538
|
+
"""
|
539
|
+
Args:
|
540
|
+
path: The path to a serialized PyTorch model.
|
541
|
+
device: If specified, load the model on the specified device.
|
542
|
+
kwargs: Additional kwargs to pass to the PyTorch ``torch.load`` function.
|
543
|
+
"""
|
544
|
+
import torch
|
545
|
+
|
546
|
+
if os.path.isdir(path):
|
547
|
+
# `path` is a directory containing a serialized PyTorch model and a text file containing
|
548
|
+
# information about the pickle module that should be used by PyTorch to load it
|
549
|
+
model_path = os.path.join(path, "model.pth")
|
550
|
+
pickle_module_path = os.path.join(path, _PICKLE_MODULE_INFO_FILE_NAME)
|
551
|
+
with open(pickle_module_path) as f:
|
552
|
+
pickle_module_name = f.read()
|
553
|
+
if "pickle_module" in kwargs and kwargs["pickle_module"].__name__ != pickle_module_name:
|
554
|
+
_logger.warning(
|
555
|
+
"Attempting to load the PyTorch model with a pickle module, '%s', that does not"
|
556
|
+
" match the pickle module that was used to save the model: '%s'.",
|
557
|
+
kwargs["pickle_module"].__name__,
|
558
|
+
pickle_module_name,
|
559
|
+
)
|
560
|
+
else:
|
561
|
+
try:
|
562
|
+
kwargs["pickle_module"] = importlib.import_module(pickle_module_name)
|
563
|
+
except ImportError as exc:
|
564
|
+
raise MlflowException(
|
565
|
+
message=(
|
566
|
+
"Failed to import the pickle module that was used to save the PyTorch"
|
567
|
+
f" model. Pickle module name: `{pickle_module_name}`"
|
568
|
+
),
|
569
|
+
error_code=RESOURCE_DOES_NOT_EXIST,
|
570
|
+
) from exc
|
571
|
+
|
572
|
+
else:
|
573
|
+
model_path = path
|
574
|
+
|
575
|
+
if Version(torch.__version__) >= Version("1.5.0"):
|
576
|
+
pytorch_model = torch.load(model_path, **kwargs)
|
577
|
+
else:
|
578
|
+
try:
|
579
|
+
# load the model as an eager model.
|
580
|
+
pytorch_model = torch.load(model_path, **kwargs)
|
581
|
+
except Exception:
|
582
|
+
# If fails, assume the model as a scripted model
|
583
|
+
# `torch.jit.load` does not accept `pickle_module`.
|
584
|
+
kwargs.pop("pickle_module", None)
|
585
|
+
pytorch_model = torch.jit.load(model_path, **kwargs)
|
586
|
+
|
587
|
+
pytorch_model.eval()
|
588
|
+
if device:
|
589
|
+
pytorch_model.to(device=device)
|
590
|
+
return pytorch_model
|
591
|
+
|
592
|
+
|
593
|
+
def load_model(model_uri, dst_path=None, **kwargs):
|
594
|
+
"""
|
595
|
+
Load a PyTorch model from a local file or a run.
|
596
|
+
|
597
|
+
Args:
|
598
|
+
model_uri: The location, in URI format, of the MLflow model, for example:
|
599
|
+
|
600
|
+
- ``/Users/me/path/to/local/model``
|
601
|
+
- ``relative/path/to/local/model``
|
602
|
+
- ``s3://my_bucket/path/to/model``
|
603
|
+
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
|
604
|
+
- ``models:/<model_name>/<model_version>``
|
605
|
+
- ``models:/<model_name>/<stage>``
|
606
|
+
|
607
|
+
For more information about supported URI schemes, see `Referencing Artifacts \
|
608
|
+
<https://www.mlflow.org/docs/latest/concepts.html#artifact-locations>`_.
|
609
|
+
dst_path: The local filesystem path to which to download the model artifact.
|
610
|
+
This directory must already exist. If unspecified, a local output path will be created.
|
611
|
+
kwargs: kwargs to pass to ``torch.load`` method.
|
612
|
+
|
613
|
+
Returns:
|
614
|
+
A PyTorch model.
|
615
|
+
|
616
|
+
.. code-block:: python
|
617
|
+
:caption: Example
|
618
|
+
|
619
|
+
import torch
|
620
|
+
import mlflow.pytorch
|
621
|
+
|
622
|
+
|
623
|
+
model = nn.Linear(1, 1)
|
624
|
+
|
625
|
+
# Log the model
|
626
|
+
with mlflow.start_run() as run:
|
627
|
+
mlflow.pytorch.log_model(model, name="model")
|
628
|
+
|
629
|
+
# Inference after loading the logged model
|
630
|
+
model_uri = f"runs:/{run.info.run_id}/model"
|
631
|
+
loaded_model = mlflow.pytorch.load_model(model_uri)
|
632
|
+
for x in [4.0, 6.0, 30.0]:
|
633
|
+
X = torch.Tensor([[x]])
|
634
|
+
y_pred = loaded_model(X)
|
635
|
+
print(f"predict X: {x}, y_pred: {y_pred.data.item():.2f}")
|
636
|
+
|
637
|
+
.. code-block:: text
|
638
|
+
:caption: Output
|
639
|
+
|
640
|
+
predict X: 4.0, y_pred: 7.57
|
641
|
+
predict X: 6.0, y_pred: 11.64
|
642
|
+
predict X: 30.0, y_pred: 60.48
|
643
|
+
"""
|
644
|
+
import torch
|
645
|
+
|
646
|
+
local_model_path = _download_artifact_from_uri(artifact_uri=model_uri, output_path=dst_path)
|
647
|
+
pytorch_conf = _get_flavor_configuration(model_path=local_model_path, flavor_name=FLAVOR_NAME)
|
648
|
+
_add_code_from_conf_to_system_path(local_model_path, pytorch_conf)
|
649
|
+
|
650
|
+
if torch.__version__ != pytorch_conf["pytorch_version"]:
|
651
|
+
_logger.warning(
|
652
|
+
"Stored model version '%s' does not match installed PyTorch version '%s'",
|
653
|
+
pytorch_conf["pytorch_version"],
|
654
|
+
torch.__version__,
|
655
|
+
)
|
656
|
+
torch_model_artifacts_path = os.path.join(local_model_path, pytorch_conf["model_data"])
|
657
|
+
return _load_model(path=torch_model_artifacts_path, **kwargs)
|
658
|
+
|
659
|
+
|
660
|
+
def _load_pyfunc(path, model_config=None, weights_only=False): # noqa: D417
|
661
|
+
"""
|
662
|
+
Load PyFunc implementation. Called by ``pyfunc.load_model``.
|
663
|
+
|
664
|
+
Args:
|
665
|
+
path: Local filesystem path to the MLflow Model with the ``pytorch`` flavor.
|
666
|
+
"""
|
667
|
+
import torch
|
668
|
+
|
669
|
+
device = model_config.get("device", None) if model_config else None
|
670
|
+
# if CUDA is available, we use the default CUDA device.
|
671
|
+
# To force inference to the CPU when the GPU is available, please set
|
672
|
+
# MLFLOW_DEFAULT_PREDICTION_DEVICE to "cpu"
|
673
|
+
# If a specific non-default device is passed in, we continue to respect that.
|
674
|
+
if device is None:
|
675
|
+
if MLFLOW_DEFAULT_PREDICTION_DEVICE.get():
|
676
|
+
device = MLFLOW_DEFAULT_PREDICTION_DEVICE.get()
|
677
|
+
elif torch.cuda.is_available():
|
678
|
+
device = _TORCH_DEFAULT_GPU_DEVICE_NAME
|
679
|
+
else:
|
680
|
+
device = _TORCH_CPU_DEVICE_NAME
|
681
|
+
|
682
|
+
# in pytorch >= 2.6.0, the `weights_only` kwarg default has been changed from
|
683
|
+
# `False` to `True`. this can cause pickle deserialization errors when loading
|
684
|
+
# models, unless the model classes have been explicitly marked as safe using
|
685
|
+
# `torch.serialization.add_safe_globals()`
|
686
|
+
if Version(torch.__version__) >= Version("2.6.0"):
|
687
|
+
return _PyTorchWrapper(
|
688
|
+
_load_model(path, device=device, weights_only=weights_only), device=device
|
689
|
+
)
|
690
|
+
|
691
|
+
return _PyTorchWrapper(_load_model(path, device=device), device=device)
|
692
|
+
|
693
|
+
|
694
|
+
class _PyTorchWrapper:
|
695
|
+
"""
|
696
|
+
Wrapper class that creates a predict function such that
|
697
|
+
predict(data: pd.DataFrame) -> model's output as pd.DataFrame (pandas DataFrame)
|
698
|
+
"""
|
699
|
+
|
700
|
+
def __init__(self, pytorch_model, device):
|
701
|
+
self.pytorch_model = pytorch_model
|
702
|
+
self.device = device
|
703
|
+
|
704
|
+
def get_raw_model(self):
|
705
|
+
"""
|
706
|
+
Returns the underlying model.
|
707
|
+
"""
|
708
|
+
return self.pytorch_model
|
709
|
+
|
710
|
+
def predict(self, data, params: Optional[dict[str, Any]] = None):
|
711
|
+
"""
|
712
|
+
Args:
|
713
|
+
data: Model input data.
|
714
|
+
params: Additional parameters to pass to the model for inference.
|
715
|
+
|
716
|
+
Returns:
|
717
|
+
Model predictions.
|
718
|
+
"""
|
719
|
+
import torch
|
720
|
+
|
721
|
+
if params and "device" in params:
|
722
|
+
raise ValueError(
|
723
|
+
"device' can no longer be specified as an inference parameter. "
|
724
|
+
"It must be specified at load time. "
|
725
|
+
"Please specify the device at load time, for example: "
|
726
|
+
"`mlflow.pyfunc.load_model(model_uri, model_config={'device': 'cuda'})`."
|
727
|
+
)
|
728
|
+
|
729
|
+
if isinstance(data, pd.DataFrame):
|
730
|
+
inp_data = data.values.astype(np.float32)
|
731
|
+
elif isinstance(data, np.ndarray):
|
732
|
+
inp_data = data
|
733
|
+
elif isinstance(data, (list, dict)):
|
734
|
+
raise TypeError(
|
735
|
+
"The PyTorch flavor does not support List or Dict input types. "
|
736
|
+
"Please use a pandas.DataFrame or a numpy.ndarray"
|
737
|
+
)
|
738
|
+
else:
|
739
|
+
raise TypeError("Input data should be pandas.DataFrame or numpy.ndarray")
|
740
|
+
|
741
|
+
device = self.device
|
742
|
+
with torch.no_grad():
|
743
|
+
input_tensor = torch.from_numpy(inp_data).to(device)
|
744
|
+
preds = self.pytorch_model(input_tensor, **(params or {}))
|
745
|
+
# if the predictions happened on a remote device, copy them back to
|
746
|
+
# the host CPU for processing
|
747
|
+
if device != _TORCH_CPU_DEVICE_NAME:
|
748
|
+
preds = preds.to(_TORCH_CPU_DEVICE_NAME)
|
749
|
+
if not isinstance(preds, torch.Tensor):
|
750
|
+
raise TypeError(
|
751
|
+
"Expected PyTorch model to output a single output tensor, "
|
752
|
+
f"but got output of type '{type(preds)}'"
|
753
|
+
)
|
754
|
+
if isinstance(data, pd.DataFrame):
|
755
|
+
predicted = pd.DataFrame(preds.numpy())
|
756
|
+
predicted.index = data.index
|
757
|
+
else:
|
758
|
+
predicted = preds.numpy()
|
759
|
+
return predicted
|
760
|
+
|
761
|
+
|
762
|
+
def log_state_dict(state_dict, artifact_path, **kwargs):
|
763
|
+
"""
|
764
|
+
Log a state_dict as an MLflow artifact for the current run.
|
765
|
+
|
766
|
+
.. warning::
|
767
|
+
This function just logs a state_dict as an artifact and doesn't generate
|
768
|
+
an :ref:`MLflow Model <models>`.
|
769
|
+
|
770
|
+
Args:
|
771
|
+
state_dict: state_dict to be saved.
|
772
|
+
artifact_path: Run-relative artifact path.
|
773
|
+
kwargs: kwargs to pass to ``torch.save``.
|
774
|
+
|
775
|
+
.. code-block:: python
|
776
|
+
:caption: Example
|
777
|
+
|
778
|
+
# Log a model as a state_dict
|
779
|
+
with mlflow.start_run():
|
780
|
+
state_dict = model.state_dict()
|
781
|
+
mlflow.pytorch.log_state_dict(state_dict, artifact_path="model")
|
782
|
+
|
783
|
+
# Log a checkpoint as a state_dict
|
784
|
+
with mlflow.start_run():
|
785
|
+
state_dict = {
|
786
|
+
"model": model.state_dict(),
|
787
|
+
"optimizer": optimizer.state_dict(),
|
788
|
+
"epoch": epoch,
|
789
|
+
"loss": loss,
|
790
|
+
}
|
791
|
+
mlflow.pytorch.log_state_dict(state_dict, artifact_path="checkpoint")
|
792
|
+
"""
|
793
|
+
|
794
|
+
with TempDir() as tmp:
|
795
|
+
local_path = tmp.path()
|
796
|
+
save_state_dict(state_dict=state_dict, path=local_path, **kwargs)
|
797
|
+
mlflow.log_artifacts(local_path, artifact_path)
|
798
|
+
|
799
|
+
|
800
|
+
def save_state_dict(state_dict, path, **kwargs):
|
801
|
+
"""
|
802
|
+
Save a state_dict to a path on the local file system
|
803
|
+
|
804
|
+
Args:
|
805
|
+
state_dict: state_dict to be saved.
|
806
|
+
path: Local path where the state_dict is to be saved.
|
807
|
+
kwargs: kwargs to pass to ``torch.save``.
|
808
|
+
"""
|
809
|
+
import torch
|
810
|
+
|
811
|
+
# The object type check here aims to prevent a scenario where a user accidentally passees
|
812
|
+
# a model instead of a state_dict and `torch.save` (which accepts both model and state_dict)
|
813
|
+
# successfully completes, leaving the user unaware of the mistake.
|
814
|
+
if not isinstance(state_dict, dict):
|
815
|
+
raise TypeError(
|
816
|
+
"Invalid object type for `state_dict`: {}. Must be an instance of `dict`".format(
|
817
|
+
type(state_dict)
|
818
|
+
)
|
819
|
+
)
|
820
|
+
|
821
|
+
os.makedirs(path, exist_ok=True)
|
822
|
+
state_dict_path = os.path.join(path, _TORCH_STATE_DICT_FILE_NAME)
|
823
|
+
torch.save(state_dict, state_dict_path, **kwargs)
|
824
|
+
|
825
|
+
|
826
|
+
def load_state_dict(state_dict_uri, **kwargs):
|
827
|
+
"""
|
828
|
+
Load a state_dict from a local file or a run.
|
829
|
+
|
830
|
+
Args:
|
831
|
+
state_dict_uri: The location, in URI format, of the state_dict, for example:
|
832
|
+
|
833
|
+
- ``/Users/me/path/to/local/state_dict``
|
834
|
+
- ``relative/path/to/local/state_dict``
|
835
|
+
- ``s3://my_bucket/path/to/state_dict``
|
836
|
+
- ``runs:/<mlflow_run_id>/run-relative/path/to/state_dict``
|
837
|
+
|
838
|
+
For more information about supported URI schemes, see `Referencing Artifacts \
|
839
|
+
<https://www.mlflow.org/docs/latest/concepts.html#artifact-locations>`_.
|
840
|
+
|
841
|
+
kwargs: kwargs to pass to ``torch.load``.
|
842
|
+
|
843
|
+
Returns:
|
844
|
+
A state_dict
|
845
|
+
|
846
|
+
.. code-block:: python
|
847
|
+
:caption: Example
|
848
|
+
|
849
|
+
with mlflow.start_run():
|
850
|
+
artifact_path = "model"
|
851
|
+
mlflow.pytorch.log_state_dict(model.state_dict(), artifact_path)
|
852
|
+
state_dict_uri = mlflow.get_artifact_uri(artifact_path)
|
853
|
+
|
854
|
+
state_dict = mlflow.pytorch.load_state_dict(state_dict_uri)
|
855
|
+
"""
|
856
|
+
import torch
|
857
|
+
|
858
|
+
local_path = _download_artifact_from_uri(artifact_uri=state_dict_uri)
|
859
|
+
state_dict_path = os.path.join(local_path, _TORCH_STATE_DICT_FILE_NAME)
|
860
|
+
return torch.load(state_dict_path, **kwargs)
|
861
|
+
|
862
|
+
|
863
|
+
@autologging_integration(FLAVOR_NAME)
|
864
|
+
def autolog(
|
865
|
+
log_every_n_epoch=1,
|
866
|
+
log_every_n_step=None,
|
867
|
+
log_models=True,
|
868
|
+
log_datasets=True,
|
869
|
+
disable=False,
|
870
|
+
exclusive=False,
|
871
|
+
disable_for_unsupported_versions=False,
|
872
|
+
silent=False,
|
873
|
+
registered_model_name=None,
|
874
|
+
extra_tags=None,
|
875
|
+
checkpoint=True,
|
876
|
+
checkpoint_monitor="val_loss",
|
877
|
+
checkpoint_mode="min",
|
878
|
+
checkpoint_save_best_only=True,
|
879
|
+
checkpoint_save_weights_only=False,
|
880
|
+
checkpoint_save_freq="epoch",
|
881
|
+
):
|
882
|
+
"""
|
883
|
+
Enables (or disables) and configures autologging from `PyTorch Lightning
|
884
|
+
<https://pytorch-lightning.readthedocs.io/en/latest>`_ to MLflow.
|
885
|
+
|
886
|
+
Autologging is performed when you call the `fit` method of
|
887
|
+
`pytorch_lightning.Trainer() \
|
888
|
+
<https://pytorch-lightning.readthedocs.io/en/latest/trainer.html#>`_.
|
889
|
+
|
890
|
+
Explore the complete `PyTorch MNIST \
|
891
|
+
<https://github.com/mlflow/mlflow/tree/master/examples/pytorch/MNIST>`_ for
|
892
|
+
an expansive example with implementation of additional lightening steps.
|
893
|
+
|
894
|
+
**Note**: Full autologging is only supported for PyTorch Lightning models,
|
895
|
+
i.e., models that subclass
|
896
|
+
`pytorch_lightning.LightningModule \
|
897
|
+
<https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html>`_.
|
898
|
+
Autologging support for vanilla PyTorch (ie models that only subclass
|
899
|
+
`torch.nn.Module <https://pytorch.org/docs/stable/generated/torch.nn.Module.html>`_)
|
900
|
+
only autologs calls to
|
901
|
+
`torch.utils.tensorboard.SummaryWriter <https://pytorch.org/docs/stable/tensorboard.html>`_'s
|
902
|
+
``add_scalar`` and ``add_hparams`` methods to mlflow. In this case, there's also
|
903
|
+
no notion of an "epoch".
|
904
|
+
|
905
|
+
Args:
|
906
|
+
log_every_n_epoch: If specified, logs metrics once every `n` epochs. By default, metrics
|
907
|
+
are logged after every epoch.
|
908
|
+
log_every_n_step: If specified, logs batch metrics once every `n` training step.
|
909
|
+
By default, metrics are not logged for steps. Note that setting this to 1 can cause
|
910
|
+
performance issues and is not recommended. Metrics are logged against Lightning's global
|
911
|
+
step number, and when multiple optimizers are used it is assumed that all optimizers
|
912
|
+
are stepped in each training step.
|
913
|
+
log_models: If ``True``, trained models are logged as MLflow model artifacts.
|
914
|
+
If ``False``, trained models are not logged.
|
915
|
+
log_datasets: If ``True``, dataset information is logged to MLflow Tracking.
|
916
|
+
If ``False``, dataset information is not logged.
|
917
|
+
disable: If ``True``, disables the PyTorch Lightning autologging integration.
|
918
|
+
If ``False``, enables the PyTorch Lightning autologging integration.
|
919
|
+
exclusive: If ``True``, autologged content is not logged to user-created fluent runs.
|
920
|
+
If ``False``, autologged content is logged to the active fluent run, which may be
|
921
|
+
user-created.
|
922
|
+
disable_for_unsupported_versions: If ``True``, disable autologging for versions of
|
923
|
+
pytorch and pytorch-lightning that have not been tested against this version
|
924
|
+
of the MLflow client or are incompatible.
|
925
|
+
silent: If ``True``, suppress all event logs and warnings from MLflow during PyTorch
|
926
|
+
Lightning autologging. If ``False``, show all events and warnings during PyTorch
|
927
|
+
Lightning autologging.
|
928
|
+
registered_model_name: If given, each time a model is trained, it is registered as a
|
929
|
+
new model version of the registered model with this name. The registered model is
|
930
|
+
created if it does not already exist.
|
931
|
+
extra_tags: A dictionary of extra tags to set on each managed run created by autologging.
|
932
|
+
checkpoint: Enable automatic model checkpointing, this feature only supports
|
933
|
+
pytorch-lightning >= 1.6.0.
|
934
|
+
checkpoint_monitor: In automatic model checkpointing, the metric name to monitor if
|
935
|
+
you set `model_checkpoint_save_best_only` to True.
|
936
|
+
checkpoint_mode: one of {"min", "max"}. In automatic model checkpointing,
|
937
|
+
if save_best_only=True, the decision to overwrite the current save file is made based on
|
938
|
+
either the maximization or the minimization of the monitored quantity.
|
939
|
+
checkpoint_save_best_only: If True, automatic model checkpointing only saves when
|
940
|
+
the model is considered the "best" model according to the quantity
|
941
|
+
monitored and previous checkpoint model is overwritten.
|
942
|
+
checkpoint_save_weights_only: In automatic model checkpointing, if True, then
|
943
|
+
only the model's weights will be saved. Otherwise, the optimizer states,
|
944
|
+
lr-scheduler states, etc are added in the checkpoint too.
|
945
|
+
checkpoint_save_freq: `"epoch"` or integer. When using `"epoch"`, the callback
|
946
|
+
saves the model after each epoch. When using integer, the callback
|
947
|
+
saves the model at end of this many batches. Note that if the saving isn't aligned to
|
948
|
+
epochs, the monitored metric may potentially be less reliable (it
|
949
|
+
could reflect as little as 1 batch, since the metrics get reset
|
950
|
+
every epoch). Defaults to `"epoch"`.
|
951
|
+
|
952
|
+
.. code-block:: python
|
953
|
+
:test:
|
954
|
+
:caption: Example
|
955
|
+
|
956
|
+
import os
|
957
|
+
|
958
|
+
import lightning as L
|
959
|
+
import torch
|
960
|
+
from torch.nn import functional as F
|
961
|
+
from torch.utils.data import DataLoader, Subset
|
962
|
+
from torchmetrics import Accuracy
|
963
|
+
from torchvision import transforms
|
964
|
+
from torchvision.datasets import MNIST
|
965
|
+
|
966
|
+
import mlflow.pytorch
|
967
|
+
from mlflow import MlflowClient
|
968
|
+
|
969
|
+
|
970
|
+
class MNISTModel(L.LightningModule):
|
971
|
+
def __init__(self):
|
972
|
+
super().__init__()
|
973
|
+
self.l1 = torch.nn.Linear(28 * 28, 10)
|
974
|
+
self.accuracy = Accuracy("multiclass", num_classes=10)
|
975
|
+
|
976
|
+
def forward(self, x):
|
977
|
+
return torch.relu(self.l1(x.view(x.size(0), -1)))
|
978
|
+
|
979
|
+
def training_step(self, batch, batch_nb):
|
980
|
+
x, y = batch
|
981
|
+
logits = self(x)
|
982
|
+
loss = F.cross_entropy(logits, y)
|
983
|
+
pred = logits.argmax(dim=1)
|
984
|
+
acc = self.accuracy(pred, y)
|
985
|
+
|
986
|
+
# PyTorch `self.log` will be automatically captured by MLflow.
|
987
|
+
self.log("train_loss", loss, on_epoch=True)
|
988
|
+
self.log("acc", acc, on_epoch=True)
|
989
|
+
return loss
|
990
|
+
|
991
|
+
def configure_optimizers(self):
|
992
|
+
return torch.optim.Adam(self.parameters(), lr=0.02)
|
993
|
+
|
994
|
+
|
995
|
+
def print_auto_logged_info(r):
|
996
|
+
tags = {k: v for k, v in r.data.tags.items() if not k.startswith("mlflow.")}
|
997
|
+
artifacts = [f.path for f in MlflowClient().list_artifacts(r.info.run_id, "model")]
|
998
|
+
print(f"run_id: {r.info.run_id}")
|
999
|
+
print(f"artifacts: {artifacts}")
|
1000
|
+
print(f"params: {r.data.params}")
|
1001
|
+
print(f"metrics: {r.data.metrics}")
|
1002
|
+
print(f"tags: {tags}")
|
1003
|
+
|
1004
|
+
|
1005
|
+
# Initialize our model.
|
1006
|
+
mnist_model = MNISTModel()
|
1007
|
+
|
1008
|
+
# Load MNIST dataset.
|
1009
|
+
train_ds = MNIST(
|
1010
|
+
os.getcwd(), train=True, download=True, transform=transforms.ToTensor()
|
1011
|
+
)
|
1012
|
+
# Only take a subset of the data for faster training.
|
1013
|
+
indices = torch.arange(32)
|
1014
|
+
train_ds = Subset(train_ds, indices)
|
1015
|
+
train_loader = DataLoader(train_ds, batch_size=8)
|
1016
|
+
|
1017
|
+
# Initialize a trainer.
|
1018
|
+
trainer = L.Trainer(max_epochs=3)
|
1019
|
+
|
1020
|
+
# Auto log all MLflow entities
|
1021
|
+
mlflow.pytorch.autolog()
|
1022
|
+
|
1023
|
+
# Train the model.
|
1024
|
+
with mlflow.start_run() as run:
|
1025
|
+
trainer.fit(mnist_model, train_loader)
|
1026
|
+
|
1027
|
+
# Fetch the auto logged parameters and metrics.
|
1028
|
+
print_auto_logged_info(mlflow.get_run(run_id=run.info.run_id))
|
1029
|
+
"""
|
1030
|
+
try:
|
1031
|
+
import pytorch_lightning as pl
|
1032
|
+
except ImportError:
|
1033
|
+
pass
|
1034
|
+
else:
|
1035
|
+
from mlflow.pytorch._lightning_autolog import patched_fit
|
1036
|
+
|
1037
|
+
safe_patch(
|
1038
|
+
FLAVOR_NAME, pl.Trainer, "fit", patched_fit, manage_run=True, extra_tags=extra_tags
|
1039
|
+
)
|
1040
|
+
|
1041
|
+
try:
|
1042
|
+
import lightning as L
|
1043
|
+
except ImportError:
|
1044
|
+
pass
|
1045
|
+
else:
|
1046
|
+
from mlflow.pytorch._lightning_autolog import patched_fit
|
1047
|
+
|
1048
|
+
safe_patch(
|
1049
|
+
FLAVOR_NAME, L.Trainer, "fit", patched_fit, manage_run=True, extra_tags=extra_tags
|
1050
|
+
)
|
1051
|
+
|
1052
|
+
try:
|
1053
|
+
import torch.utils.tensorboard.writer
|
1054
|
+
except ImportError:
|
1055
|
+
pass
|
1056
|
+
else:
|
1057
|
+
from mlflow.pytorch._pytorch_autolog import (
|
1058
|
+
flush_metrics_queue,
|
1059
|
+
patched_add_event,
|
1060
|
+
patched_add_hparams,
|
1061
|
+
patched_add_summary,
|
1062
|
+
)
|
1063
|
+
|
1064
|
+
safe_patch(
|
1065
|
+
FLAVOR_NAME,
|
1066
|
+
torch.utils.tensorboard.writer.FileWriter,
|
1067
|
+
"add_event",
|
1068
|
+
partial(patched_add_event, mlflow_log_every_n_step=log_every_n_step),
|
1069
|
+
manage_run=True,
|
1070
|
+
extra_tags=extra_tags,
|
1071
|
+
)
|
1072
|
+
safe_patch(
|
1073
|
+
FLAVOR_NAME,
|
1074
|
+
torch.utils.tensorboard.writer.FileWriter,
|
1075
|
+
"add_summary",
|
1076
|
+
patched_add_summary,
|
1077
|
+
manage_run=True,
|
1078
|
+
extra_tags=extra_tags,
|
1079
|
+
)
|
1080
|
+
safe_patch(
|
1081
|
+
FLAVOR_NAME,
|
1082
|
+
torch.utils.tensorboard.SummaryWriter,
|
1083
|
+
"add_hparams",
|
1084
|
+
patched_add_hparams,
|
1085
|
+
manage_run=True,
|
1086
|
+
extra_tags=extra_tags,
|
1087
|
+
)
|
1088
|
+
|
1089
|
+
atexit.register(flush_metrics_queue)
|
1090
|
+
|
1091
|
+
|
1092
|
+
if autolog.__doc__ is not None:
|
1093
|
+
autolog.__doc__ = autolog.__doc__.replace("MIN_REQ_VERSION", str(MIN_REQ_VERSION)).replace(
|
1094
|
+
"MAX_REQ_VERSION", str(MAX_REQ_VERSION)
|
1095
|
+
)
|
1096
|
+
|
1097
|
+
|
1098
|
+
def load_checkpoint(model_class, run_id=None, epoch=None, global_step=None, kwargs=None):
|
1099
|
+
"""
|
1100
|
+
If you enable "checkpoint" in autologging, during pytorch-lightning model
|
1101
|
+
training execution, checkpointed models are logged as MLflow artifacts.
|
1102
|
+
Using this API, you can load the checkpointed model.
|
1103
|
+
|
1104
|
+
If you want to load the latest checkpoint, set both `epoch` and `global_step` to None.
|
1105
|
+
If "checkpoint_save_freq" is set to "epoch" in autologging,
|
1106
|
+
you can set `epoch` param to the epoch of the checkpoint to load specific epoch checkpoint.
|
1107
|
+
If "checkpoint_save_freq" is set to an integer in autologging,
|
1108
|
+
you can set `global_step` param to the global step of the checkpoint to load specific
|
1109
|
+
global step checkpoint.
|
1110
|
+
`epoch` param and `global_step` can't be set together.
|
1111
|
+
|
1112
|
+
Args:
|
1113
|
+
model_class: The class of the training model, the class should inherit
|
1114
|
+
'pytorch_lightning.LightningModule'.
|
1115
|
+
run_id: The id of the run which model is logged to. If not provided,
|
1116
|
+
current active run is used.
|
1117
|
+
epoch: The epoch of the checkpoint to be loaded, if you set
|
1118
|
+
"checkpoint_save_freq" to "epoch".
|
1119
|
+
global_step: The global step of the checkpoint to be loaded, if
|
1120
|
+
you set "checkpoint_save_freq" to an integer.
|
1121
|
+
kwargs: Any extra kwargs needed to init the model.
|
1122
|
+
|
1123
|
+
Returns:
|
1124
|
+
The instance of a pytorch-lightning model restored from the specified checkpoint.
|
1125
|
+
|
1126
|
+
.. code-block:: python
|
1127
|
+
:caption: Example
|
1128
|
+
|
1129
|
+
import mlflow
|
1130
|
+
|
1131
|
+
mlflow.pytorch.autolog(checkpoint=True)
|
1132
|
+
|
1133
|
+
model = MyLightningModuleNet() # A custom-pytorch lightning model
|
1134
|
+
train_loader = create_train_dataset_loader()
|
1135
|
+
trainer = Trainer()
|
1136
|
+
|
1137
|
+
with mlflow.start_run() as run:
|
1138
|
+
trainer.fit(model, train_loader)
|
1139
|
+
|
1140
|
+
run_id = run.info.run_id
|
1141
|
+
|
1142
|
+
# load latest checkpoint model
|
1143
|
+
latest_checkpoint_model = mlflow.pytorch.load_checkpoint(MyLightningModuleNet, run_id)
|
1144
|
+
|
1145
|
+
# load history checkpoint model logged in second epoch
|
1146
|
+
checkpoint_model = mlflow.pytorch.load_checkpoint(MyLightningModuleNet, run_id, epoch=2)
|
1147
|
+
"""
|
1148
|
+
with TempDir() as tmp_dir:
|
1149
|
+
downloaded_checkpoint_filepath = download_checkpoint_artifact(
|
1150
|
+
run_id=run_id, epoch=epoch, global_step=global_step, dst_path=tmp_dir.path()
|
1151
|
+
)
|
1152
|
+
return model_class.load_from_checkpoint(downloaded_checkpoint_filepath, **(kwargs or {}))
|
1153
|
+
|
1154
|
+
|
1155
|
+
__all__ = [
|
1156
|
+
"autolog",
|
1157
|
+
"load_model",
|
1158
|
+
"save_model",
|
1159
|
+
"log_model",
|
1160
|
+
"get_default_pip_requirements",
|
1161
|
+
"get_default_conda_env",
|
1162
|
+
"load_checkpoint",
|
1163
|
+
]
|
1164
|
+
|
1165
|
+
try:
|
1166
|
+
from mlflow.pytorch._lightning_autolog import MlflowModelCheckpointCallback # noqa: F401
|
1167
|
+
|
1168
|
+
__all__.append("MlflowModelCheckpointCallback")
|
1169
|
+
except ImportError:
|
1170
|
+
# Swallow exception if pytorch-lightning is not installed.
|
1171
|
+
pass
|