https://mooseframework.inl.gov
Loading...
Searching...
No Matches
LibtorchDRLControlTrainer.C
Go to the documentation of this file.
1//* This file is part of the MOOSE framework
2//* https://mooseframework.inl.gov
3//*
4//* All rights reserved, see COPYRIGHT for full restrictions
5//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6//*
7//* Licensed under LGPL 2.1, please see LICENSE for details
8//* https://www.gnu.org/licenses/lgpl-2.1.html
9
10#ifdef MOOSE_LIBTORCH_ENABLED
11
13#include "LibtorchRandomUtils.h"
14
16
19{
21
23 "Trains a neural network controller using fixed-horizon PPO on top of the libtorch RL core.");
24
25 params.addRequiredParam<std::vector<ReporterName>>(
26 "observation", "Reporter values containing the observation values from the model.");
27 params.addParam<std::vector<Real>>(
28 "observation_shift_factors",
29 {},
30 "Optional offsets applied to the observed state values before scaling.");
31 params.addParam<std::vector<Real>>(
32 "observation_scaling_factors",
33 {},
34 "Optional multipliers applied after shifting the observed state values.");
35 params.addRequiredParam<std::vector<ReporterName>>(
36 "control",
37 "Reporters containing the values of the controlled quantities (control signals) from the "
38 "model simulations.");
39 params.addParam<std::vector<Real>>(
40 "action_scaling_factors",
41 {},
42 "Scale factors embedded into the trained policy outputs so transferred and checkpointed "
43 "controllers operate in physical units.");
44 params.addRequiredParam<std::vector<ReporterName>>(
45 "log_probability",
46 "Reporters containing the log probabilities of the actions taken during the simulations.");
48 "reward", "Reporter containing the earned time-dependent rewards from the simulation.");
49 params.addRangeCheckedParam<unsigned int>(
50 "input_timesteps",
51 1,
52 "1<=input_timesteps",
53 "Number of time steps to use in the input data, if larger than 1, "
54 "data from the previous timesteps will be used as inputs in the training.");
55
56 params.addRequiredParam<unsigned int>("num_epochs", "Number of epochs for the training.");
57
58 params.addRequiredRangeCheckedParam<Real>("critic_learning_rate",
59 "0<critic_learning_rate",
60 "Learning rate used by the critic optimizer.");
61 params.addRequiredParam<std::vector<unsigned int>>("num_critic_neurons_per_layer",
62 "Hidden-layer widths for the critic network.");
63 params.addParam<std::vector<std::string>>(
64 "critic_activation_functions",
65 std::vector<std::string>({"relu"}),
66 "Activation name for each critic hidden layer, or one shared value for all layers.");
67
68 params.addRequiredRangeCheckedParam<Real>("control_learning_rate",
69 "0<control_learning_rate",
70 "Learning rate used by the actor optimizer.");
71 params.addRequiredParam<std::vector<unsigned int>>(
72 "num_control_neurons_per_layer",
73 "Number of neurons per layer for the control neural network.");
74 params.addParam<std::vector<std::string>>(
75 "control_activation_functions",
76 std::vector<std::string>({"relu"}),
77 "Activation name for each actor hidden layer, or one shared value for all layers.");
78
79 params.addParam<std::string>("filename_base",
80 "Base filename used when writing actor and critic checkpoints.");
81
82 params.addParam<unsigned int>(
83 "seed", 11, "Random number generator seed for stochastic optimizers.");
84
85 params.addParam<Real>(
86 "clip_parameter", 0.2, "Clip parameter used while clamping the advantage value.");
87 params.addRangeCheckedParam<unsigned int>(
88 "update_frequency",
89 1,
90 "1<=update_frequency",
91 "Number of transient simulation data to collect for updating the controller neural network.");
92
93 params.addRangeCheckedParam<Real>(
94 "decay_factor",
95 1.0,
96 "0.0<=decay_factor<=1.0",
97 "Discount factor used when building PPO return and GAE targets.");
98
99 params.addRangeCheckedParam<Real>("lambda_factor", 1.0, "0.0<=lambda_factor<=1.0", "GAE lambda.");
100
101 params.addParam<bool>(
102 "read_from_file", false, "Switch to read the neural network parameters from a file.");
103 params.addParam<bool>(
104 "shift_outputs",
105 true,
106 "Whether to shift rollout outputs so observations and actions line up in time.");
107 params.addParam<bool>(
108 "standardize_advantage",
109 true,
110 "Switch to enable the shifting and normalization of the advantages in the PPO algorithm.");
111 params.addParam<unsigned int>(
112 "loss_print_frequency", 0, "Print PPO loss values every N updates. Use 0 to stay quiet.");
113 params.addParam<unsigned int>("batch_size", 100, "Number of flattened samples per mini-batch.");
114 params.addParam<std::vector<Real>>(
115 "min_control_value", {}, "Optional lower bounds for each control signal.");
116 params.addParam<std::vector<Real>>(
117 "max_control_value", {}, "Optional upper bounds for each control signal.");
118 params.addParam<bool>(
119 "state_independent_std",
120 true,
121 "If true, learn one Gaussian log-std parameter per action dimension. If false, learn a "
122 "state-dependent std head as in the older MOOSE actor implementation.");
123
124 params.addParam<Real>(
125 "entropy_coeff", 0.01, "Entropy bonus coefficient used in the PPO actor loss.");
126
127 params.addRangeCheckedParam<unsigned int>(
128 "timestep_window",
129 1,
130 "1<=timestep_window",
131 "Use every nth reporter timestep when assembling trajectories. Observation history lags "
132 "also span this many timesteps, so it should match the controller's "
133 "'num_steps_in_period'.");
134 params.addParam<bool>("average_reward_over_timestep_window",
135 false,
136 "Average reward reporter values over each timestep_window interval instead "
137 "of sampling one value at the end of the interval.");
138
139 return params;
140}
141
143 : SurrogateTrainerBase(parameters),
144 _state_names(getParam<std::vector<ReporterName>>("observation")),
145 _state_shift_factors(isParamSetByUser("observation_shift_factors")
146 ? getParam<std::vector<Real>>("observation_shift_factors")
147 : std::vector<Real>(_state_names.size(), 0.0)),
148 _state_scaling_factors(isParamSetByUser("observation_scaling_factors")
149 ? getParam<std::vector<Real>>("observation_scaling_factors")
150 : std::vector<Real>(_state_names.size(), 1.0)),
151 _action_names(getParam<std::vector<ReporterName>>("control")),
152 _action_scaling_factors(isParamSetByUser("action_scaling_factors")
153 ? getParam<std::vector<Real>>("action_scaling_factors")
154 : std::vector<Real>(_action_names.size(), 1.0)),
155 _log_probability_names(getParam<std::vector<ReporterName>>("log_probability")),
156 _reward_name(getParam<ReporterName>("reward")),
157 _reward_value_pointer(&getReporterValueByName<std::vector<std::vector<Real>>>(_reward_name)),
158 _input_timesteps(getParam<unsigned int>("input_timesteps")),
159 _num_inputs(_input_timesteps * _state_names.size()),
160 _num_outputs(_action_names.size()),
161 _num_epochs(getParam<unsigned int>("num_epochs")),
162 _num_critic_neurons_per_layer(
163 getParam<std::vector<unsigned int>>("num_critic_neurons_per_layer")),
164 _critic_learning_rate(getParam<Real>("critic_learning_rate")),
165 _num_control_neurons_per_layer(
166 getParam<std::vector<unsigned int>>("num_control_neurons_per_layer")),
167 _control_learning_rate(getParam<Real>("control_learning_rate")),
168 _update_frequency(getParam<unsigned int>("update_frequency")),
169 _clip_param(getParam<Real>("clip_parameter")),
170 _decay_factor(getParam<Real>("decay_factor")),
171 _lambda_factor(getParam<Real>("lambda_factor")),
172 _filename_base(isParamValid("filename_base") ? getParam<std::string>("filename_base") : ""),
173 _read_from_file(getParam<bool>("read_from_file")),
174 _shift_outputs(getParam<bool>("shift_outputs")),
175 _average_reward_over_timestep_window(getParam<bool>("average_reward_over_timestep_window")),
176 _average_episode_reward(0.0),
177 _std_episode_reward(0.0),
178 _standardize_advantage(getParam<bool>("standardize_advantage")),
179 _loss_print_frequency(getParam<unsigned int>("loss_print_frequency")),
180 _seed(getParam<unsigned int>("seed")),
181 _min_values(getParam<std::vector<Real>>("min_control_value")),
182 _max_values(getParam<std::vector<Real>>("max_control_value")),
183 _highest_reward(-1e8),
184 _entropy_coeff(getParam<Real>("entropy_coeff")),
185 _update_counter(_update_frequency),
186 _trajectory_assembler(_input_timesteps,
187 getParam<unsigned int>("timestep_window"),
188 _shift_outputs,
189 _average_reward_over_timestep_window),
190 _sampler(LibtorchRLMiniBatchSampler()),
191 _value_estimator(_decay_factor, _lambda_factor),
192 _ppo_loss(_clip_param, _entropy_coeff)
193{
194 if (_state_names.size() != _state_shift_factors.size())
195 paramError("observation_shift_factors",
196 "The number of shift factors is not the same as the number of observations!");
197
198 if (_state_names.size() != _state_scaling_factors.size())
199 paramError("observation_scaling_factors",
200 "The number of normalization coefficients is not the same as the number of "
201 "observations!");
202
203 if (_action_names.size() != _log_probability_names.size())
204 paramError("log_probability",
205 "The number of log-probability reporters must match the number of control "
206 "reporters.");
207
208 if (_action_names.size() != _action_scaling_factors.size())
209 paramError("action_scaling_factors",
210 "The number of action scaling factors must match the number of control "
211 "reporters.");
212
213 // We establish the links with the chosen reporters
217
218 bool filename_valid = isParamValid("filename_base");
219 const LibtorchObservationHistoryHelper observation_history(_input_timesteps);
220 const auto input_shift_factors =
222 const auto input_scaling_factors =
224
225 // Initializing the control neural net so that the control can grab it right away
226 _control_nn = std::make_shared<Moose::LibtorchActorNeuralNet>(
227 filename_valid ? _filename_base + "_control.net" : "control.net",
231 getParam<std::vector<std::string>>("control_activation_functions"),
234 torch::kCPU,
235 torch::kDouble,
236 true,
237 input_shift_factors,
238 input_scaling_factors,
240 getParam<bool>("state_independent_std"));
241
242 // We read parameters for the control neural net if it is requested
243 if (_read_from_file)
244 {
246 _console << "Loaded requested .pt file." << std::endl;
247 }
248 else if (filename_valid)
249 torch::save(_control_nn, _control_nn->name());
250
251 // Initialize the critic neural net
252 _critic_nn = std::make_shared<Moose::LibtorchArtificialNeuralNet>(
253 filename_valid ? _filename_base + "_ctiric.net" : "ctiric.net",
255 1,
257 getParam<std::vector<std::string>>("critic_activation_functions"),
258 torch::kCPU,
259 torch::kDouble,
260 true,
261 input_shift_factors,
262 input_scaling_factors);
263
264 _actor_optimizer = std::make_unique<torch::optim::Adam>(
265 _control_nn->parameters(), torch::optim::AdamOptions(_control_learning_rate));
266 _critic_optimizer = std::make_unique<torch::optim::Adam>(
267 _critic_nn->parameters(), torch::optim::AdamOptions(_critic_learning_rate));
268
269 // We read parameters for the critic neural net if it is requested
270 if (_read_from_file)
271 {
272 try
273 {
275 _console << "Loaded requested .pt file." << std::endl;
276 }
277 catch (const c10::Error & e)
278 {
279 mooseError("The requested pytorch file could not be loaded for the critic neural net.\n",
280 e.msg());
281 }
282 }
283 else if (filename_valid)
284 torch::save(_critic_nn, _critic_nn->name());
285
286 // A loaded checkpoint already contains initialized parameters. Reinitializing here would
287 // silently discard the actor and critic states requested with read_from_file.
288 if (!_read_from_file)
289 {
290 _control_nn->initializeNeuralNetwork(
291 Moose::makeLibtorchCPUGenerator(static_cast<uint64_t>(_seed)));
292 _critic_nn->initializeNeuralNetwork(
293 Moose::makeLibtorchCPUGenerator(static_cast<uint64_t>(_seed) + 1));
294 }
295}
296
297void
299{
300 // Only executions that collect trajectories count toward update_frequency, so an execution
301 // without complete trajectories, such as on INITIAL, neither triggers nor delays training.
302 bool collected_trajectories = collectTrajectoriesFromReporters();
303 _communicator.max(collected_trajectories);
304 if (!collected_trajectories)
305 return;
306
307 mooseAssert(_update_counter > 0, "The update counter is reset after every training.");
308 if (--_update_counter != 0)
309 return;
310
314
316 {
317 torch::save(_control_nn, _control_nn->name() + "_best");
319 }
321
322 if (processor_id() == 0)
324 const auto batch = _trajectory_buffer.flatten();
325
326 trainController(batch);
327 resetData();
328}
329
330void
332{
333 const auto statistics = _trajectory_buffer.rewardStatistics();
334 _average_episode_reward = statistics.mean;
335 _std_episode_reward = statistics.std;
336 _sample_average_episode_reward = statistics.trajectory_means;
337 _sample_std_episode_reward = statistics.trajectory_stds;
338}
339
340void
342{
343 bool has_batch_data = batch.size();
344 _communicator.max(has_batch_data);
345
346 if (!has_batch_data)
347 return;
348
349 // We only train on the rank 0 partition. Libtorch should still be able to
350 // fetch the local threads which are available.
351 if (processor_id() == 0 && batch.size())
352 {
353 auto shuffle_generator = Moose::makeLibtorchCPUGenerator(
354 static_cast<uint64_t>(_seed) + static_cast<uint64_t>(_fe_problem.timeStep()));
355
356 for (unsigned int epoch = 0; epoch < _num_epochs; ++epoch)
357 {
358 const auto mini_batches = _sampler.sample(
359 batch, getParam<unsigned int>("batch_size"), _standardize_advantage, shuffle_generator);
360 bool printed_losses = false;
361 for (const auto & mini_batch : mini_batches)
362 {
363 const auto losses = _ppo_loss.compute(*_control_nn, *_critic_nn, mini_batch);
364
365 _actor_optimizer->zero_grad();
366 losses.actor_loss.backward();
367 _actor_optimizer->step();
368
369 _critic_optimizer->zero_grad();
370 losses.critic_loss.backward();
371 _critic_optimizer->step();
372
373 if (_loss_print_frequency && epoch % _loss_print_frequency == 0 && !printed_losses)
374 {
375 _console << "Epoch: " << epoch << " | Actor Loss: " << COLOR_GREEN
376 << losses.actor_loss.item<double>() << COLOR_DEFAULT
377 << " | Critic Loss: " << COLOR_GREEN << losses.critic_loss.item<double>()
378 << COLOR_DEFAULT << std::endl;
379 printed_losses = true;
380 }
381 }
382 }
383
384 _console << "Best model so far: " << _highest_reward << std::endl;
385 }
386
387 // It is time to send the trained data to every other processor so that the neural networks
388 // are the same on all ranks. TODO: Make sure this can be done on a GPU as well.
389 for (auto & param : _control_nn->named_parameters())
390 {
391 MPI_Bcast(param.value().data_ptr(), param.value().numel(), MPI_DOUBLE, 0, _communicator.get());
392 }
393
394 for (auto & param : _critic_nn->named_parameters())
395 {
396 MPI_Bcast(param.value().data_ptr(), param.value().numel(), MPI_DOUBLE, 0, _communicator.get());
397 }
398
399 // Save the controller neural net so our controller can read it, we also save the critic if we
400 // want to continue training
401 if (processor_id() == 0)
402 {
403 torch::save(_control_nn, _control_nn->name());
404 torch::save(_critic_nn, _critic_nn->name());
405 }
406}
407
408void
414
415bool
417{
422 for (auto & trajectory : trajectories)
423 _trajectory_buffer.addTrajectory(std::move(trajectory));
424 return !trajectories.empty();
425}
426
427void
429 const std::vector<ReporterName> & reporter_names,
430 std::vector<const std::vector<std::vector<Real>> *> & pointer_storage)
431{
432 pointer_storage.clear();
433 for (const auto & name : reporter_names)
434 pointer_storage.push_back(&getReporterValueByName<std::vector<std::vector<Real>>>(name));
435}
436
437#endif
registerMooseObject("StochasticToolsApp", LibtorchDRLControlTrainer)
void ErrorVector unsigned int
const ConsoleStream _console
virtual int & timeStep() const
void addRequiredRangeCheckedParam(const std::string &name, const std::string &parsed_function, const std::string &doc_string)
void addRequiredParam(const std::string &name, const std::string &doc_string)
void addParam(const std::string &name, const std::initializer_list< typename T::value_type > &value, const std::string &doc_string)
void addClassDescription(const std::string &doc_string)
void addRangeCheckedParam(const std::string &name, const T &value, const std::string &parsed_function, const std::string &doc_string)
Fixed-horizon actor-critic trainer that collects trajectories from MOOSE reporters and runs a PPO upd...
std::vector< const std::vector< std::vector< Real > > * > _log_probability_value_pointers
Pointers to the current values of the control log probabilities We can have multiple control signals,...
const Real _control_learning_rate
The learning rate for the optimization algorithm for the control.
std::vector< Real > _min_values
Optional lower bounds for each control signal.
const LibtorchRLMiniBatchSampler _sampler
Mini-batch sampler used to split flattened rollout data for PPO updates.
LibtorchDRLControlTrainer(const InputParameters &parameters)
Build the PPO-based DRL trainer.
std::shared_ptr< Moose::LibtorchArtificialNeuralNet > _critic_nn
Pointer to the critic neural net object.
const bool _standardize_advantage
Switch to enable the standardization of the advantages.
void resetData()
Reset the stored rollout data after an update.
const unsigned int _num_epochs
Number of epochs for the training of the emulator.
Real _highest_reward
Best average episode reward seen so far while training.
const unsigned int _update_frequency
Number of transients to run and collect data from before updating the controller neural net.
const LibtorchRLPPOLoss _ppo_loss
PPO loss helper for the actor and critic updates.
std::shared_ptr< Moose::LibtorchActorNeuralNet > _control_nn
Pointer to the control (or actor) neural net object.
unsigned int _update_counter
Counter for number of transient simulations that have been run before updating the controller.
const Real _critic_learning_rate
The learning rate for the optimization algorithm for the critic.
Real _std_episode_reward
Storage for the current episode reward standard deviation.
bool collectTrajectoriesFromReporters()
Pull trajectories out of the reporters and append them to the trajectory buffer.
const unsigned int _loss_print_frequency
The frequency the loss should be printed.
virtual void execute() override
Pull fresh rollout data from the reporters and trigger training when ready.
std::unique_ptr< torch::optim::Adam > _actor_optimizer
Adam optimizer used to update the actor network.
unsigned int _num_inputs
Number of inputs for the control and critic neural nets.
const std::vector< unsigned int > _num_control_neurons_per_layer
Number of neurons within the hidden layers in the control neural net.
void getReporterPointers(const std::vector< ReporterName > &reporter_names, std::vector< const std::vector< std::vector< Real > > * > &pointer_storage)
Resolve reporter names into cached pointer storage.
static InputParameters validParams()
Return the input parameters supported by this trainer.
const std::vector< std::vector< Real > > * _reward_value_pointer
Pointer to the current values of the reward We can have multiple samples, multiple timesteps.
const std::vector< Real > _action_scaling_factors
Multiplicative action scaling embedded in the actor outputs.
const std::vector< ReporterName > _action_names
Control reporter names.
const LibtorchRLTrajectoryAssembler _trajectory_assembler
Builds rollout trajectories from the raw reporter sequences.
const std::vector< ReporterName > _state_names
Observation reporter names.
const bool _read_from_file
Switch indicating if an already existing neural net should be read from a file or not.
const std::vector< unsigned int > _num_critic_neurons_per_layer
Number of neurons within the hidden layers in the critic neural net.
const std::vector< ReporterName > _log_probability_names
Log probability reporter names.
unsigned int _num_outputs
Number of outputs for the control neural network.
const std::vector< Real > _state_shift_factors
Shifting constants for the observations.
const LibtorchRLValueEstimator _value_estimator
Helper that builds value targets and advantages from collected trajectories.
const unsigned int _input_timesteps
Number of timesteps to fetch from the reporters to be the input of then eural nets.
Real _average_episode_reward
Storage for the current average episode reward.
std::vector< const std::vector< std::vector< Real > > * > _action_value_pointers
Pointers to the current values of the control signals We can have multiple control signals,...
const std::vector< Real > _state_scaling_factors
Scaling constants for the observations.
std::vector< const std::vector< std::vector< Real > > * > _state_value_pointers
Pointers to the current values of the observations We can have multiple observations,...
void trainController(const LibtorchRLTrajectoryBuffer::TensorBatch &batch)
Run the PPO update on a flattened on-policy batch.
const unsigned int _seed
Base seed for stochastic optimizers and policy sampling.
std::vector< Real > _sample_average_episode_reward
Per-sample mean episodic rewards over the latest update window.
LibtorchRLTrajectoryBuffer _trajectory_buffer
Accumulated on-policy rollout data waiting to be flattened and trained on.
const std::string _filename_base
Name of the pytorch output file.
void computeEpisodeRewardStatistics()
Compute the average episodic reward statistics for the latest samples.
std::vector< Real > _sample_std_episode_reward
Per-sample episodic reward standard deviations over the latest update window.
std::unique_ptr< torch::optim::Adam > _critic_optimizer
Adam optimizer used to update the critic network.
std::vector< Real > _max_values
Optional upper bounds for each control signal.
std::vector< Real > expandObservationFactors(const std::vector< Real > &observation_factors) const
Samples shuffled mini-batches from a flattened on-policy trajectory batch.
std::vector< LibtorchRLMiniBatch > sample(const LibtorchRLTrajectoryBuffer::TensorBatch &batch, unsigned int batch_size, bool standardize_advantage, c10::optional< at::Generator > generator=c10::nullopt) const
Shuffle a flattened rollout batch into PPO-sized chunks.
LibtorchRLPPOLossOutput compute(Moose::LibtorchActorNeuralNet &policy_network, Moose::LibtorchArtificialNeuralNet &value_network, const LibtorchRLMiniBatch &batch) const
Compute actor, critic, and entropy terms for one mini-batch.
std::vector< LibtorchRLTrajectoryBuffer::Trajectory > assemble(const ReporterData &observations, const ReporterData &actions, const ReporterData &log_probabilities, const std::vector< std::vector< Real > > &rewards) const
Assemble one trajectory per sample that holds at least one transition.
void addTrajectory(Trajectory trajectory)
Append one trajectory to the on-policy buffer.
TensorBatch flatten() const
Flatten every stored trajectory into one tensor batch.
RewardStatistics rewardStatistics() const
Compute reward statistics over the stored trajectories.
void clear()
Clear every stored trajectory.
void computeValueTargets(LibtorchRLTrajectoryBuffer &buffer, Moose::LibtorchArtificialNeuralNet &value_network) const
Fill every trajectory in the buffer with value targets and advantages.
const std::string & name() const
void paramError(const std::string &param, Args... args) const
void mooseError(Args &&... args) const
bool isParamValid(const std::string &name) const
const T & getReporterValueByName(const ReporterName &reporter_name, const std::size_t time_index=0)
This is the base trainer class whose main functionality is the API for declaring model data.
static InputParameters validParams()
void max(const T &r, T &o, Request &req) const
void broadcast(T &data, const unsigned int root_id=0, const bool identical_sizes=false) const
FEProblemBase & _fe_problem
const Parallel::Communicator & _communicator
processor_id_type processor_id() const
at::Generator makeLibtorchCPUGenerator()
void loadLibtorchActorNeuralNetState(Moose::LibtorchActorNeuralNet &nn, const std::string &filename)
Load an actor checkpoint written as a native libtorch state archive.
void loadLibtorchArtificialNeuralNetState(Moose::LibtorchArtificialNeuralNet &nn, const std::string &filename)
torch::Tensor actor_loss
Clipped actor loss for the current mini-batch.
Real mean
Mean reward over every stored transition.
Flattened tensor data assembled from the stored trajectories.
std::int64_t size() const
Return the number of transitions represented by the batch.