Setting the file. One moment.
Sft · 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/ sft.py
Python · 152 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: Create Dataset and Model Package Group
38
39 # Create Model Package Group
40 try :
41 model_package_group = ModelPackageGroup.create(
42 model_package_group_name = MODEL_PACKAGE_GROUP_NAME ,
43 model_package_group_description = "" ,
44 )
45 print ( f "Created new model package group named { MODEL_PACKAGE_GROUP_NAME } " )
46 except ClientError as e:
47 if e.response[ "Error" ][ "Code" ] in ( "ResourceInUse" , "ValidationException" ):
48 model_package_group = ModelPackageGroup.get(
49 model_package_group_name = MODEL_PACKAGE_GROUP_NAME
50 )
51 print (
52 f "There is already a model package group with the name { MODEL_PACKAGE_GROUP_NAME } . If you want to save your finetuned model under a different name, change the value of MODEL_PACKAGE_GROUP_NAME in the previous cell."
53 )
54 else :
55 raise
56
57 # Create Dataset
58 # Register dataset in SageMaker AI Registry. This creates a versioned dataset that can be referenced by ARN
59 dataset = DataSet.create( name = MODEL_PACKAGE_GROUP_NAME , source = TRAINING_DATA_S3 , wait = True )
60
61 TRAINING_DATASET_ARN = dataset.arn
62 print ( f "Here is your model package group ARN: { model_package_group.model_package_group_arn }\n " )
63 print ( f "Here is your training dataset ARN: { dataset.arn } " )
64
65 # Cell 4: Configure Trainer
66
67 from sagemaker.train.common import TrainingType
68 from sagemaker.train.sft_trainer import SFTTrainer
69
70 trainer = SFTTrainer(
71 model = BASE_MODEL ,
72 training_type = TrainingType. LORA ,
73 model_package_group = model_package_group,
74 training_dataset = TRAINING_DATASET_ARN ,
75 s3_output_path = S3_OUTPUT_PATH ,
76 sagemaker_session = sagemaker_session,
77 # accept_eula=ACCEPT_EULA, # Uncomment for Meta models
78 role = ROLE_ARN ,
79 )
80
81 print ( "Here are the recommended hyperparameters for the current training job:" )
82 print ( f "Batch size: { trainer.hyperparameters.global_batch_size } " )
83 print ( f "Learning rate: { trainer.hyperparameters.learning_rate } " )
84 # Remove the following two print statements for Nova models (Nova models don't use max_epochs or lr_warmup_steps_ratio)
85 print ( f "Number of epochs: { trainer.hyperparameters.max_epochs } " )
86 print ( f "Learning rate warmup steps ratio: { trainer.hyperparameters.lr_warmup_steps_ratio } " )
87
88 # Cell 5: Hyperparameter Overrides
89
90 # To change a hyperparameter, uncomment its corresponding line, and set the value you want.
91
92 # Note: If the value you choose is not supported for your model, you will get an error indicating the allowed range.
93
94 # Uncomment the following line to change the learning rate
95 # trainer.hyperparameters.learning_rate = 0.0002
96
97 # Uncomment the following line to change the batch size
98 # trainer.hyperparameters.global_batch_size = 16
99
100 # Uncomment the following line to change the number of epochs (unavailable for Nova models)
101 # trainer.hyperparameters.max_epochs = 5
102
103 # Uncomment the following line to change the learning rate warmup steps ratio (unavailable for Nova models)
104 # trainer.hyperparameters.lr_warmup_steps_ratio = 0.05
105
106 # Cell 6: Start Training
107
108 # Start training
109 training_job = trainer.train( wait = True )
110
111 print ( f "Training Job Name: { training_job.training_job_name } " )
112 print ( f "Training Status: { training_job.training_job_status } " )
113
114 # Save manifest
115 manifest_dir = Path( "[PROJECT_DIR]" ) / "manifests"
116 manifest_dir.mkdir( parents = True , exist_ok = True )
117 manifest_path = manifest_dir / f "training- { training_job.training_job_name } .json"
118 manifest_path.write_text(
119 json.dumps(
120 {
121 "training_job_name" : training_job.training_job_name,
122 "model_package_group_name" : MODEL_PACKAGE_GROUP_NAME ,
123 },
124 indent = 2 ,
125 )
126 )
127 print ( f "Manifest saved: { manifest_path } " )
128
129 # Cell 7: Plot and Display Metrics # NOTEBOOK_ONLY_SECTION
130
131 import matplotlib.pyplot as plt
132 import mlflow
133 from mlflow.tracking import MlflowClient
134
135 run_id = training_job.mlflow_details.mlflow_run_id
136 mlflow.set_tracking_uri(training_job.mlflow_config.mlflow_resource_arn)
137 client = MlflowClient()
138
139 fig, axes = plt.subplots( 1 , 2 , figsize = ( 12 , 3 ))
140 for idx, metric in enumerate ([ "total_loss" , "val_eval_total_loss" ]):
141 history = client.get_metric_history(run_id, metric)
142 axes[idx].plot(
143 [h.step for h in history], [h.value for h in history], linewidth = 2 , marker = "o" , markersize = 4
144 )
145 axes[idx].set_xlabel( "Step" )
146 axes[idx].set_ylabel( "Loss" )
147 axes[idx].set_title(metric, fontweight = "bold" )
148 axes[idx].grid( True , alpha = 0.3 )
149
150 plt.suptitle( f "Training Metrics: { training_job.training_job_name } " , fontweight = "bold" )
151 plt.tight_layout()
152 plt.show()