Setting the file. One moment.
Rlvr · 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/ rlvr.py
Python · 182 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
21 set_attribution(Attribution. SAGEMAKER_AGENT_PLUGIN )
22
23 # Setup
24 sm_client = boto3.Session().client( "sagemaker" )
25 sagemaker_session = Session( sagemaker_client = sm_client)
26 bucket = sagemaker_session.default_bucket()
27
28 # Configuration - USER please fill in these fields with your information:
29
30 BASE_MODEL = "" # e.g., "meta-textgeneration-llama-3-8b"
31 TRAINING_DATA_S3 = "" # S3 path
32 S3_OUTPUT_PATH = f "s3:// { bucket } /finetuning-output/"
33 ROLE_ARN = get_execution_role() # You can change this to a specific role.
34 ACCEPT_EULA = False # Set to True to accept the base model's End-User License Agreement
35 MODEL_PACKAGE_GROUP_NAME = "" # Auto-generated based on use case
36
37 # Cell 3: Register Reward Function
38
39 from sagemaker.ai_registry.evaluator import Evaluator
40
41 reward_function_path = (
42 "" # Insert path to the local reward function (usually ../scripts/lambda_function.py)
43 )
44
45 evaluator = Evaluator.create(
46 name = "[GENERATE A NAME FOR THE EVALUATOR HERE]" ,
47 type = "RewardFunction" ,
48 source = reward_function_path,
49 )
50 CUSTOM_REWARD_FUNCTION = evaluator.arn
51 print ( f "Reward Function ARN: { CUSTOM_REWARD_FUNCTION } " )
52
53 # Cell 4: Create Dataset and Model Package Group
54
55 # Create Model Package Group
56 try :
57 model_package_group = ModelPackageGroup.create(
58 model_package_group_name = MODEL_PACKAGE_GROUP_NAME ,
59 model_package_group_description = "" ,
60 )
61 print ( f "Created new model package group named { MODEL_PACKAGE_GROUP_NAME } " )
62 except ClientError as e:
63 if e.response[ "Error" ][ "Code" ] in ( "ResourceInUse" , "ValidationException" ):
64 model_package_group = ModelPackageGroup.get(
65 model_package_group_name = MODEL_PACKAGE_GROUP_NAME
66 )
67 print (
68 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."
69 )
70 else :
71 raise
72
73 # Create Dataset
74 # Register dataset in SageMaker AI Registry. This creates a versioned dataset that can be referenced by ARN
75 dataset = DataSet.create( name = MODEL_PACKAGE_GROUP_NAME , source = TRAINING_DATA_S3 , wait = True )
76 TRAINING_DATASET_ARN = dataset.arn
77
78 print ( f "Here is your model package group ARN: { model_package_group.model_package_group_arn }\n " )
79 print ( f "Here is your training dataset ARN: { dataset.arn } " )
80
81 # Cell 5: Configure Trainer
82
83 from sagemaker.train.common import TrainingType
84 from sagemaker.train.rlvr_trainer import RLVRTrainer
85
86 trainer = RLVRTrainer(
87 model = BASE_MODEL ,
88 model_package_group = model_package_group,
89 training_dataset = TRAINING_DATASET_ARN ,
90 s3_output_path = S3_OUTPUT_PATH ,
91 sagemaker_session = sagemaker_session,
92 # accept_eula=ACCEPT_EULA, # Uncomment for Meta models
93 role = ROLE_ARN ,
94 custom_reward_function = CUSTOM_REWARD_FUNCTION ,
95 )
96
97 print ( "Here are the recommended hyperparameters for the current training job:" )
98 print ( f "Batch size: { trainer.hyperparameters.global_batch_size } " )
99 print ( f "Learning rate: { trainer.hyperparameters.learning_rate } " )
100 # Delete the following print statement for Nova models (Nova models don't use max_epochs)
101 print ( f "Number of epochs: { trainer.hyperparameters.max_epochs } " )
102
103 # Cell 6: Hyperparameter Overrides
104
105 # To change a hyperparameter, uncomment its corresponding line, and set the value you want.
106
107 # Note: If the value you choose is not supported for your model, you will get an error indicating the allowed range.
108
109 # Uncomment the following line to change the learning rate
110 # trainer.hyperparameters.learning_rate = 0.0002
111
112 # Uncomment the following line to change the batch size
113 # trainer.hyperparameters.global_batch_size = 16
114
115 # Uncomment the following line to change the number of epochs (unavailable for Nova models)
116 # trainer.hyperparameters.max_epochs = 5
117
118 # Cell 7: Start Training
119
120 # Start training
121 training_job = trainer.train( wait = True )
122
123 print ( f "Training Job Name: { training_job.training_job_name } " )
124 print ( f "Training Status: { training_job.training_job_status } " )
125
126 # Save manifest
127 manifest_dir = Path( "[PROJECT_DIR]" ) / "manifests"
128 manifest_dir.mkdir( parents = True , exist_ok = True )
129 manifest_path = manifest_dir / f "training- { training_job.training_job_name } .json"
130 manifest_path.write_text(
131 json.dumps(
132 {
133 "training_job_name" : training_job.training_job_name,
134 "model_package_group_name" : MODEL_PACKAGE_GROUP_NAME ,
135 },
136 indent = 2 ,
137 )
138 )
139 print ( f "Manifest saved: { manifest_path } " )
140
141 # Cell 8: Plot and Display Metrics # NOTEBOOK_ONLY_SECTION
142
143 import matplotlib.pyplot as plt
144 import mlflow
145 from mlflow.tracking import MlflowClient
146
147 run_id = training_job.mlflow_details.mlflow_run_id
148 mlflow.set_tracking_uri(training_job.mlflow_config.mlflow_resource_arn)
149 client = MlflowClient()
150
151 # Core RL metrics - adjust val-core metric names based on your data source and reward function
152 metrics = [
153 "critic/rewards/mean" ,
154 "response_length/mean" ,
155 "actor/entropy_loss" ,
156 "actor/grad_norm" ,
157 "critic/advantages/mean" ,
158 ]
159 # Note: Validation reward metrics follow the pattern: val-core/{data_source}/reward(/acc)/mean@{k}
160 # Add your specific val-core metrics to the list above, e.g.:
161 # "val-core/my_dataset/reward/mean@1"
162 # ResponseQuality: Verl allows printing to a file. Check training job output for details.
163
164 fig, axes = plt.subplots( 1 , len (metrics), figsize = ( 4 * len (metrics), 3 ))
165 for idx, metric in enumerate (metrics):
166 history = client.get_metric_history(run_id, metric)
167 if history:
168 axes[idx].plot(
169 [h.step for h in history],
170 [h.value for h in history],
171 linewidth = 2 ,
172 marker = "o" ,
173 markersize = 4 ,
174 )
175 axes[idx].set_xlabel( "Step" )
176 axes[idx].set_ylabel(metric.split( "/" )[ - 1 ])
177 axes[idx].set_title(metric, fontweight = "bold" )
178 axes[idx].grid( True , alpha = 0.3 )
179
180 plt.suptitle( f "Training Metrics: { training_job.training_job_name } " , fontweight = "bold" )
181 plt.tight_layout()
182 plt.show()