-
Notifications
You must be signed in to change notification settings - Fork 320
/
_language_models.py
4112 lines (3549 loc) · 166 KB
/
_language_models.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2023 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.
#
"""Classes for working with language models."""
import abc
import dataclasses
import collections.abc
from typing import (
Any,
AsyncIterator,
Dict,
Iterator,
List,
Literal,
Optional,
Sequence,
Tuple,
Union,
)
import warnings
from google.cloud import aiplatform
from google.cloud.aiplatform import _streaming_prediction
from google.cloud.aiplatform import base
from google.cloud.aiplatform import initializer as aiplatform_initializer
from google.cloud.aiplatform import utils as aiplatform_utils
from google.cloud.aiplatform.compat import types as aiplatform_types
from google.cloud.aiplatform.utils import gcs_utils
from vertexai._model_garden import _model_garden_models
from vertexai.language_models import (
_evaluatable_language_models,
)
try:
import pandas
except ImportError:
pandas = None
_LOGGER = base.Logger(__name__)
# Endpoint label/metadata key to preserve the base model ID information
_TUNING_BASE_MODEL_ID_LABEL_KEY = "google-vertex-llm-tuning-base-model-id"
# Default URI for RLHF training template in the Vertex Template Gallery
_DEFAULT_RLHF_TUNING_PIPELINE_URI = "https://us-kfp.pkg.dev/ml-pipeline/google-cloud-registry/rlhf-train-template/default"
_ACCELERATOR_TYPES = ["TPU", "GPU"]
_ACCELERATOR_TYPE_TYPE = Literal["TPU", "GPU"]
def _get_model_id_from_tuning_model_id(tuning_model_id: str) -> str:
"""Gets the base model ID for the model ID labels used the tuned models.
Args:
tuning_model_id: The model ID used in tuning. E.g. `text-bison-001`
Returns:
The publisher model ID
Raises:
ValueError: If tuning model ID is unsupported
"""
model_name, _, version = tuning_model_id.rpartition("-")
# "publishers/google/models/text-bison@001"
return f"publishers/google/models/{model_name}@{version}"
def _get_tensorboard_resource_id_from_evaluation_spec(
eval_spec: "TuningEvaluationSpec",
tuning_job_location: str,
) -> Optional[str]:
"""Gets the Tensorboard resource ID from an evaluation spec.
Args:
eval_spec: To extract Tensorboard resource ID from.
tuning_job_location: Location . Used to check that the tensorboard
location is in the same region as tuning.
Returns:
Tensorboard resource ID, if it was set.
Raises:
ValueError: If Tensorboard location is not in the same region as tuning
TypeError: If Tensorboard URI is not a string.
"""
if eval_spec.tensorboard is None:
return None
elif isinstance(eval_spec.tensorboard, aiplatform.Tensorboard):
if eval_spec.tensorboard.location != tuning_job_location:
raise ValueError(
"The Tensorboard must be in the same location as the tuning job."
)
return eval_spec.tensorboard.resource_name
elif isinstance(eval_spec.tensorboard, str):
resource_name_parts = aiplatform.Tensorboard._parse_resource_name(
eval_spec.tensorboard
)
if resource_name_parts["location"] != tuning_job_location:
raise ValueError(
"The Tensorboard must be in the same location as the tuning job. "
f"Tensorboard location: {resource_name_parts['location']}, "
f"tuning job location: {tuning_job_location}"
)
return eval_spec.tensorboard
else:
raise TypeError("Tensorboard should be a URI string")
class _LanguageModel(_model_garden_models._ModelGardenModel):
"""_LanguageModel is a base class for all language models."""
def __init__(self, model_id: str, endpoint_name: Optional[str] = None):
"""Creates a LanguageModel.
This constructor should not be called directly.
Use `LanguageModel.from_pretrained(model_name=...)` instead.
Args:
model_id: Identifier of a Vertex LLM. Example: "text-bison@001"
endpoint_name: Vertex Endpoint resource name for the model
"""
super().__init__(
model_id=model_id,
endpoint_name=endpoint_name,
)
@property
def _model_resource_name(self) -> str:
"""Full resource name of the model."""
if "publishers/" in self._endpoint_name:
return self._endpoint_name
else:
# This is a ModelRegistry resource name
return self._endpoint.list_models()[0].model
@dataclasses.dataclass
class _PredictionRequest:
"""A single-instance prediction request."""
instance: Dict[str, Any]
parameters: Optional[Dict[str, Any]] = None
@dataclasses.dataclass
class _MultiInstancePredictionRequest:
"""A multi-instance prediction request."""
instances: List[Dict[str, Any]]
parameters: Optional[Dict[str, Any]] = None
class _GetTunedModelMixin(_model_garden_models._ModelGardenModel):
"""Mixin that adds methods that list and get tuned language models."""
def list_tuned_model_names(self) -> Sequence[str]:
"""Lists the names of tuned models.
Returns:
A list of tuned models that can be used with the `get_tuned_model` method.
"""
model_info = _model_garden_models._get_model_info(
model_id=self._model_id,
schema_to_class_map={self._INSTANCE_SCHEMA_URI: type(self)},
)
return _list_tuned_model_names(model_id=model_info.tuning_model_id)
@classmethod
def get_tuned_model(cls, tuned_model_name: str) -> "_LanguageModel":
"""Loads the specified tuned language model."""
tuned_vertex_model = aiplatform.Model(tuned_model_name)
tuned_model_labels = tuned_vertex_model.labels
if _TUNING_BASE_MODEL_ID_LABEL_KEY not in tuned_model_labels:
raise ValueError(
f"The provided model {tuned_model_name} does not have a base model ID."
)
tuning_model_id = tuned_vertex_model.labels[_TUNING_BASE_MODEL_ID_LABEL_KEY]
tuned_model_deployments = tuned_vertex_model.gca_resource.deployed_models
if len(tuned_model_deployments) == 0:
# Deploying the model
endpoint_name = tuned_vertex_model.deploy().resource_name
else:
endpoint_name = tuned_model_deployments[0].endpoint
base_model_id = _get_model_id_from_tuning_model_id(tuning_model_id)
model_info = _model_garden_models._get_model_info(
model_id=base_model_id,
schema_to_class_map={cls._INSTANCE_SCHEMA_URI: cls},
)
model = model_info.interface_class(
model_id=base_model_id,
endpoint_name=endpoint_name,
)
return model
class _TunableModelMixin(_LanguageModel, _GetTunedModelMixin):
"""Model that can be tuned with supervised fine tuning (SFT)."""
def tune_model(
self,
training_data: Union[str, "pandas.core.frame.DataFrame"],
*,
corpus_data: Optional[str] = None,
queries_data: Optional[str] = None,
test_data: Optional[str] = None,
validation_data: Optional[str] = None,
batch_size: Optional[int] = None,
train_steps: Optional[int] = None,
learning_rate: Optional[float] = None,
learning_rate_multiplier: Optional[float] = None,
tuning_job_location: Optional[str] = None,
tuned_model_location: Optional[str] = None,
model_display_name: Optional[str] = None,
tuning_evaluation_spec: Optional["TuningEvaluationSpec"] = None,
default_context: Optional[str] = None,
task_type: Optional[str] = None,
machine_type: Optional[str] = None,
accelerator: Optional[str] = None,
accelerator_count: Optional[int] = None,
accelerator_type: Optional[_ACCELERATOR_TYPE_TYPE] = None,
max_context_length: Optional[str] = None,
output_dimensionality: Optional[int] = None,
) -> "_LanguageModelTuningJob":
"""Tunes a model based on training data.
This method launches and returns an asynchronous model tuning job.
Usage:
```
tuning_job = model.tune_model(...)
... do some other work
tuned_model = tuning_job.get_tuned_model() # Blocks until tuning is complete
```
Args:
training_data: A URI to training data in TSV (for embedding models), or JSON lines format, or a Pandas DataFrame.
corpus_data: A URI to corpus in JSON lines format.
queries_data: A URI to queries in JSON lines format.
test_data: A URI to test data in TSV format.
validation_data: A URI to validation data in TSV format.
batch_size: Size of batch (for embedding models).
train_steps: Number of training batches to tune on (batch size is 8 samples).
learning_rate: Deprecated. Use learning_rate_multiplier instead.
Learning rate to use in tuning.
learning_rate_multiplier: Learning rate multiplier to use in tuning.
tuning_job_location: GCP location where the tuning job should be run.
tuned_model_location: GCP location where the tuned model should be deployed.
model_display_name: Custom display name for the tuned model.
tuning_evaluation_spec: Specification for the model evaluation during tuning.
default_context: The context to use for all training samples by default.
task_type: Type of task. Can be "RETRIEVAL_QUERY", "RETRIEVAL_DOCUMENT", "SEMANTIC_SIMILARITY", "CLASSIFICATION", "CLUSTERING", "QUESTION_ANSWERING", or "FACT_VERIFICATION".
machine_type: Machine type. E.g., "a2-highgpu-1g". See also: https://cloud.google.com/vertex-ai/docs/training/configure-compute.
accelerator: Kind of accelerator. E.g., "NVIDIA_TESLA_A100". See also: https://cloud.google.com/vertex-ai/docs/training/configure-compute.
accelerator_count: Count of accelerators.
accelerator_type: Type of accelerator to use. Type can be "TPU" or "GPU". Type is ignored, if accelerator is specified.
max_context_length: The max context length used for tuning.
Can be either '8k' or '32k'
output_dimensionality: The output dimensionality of the tuned model,
for text embedding tuning.
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the "tuning_job_location" value is not supported
ValueError: If the "tuned_model_location" value is not supported
RuntimeError: If the model does not support tuning
"""
if tuning_job_location is None:
tuning_job_location = aiplatform_initializer.global_config.location
if tuned_model_location is None:
tuned_model_location = aiplatform_initializer.global_config.location
tuning_parameters = {}
if batch_size is not None:
tuning_parameters["batch_size"] = batch_size
if train_steps is not None:
tuning_parameters["train_steps"] = train_steps
if output_dimensionality is not None:
tuning_parameters["output_dimensionality"] = output_dimensionality
if learning_rate is not None:
_LOGGER.warning(
"The learning_rate parameter is deprecated."
"Use the learning_rate_multiplier parameter instead."
)
tuning_parameters["learning_rate"] = learning_rate
if learning_rate_multiplier is not None:
tuning_parameters["learning_rate_multiplier"] = learning_rate_multiplier
eval_spec = tuning_evaluation_spec
if eval_spec is not None:
if eval_spec.evaluation_data:
if isinstance(eval_spec.evaluation_data, str):
if eval_spec.evaluation_data.startswith("gs://"):
tuning_parameters[
"evaluation_data_uri"
] = eval_spec.evaluation_data
else:
raise ValueError("evaluation_data should be a GCS URI")
else:
raise TypeError("evaluation_data should be a URI string")
if eval_spec.evaluation_interval is not None:
tuning_parameters["evaluation_interval"] = eval_spec.evaluation_interval
if eval_spec.enable_early_stopping is not None:
tuning_parameters[
"enable_early_stopping"
] = eval_spec.enable_early_stopping
if eval_spec.enable_checkpoint_selection is not None:
tuning_parameters[
"enable_checkpoint_selection"
] = eval_spec.enable_checkpoint_selection
tensorboard_resource_id = _get_tensorboard_resource_id_from_evaluation_spec(
eval_spec, tuning_job_location
)
if tensorboard_resource_id is not None:
tuning_parameters["tensorboard_resource_id"] = tensorboard_resource_id
if default_context:
tuning_parameters["default_context"] = default_context
if task_type is not None:
tuning_parameters["task_type"] = task_type
if machine_type is not None:
tuning_parameters["machine_type"] = machine_type
if accelerator_count is not None:
tuning_parameters["accelerator_count"] = accelerator_count
if accelerator is not None:
tuning_parameters["accelerator_type"] = accelerator
elif accelerator_type:
if accelerator_type not in _ACCELERATOR_TYPES:
raise ValueError(
f"Unsupported accelerator type: {accelerator_type}."
f" Supported types: {_ACCELERATOR_TYPES}"
)
tuning_parameters["accelerator_type"] = accelerator_type
if max_context_length:
tuning_parameters["max_context_length"] = max_context_length
if corpus_data is not None:
tuning_parameters["corpus_path"] = corpus_data
if queries_data is not None:
tuning_parameters["queries_path"] = queries_data
if test_data is not None:
tuning_parameters["test_label_path"] = test_data
if validation_data is not None:
tuning_parameters["validation_label_path"] = validation_data
return self._tune_model(
training_data=training_data,
tuning_parameters=tuning_parameters,
tuning_job_location=tuning_job_location,
tuned_model_location=tuned_model_location,
model_display_name=model_display_name,
)
def _tune_model(
self,
training_data: Union[str, "pandas.core.frame.DataFrame"],
*,
tuning_parameters: Dict[str, Any],
tuning_job_location: Optional[str] = None,
tuned_model_location: Optional[str] = None,
model_display_name: Optional[str] = None,
):
"""Tunes a model based on training data.
This method launches a model tuning job that can take some time.
Args:
training_data: A Pandas DataFrame or a URI pointing to data in JSON lines format.
The dataset schema is model-specific.
See https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-models#dataset_format
tuning_parameters: Tuning pipeline parameter values.
tuning_job_location: GCP location where the tuning job should be run.
tuned_model_location: GCP location where the tuned model should be deployed.
model_display_name: Custom display name for the tuned model.
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the "tuning_job_location" value is not supported
ValueError: If the "tuned_model_location" value is not supported
RuntimeError: If the model does not support tuning
"""
if tuning_job_location and tuning_job_location not in _TUNING_LOCATIONS:
raise ValueError(
_get_invalid_tuning_location_msg(
requested_location=tuning_job_location,
valid_locations=_TUNING_LOCATIONS,
)
)
if tuned_model_location and tuned_model_location not in _TUNED_MODEL_LOCATIONS:
raise ValueError(
"Tuned model deployment is only supported in the following locations: "
f"{_TUNED_MODEL_LOCATIONS}"
)
model_info = _model_garden_models._get_model_info(
model_id=self._model_id,
schema_to_class_map={self._INSTANCE_SCHEMA_URI: type(self)},
)
if _is_text_embedding_tuning_pipeline(model_info.tuning_pipeline_uri):
tunable_base_model_id = self._model_id.rpartition("/")[-1]
tuning_parameters["base_model_version_id"] = tunable_base_model_id
else:
tuning_parameters["large_model_reference"] = model_info.tuning_model_id
tuning_parameters.update(
{
"project": aiplatform_initializer.global_config.project,
# TODO(b/275444096): Remove the explicit location once tuning
# can happen in all regions.
# "location": aiplatform_initializer.global_config.location,
"location": tuned_model_location,
}
)
if aiplatform_initializer.global_config.encryption_spec_key_name:
tuning_parameters[
"encryption_spec_key_name"
] = aiplatform_initializer.global_config.encryption_spec_key_name
if not model_info.tuning_pipeline_uri:
raise RuntimeError(f"The {self._model_id} model does not support tuning")
pipeline_job = _launch_tuning_job(
training_data=training_data,
model_id=model_info.tuning_model_id,
tuning_pipeline_uri=model_info.tuning_pipeline_uri,
tuning_parameters=tuning_parameters,
model_display_name=model_display_name,
tuning_job_location=tuning_job_location,
tuned_model_location=tuned_model_location,
)
return self._bundle_up_tuning_job(pipeline_job)
def _bundle_up_tuning_job(self, pipeline_job):
return _LanguageModelTuningJob(
base_model=self,
job=pipeline_job,
)
@dataclasses.dataclass(frozen=True)
class _RlhfTuningParameters:
"""Configurable parameters for RLHF tuning."""
prompt_dataset: str
preference_dataset: str
large_model_reference: str
location: str
model_display_name: Optional[str] = None
prompt_sequence_length: Optional[int] = None
target_sequence_length: Optional[int] = None
reward_model_learning_rate_multiplier: Optional[float] = None
reinforcement_learning_rate_multiplier: Optional[float] = None
reward_model_train_steps: Optional[int] = None
reinforcement_learning_train_steps: Optional[int] = None
kl_coeff: Optional[float] = None
instruction: Optional[str] = None
deploy_model: Optional[bool] = None
eval_dataset: Optional[str] = None
project: Optional[str] = None
accelerator_type: Optional[_ACCELERATOR_TYPE_TYPE] = None
tensorboard_resource_id: Optional[str] = None
def asdict(self) -> Dict[str, Any]:
"""Returns a dictionary of tuning parameters with undefined optional keys removed."""
data = dataclasses.asdict(self)
return {key: value for key, value in data.items() if value is not None}
class _RlhfTunableModelMixin(_LanguageModel, _GetTunedModelMixin):
"""Model that can be tuned with reinforcement learning from human feedback (RLHF)."""
def tune_model_rlhf(
self,
*,
prompt_data: Union[str, "pandas.core.frame.DataFrame"],
preference_data: Union[str, "pandas.core.frame.DataFrame"],
model_display_name: Optional[str] = None,
prompt_sequence_length: Optional[int] = None,
target_sequence_length: Optional[int] = None,
reward_model_learning_rate_multiplier: Optional[float] = None,
reinforcement_learning_rate_multiplier: Optional[float] = None,
reward_model_train_steps: Optional[int] = None,
reinforcement_learning_train_steps: Optional[int] = None,
kl_coeff: Optional[float] = None,
default_context: Optional[str] = None,
tuning_job_location: Optional[str] = None,
accelerator_type: Optional[_ACCELERATOR_TYPE_TYPE] = None,
tuning_evaluation_spec: Optional["TuningEvaluationSpec"] = None,
) -> "_LanguageModelTuningJob":
"""Tunes a model using reinforcement learning from human feedback.
This method launches and returns an asynchronous model tuning job.
Usage:
```
tuning_job = model.tune_model_rlhf(...)
... do some other work
tuned_model = tuning_job.get_tuned_model() # Blocks until tuning is complete
```
Args:
prompt_data: A Pandas DataFrame or a URI pointing to data in JSON lines
format. The dataset schema is model-specific.
See https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-text-models-rlhf#prompt-dataset
preference_data: A Pandas DataFrame or a URI pointing to data in JSON lines
format. The dataset schema is model-specific.
See https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-text-models-rlhf#human-preference-dataset
model_display_name: Custom display name for the tuned model.
If not provided, a default name will be created.
prompt_sequence_length: Maximum tokenized sequence length for input text.
Higher values increase memory overhead.
This value should be at most 8192. Default value is 512.
target_sequence_length: Maximum tokenized sequence length for target text.
Higher values increase memory overhead.
This value should be at most 1024. Default value is 64.
reward_model_learning_rate_multiplier: Constant used to adjust the base
learning rate used when training a reward model. Multiply by a
number > 1 to increase the magnitude of updates applied at each
training step or multiply by a number < 1 to decrease the magnitude
of updates. Default value is 1.0.
reinforcement_learning_rate_multiplier: Constant used to adjust the base
learning rate used during reinforcement learning. Multiply by a
number > 1 to increase the magnitude of updates applied at each
training step or multiply by a number < 1 to decrease the magnitude
of updates. Default value is 1.0.
reward_model_train_steps: Number of steps to use when training a reward
model. Default value is 1000.
reinforcement_learning_train_steps: Number of reinforcement learning steps
to perform when tuning a base model. Default value is 1000.
kl_coeff: Coefficient for KL penalty. This regularizes the policy model and
penalizes if it diverges from its initial distribution. If set to 0,
the reference language model is not loaded into memory. Default value
is 0.1.
default_context: This field lets the model know what task to perform.
Base models have been trained over a large set of varied instructions.
You can give a simple and intuitive description of the task and the
model will follow it, e.g. "Classify this movie review as positive or
negative" or "Translate this sentence to Danish". Do not specify this
if your dataset already prepends the instruction to the inputs field.
tuning_job_location: GCP location where the tuning job should be run.
accelerator_type: Type of accelerator to use. Can be "TPU" or "GPU".
tuning_evaluation_spec: Evaluation settings to use during tuning.
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the "tuning_job_location" value is not supported
RuntimeError: If the model does not support tuning
"""
tuning_job_location = (
tuning_job_location or aiplatform_initializer.global_config.location
)
eval_dataset = None
tensorboard_resource_id = None
if tuning_evaluation_spec is not None:
_check_unused_rlhf_eval_specs(tuning_evaluation_spec)
eval_dataset = tuning_evaluation_spec.evaluation_data
if eval_dataset is not None and not eval_dataset.startswith("gs://"):
raise ValueError(
"evaluation_data must be a GCS URI that starts with gs://"
)
tensorboard_resource_id = _get_tensorboard_resource_id_from_evaluation_spec(
tuning_evaluation_spec, tuning_job_location
)
prompt_dataset_uri = _maybe_upload_training_data(
training_data=prompt_data,
model_id=self._model_id,
)
preference_dataset_uri = _maybe_upload_training_data(
training_data=preference_data,
model_id=self._model_id,
)
if accelerator_type:
if accelerator_type not in _ACCELERATOR_TYPES:
raise ValueError(
f"Unsupported accelerator type: {accelerator_type}."
f" Supported types: {_ACCELERATOR_TYPES}"
)
tuning_parameters = _RlhfTuningParameters(
prompt_dataset=prompt_dataset_uri,
preference_dataset=preference_dataset_uri,
large_model_reference=self._model_id.rsplit("/", 1)[-1],
location=tuning_job_location,
model_display_name=model_display_name,
prompt_sequence_length=prompt_sequence_length,
target_sequence_length=target_sequence_length,
reward_model_learning_rate_multiplier=reward_model_learning_rate_multiplier,
reinforcement_learning_rate_multiplier=reinforcement_learning_rate_multiplier,
reward_model_train_steps=reward_model_train_steps,
reinforcement_learning_train_steps=reinforcement_learning_train_steps,
kl_coeff=kl_coeff,
instruction=default_context,
eval_dataset=eval_dataset,
accelerator_type=accelerator_type,
tensorboard_resource_id=tensorboard_resource_id,
)
return self._tune_model_rlhf(
tuning_parameters=tuning_parameters,
)
def _tune_model_rlhf(
self,
*,
tuning_parameters: _RlhfTuningParameters,
):
"""Tunes a model using reinforcement learning from human feedback.
This method launches a tuning job that can take some time.
Args:
tuning_parameters: Tuning pipeline parameter values.
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the tuning location is not supported
RuntimeError: If the model does not support tuning
"""
if tuning_parameters.location not in _TUNING_LOCATIONS:
raise ValueError(
_get_invalid_tuning_location_msg(
requested_location=tuning_parameters.location,
valid_locations=_TUNING_LOCATIONS,
)
)
if self._model_id not in _SUPPORTED_RLHF_MODELS:
raise ValueError(
_get_invalid_rlhf_model_msg(
requested_model=self._model_id,
)
)
pipeline_job = _launch_rlhf_tuning_job(tuning_parameters)
job = _LanguageModelTuningJob(
base_model=self,
job=pipeline_job,
)
return job
class _TunableTextModelMixin(_TunableModelMixin):
"""Text model that can be tuned."""
def tune_model(
self,
training_data: Union[str, "pandas.core.frame.DataFrame"],
*,
train_steps: Optional[int] = None,
learning_rate_multiplier: Optional[float] = None,
tuning_job_location: Optional[str] = None,
tuned_model_location: Optional[str] = None,
model_display_name: Optional[str] = None,
tuning_evaluation_spec: Optional["TuningEvaluationSpec"] = None,
accelerator_type: Optional[_ACCELERATOR_TYPE_TYPE] = None,
max_context_length: Optional[str] = None,
) -> "_LanguageModelTuningJob":
"""Tunes a model based on training data.
This method launches and returns an asynchronous model tuning job.
Usage:
```
tuning_job = model.tune_model(...)
... do some other work
tuned_model = tuning_job.get_tuned_model() # Blocks until tuning is complete
Args:
training_data: A Pandas DataFrame or a URI pointing to data in JSON lines format.
The dataset schema is model-specific.
See https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-models#dataset_format
train_steps: Number of training batches to tune on (batch size is 8 samples).
learning_rate_multiplier: Learning rate multiplier to use in tuning.
tuning_job_location: GCP location where the tuning job should be run.
tuned_model_location: GCP location where the tuned model should be deployed.
model_display_name: Custom display name for the tuned model.
tuning_evaluation_spec: Specification for the model evaluation during tuning.
accelerator_type: Type of accelerator to use. Can be "TPU" or "GPU".
max_context_length: The max context length used for tuning.
Can be either '8k' or '32k'
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the "tuning_job_location" value is not supported
ValueError: If the "tuned_model_location" value is not supported
RuntimeError: If the model does not support tuning
"""
# Note: Chat models do not support default_context
return super().tune_model(
training_data=training_data,
train_steps=train_steps,
learning_rate_multiplier=learning_rate_multiplier,
tuning_job_location=tuning_job_location,
tuned_model_location=tuned_model_location,
model_display_name=model_display_name,
tuning_evaluation_spec=tuning_evaluation_spec,
accelerator_type=accelerator_type,
max_context_length=max_context_length,
)
class _PreviewTunableTextModelMixin(_TunableModelMixin):
"""Text model that can be tuned."""
def tune_model(
self,
training_data: Union[str, "pandas.core.frame.DataFrame"],
*,
train_steps: int = 1000,
learning_rate: Optional[float] = None,
learning_rate_multiplier: Optional[float] = None,
tuning_job_location: Optional[str] = None,
tuned_model_location: Optional[str] = None,
model_display_name: Optional[str] = None,
tuning_evaluation_spec: Optional["TuningEvaluationSpec"] = None,
accelerator_type: Optional[_ACCELERATOR_TYPE_TYPE] = None,
max_context_length: Optional[str] = None,
) -> "_LanguageModelTuningJob":
"""Tunes a model based on training data.
This method launches a model tuning job, waits for completion,
updates the model in-place. This method returns job object for forward
compatibility.
In the future (GA), this method will become asynchronous and will stop
updating the model in-place.
Usage:
```
tuning_job = model.tune_model(...) # Blocks until tuning is complete
tuned_model = tuning_job.get_tuned_model() # Blocks until tuning is complete
```
Args:
training_data: A Pandas DataFrame or a URI pointing to data in JSON lines format.
The dataset schema is model-specific.
See https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-models#dataset_format
train_steps: Number of training batches to tune on (batch size is 8 samples).
learning_rate: Deprecated. Use learning_rate_multiplier instead.
Learning rate to use in tuning.
learning_rate_multiplier: Learning rate multiplier to use in tuning.
tuning_job_location: GCP location where the tuning job should be run.
tuned_model_location: GCP location where the tuned model should be deployed.
model_display_name: Custom display name for the tuned model.
tuning_evaluation_spec: Specification for the model evaluation during tuning.
accelerator_type: Type of accelerator to use. Can be "TPU" or "GPU".
max_context_length: The max context length used for tuning.
Can be either '8k' or '32k'
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the "tuning_job_location" value is not supported
ValueError: If the "tuned_model_location" value is not supported
RuntimeError: If the model does not support tuning
"""
# Note: Chat models do not support default_context
job = super().tune_model(
training_data=training_data,
train_steps=train_steps,
learning_rate=learning_rate,
learning_rate_multiplier=learning_rate_multiplier,
tuning_job_location=tuning_job_location,
tuned_model_location=tuned_model_location,
model_display_name=model_display_name,
tuning_evaluation_spec=tuning_evaluation_spec,
accelerator_type=accelerator_type,
max_context_length=max_context_length,
)
tuned_model = job.get_tuned_model()
self._endpoint = tuned_model._endpoint
self._endpoint_name = tuned_model._endpoint_name
return job
class _TunableChatModelMixin(_TunableModelMixin):
"""Chat model that can be tuned."""
def tune_model(
self,
training_data: Union[str, "pandas.core.frame.DataFrame"],
*,
train_steps: Optional[int] = None,
learning_rate_multiplier: Optional[float] = None,
tuning_job_location: Optional[str] = None,
tuned_model_location: Optional[str] = None,
model_display_name: Optional[str] = None,
default_context: Optional[str] = None,
accelerator_type: Optional[_ACCELERATOR_TYPE_TYPE] = None,
tuning_evaluation_spec: Optional["TuningEvaluationSpec"] = None,
) -> "_LanguageModelTuningJob":
"""Tunes a model based on training data.
This method launches and returns an asynchronous model tuning job.
Usage:
```
tuning_job = model.tune_model(...)
... do some other work
tuned_model = tuning_job.get_tuned_model() # Blocks until tuning is complete
```
Args:
training_data: A Pandas DataFrame or a URI pointing to data in JSON lines format.
The dataset schema is model-specific.
See https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-models#dataset_format
train_steps: Number of training batches to tune on (batch size is 8 samples).
learning_rate: Deprecated. Use learning_rate_multiplier instead.
Learning rate to use in tuning.
learning_rate_multiplier: Learning rate multiplier to use in tuning.
tuning_job_location: GCP location where the tuning job should be run.
tuned_model_location: GCP location where the tuned model should be deployed.
model_display_name: Custom display name for the tuned model.
default_context: The context to use for all training samples by default.
accelerator_type: Type of accelerator to use. Can be "TPU" or "GPU".
tuning_evaluation_spec: Specification for the model evaluation during tuning.
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the "tuning_job_location" value is not supported
ValueError: If the "tuned_model_location" value is not supported
RuntimeError: If the model does not support tuning
AttributeError: If any attribute in the "tuning_evaluation_spec" is not supported
"""
if tuning_evaluation_spec is not None:
unsupported_chat_model_tuning_eval_spec = {
"evaluation_data": tuning_evaluation_spec.evaluation_data,
"evaluation_interval": tuning_evaluation_spec.evaluation_interval,
"enable_early_stopping": tuning_evaluation_spec.enable_early_stopping,
"enable_checkpoint_selection": tuning_evaluation_spec.enable_checkpoint_selection,
}
for att_name, att_value in unsupported_chat_model_tuning_eval_spec.items():
if att_value is not None:
raise AttributeError(
(
f"ChatModel and CodeChatModel only support tensorboard as attribute for TuningEvaluationSpec"
f"found attribute name {att_name} with value {att_value}, please leave {att_name} to None"
)
)
return super().tune_model(
training_data=training_data,
train_steps=train_steps,
learning_rate_multiplier=learning_rate_multiplier,
tuning_job_location=tuning_job_location,
tuned_model_location=tuned_model_location,
model_display_name=model_display_name,
default_context=default_context,
accelerator_type=accelerator_type,
tuning_evaluation_spec=tuning_evaluation_spec,
)
class _PreviewTunableChatModelMixin(_TunableModelMixin):
"""Chat model that can be tuned."""
def tune_model(
self,
training_data: Union[str, "pandas.core.frame.DataFrame"],
*,
train_steps: int = 1000,
learning_rate: Optional[float] = None,
learning_rate_multiplier: Optional[float] = None,
tuning_job_location: Optional[str] = None,
tuned_model_location: Optional[str] = None,
model_display_name: Optional[str] = None,
default_context: Optional[str] = None,
accelerator_type: Optional[_ACCELERATOR_TYPE_TYPE] = None,
) -> "_LanguageModelTuningJob":
"""Tunes a model based on training data.
This method launches a model tuning job, waits for completion,
updates the model in-place. This method returns job object for forward
compatibility.
In the future (GA), this method will become asynchronous and will stop
updating the model in-place.
Usage:
```
tuning_job = model.tune_model(...) # Blocks until tuning is complete
tuned_model = tuning_job.get_tuned_model() # Blocks until tuning is complete
```
Args:
training_data: A Pandas DataFrame or a URI pointing to data in JSON lines format.
The dataset schema is model-specific.
See https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-models#dataset_format
train_steps: Number of training batches to tune on (batch size is 8 samples).
learning_rate: Deprecated. Use learning_rate_multiplier instead.
Learning rate to use in tuning.
learning_rate_multiplier: Learning rate multiplier to use in tuning.
tuning_job_location: GCP location where the tuning job should be run.
tuned_model_location: GCP location where the tuned model should be deployed.
model_display_name: Custom display name for the tuned model.
default_context: The context to use for all training samples by default.
accelerator_type: Type of accelerator to use. Can be "TPU" or "GPU".
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the "tuning_job_location" value is not supported
ValueError: If the "tuned_model_location" value is not supported
RuntimeError: If the model does not support tuning
"""
# Note: Chat models do not support tuning_evaluation_spec
job = super().tune_model(
training_data=training_data,
train_steps=train_steps,
learning_rate=learning_rate,
learning_rate_multiplier=learning_rate_multiplier,
tuning_job_location=tuning_job_location,
tuned_model_location=tuned_model_location,
model_display_name=model_display_name,
default_context=default_context,
accelerator_type=accelerator_type,
)
tuned_model = job.get_tuned_model()
self._endpoint = tuned_model._endpoint
self._endpoint_name = tuned_model._endpoint_name
return job
@dataclasses.dataclass
class CountTokensResponse:
"""The response from a count_tokens request.
Attributes:
total_tokens (int):
The total number of tokens counted across all
instances passed to the request.
total_billable_characters (int):
The total number of billable characters
counted across all instances from the request.
"""
total_tokens: int
total_billable_characters: int
_count_tokens_response: Any
class _CountTokensMixin(_LanguageModel):
"""Mixin for models that support the CountTokens API"""
def count_tokens(
self,
prompts: List[str],
) -> CountTokensResponse:
"""Counts the tokens and billable characters for a given prompt.
Note: this does not make a prediction request to the model, it only counts the tokens
in the request.
Args:
prompts (List[str]):
Required. A list of prompts to ask the model. For example: ["What should I do today?", "How's it going?"]
Returns:
A `CountTokensResponse` object that contains the number of tokens
in the text and the number of billable characters.
"""
instances = []
for prompt in prompts:
instances.append({"content": prompt})