GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat: Lazy load Endpoint class (#655) · googleapis/python-aiplatform@c795c6f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • google/cloud/aiplatform
    • models.py
  • tests
    • system/aiplatform
      • test_e2e_tabular.py
    • unit/aiplatform
      • test_end_to_end.py
      • test_endpoints.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎google/cloud/aiplatform/models.py‎

Copy file name to clipboardExpand all lines: google/cloud/aiplatform/models.py
+39-4Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,12 +110,43 @@ def __init__(
110110
credentials=credentials,
111111
resource_name=endpoint_name,
112112
)
113-
self._gca_resource = self._get_gca_resource(resource_name=endpoint_name)
113+
114+
endpoint_name = utils.full_resource_name(
115+
resource_name=endpoint_name,
116+
resource_noun="endpoints",
117+
project=project,
118+
location=location,
119+
)
120+
121+
# Lazy load the Endpoint gca_resource until needed
122+
self._gca_resource = gca_endpoint_compat.Endpoint(name=endpoint_name)
114123

115124
self._prediction_client = self._instantiate_prediction_client(
116125
location=self.location, credentials=credentials,
117126
)
118127

128+
def _skipped_getter_call(self) -> bool:
129+
"""Check if GAPIC resource was populated by call to get/list API methods
130+
131+
Returns False if `_gca_resource` is None or fully populated. Returns True
132+
if `_gca_resource` is partially populated
133+
"""
134+
return self._gca_resource and not self._gca_resource.create_time
135+
136+
def _sync_gca_resource_if_skipped(self) -> None:
137+
"""Sync GAPIC service representation of Endpoint class resource only if
138+
get_endpoint() was never called."""
139+
if self._skipped_getter_call():
140+
self._gca_resource = self._get_gca_resource(
141+
resource_name=self._gca_resource.name
142+
)
143+
144+
def _assert_gca_resource_is_available(self) -> None:
145+
"""Ensures Endpoint getter was called at least once before
146+
asserting on gca_resource's availability."""
147+
super()._assert_gca_resource_is_available()
148+
self._sync_gca_resource_if_skipped()
149+
119150
@property
120151
def traffic_split(self) -> Dict[str, int]:
121152
"""A map from a DeployedModel's ID to the percentage of this Endpoint's
@@ -315,8 +346,8 @@ def _create(
315346

316347
_LOGGER.log_create_complete(cls, created_endpoint, "endpoint")
317348

318-
return cls(
319-
endpoint_name=created_endpoint.name,
349+
return cls._construct_sdk_resource_from_gapic(
350+
gapic_resource=created_endpoint,
320351
project=project,
321352
location=location,
322353
credentials=credentials,
@@ -622,6 +653,7 @@ def deploy(
622653
will be executed in concurrent Future and any downstream object will
623654
be immediately returned and synced when the Future has completed.
624655
"""
656+
self._sync_gca_resource_if_skipped()
625657

626658
self._validate_deploy_args(
627659
min_replica_count,
@@ -967,6 +999,8 @@ def undeploy(
967999
Optional. Strings which should be sent along with the request as
9681000
metadata.
9691001
"""
1002+
self._sync_gca_resource_if_skipped()
1003+
9701004
if traffic_split is not None:
9711005
if deployed_model_id in traffic_split and traffic_split[deployed_model_id]:
9721006
raise ValueError("Model being undeployed should have 0 traffic.")
@@ -1011,6 +1045,7 @@ def _undeploy(
10111045
Optional. Strings which should be sent along with the request as
10121046
metadata.
10131047
"""
1048+
self._sync_gca_resource_if_skipped()
10141049
current_traffic_split = traffic_split or dict(self._gca_resource.traffic_split)
10151050

10161051
if deployed_model_id in current_traffic_split:
@@ -1095,7 +1130,7 @@ def predict(self, instances: List, parameters: Optional[Dict] = None) -> Predict
10951130
self.wait()
10961131

10971132
prediction_response = self._prediction_client.predict(
1098-
endpoint=self.resource_name, instances=instances, parameters=parameters
1133+
endpoint=self._gca_resource.name, instances=instances, parameters=parameters
10991134
)
11001135

11011136
return Prediction(
Collapse file

‎tests/system/aiplatform/test_e2e_tabular.py‎

Copy file name to clipboardExpand all lines: tests/system/aiplatform/test_e2e_tabular.py
+17-26Lines changed: 17 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,16 @@
3434
_LOCAL_TRAINING_SCRIPT_PATH = os.path.join(
3535
_DIR_NAME, "test_resources/california_housing_training_script.py"
3636
)
37+
_INSTANCE = {
38+
"longitude": -124.35,
39+
"latitude": 40.54,
40+
"housing_median_age": 52.0,
41+
"total_rooms": 1820.0,
42+
"total_bedrooms": 300.0,
43+
"population": 806,
44+
"households": 270.0,
45+
"median_income": 3.014700,
46+
}
3747

3848

3949
@pytest.mark.usefixtures("prepare_staging_bucket", "delete_staging_bucket", "teardown")
@@ -136,39 +146,20 @@ def test_end_to_end_tabular(self, shared_state):
136146
# Send online prediction with same instance to both deployed models
137147
# This sample is taken from an observation where median_house_value = 94600
138148
custom_endpoint.wait()
139-
custom_prediction = custom_endpoint.predict(
140-
[
141-
{
142-
"longitude": -124.35,
143-
"latitude": 40.54,
144-
"housing_median_age": 52.0,
145-
"total_rooms": 1820.0,
146-
"total_bedrooms": 300.0,
147-
"population": 806,
148-
"households": 270.0,
149-
"median_income": 3.014700,
150-
},
151-
]
152-
)
149+
custom_prediction = custom_endpoint.predict([_INSTANCE])
153150

154151
custom_batch_prediction_job.wait()
155152

156153
automl_endpoint.wait()
157154
automl_prediction = automl_endpoint.predict(
158-
[
159-
{
160-
"longitude": "-124.35",
161-
"latitude": "40.54",
162-
"housing_median_age": "52.0",
163-
"total_rooms": "1820.0",
164-
"total_bedrooms": "300.0",
165-
"population": "806",
166-
"households": "270.0",
167-
"median_income": "3.014700",
168-
},
169-
]
155+
[{k: str(v) for k, v in _INSTANCE.items()}] # Cast int values to strings
170156
)
171157

158+
# Test lazy loading of Endpoint, check getter was never called after predict()
159+
custom_endpoint = aiplatform.Endpoint(custom_endpoint.resource_name)
160+
custom_endpoint.predict([_INSTANCE])
161+
assert custom_endpoint._skipped_getter_call()
162+
172163
assert (
173164
custom_job.state
174165
== gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED
Collapse file

‎tests/unit/aiplatform/test_end_to_end.py‎

Copy file name to clipboardExpand all lines: tests/unit/aiplatform/test_end_to_end.py
+6Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,12 @@ def test_dataset_create_to_model_predict(
151151
assert endpoint_deploy_return is None
152152

153153
if not sync:
154+
# Accessing attribute in Endpoint that has not been created raises informatively
155+
with pytest.raises(
156+
RuntimeError, match=r"Endpoint resource has not been created."
157+
):
158+
my_endpoint.network
159+
154160
my_endpoint.wait()
155161
created_endpoint.wait()
156162

Collapse file

‎tests/unit/aiplatform/test_endpoints.py‎

Copy file name to clipboardExpand all lines: tests/unit/aiplatform/test_endpoints.py
+52-15Lines changed: 52 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,15 @@ def get_endpoint_mock():
169169
yield get_endpoint_mock
170170

171171

172+
@pytest.fixture
173+
def get_empty_endpoint_mock():
174+
with mock.patch.object(
175+
endpoint_service_client.EndpointServiceClient, "get_endpoint"
176+
) as get_endpoint_mock:
177+
get_endpoint_mock.return_value = gca_endpoint.Endpoint(name=_TEST_ENDPOINT_NAME)
178+
yield get_endpoint_mock
179+
180+
172181
@pytest.fixture
173182
def get_endpoint_alt_location_mock():
174183
with mock.patch.object(
@@ -213,7 +222,9 @@ def create_endpoint_mock():
213222
) as create_endpoint_mock:
214223
create_endpoint_lro_mock = mock.Mock(ga_operation.Operation)
215224
create_endpoint_lro_mock.result.return_value = gca_endpoint.Endpoint(
216-
name=_TEST_ENDPOINT_NAME, display_name=_TEST_DISPLAY_NAME
225+
name=_TEST_ENDPOINT_NAME,
226+
display_name=_TEST_DISPLAY_NAME,
227+
encryption_spec=_TEST_ENCRYPTION_SPEC,
217228
)
218229
create_endpoint_mock.return_value = create_endpoint_lro_mock
219230
yield create_endpoint_mock
@@ -378,19 +389,35 @@ def test_constructor(self, create_endpoint_client_mock):
378389
]
379390
)
380391

381-
def test_constructor_with_endpoint_id(self, get_endpoint_mock):
382-
models.Endpoint(_TEST_ID)
383-
get_endpoint_mock.assert_called_with(name=_TEST_ENDPOINT_NAME)
392+
def test_lazy_constructor_with_endpoint_id(self, get_endpoint_mock):
393+
ep = models.Endpoint(_TEST_ID)
394+
assert ep._gca_resource.name == _TEST_ENDPOINT_NAME
395+
assert ep._skipped_getter_call()
396+
assert not get_endpoint_mock.called
384397

385-
def test_constructor_with_endpoint_name(self, get_endpoint_mock):
386-
models.Endpoint(_TEST_ENDPOINT_NAME)
398+
def test_lazy_constructor_with_endpoint_name(self, get_endpoint_mock):
399+
ep = models.Endpoint(_TEST_ENDPOINT_NAME)
400+
assert ep._gca_resource.name == _TEST_ENDPOINT_NAME
401+
assert ep._skipped_getter_call()
402+
assert not get_endpoint_mock.called
403+
404+
def test_lazy_constructor_calls_get_on_property_access(self, get_endpoint_mock):
405+
ep = models.Endpoint(_TEST_ENDPOINT_NAME)
406+
assert ep._gca_resource.name == _TEST_ENDPOINT_NAME
407+
assert ep._skipped_getter_call()
408+
assert not get_endpoint_mock.called
409+
410+
ep.display_name # Retrieve a property that requires a call to Endpoint getter
387411
get_endpoint_mock.assert_called_with(name=_TEST_ENDPOINT_NAME)
388412

389-
def test_constructor_with_custom_project(self, get_endpoint_mock):
390-
models.Endpoint(endpoint_name=_TEST_ID, project=_TEST_PROJECT_2)
413+
def test_lazy_constructor_with_custom_project(self, get_endpoint_mock):
414+
ep = models.Endpoint(endpoint_name=_TEST_ID, project=_TEST_PROJECT_2)
391415
test_endpoint_resource_name = endpoint_service_client.EndpointServiceClient.endpoint_path(
392416
_TEST_PROJECT_2, _TEST_LOCATION, _TEST_ID
393417
)
418+
assert not get_endpoint_mock.called
419+
420+
ep.name # Retrieve a property that requires a call to Endpoint getter
394421
get_endpoint_mock.assert_called_with(name=test_endpoint_resource_name)
395422

396423
@pytest.mark.usefixtures("get_endpoint_mock")
@@ -406,11 +433,19 @@ def test_constructor_with_conflicting_location(self):
406433
regexp=r"is provided, but different from the resource location"
407434
)
408435

409-
def test_constructor_with_custom_location(self, get_endpoint_alt_location_mock):
410-
models.Endpoint(endpoint_name=_TEST_ID, location=_TEST_LOCATION_2)
436+
def test_lazy_constructor_with_custom_location(
437+
self, get_endpoint_alt_location_mock
438+
):
439+
ep = models.Endpoint(endpoint_name=_TEST_ID, location=_TEST_LOCATION_2)
411440
test_endpoint_resource_name = endpoint_service_client.EndpointServiceClient.endpoint_path(
412441
_TEST_PROJECT, _TEST_LOCATION_2, _TEST_ID
413442
)
443+
444+
# Get Endpoint not called due to lazy loading
445+
assert not get_endpoint_alt_location_mock.called
446+
447+
ep.network # Accessing a property that requires calling getter
448+
414449
get_endpoint_alt_location_mock.assert_called_with(
415450
name=test_endpoint_resource_name
416451
)
@@ -481,15 +516,17 @@ def test_create(self, create_endpoint_mock, sync):
481516
)
482517

483518
expected_endpoint.name = _TEST_ENDPOINT_NAME
484-
assert my_endpoint.gca_resource == expected_endpoint
485-
assert my_endpoint.network is None
519+
assert my_endpoint._gca_resource == expected_endpoint
486520

487-
@pytest.mark.usefixtures("get_endpoint_mock")
521+
@pytest.mark.usefixtures("get_empty_endpoint_mock")
488522
def test_accessing_properties_with_no_resource_raises(self,):
523+
"""Ensure a descriptive RuntimeError is raised when the
524+
GAPIC object has not been populated"""
489525

490526
my_endpoint = aiplatform.Endpoint(_TEST_ENDPOINT_NAME)
491527

492-
my_endpoint._gca_resource = None
528+
# Create a gca_resource without `name` being populated
529+
my_endpoint._gca_resource = gca_endpoint.Endpoint(create_time=datetime.now())
493530

494531
with pytest.raises(RuntimeError) as e:
495532
my_endpoint.gca_resource
@@ -909,7 +946,7 @@ def test_undeploy(self, undeploy_model_mock, sync):
909946
traffic_split={"model1": 100},
910947
)
911948
test_endpoint = models.Endpoint(_TEST_ENDPOINT_NAME)
912-
assert dict(test_endpoint._gca_resource.traffic_split) == {"model1": 100}
949+
assert dict(test_endpoint.traffic_split) == {"model1": 100}
913950
test_endpoint.undeploy("model1", sync=sync)
914951
if not sync:
915952
test_endpoint.wait()

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.