burn_core/module/param/
running.rs1use super::ParamId;
2use crate::module::{
3 AutodiffModule, Content, Module, ModuleDisplay, ModuleDisplayDefault, ModuleMapper,
4 ModuleVisitor, Param,
5};
6
7use alloc::string::ToString;
8use alloc::vec::Vec;
9
10#[cfg(target_has_atomic = "ptr")]
11use alloc::sync::Arc;
12
13#[cfg(not(target_has_atomic = "ptr"))]
14use portable_atomic_util::Arc;
15
16use burn_common::stub::Mutex;
17use burn_tensor::{
18 Tensor,
19 backend::{AutodiffBackend, Backend},
20 ops::Device,
21};
22
23#[cfg(feature = "std")]
24mod threading {
25 pub(super) use std::collections::HashMap;
26 pub(super) use std::thread::ThreadId;
27
28 #[inline(always)]
29 pub(super) fn get_thread_current_id() -> ThreadId {
30 std::thread::current().id()
31 }
32}
33
34#[cfg(not(feature = "std"))]
35mod threading {
36 pub(super) use burn_common::stub::ThreadId;
37 pub(super) use hashbrown::HashMap;
38
39 #[inline(always)]
40 pub(super) fn get_thread_current_id() -> ThreadId {
41 panic!("Current thread id is not available")
42 }
43}
44
45use threading::*;
47
48#[derive(Clone, Debug)]
54pub struct RunningState<V> {
55 id: ParamId,
56 values: Arc<Mutex<HashMap<ThreadId, V>>>,
57 value: Arc<Mutex<V>>,
58}
59
60impl<V> core::fmt::Display for RunningState<V> {
63 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
64 write!(f, "RunningState(id={})", self.id)
65 }
66}
67
68impl<V> ModuleDisplayDefault for RunningState<V> {
69 fn content(&self, content: Content) -> Option<Content> {
70 content
71 .add_formatted(&"RunningState".to_string())
72 .optional()
73 }
74}
75
76impl<V> ModuleDisplay for RunningState<V> {}
77
78impl<const D: usize, B: Backend> Module<B> for RunningState<Tensor<B, D>> {
79 type Record = Param<Tensor<B, D>>;
80
81 fn visit<V: ModuleVisitor<B>>(&self, visitor: &mut V) {
82 let tensor = self.value.lock().unwrap();
83 visitor.visit_float(self.id, &tensor)
84 }
85
86 fn map<M: ModuleMapper<B>>(self, mapper: &mut M) -> Self {
87 let mut tensor = self.value.lock().unwrap();
88 let tensor_out = mapper.map_float(self.id, tensor.clone());
89
90 *tensor = tensor_out;
91 core::mem::drop(tensor);
92
93 self
94 }
95
96 fn into_record(self) -> Self::Record {
97 self.sync();
98 let tensor = self.value.lock().unwrap();
99
100 Param::initialized(self.id, tensor.clone())
101 }
102
103 fn load_record(mut self, record: Self::Record) -> Self {
104 let mut tensor = self.value.lock().unwrap();
105 *tensor = record.val().to_device(&tensor.device());
106 self.id = record.id;
107
108 core::mem::drop(tensor);
109
110 self
111 }
112
113 fn to_device(self, device: &Device<B>) -> Self {
114 let mut tensor = self.value.lock().unwrap();
115 let tensor_out = tensor.clone().to_device(device);
116
117 *tensor = tensor_out;
118 core::mem::drop(tensor);
119
120 self
121 }
122
123 fn fork(self, device: &Device<B>) -> Self {
124 self.to_device(device) }
126
127 fn collect_devices(&self, mut devices: Vec<Device<B>>) -> Vec<Device<B>> {
128 let device = self.value.lock().unwrap().device();
129
130 if !devices.contains(&device) {
131 devices.push(device)
132 }
133
134 devices
135 }
136}
137
138impl<const D: usize, B: Backend> RunningState<Tensor<B, D>> {
139 pub fn new(value: Tensor<B, D>) -> Self {
141 Self {
142 id: ParamId::new(),
143 values: Arc::new(Mutex::new(HashMap::new())),
144 value: Arc::new(Mutex::new(value)),
145 }
146 }
147
148 pub fn with_id(id: ParamId, value: Tensor<B, D>) -> Self {
150 Self {
151 id,
152 values: Arc::new(Mutex::new(HashMap::new())),
153 value: Arc::new(Mutex::new(value)),
154 }
155 }
156
157 pub fn from_record(record: Param<Tensor<B, D>>) -> Self {
159 let tensor = record.val();
160 Self {
161 id: record.id,
162 values: Arc::new(Mutex::new(HashMap::new())),
163 value: Arc::new(Mutex::new(tensor)),
164 }
165 }
166
167 pub fn update(&self, value: Tensor<B, D>) {
169 let thread_id = get_thread_current_id();
170 let mut map = self.values.lock().unwrap();
171
172 if map.contains_key(&thread_id) {
173 self.update_value(&mut map);
174 }
175
176 map.insert(thread_id, value);
177 }
178
179 pub fn value(&self) -> Tensor<B, D> {
185 let value = self.value.lock().unwrap();
186 value.clone()
187 }
188
189 pub fn value_sync(&self) -> Tensor<B, D> {
196 let thread_id = get_thread_current_id();
197 let mut map = self.values.lock().unwrap();
198
199 if map.contains_key(&thread_id) {
200 self.update_value(&mut map);
201 }
202
203 let value = self.value.lock().unwrap();
204 value.clone()
205 }
206
207 fn sync(&self) {
208 let mut map = self.values.lock().unwrap();
209
210 if !map.is_empty() {
211 self.update_value(&mut map);
212 }
213 }
214
215 fn update_value(&self, map: &mut HashMap<ThreadId, Tensor<B, D>>) {
216 let mut value_updated: Option<Tensor<B, D>> = None;
217 let mut counter = 0;
218
219 for (_key, tensor) in map.drain() {
220 counter += 1;
221
222 value_updated = match value_updated {
223 Some(current) => {
224 let device = current.device();
225 Some(tensor.to_device(&device).add(current))
226 }
227 None => Some(tensor),
228 };
229 }
230
231 if let Some(value) = value_updated {
232 let value = value.div_scalar(counter);
233 let mut value_old = self.value.lock().unwrap();
234 *value_old = value;
235 }
236 }
237}
238
239impl<const D: usize, B: AutodiffBackend> AutodiffModule<B> for RunningState<Tensor<B, D>> {
240 type InnerModule = RunningState<Tensor<B::InnerBackend, D>>;
241
242 fn valid(&self) -> Self::InnerModule {
243 self.sync();
244 let value = self.value();
245
246 RunningState::with_id(self.id, value.inner())
247 }
248}