10#ifdef MOOSE_LIBTORCH_ENABLED
14#include <torch/torch.h>
23#include "libmesh/utility.h"
48 virtual void execute()
override;
89 unsigned int timestepWindow()
const {
return getParam<unsigned int>(
"timestep_window"); }
231 std::shared_ptr<Moose::LibtorchArtificialNeuralNet>
_critic_nn;
250 std::vector<
const std::vector<std::vector<Real>> *> & pointer_storage);
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.
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.
const bool _average_reward_over_timestep_window
Average rewards over each reporter timestep window instead of sampling one boundary value.
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.
unsigned int numberOfObservations() const
Return the number of observation reporters read at each time level.
virtual void execute() override
Pull fresh rollout data from the reporters and trigger training when ready.
Real _entropy_coeff
Entropy bonus coefficient used in the PPO actor loss.
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.
const Moose::LibtorchActorNeuralNet & controlNeuralNet() const
Return the current actor network.
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 Real _lambda_factor
GAE lambda factor used while estimating advantages and returns.
const std::vector< ReporterName > _state_names
Observation reporter names.
const bool _shift_outputs
Currently, the controls are executed after the user objects at initial in moose.
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.
std::vector< Real > sampleAverageEpsiodeRewards()
Return per-sample mean episodic rewards from the latest update window.
const Real _decay_factor
Decaying factor that is used when calculating the return from the reward.
Real _average_episode_reward
Storage for the current average episode reward.
unsigned int seed() const
Return the trainer seed used for sampling and shuffling.
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,...
unsigned int timestepWindow() const
Return the number of raw reporter entries per training transition.
void trainController(const LibtorchRLTrajectoryBuffer::TensorBatch &batch)
Run the PPO update on a flattened on-policy batch.
unsigned int numberOfControlSignals() const
Return the number of control signals produced by the actor.
const unsigned int _seed
Base seed for stochastic optimizers and policy sampling.
const Real _clip_param
The clip parameter used while clamping the advantage value.
std::vector< Real > _sample_average_episode_reward
Per-sample mean episodic rewards over the latest update window.
Real averageEpisodeReward()
Return the current average episodic reward.
unsigned int inputTimesteps() const
Return the number of observation time levels stacked into the network inputs.
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::vector< Real > sampleStdEpsiodeRewards()
Return per-sample episodic reward standard deviations from the latest update window.
Real stdEpisodeReward()
Return the current episodic reward standard deviation.
std::unique_ptr< torch::optim::Adam > _critic_optimizer
Adam optimizer used to update the critic network.
const ReporterName _reward_name
Reward reporter name.
std::vector< Real > _max_values
Optional upper bounds for each control signal.
Samples shuffled mini-batches from a flattened on-policy trajectory batch.
PPO clipped surrogate loss on top of the reusable RL buffer/value-estimation core.
Builds fixed-horizon RL trajectories from raw per-sample reporter sequences.
On-policy trajectory storage for fixed-horizon RL training.
Computes generalized-advantage estimates and value targets for an on-policy trajectory buffer,...
const InputParameters & parameters() const
Feed-forward actor network coupled to a Gaussian or Beta action distribution.
This is the base trainer class whose main functionality is the API for declaring model data.
Flattened tensor data assembled from the stored trajectories.