10#ifdef MOOSE_LIBTORCH_ENABLED
19std::vector<LibtorchRLMiniBatch>
21 const unsigned int batch_size,
22 const bool standardize_advantage,
23 const c10::optional<at::Generator> generator)
const
25 std::vector<LibtorchRLMiniBatch> mini_batches;
32 const auto effective_batch_size = std::max<unsigned int>(1, batch_size);
34 at::randperm(batch.
size(), generator, torch::TensorOptions().dtype(torch::kLong));
36 for (std::int64_t batch_begin = 0; batch_begin < batch.
size();
37 batch_begin += effective_batch_size)
39 const auto batch_end = std::min<std::int64_t>(
40 batch.
size(), batch_begin +
static_cast<std::int64_t
>(effective_batch_size));
41 const auto indices = permutation.narrow(0, batch_begin, batch_end - batch_begin);
42 mini_batches.push_back(
makeMiniBatch(batch, indices, standardize_advantage));
53 mooseError(
"RL tensor batches must define observations, actions, log probabilities, value "
54 "targets, and advantages before mini-batch sampling.");
56 const auto batch_size = batch.
size();
57 const auto validate_rows = [batch_size](
const torch::Tensor & tensor, std::string_view
name)
59 if (!tensor.defined() || tensor.size(0) != batch_size)
61 "RL tensor batch field ",
name,
" must have the same number of rows as observations.");
64 validate_rows(batch.
actions,
"actions");
72 const torch::Tensor & indices,
73 const bool standardize_advantage)
83 if (standardize_advantage)
void mooseError(Args &&... args)
static void validateBatch(const LibtorchRLTrajectoryBuffer::TensorBatch &batch)
Sanity-check that the flattened rollout tensors all line up.
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.
static LibtorchRLMiniBatch makeMiniBatch(const LibtorchRLTrajectoryBuffer::TensorBatch &batch, const torch::Tensor &indices, bool standardize_advantage)
Slice one shuffled mini-batch out of the flattened rollout tensors.
Tensor data for one PPO mini-batch.
torch::Tensor actions
Action rows that match the sampled observations.
torch::Tensor value_targets
Critic targets aligned with the sampled observations.
torch::Tensor old_log_probabilities
Behavior-policy log probabilities for the sampled actions.
torch::Tensor advantages
Advantage estimates aligned with the sampled observations.
torch::Tensor observations
Flattened observation rows for the mini-batch.
Flattened tensor data assembled from the stored trajectories.
torch::Tensor actions
Flattened action matrix.
torch::Tensor value_targets
Flattened critic targets.
torch::Tensor observations
Flattened observation matrix.
torch::Tensor advantages
Flattened advantages.
torch::Tensor log_probabilities
Flattened action log-probabilities.
std::int64_t size() const
Return the number of transitions represented by the batch.