Setting the file. One moment.
Rlaif Builtin · AWS AI ML · aws/agent-toolkit-for-aws · Skills Docs
Issue No. 14 · AWS AI ML
↖ Back to the coverMessaging And Streaming Skills
Migration And Modernization Skills
Networking And Content Delivery Skills
Security And Identity Skills
Web And Mobile Development
120 chapters · 648 min
ContentsBack to the top of the page 10
Setup DevOps Agent
24.7
Code Output Guide · references
RDS Oracle
(opens in a new tab)
references/finetuning/code_templates/ rlaif_builtin.py
Python · 169 lines · 6 KB
16 from sagemaker.ai_registry.dataset import DataSet
17 from sagemaker.core import Attribution, set_attribution
18 from sagemaker.core.helper.session_helper import Session, get_execution_role
19 from sagemaker.core.resources import ModelPackageGroup
20 from sagemaker.train.common import TrainingType
21 from sagemaker.train.rlaif_trainer import RLAIFTrainer
22
23 set_attribution(Attribution. SAGEMAKER_AGENT_PLUGIN )
24
25 # Setup
26 sm_client = boto3.Session().client( "sagemaker" )
27 sagemaker_session = Session( sagemaker_client = sm_client)
28 bucket = sagemaker_session.default_bucket()
29
30 # Configuration - USER please fill in these fields with your information:
31
32 BASE_MODEL = "" # Sagemaker Hub model id
33 TRAINING_DATA_S3 = "" # S3 path
34 S3_OUTPUT_PATH = f "s3:// { bucket } /finetuning-output/"
35 ROLE_ARN = get_execution_role() # You can change this to a specific role
36 ACCEPT_EULA = (
37 False # Set to True to accept the base model's End-User License Agreement (OSS models only)
38 )
39 MODEL_PACKAGE_GROUP_NAME = "" # Auto-generated based on use case
40
41 # Reward model — the Bedrock LLM used as judge
42 # Available models and regions: see references/rlaif_guide.md
43 REWARD_MODEL_ID = ""
44
45 # Builtin reward prompt value — choose one that matches your use case:
46 # "Builtin.Summarize", "Builtin.Faithfulness", "Builtin.ChainOfThought", "Builtin.Evaluation"
47 REWARD_PROMPT_VALUE = ""
48
49 # Cell 3: Create Dataset and Model Package Group
50
51 # Create Model Package Group
52 try :
53 model_package_group = ModelPackageGroup.create(
54 model_package_group_name = MODEL_PACKAGE_GROUP_NAME ,
55 model_package_group_description = "" ,
56 )
57 print ( f "Created new model package group named { MODEL_PACKAGE_GROUP_NAME } " )
58 except ClientError as e:
59 if e.response[ "Error" ][ "Code" ] in ( "ResourceInUse" , "ValidationException" ):
60 model_package_group = ModelPackageGroup.get(
61 model_package_group_name = MODEL_PACKAGE_GROUP_NAME
62 )
63 print (
64 f "There is already a model package group with the name { MODEL_PACKAGE_GROUP_NAME } . \n If you want to save your finetuned model under a different name, change the value of MODEL_PACKAGE_GROUP_NAME in the previous cell."
65 )
66 else :
67 raise
68
69 # Create Dataset
70 dataset = DataSet.create( name = MODEL_PACKAGE_GROUP_NAME , source = TRAINING_DATA_S3 , wait = True )
71 TRAINING_DATASET_ARN = dataset.arn
72
73 print ( f "Here is your model package group ARN: { model_package_group.model_package_group_arn }\n " )
74 print ( f "Here is your training dataset ARN: { dataset.arn } " )
75
76 # Cell 4: Configure Trainer
77
78 trainer = RLAIFTrainer(
79 model = BASE_MODEL ,
80 model_package_group = model_package_group,
81 reward_model_id = REWARD_MODEL_ID ,
82 reward_prompt = REWARD_PROMPT_VALUE ,
83 training_dataset = TRAINING_DATASET_ARN ,
84 s3_output_path = S3_OUTPUT_PATH ,
85 sagemaker_session = sagemaker_session,
86 # accept_eula=ACCEPT_EULA, # Uncomment for Meta models
87 role = ROLE_ARN ,
88 )
89
90 print ( "Here are the recommended hyperparameters for the current training job:" )
91 print ( f "Batch size: { trainer.hyperparameters.global_batch_size } " )
92 print ( f "Learning rate: { trainer.hyperparameters.learning_rate } " )
93 print ( f "Epochs: { trainer.hyperparameters.max_epochs } " )
94
95 # Cell 5: Hyperparameter Overrides
96
97 # To change a hyperparameter, uncomment its corresponding line, and set the value you want.
98
99 # Note: If the value you choose is not supported for your model, you will get an error indicating the allowed range.
100
101 # Uncomment the following line to change the learning rate
102 # trainer.hyperparameters.learning_rate = 0.0002
103
104 # Uncomment the following line to change the batch size
105 # trainer.hyperparameters.global_batch_size = 16
106
107 # Uncomment the following line to change the number of epochs
108 # trainer.hyperparameters.max_epochs = 5
109
110 # Cell 6: Start Training
111
112 # Start training
113 training_job = trainer.train( wait = True )
114
115 print ( f "Training Job Name: { training_job.training_job_name } " )
116 print ( f "Training Status: { training_job.training_job_status } " )
117
118 # Save manifest
119 manifest_dir = Path( "[PROJECT_DIR]" ) / "manifests"
120 manifest_dir.mkdir( parents = True , exist_ok = True )
121 manifest_path = manifest_dir / f "training- { training_job.training_job_name } .json"
122 manifest_path.write_text(
123 json.dumps(
124 {
125 "training_job_name" : training_job.training_job_name,
126 "model_package_group_name" : MODEL_PACKAGE_GROUP_NAME ,
127 },
128 indent = 2 ,
129 )
130 )
131 print ( f "Manifest saved: { manifest_path } " )
132
133 # Cell 7: Plot and Display Metrics # NOTEBOOK_ONLY_SECTION
134
135 import matplotlib.pyplot as plt
136 import mlflow
137 from mlflow.tracking import MlflowClient
138
139 run_id = training_job.mlflow_details.mlflow_run_id
140 mlflow.set_tracking_uri(training_job.mlflow_config.mlflow_resource_arn)
141 client = MlflowClient()
142
143 metrics = [
144 "critic/rewards/mean" ,
145 "response_length/mean" ,
146 "actor/entropy_loss" ,
147 "actor/grad_norm" ,
148 "critic/advantages/mean" ,
149 ]
150
151 fig, axes = plt.subplots( 1 , len (metrics), figsize = ( 4 * len (metrics), 3 ))
152 for idx, metric in enumerate (metrics):
153 history = client.get_metric_history(run_id, metric)
154 if history:
155 axes[idx].plot(
156 [h.step for h in history],
157 [h.value for h in history],
158 linewidth = 2 ,
159 marker = "o" ,
160 markersize = 4 ,
161 )
162 axes[idx].set_xlabel( "Step" )
163 axes[idx].set_ylabel(metric.split( "/" )[ - 1 ])
164 axes[idx].set_title(metric, fontweight = "bold" )
165 axes[idx].grid( True , alpha = 0.3 )
166
167 plt.suptitle( f "Training Metrics: { training_job.training_job_name } " , fontweight = "bold" )
168 plt.tight_layout()
169 plt.show()