/
test_e2e_tabular.py
187 lines (150 loc) · 6.72 KB
/
test_e2e_tabular.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# -*- coding: utf-8 -*-
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
from urllib import request
import pytest
from google.cloud import aiplatform
from google.cloud.aiplatform.compat.types import (
job_state as gca_job_state,
pipeline_state as gca_pipeline_state,
)
from tests.system.aiplatform import e2e_base
_BLOB_PATH = "california-housing-data.csv"
_DATASET_SRC = "https://dl.google.com/mlcc/mledu-datasets/california_housing_train.csv"
_DIR_NAME = os.path.dirname(os.path.abspath(__file__))
_LOCAL_TRAINING_SCRIPT_PATH = os.path.join(
_DIR_NAME, "test_resources/california_housing_training_script.py"
)
_INSTANCE = {
"longitude": -124.35,
"latitude": 40.54,
"housing_median_age": 52.0,
"total_rooms": 1820.0,
"total_bedrooms": 300.0,
"population": 806,
"households": 270.0,
"median_income": 3.014700,
}
@pytest.mark.usefixtures("prepare_staging_bucket", "delete_staging_bucket", "teardown")
class TestEndToEndTabular(e2e_base.TestEndToEnd):
"""End to end system test of the Vertex SDK with tabular data adapted from
reference notebook http://shortn/_eyoNx3SN0X"""
_temp_prefix = "temp-vertex-sdk-e2e-tabular"
def test_end_to_end_tabular(self, shared_state):
"""Build dataset, train a custom and AutoML model, deploy, and get predictions"""
assert shared_state["bucket"]
bucket = shared_state["bucket"]
blob = bucket.blob(_BLOB_PATH)
# Download the CSV file into memory and save it directory to staging bucket
with request.urlopen(_DATASET_SRC) as response:
data = response.read()
blob.upload_from_string(data)
# Collection of resources generated by this test, to be deleted during teardown
shared_state["resources"] = []
aiplatform.init(
project=e2e_base._PROJECT,
location=e2e_base._LOCATION,
staging_bucket=shared_state["staging_bucket_name"],
)
# Create and import to single managed dataset for both training jobs
dataset_gcs_source = f'gs://{shared_state["staging_bucket_name"]}/{_BLOB_PATH}'
ds = aiplatform.TabularDataset.create(
display_name=self._make_display_name("dataset"),
gcs_source=[dataset_gcs_source],
sync=False,
)
shared_state["resources"].extend([ds])
# Define both training jobs
custom_job = aiplatform.CustomTrainingJob(
display_name=self._make_display_name("train-housing-custom"),
script_path=_LOCAL_TRAINING_SCRIPT_PATH,
container_uri="gcr.io/cloud-aiplatform/training/tf-cpu.2-2:latest",
requirements=["gcsfs==0.7.1"],
model_serving_container_image_uri="gcr.io/cloud-aiplatform/prediction/tf2-cpu.2-2:latest",
)
automl_job = aiplatform.AutoMLTabularTrainingJob(
display_name=self._make_display_name("train-housing-automl"),
optimization_prediction_type="regression",
optimization_objective="minimize-rmse",
)
# Kick off both training jobs, AutoML job will take approx one hour to run
custom_model = custom_job.run(
ds,
replica_count=1,
model_display_name=self._make_display_name("custom-housing-model"),
sync=False,
)
automl_model = automl_job.run(
dataset=ds,
target_column="median_house_value",
model_display_name=self._make_display_name("automl-housing-model"),
sync=False,
)
shared_state["resources"].extend(
[automl_job, automl_model, custom_job, custom_model]
)
# Deploy both models after training completes
custom_endpoint = custom_model.deploy(machine_type="n1-standard-4", sync=False)
automl_endpoint = automl_model.deploy(machine_type="n1-standard-4", sync=False)
shared_state["resources"].extend([automl_endpoint, custom_endpoint])
custom_batch_prediction_job = custom_model.batch_predict(
job_display_name=self._make_display_name("automl-housing-model"),
instances_format="csv",
machine_type="n1-standard-4",
gcs_source=dataset_gcs_source,
gcs_destination_prefix=f'gs://{shared_state["staging_bucket_name"]}/bp_results/',
sync=False,
)
shared_state["resources"].append(custom_batch_prediction_job)
custom_job.wait_for_resource_creation()
automl_job.wait_for_resource_creation()
custom_batch_prediction_job.wait_for_resource_creation()
# Send online prediction with same instance to both deployed models
# This sample is taken from an observation where median_house_value = 94600
custom_endpoint.wait()
custom_prediction = custom_endpoint.predict([_INSTANCE])
custom_batch_prediction_job.wait()
automl_endpoint.wait()
automl_prediction = automl_endpoint.predict(
[{k: str(v) for k, v in _INSTANCE.items()}] # Cast int values to strings
)
# Test lazy loading of Endpoint, check getter was never called after predict()
custom_endpoint = aiplatform.Endpoint(custom_endpoint.resource_name)
custom_endpoint.predict([_INSTANCE])
assert custom_endpoint._skipped_getter_call()
assert (
custom_job.state
== gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED
)
assert (
automl_job.state
== gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED
)
assert (
custom_batch_prediction_job.state
== gca_job_state.JobState.JOB_STATE_SUCCEEDED
)
# Ensure a single prediction was returned
assert len(custom_prediction.predictions) == 1
assert len(automl_prediction.predictions) == 1
# Ensure the models are remotely accurate
try:
automl_result = automl_prediction.predictions[0]["value"]
custom_result = custom_prediction.predictions[0][0]
assert 200000 > automl_result > 50000
assert 200000 > custom_result > 50000
except KeyError as e:
raise RuntimeError("Unexpected prediction response structure:", e)