|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright 2024 Google LLC |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | +"""Unit tests for generative model tuning.""" |
| 18 | +# pylint: disable=protected-access,bad-continuation |
| 19 | + |
| 20 | +import copy |
| 21 | +import datetime |
| 22 | +from typing import Dict, Iterable |
| 23 | +from unittest import mock |
| 24 | +import uuid |
| 25 | + |
| 26 | +import vertexai |
| 27 | +from google.cloud.aiplatform import compat |
| 28 | +from google.cloud.aiplatform import initializer |
| 29 | +from google.cloud.aiplatform import utils as aiplatform_utils |
| 30 | +from google.cloud.aiplatform_v1.services import gen_ai_tuning_service |
| 31 | +from google.cloud.aiplatform_v1.types import job_state |
| 32 | +from google.cloud.aiplatform_v1.types import tuning_job as gca_tuning_job |
| 33 | +from vertexai.preview import tuning |
| 34 | +from vertexai.preview.tuning import sft as supervised_tuning |
| 35 | + |
| 36 | +import pytest |
| 37 | + |
| 38 | +from google.rpc import status_pb2 |
| 39 | + |
| 40 | + |
| 41 | +_TEST_PROJECT = "test-project" |
| 42 | +_TEST_LOCATION = "us-central1" |
| 43 | + |
| 44 | + |
| 45 | +_global_tuning_jobs: Dict[str, gca_tuning_job.TuningJob] = {} |
| 46 | + |
| 47 | + |
| 48 | +class MockGenAiTuningServiceClient(gen_ai_tuning_service.GenAiTuningServiceClient): |
| 49 | + @property |
| 50 | + def _tuning_jobs(self) -> Dict[str, gca_tuning_job.TuningJob]: |
| 51 | + return _global_tuning_jobs |
| 52 | + |
| 53 | + def create_tuning_job( |
| 54 | + self, |
| 55 | + *, |
| 56 | + parent: str, |
| 57 | + tuning_job: gca_tuning_job.TuningJob, |
| 58 | + **_, |
| 59 | + ) -> gca_tuning_job.TuningJob: |
| 60 | + tuning_job = copy.deepcopy(tuning_job) |
| 61 | + resource_id = uuid.uuid4().hex |
| 62 | + resource_name = f"{parent}/tuningJobs/{resource_id}" |
| 63 | + tuning_job.name = resource_name |
| 64 | + current_time = datetime.datetime.now(datetime.timezone.utc) |
| 65 | + tuning_job.create_time = current_time |
| 66 | + tuning_job.update_time = current_time |
| 67 | + tuning_job.state = job_state.JobState.JOB_STATE_PENDING |
| 68 | + self._tuning_jobs[resource_name] = tuning_job |
| 69 | + return tuning_job |
| 70 | + |
| 71 | + def _progress_tuning_job(self, name: str): |
| 72 | + tuning_job: gca_tuning_job.TuningJob = self._tuning_jobs[name] |
| 73 | + current_time = datetime.datetime.now(datetime.timezone.utc) |
| 74 | + if tuning_job.state == job_state.JobState.JOB_STATE_PENDING: |
| 75 | + if ( |
| 76 | + "invalid_dataset" |
| 77 | + in tuning_job.supervised_tuning_spec.training_dataset_uri |
| 78 | + ): |
| 79 | + tuning_job.state = job_state.JobState.JOB_STATE_FAILED |
| 80 | + tuning_job.error = status_pb2.Status( |
| 81 | + code=400, message="Invalid dataset." |
| 82 | + ) |
| 83 | + else: |
| 84 | + tuning_job.state = job_state.JobState.JOB_STATE_RUNNING |
| 85 | + tuning_job.update_time = current_time |
| 86 | + elif tuning_job.state == job_state.JobState.JOB_STATE_RUNNING: |
| 87 | + parent = tuning_job.name.partition("/tuningJobs/")[0] |
| 88 | + tuning_job.state = job_state.JobState.JOB_STATE_SUCCEEDED |
| 89 | + experiment_id = uuid.uuid4().hex |
| 90 | + tuned_model_id = uuid.uuid4().hex |
| 91 | + tuned_model_endpoint_id = uuid.uuid4().hex |
| 92 | + tuning_job.experiment = ( |
| 93 | + f"{parent}/metadataStores/default/contexts/{experiment_id}" |
| 94 | + ) |
| 95 | + tuning_job.tuned_model = gca_tuning_job.TunedModel( |
| 96 | + model=f"{parent}/models/{tuned_model_id}", |
| 97 | + endpoint=f"{parent}/endpoints/{tuned_model_endpoint_id}", |
| 98 | + ) |
| 99 | + tuning_job.end_time = current_time |
| 100 | + tuning_job.update_time = current_time |
| 101 | + else: |
| 102 | + pass |
| 103 | + |
| 104 | + def get_tuning_job(self, *, name: str, **_) -> gca_tuning_job.TuningJob: |
| 105 | + tuning_job = self._tuning_jobs[name] |
| 106 | + tuning_job = copy.deepcopy(tuning_job) |
| 107 | + self._progress_tuning_job(name) |
| 108 | + |
| 109 | + return tuning_job |
| 110 | + |
| 111 | + def list_tuning_jobs( |
| 112 | + self, *, parent: str, **_ |
| 113 | + ) -> Iterable[gca_tuning_job.TuningJob]: |
| 114 | + return [ |
| 115 | + tuning_job |
| 116 | + for name, tuning_job in self._tuning_jobs.items() |
| 117 | + if name.startswith(parent + "/") |
| 118 | + ] |
| 119 | + |
| 120 | + def cancel_tuning_job(self, *, name: str, **_) -> None: |
| 121 | + tuning_job = self._tuning_jobs[name] |
| 122 | + assert tuning_job.state in ( |
| 123 | + job_state.JobState.JOB_STATE_RUNNING, |
| 124 | + job_state.JobState.JOB_STATE_PENDING, |
| 125 | + ) |
| 126 | + tuning_job.state = job_state.JobState.JOB_STATE_CANCELLED |
| 127 | + |
| 128 | + |
| 129 | +class MockTuningJobClientWithOverride(aiplatform_utils.ClientWithOverride): |
| 130 | + _is_temporary = False |
| 131 | + _default_version = compat.V1 |
| 132 | + _version_map = ( |
| 133 | + (compat.V1, MockGenAiTuningServiceClient), |
| 134 | + # v1beta1 version does not exist |
| 135 | + # (compat.V1BETA1, gen_ai_tuning_service_v1beta1.client.JobServiceClient), |
| 136 | + ) |
| 137 | + |
| 138 | + |
| 139 | +@pytest.mark.usefixtures("google_auth_mock") |
| 140 | +class TestgenerativeModelTuning: |
| 141 | + """Unit tests for generative model tuning.""" |
| 142 | + |
| 143 | + def setup_method(self): |
| 144 | + vertexai.init( |
| 145 | + project=_TEST_PROJECT, |
| 146 | + location=_TEST_LOCATION, |
| 147 | + ) |
| 148 | + |
| 149 | + def teardown_method(self): |
| 150 | + initializer.global_pool.shutdown(wait=True) |
| 151 | + |
| 152 | + @mock.patch.object( |
| 153 | + target=tuning.TuningJob, |
| 154 | + attribute="client_class", |
| 155 | + new=MockTuningJobClientWithOverride, |
| 156 | + ) |
| 157 | + def test_genai_tuning_service_supervised_tuning_tune_model(self): |
| 158 | + sft_tuning_job = supervised_tuning.train( |
| 159 | + source_model="gemini-1.0-pro-001", |
| 160 | + train_dataset="gs://some-bucket/some_dataset.jsonl", |
| 161 | + # Optional: |
| 162 | + validation_dataset="gs://some-bucket/some_dataset.jsonl", |
| 163 | + epochs=300, |
| 164 | + learning_rate_multiplier=1.0, |
| 165 | + ) |
| 166 | + assert sft_tuning_job.state == job_state.JobState.JOB_STATE_PENDING |
| 167 | + assert not sft_tuning_job.has_ended |
| 168 | + assert not sft_tuning_job.has_succeeded |
| 169 | + |
| 170 | + # Refreshing the job |
| 171 | + sft_tuning_job.refresh() |
| 172 | + assert sft_tuning_job.state == job_state.JobState.JOB_STATE_PENDING |
| 173 | + assert not sft_tuning_job.has_ended |
| 174 | + assert not sft_tuning_job.has_succeeded |
| 175 | + |
| 176 | + # Refreshing the job |
| 177 | + sft_tuning_job.refresh() |
| 178 | + assert sft_tuning_job.state == job_state.JobState.JOB_STATE_RUNNING |
| 179 | + assert not sft_tuning_job.has_ended |
| 180 | + assert not sft_tuning_job.has_succeeded |
| 181 | + |
| 182 | + # Refreshing the job |
| 183 | + sft_tuning_job.refresh() |
| 184 | + assert sft_tuning_job.state == job_state.JobState.JOB_STATE_SUCCEEDED |
| 185 | + assert sft_tuning_job.has_ended |
| 186 | + assert sft_tuning_job.has_succeeded |
| 187 | + assert sft_tuning_job._experiment_name |
| 188 | + assert sft_tuning_job.tuned_model_name |
| 189 | + assert sft_tuning_job.tuned_model_endpoint_name |
0 commit comments