bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
torch_tensor_utils.h
Go to the documentation of this file.
1#ifndef TORCH_TENSOR_UTILS_H
2#define TORCH_TENSOR_UTILS_H
3
4#include "bitrl/base/bitrl_config.h"
5
6#ifdef USE_PYTORCH
7
9#include <torch/torch.h>
10
11#include <cstdint>
12#include <stdexcept>
13#include <string>
14#include <vector>
15
16namespace bitrl
17{
18namespace torch_utils
19{
20
25template <typename ContainerType> torch_tensor_t create_mask(const ContainerType &container)
26{
27 std::vector<std::int64_t> values;
28 values.reserve(container.size());
29 for (const auto &value : container)
30 {
31 values.push_back(static_cast<bool>(value) ? 1 : 0);
32 }
33 return torch::tensor(values, torch::dtype(torch::kInt64)).to(torch::kBool);
34}
35
41template <typename TorchNetType> void copy_parameters(const TorchNetType &from, TorchNetType &to)
42{
43 torch::NoGradGuard no_grad;
44
45 auto params = to->named_parameters(true /*recurse*/);
46 for (const auto &item : from->named_parameters(true /*recurse*/))
47 {
48 auto *param = params.find(item.key());
49 if (param == nullptr)
50 {
51 throw std::invalid_argument("copy_parameters: no parameter " + item.key());
52 }
53 param->copy_(item.value());
54 }
55
56 auto buffers = to->named_buffers(true /*recurse*/);
57 for (const auto &item : from->named_buffers(true /*recurse*/))
58 {
59 auto *buffer = buffers.find(item.key());
60 if (buffer == nullptr)
61 {
62 throw std::invalid_argument("copy_parameters: no buffer " + item.key());
63 }
64 buffer->copy_(item.value());
65 }
66}
67
73template <typename TorchNetType>
74void copy_parameters_to(TorchNetType &to, const std::string &params_path)
75{
76 TorchNetType from;
77 torch::load(from, params_path);
78 copy_parameters(from, to);
79}
80
81} // namespace torch_utils
82} // namespace bitrl
83
84#endif
85
86#endif // TORCH_TENSOR_UTILS_H
Definition torch_tensor_utils.h:19
void copy_parameters(const TorchNetType &from, TorchNetType &to)
copy_parameters. Copy the parameters and buffers of one network into another of the same type,...
Definition torch_tensor_utils.h:41
torch_tensor_t create_mask(const ContainerType &container)
create_mask. Create a boolean mask from the given container. The container should hold values convert...
Definition torch_tensor_utils.h:25
void copy_parameters_to(TorchNetType &to, const std::string &params_path)
copy_parameters_to. Copy into to the parameters and buffers of a network of the same type that was sa...
Definition torch_tensor_utils.h:74
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95