https://mooseframework.inl.gov
Loading...
Searching...
No Matches
Classes | Public Member Functions | Static Private Member Functions | Private Attributes | List of all members
LibtorchRLTrajectoryBuffer Class Reference

On-policy trajectory storage for fixed-horizon RL training. More...

#include <LibtorchRLTrajectoryBuffer.h>

Classes

struct  RewardStatistics
 Reward statistics over the stored trajectories. More...
 
struct  TensorBatch
 Flattened tensor data assembled from the stored trajectories. More...
 
struct  Trajectory
 Vector data for one on-policy trajectory. More...
 

Public Member Functions

void addTrajectory (Trajectory trajectory)
 Append one trajectory to the on-policy buffer.
 
void clear ()
 Clear every stored trajectory.
 
bool empty () const
 Return true if the buffer contains no trajectories.
 
std::size_t numTrajectories () const
 Return the number of stored trajectories.
 
std::size_t numTransitions () const
 Count the total number of transitions stored across every trajectory.
 
std::vector< Trajectory > & trajectories ()
 Return mutable access to the stored trajectories.
 
const std::vector< Trajectory > & trajectories () const
 Return read-only access to the stored trajectories.
 
TensorBatch flatten () const
 Flatten every stored trajectory into one tensor batch.
 
RewardStatistics rewardStatistics () const
 Compute reward statistics over the stored trajectories.
 

Static Private Member Functions

static void validateTrajectory (const Trajectory &trajectory)
 Validate a trajectory before it is stored.
 

Private Attributes

std::vector< Trajectory > _trajectories
 Stored on-policy trajectories.
 

Detailed Description

On-policy trajectory storage for fixed-horizon RL training.

Definition at line 24 of file LibtorchRLTrajectoryBuffer.h.

Member Function Documentation

◆ addTrajectory()

void LibtorchRLTrajectoryBuffer::addTrajectory ( Trajectory  trajectory)

Append one trajectory to the on-policy buffer.

Parameters
trajectoryTrajectory to store.

Definition at line 67 of file LibtorchRLTrajectoryBuffer.C.

68{
69 validateTrajectory(trajectory);
70 _trajectories.push_back(std::move(trajectory));
71}
static void validateTrajectory(const Trajectory &trajectory)
Validate a trajectory before it is stored.
std::vector< Trajectory > _trajectories
Stored on-policy trajectories.

Referenced by LibtorchDRLControlTrainer::collectTrajectoriesFromReporters().

◆ clear()

void LibtorchRLTrajectoryBuffer::clear ( )

Clear every stored trajectory.

Definition at line 74 of file LibtorchRLTrajectoryBuffer.C.

75{
76 _trajectories.clear();
77}

Referenced by LibtorchDRLControlTrainer::resetData().

◆ empty()

bool LibtorchRLTrajectoryBuffer::empty ( ) const
inline

Return true if the buffer contains no trajectories.

Definition at line 105 of file LibtorchRLTrajectoryBuffer.h.

105{ return _trajectories.empty(); }

◆ flatten()

LibtorchRLTrajectoryBuffer::TensorBatch LibtorchRLTrajectoryBuffer::flatten ( ) const

Flatten every stored trajectory into one tensor batch.

Returns
Tensor batch ready for mini-batch sampling.

Definition at line 89 of file LibtorchRLTrajectoryBuffer.C.

90{
91 TensorBatch batch;
92
93 if (_trajectories.empty())
94 return batch;
95
96 std::vector<std::vector<Real>> observations;
97 std::vector<std::vector<Real>> next_observations;
98 std::vector<std::vector<Real>> actions;
99 std::vector<std::vector<Real>> log_probabilities;
100 std::vector<Real> rewards;
101 std::vector<Real> value_targets;
102 std::vector<Real> advantages;
103
104 observations.reserve(numTransitions());
105 next_observations.reserve(numTransitions());
106 actions.reserve(numTransitions());
107 log_probabilities.reserve(numTransitions());
108 rewards.reserve(numTransitions());
109 value_targets.reserve(numTransitions());
110 advantages.reserve(numTransitions());
111
112 for (const auto & trajectory : _trajectories)
113 {
114 if (!trajectory.value_targets.empty() &&
115 trajectory.value_targets.size() != trajectory.rewards.size())
116 mooseError("Value targets must match the reward length of the trajectory.");
117 if (!trajectory.advantages.empty() && trajectory.advantages.size() != trajectory.rewards.size())
118 mooseError("Advantages must match the reward length of the trajectory.");
119
120 observations.insert(
121 observations.end(), trajectory.observations.begin(), trajectory.observations.end());
122 next_observations.insert(next_observations.end(),
123 trajectory.next_observations.begin(),
124 trajectory.next_observations.end());
125 actions.insert(actions.end(), trajectory.actions.begin(), trajectory.actions.end());
126 log_probabilities.insert(log_probabilities.end(),
127 trajectory.log_probabilities.begin(),
128 trajectory.log_probabilities.end());
129 rewards.insert(rewards.end(), trajectory.rewards.begin(), trajectory.rewards.end());
130 value_targets.insert(
131 value_targets.end(), trajectory.value_targets.begin(), trajectory.value_targets.end());
132 advantages.insert(advantages.end(), trajectory.advantages.begin(), trajectory.advantages.end());
133 }
134
135 batch.observations = bufferMatrixToTensor(observations);
136 batch.next_observations = bufferMatrixToTensor(next_observations);
137 batch.actions = bufferMatrixToTensor(actions);
138 batch.log_probabilities = bufferMatrixToTensor(log_probabilities);
139 batch.rewards = bufferVectorToColumnTensor(rewards);
140 batch.value_targets = bufferVectorToColumnTensor(value_targets);
141 batch.advantages = bufferVectorToColumnTensor(advantages);
142
143 return batch;
144}
void mooseError(Args &&... args)
std::size_t numTransitions() const
Count the total number of transitions stored across every trajectory.

Referenced by LibtorchDRLControlTrainer::execute().

◆ numTrajectories()

std::size_t LibtorchRLTrajectoryBuffer::numTrajectories ( ) const
inline

Return the number of stored trajectories.

Definition at line 110 of file LibtorchRLTrajectoryBuffer.h.

110{ return _trajectories.size(); }

◆ numTransitions()

std::size_t LibtorchRLTrajectoryBuffer::numTransitions ( ) const

Count the total number of transitions stored across every trajectory.

Returns
Total transition count.

Definition at line 80 of file LibtorchRLTrajectoryBuffer.C.

81{
82 std::size_t transitions = 0;
83 for (const auto & trajectory : _trajectories)
84 transitions += trajectory.rewards.size();
85 return transitions;
86}

Referenced by flatten(), and rewardStatistics().

◆ rewardStatistics()

LibtorchRLTrajectoryBuffer::RewardStatistics LibtorchRLTrajectoryBuffer::rewardStatistics ( ) const

Compute reward statistics over the stored trajectories.

Returns
Overall and per-trajectory reward means and standard deviations.

Definition at line 147 of file LibtorchRLTrajectoryBuffer.C.

148{
149 RewardStatistics statistics;
150
151 const auto num_transitions = numTransitions();
152 if (!num_transitions)
153 return statistics;
154
155 const auto squared_deviation_sum = [](const std::vector<Real> & values, const Real mean)
156 {
157 return std::transform_reduce(values.begin(),
158 values.end(),
159 0.0,
160 std::plus<>(),
161 [mean](const Real value)
162 { return (value - mean) * (value - mean); });
163 };
164
165 Real reward_sum = 0.0;
166 for (const auto & trajectory : _trajectories)
167 {
168 const auto & rewards = trajectory.rewards;
169 if (rewards.empty())
170 continue;
171
172 const Real trajectory_sum = std::accumulate(rewards.begin(), rewards.end(), 0.0);
173 const Real trajectory_mean = trajectory_sum / rewards.size();
174 statistics.trajectory_means.push_back(trajectory_mean);
175 statistics.trajectory_stds.push_back(
176 std::sqrt(squared_deviation_sum(rewards, trajectory_mean) / rewards.size()));
177 reward_sum += trajectory_sum;
178 }
179 statistics.mean = reward_sum / num_transitions;
180
181 // The deviations are taken about the overall mean so the spread between trajectories counts.
182 Real overall_squared_deviation_sum = 0.0;
183 for (const auto & trajectory : _trajectories)
184 overall_squared_deviation_sum += squared_deviation_sum(trajectory.rewards, statistics.mean);
185 statistics.std = std::sqrt(overall_squared_deviation_sum / num_transitions);
186
187 return statistics;
188}
std::array< Real, 2 > values
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real

Referenced by LibtorchDRLControlTrainer::computeEpisodeRewardStatistics().

◆ trajectories() [1/2]

std::vector< Trajectory > & LibtorchRLTrajectoryBuffer::trajectories ( )
inline

Return mutable access to the stored trajectories.

Definition at line 121 of file LibtorchRLTrajectoryBuffer.h.

121{ return _trajectories; }

Referenced by LibtorchRLValueEstimator::computeValueTargets().

◆ trajectories() [2/2]

const std::vector< Trajectory > & LibtorchRLTrajectoryBuffer::trajectories ( ) const
inline

Return read-only access to the stored trajectories.

Definition at line 126 of file LibtorchRLTrajectoryBuffer.h.

126{ return _trajectories; }

◆ validateTrajectory()

void LibtorchRLTrajectoryBuffer::validateTrajectory ( const Trajectory &  trajectory)
staticprivate

Validate a trajectory before it is stored.

Parameters
trajectoryTrajectory to validate.

Definition at line 191 of file LibtorchRLTrajectoryBuffer.C.

192{
193 const auto num_steps = trajectory.rewards.size();
194
195 if (trajectory.observations.size() != num_steps)
196 mooseError("RL trajectory observations must match the reward sequence length.");
197
198 if (trajectory.next_observations.size() != num_steps)
199 mooseError("RL trajectory next observations must match the reward sequence length.");
200
201 if (trajectory.actions.size() != num_steps)
202 mooseError("RL trajectory actions must match the reward sequence length.");
203
204 if (trajectory.log_probabilities.size() != num_steps)
205 mooseError("RL trajectory log probabilities must match the reward sequence length.");
206
207 if (!trajectory.terminals.empty() && trajectory.terminals.size() != num_steps)
208 mooseError("RL trajectory terminal flags must match the reward sequence length.");
209
210 if (!trajectory.value_targets.empty() && trajectory.value_targets.size() != num_steps)
211 mooseError("RL trajectory value targets must match the reward sequence length.");
212
213 if (!trajectory.advantages.empty() && trajectory.advantages.size() != num_steps)
214 mooseError("RL trajectory advantages must match the reward sequence length.");
215}

Referenced by addTrajectory().

Member Data Documentation

◆ _trajectories

std::vector<Trajectory> LibtorchRLTrajectoryBuffer::_trajectories
private

The documentation for this class was generated from the following files: