bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
torch_parameters.h
Go to the documentation of this file.
1#ifndef BITRL_RL_DISTRIBUTED_TORCH_PARAMETERS_H
2#define BITRL_RL_DISTRIBUTED_TORCH_PARAMETERS_H
3
4#include "bitrl/base/bitrl_config.h"
5
6#ifdef USE_PYTORCH
7
10
11#include <torch/torch.h>
12
13#include <cstdint>
14#include <cstring>
15#include <stdexcept>
16#include <vector>
17
18namespace bitrl
19{
20namespace rl::distributed
21{
22
23namespace detail
24{
25inline void check_float_(const torch::Tensor &t)
26{
27 if (t.scalar_type() != torch::kFloat32)
28 {
29 throw std::invalid_argument("bitrl::rl::distributed: the parameters must be float32");
30 }
31}
32
33template <typename Get>
34std::vector<float> flatten_(const std::vector<torch::Tensor> &tensors, Get get)
35{
36 std::vector<float> flat;
37 for (const auto &p : tensors)
38 {
39 check_float_(p);
40 const auto t = get(p);
41 const auto n = static_cast<std::size_t>(p.numel());
42 if (!t.defined())
43 {
44 flat.insert(flat.end(), n, 0.0f);
45 continue;
46 }
47 const auto c = t.detach().contiguous();
48 flat.insert(flat.end(), c.template data_ptr<float>(), c.template data_ptr<float>() + n);
49 }
50 return flat;
51}
52} // namespace detail
53
57inline std::vector<float> flatten_parameters(const std::vector<torch::Tensor> &parameters)
58{
59 return detail::flatten_(parameters, [](const torch::Tensor &p) { return p; });
60}
61
65inline std::vector<float> flatten_gradients(const std::vector<torch::Tensor> &parameters)
66{
67 return detail::flatten_(parameters, [](const torch::Tensor &p) { return p.grad(); });
68}
69
73inline void set_parameters(const std::vector<torch::Tensor> &parameters,
74 const std::vector<float> &values)
75{
76 torch::NoGradGuard no_grad;
77 std::size_t at = 0;
78 for (auto p : parameters)
79 {
80 const auto n = static_cast<std::size_t>(p.numel());
81 if (at + n > values.size())
82 {
83 throw std::invalid_argument("set_parameters: too few values");
84 }
85 const auto src = torch::from_blob(const_cast<float *>(values.data() + at), p.sizes(),
86 torch::TensorOptions().dtype(torch::kFloat32));
87 p.copy_(src);
88 at += n;
89 }
90 if (at != values.size())
91 {
92 throw std::invalid_argument("set_parameters: too many values");
93 }
94}
95
99inline void set_gradients(const std::vector<torch::Tensor> &parameters,
100 const std::vector<float> &values)
101{
102 std::size_t at = 0;
103 for (auto p : parameters)
104 {
105 const auto n = static_cast<std::size_t>(p.numel());
106 if (at + n > values.size())
107 {
108 throw std::invalid_argument("set_gradients: too few values");
109 }
110 const auto src = torch::from_blob(const_cast<float *>(values.data() + at), p.sizes(),
111 torch::TensorOptions().dtype(torch::kFloat32))
112 .clone();
113 if (p.mutable_grad().defined())
114 {
115 p.mutable_grad().copy_(src);
116 }
117 else
118 {
119 p.mutable_grad() = src;
120 }
121 at += n;
122 }
123 if (at != values.size())
124 {
125 throw std::invalid_argument("set_gradients: too many values");
126 }
127}
128
132inline void average_gradients(Communicator &communicator,
133 const std::vector<torch::Tensor> &parameters)
134{
135 auto g = flatten_gradients(parameters);
136 communicator.all_reduce_sum(g);
137 const float n = static_cast<float>(communicator.world_size());
138 for (auto &v : g)
139 {
140 v /= n;
141 }
142 set_gradients(parameters, g);
143}
144
148inline void broadcast_parameters(Communicator &communicator,
149 const std::vector<torch::Tensor> &parameters, uint_t root = 0)
150{
151 auto values = flatten_parameters(parameters);
152 communicator.broadcast(values, root);
153 set_parameters(parameters, values);
154}
155
159inline std::uint64_t parameters_checksum(const std::vector<torch::Tensor> &parameters)
160{
161 const auto values = flatten_parameters(parameters);
162 std::uint64_t h = 1469598103934665603ULL; // FNV-1a
163 for (const float v : values)
164 {
165 std::uint32_t bits;
166 std::memcpy(&bits, &v, sizeof(bits));
167 for (int b = 0; b < 32; b += 8)
168 {
169 h ^= (bits >> b) & 0xFFu;
170 h *= 1099511628211ULL;
171 }
172 }
173 return h;
174}
175
176} // namespace rl::distributed
177} // namespace bitrl
178
179#endif // USE_PYTORCH
180#endif // BITRL_RL_DISTRIBUTED_TORCH_PARAMETERS_H
How the ranks of a distributed training exchange numbers.
Definition communicator.h:32
virtual std::string broadcast(const std::string &bytes, uint_t root)=0
What root gave; the other ranks' bytes are ignored.
void all_reduce_sum(std::vector< T > &values)
Replace values with the sum of every rank's values.
Definition communicator.h:110
virtual uint_t world_size() const noexcept=0
Definition torch_parameters.h:24
void check_float_(const torch::Tensor &t)
Definition torch_parameters.h:25
std::vector< float > flatten_(const std::vector< torch::Tensor > &tensors, Get get)
Definition torch_parameters.h:34
Definition communicator.h:17
std::vector< float > flatten_gradients(const std::vector< torch::Tensor > &parameters)
The gradients of the parameters, one after the other; 0 where a parameter has none.
Definition torch_parameters.h:65
void average_gradients(Communicator &communicator, const std::vector< torch::Tensor > &parameters)
Replace the gradients of every rank with their mean over the ranks.
Definition torch_parameters.h:132
void set_parameters(const std::vector< torch::Tensor > &parameters, const std::vector< float > &values)
Copy values, as flatten_parameters() gives them, into the parameters.
Definition torch_parameters.h:73
void set_gradients(const std::vector< torch::Tensor > &parameters, const std::vector< float > &values)
Copy values, as flatten_gradients() gives them, into the gradients.
Definition torch_parameters.h:99
std::uint64_t parameters_checksum(const std::vector< torch::Tensor > &parameters)
A checksum of the parameters, to tell that the ranks have the same.
Definition torch_parameters.h:159
std::vector< float > flatten_parameters(const std::vector< torch::Tensor > &parameters)
The values of the parameters, one after the other.
Definition torch_parameters.h:57
void broadcast_parameters(Communicator &communicator, const std::vector< torch::Tensor > &parameters, uint_t root=0)
Give every rank the parameters of root.
Definition torch_parameters.h:148
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
std::size_t uint_t
uint_t
Definition bitsim_types.h:40