自定义预测例程

通过自定义预测例程 (CPR),您可以轻松构建具有预处理/后处理代码的自定义容器,而无需处理 HTTP 服务器设置或从头开始构建容器的详细信息。您可以使用预处理来对输入进行归一化/转换,或者调用外部服务以获取其他数据,并使用后处理设置模型预测的格式或运行业务逻辑。

下图展示了使用和不使用自定义预测例程的用户工作流。

主要区别如下:

  • 您无需编写模型服务器或 Dockerfile。系统会为您提供模型服务器,即托管模型的 HTTP 服务器。

  • 您可以在本地部署和调试模型,从而加快开发期间的迭代周期。

构建和部署自定义容器

本部分介绍如何使用 CPR 构建具有预处理/后处理逻辑的自定义容器,并将其部署到本地和在线端点。

初始设置

您必须在环境中安装 Vertex AI SDKDocker

编写自定义 Predictor

实现 Predictor 接口。

class Predictor(ABC):
    """Interface of the Predictor class for Custom Prediction Routines.
    The Predictor is responsible for the ML logic for processing a prediction request.
    Specifically, the Predictor must define:
    (1) How to load all model artifacts used during prediction into memory.
    (2) The logic that should be executed at predict time.
    When using the default PredictionHandler, the Predictor will be invoked as follows:
      predictor.postprocess(predictor.predict(predictor.preprocess(prediction_input)))
    """

    @abstractmethod
    def load(self, artifacts_uri: str) -> None:
        """Loads the model artifact.
        Args:
            artifacts_uri (str):
                Required. The value of the environment variable AIP_STORAGE_URI.
        """
        pass

    def preprocess(self, prediction_input: Any) -> Any:
        """Preprocesses the prediction input before doing the prediction.
        Args:
            prediction_input (Any):
                Required. The prediction input that needs to be preprocessed.
        Returns:
            The preprocessed prediction input.
        """
        return prediction_input

    @abstractmethod
    def predict(self, instances: Any) -> Any:
        """Performs prediction.
        Args:
            instances (Any):
                Required. The instance(s) used for performing prediction.
        Returns:
            Prediction results.
        """
        pass

    def postprocess(self, prediction_results: Any) -> Any:
        """Postprocesses the prediction results.
        Args:
            prediction_results (Any):
                Required. The prediction results.
        Returns:
            The postprocessed prediction results.
        """
        return prediction_results

例如,请参阅 Sklearn 的 Predictor 实现

编写自定义 Handler(可选)

自定义处理程序可以访问原始请求对象,因此,在您需要自定义网络服务器相关逻辑(例如支持其他请求/响应标头或反序列化非 JSON 格式的预测请求)的极少数情况下,自定义处理程序非常有用。

这是一个同时实现 Predictor 和处理程序的示例笔记本

虽然并非必需,但为了更好地整理和重复使用代码,我们建议您在处理程序中实现网络服务器逻辑,并在 Predictor 中实现机器学习逻辑(如默认处理程序中所示)。

构建自定义容器

将自定义代码和额外的 requirements.txt 文件(如果需要安装映像中的任何软件包)放在目录中。

使用 Vertex SDK 构建自定义容器,如下所示:

from google.cloud.aiplatform.prediction import LocalModel

# {import your predictor and handler}

local_model = LocalModel.build_cpr_model(
    {PATH_TO_THE_SOURCE_DIR},
    f"{REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}",
    predictor={PREDICTOR_CLASS},
    handler={HANDLER_CLASS},
    requirements_path={PATH_TO_REQUIREMENTS_TXT},
)

您可以检查容器的规范以获取有用的信息,例如映像 URI 和环境变量。

local_model.get_serving_container_spec()

在本地运行容器(可选)

仅当您要在本地运行和测试容器时,才需要执行此步骤,这有助于加快迭代速度。在以下示例中,我们部署到本地端点并发送预测请求(请求正文的格式)。

with local_model.deploy_to_local_endpoint(
    artifact_uri={GCS_PATH_TO_MODEL_ARTIFACTS},
    credential_path={PATH_TO_CREDENTIALS},
) as local_endpoint:
    health_check_response = local_endpoint.run_health_check()
    predict_response = local_endpoint.predict(
        request_file={PATH_TO_INPUT_FILE},
        headers={ANY_NEEDED_HEADERS},
    )

输出健康检查和预测响应。

print(health_check_response, health_check_response.content)
print(predict_response, predict_response.content)

输出所有容器日志。

local_endpoint.print_container_logs(show_all=True)

上传到 Vertex AI Model Registry

您的模型需要访问模型工件(训练中的文件),因此请确保将它们上传到 Google Cloud Storage。

将映像推送到 Artifact Registry

local_model.push_image()

然后,上传到模型注册表。

from google.cloud import aiplatform

model = aiplatform.Model.upload(
    local_model=local_model,
    display_name={MODEL_DISPLAY_NAME},
    artifact_uri={GCS_PATH_TO_MODEL_ARTIFACTS},
)

将模型上传到 Vertex AI Model Registry 后,该模型可能会用于进行批量预测,或部署到 Vertex AI 端点以获取在线预测结果。

部署到 Vertex AI 端点

endpoint = model.deploy(machine_type="n1-standard-4")

部署后,您可以获取在线预测结果

笔记本示例

这些示例展示了在 Vertex AI Prediction 上使用自定义预处理/后处理部署模型的不同方式。