-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathvariables.py
More file actions
426 lines (350 loc) · 13.6 KB
/
variables.py
File metadata and controls
426 lines (350 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# Copyright 2025 BrainX Ecosystem Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from typing import Optional, Any, Sequence
import brainstate
import jax
import numpy as np
from brainstate._state import record_state_value_read, record_state_value_write
from jax import numpy as jnp
from jax.dtypes import canonicalize_dtype
from jax.tree_util import register_pytree_node_class
from brainpy._errors import MathError
from brainpy.math.ndarray import Array
from brainpy.math.sharding import BATCH_AXIS
__all__ = [
'Variable',
'TrainVar',
'Parameter',
'VariableView',
'VarList', 'var_list',
'VarDict', 'var_dict',
]
@register_pytree_node_class
class Variable(brainstate.State, Array):
"""The pointer to specify the dynamical variable.
Initializing an instance of ``Variable`` by two ways:
>>> import brainpy.math as bm
>>> # 1. init a Variable by the concreate data
>>> v1 = bm.Variable(bm.zeros(10))
>>> # 2. init a Variable by the data shape
>>> v2 = bm.Variable(10)
Note that when initializing a `Variable` by the data shape,
all values in this `Variable` will be initialized as zeros.
Args:
value_or_size: Shape, Array, int. The value or the size of the value.
dtype: Any. The type of the data.
batch_axis: optional, int. The batch axis.
axis_names: sequence of str. The name for each axis.
"""
def __init__(
self,
value_or_size: Any,
dtype: type = None,
batch_axis: int = None,
*,
axis_names: Optional[Sequence[str]] = None,
):
if isinstance(value_or_size, int):
value = jnp.zeros(value_or_size, dtype=dtype)
elif isinstance(value_or_size, (tuple, list)) and all([isinstance(s, int) for s in value_or_size]):
value = jnp.zeros(value_or_size, dtype=dtype)
else:
value = value_or_size
if isinstance(value, Array):
value = value.value
Array.__init__(self, value, dtype=dtype)
brainstate.State.__init__(self, value)
# check batch axis
if isinstance(value, Variable):
if value.batch_axis is not None and batch_axis is not None:
if batch_axis != value.batch_axis:
raise ValueError(f'"batch_axis" is not consistent. Got batch_axis in the given value '
f'is {value.batch_axis}, but the specified batch_axis is {batch_axis}')
batch_axis = value.batch_axis
# assign batch axis
self._batch_axis = batch_axis
if batch_axis is not None:
if batch_axis >= np.ndim(self._value):
raise MathError(f'This variables has {np.ndim(self._value)} dimension, '
f'but the batch axis is set to be {batch_axis}.')
# ready to trace the variable
if axis_names is not None:
if len(axis_names) + 1 == self.ndim:
axis_names = list(axis_names)
axis_names.insert(self.batch_axis, BATCH_AXIS)
assert len(axis_names) == self.ndim
axis_names = tuple(axis_names)
self.axis_names = axis_names
@property
def size_without_batch(self):
if self.batch_axis is None:
return self.size
else:
sizes = self.size
return sizes[:self.batch_axis] + sizes[self.batch_axis + 1:]
@property
def batch_axis(self) -> Optional[int]:
return self._batch_axis
@batch_axis.setter
def batch_axis(self, val):
raise ValueError(f'Cannot set "batch_axis" after creating a {self.__class__.__name__} instance.')
@property
def batch_size(self) -> Optional[int]:
if self.batch_axis is None:
return None
else:
return self.shape[self.batch_axis]
@batch_size.setter
def batch_size(self, val):
raise ValueError(f'Cannot set "batch_size" manually.')
def _ensure_value_exists(self):
pass
@property
def value(self):
self._ensure_value_exists()
record_state_value_read(self)
return self._read_value()
@value.setter
def value(self, v):
_value = self.value
ext_shape = jnp.shape(v)
int_shape = jnp.shape(_value)
if self._batch_axis is not None:
ext_shape = ext_shape[:self._batch_axis] + ext_shape[self._batch_axis + 1:]
int_shape = int_shape[:self._batch_axis] + int_shape[self._batch_axis + 1:]
if ext_shape != int_shape:
error = f"The shape of the original data is {int_shape}, while we got {ext_shape}"
error += f' with batch_axis={self._batch_axis}.'
raise MathError(error)
ext_dtype = _get_dtype(v)
int_dtype = self.dtype
if ext_dtype != int_dtype:
raise MathError(f"The dtype of the original data is {int_dtype}, "
f"while we got {ext_dtype}.")
if isinstance(v, Array):
v = v.value
elif isinstance(v, np.ndarray):
v = jnp.asarray(v)
else:
v = v
if isinstance(v, brainstate.State): # value checking
v = v.value
self._check_value_tree(v) # check the tree structure
record_state_value_write(self) # record the value by the stack (>= level)
self._been_writen = True # set the flag
self._write_value(v) # write the value
def _get_dtype(v):
if hasattr(v, 'dtype'):
dtype = v.dtype
else:
dtype = canonicalize_dtype(type(v))
return dtype
def _as_jax_array_(obj):
return obj.value if isinstance(obj, Array) else obj
@register_pytree_node_class
class TrainVar(Variable):
"""The pointer to specify the trainable variable.
"""
def __init__(
self,
value_or_size: Any,
dtype: type = None,
batch_axis: int = None,
*,
axis_names: Optional[Sequence[str]] = None,
):
super().__init__(
value_or_size,
dtype=dtype,
batch_axis=batch_axis,
axis_names=axis_names,
)
@register_pytree_node_class
class Parameter(Variable):
"""The pointer to specify the parameter.
"""
def __init__(
self,
value_or_size: Any,
dtype: type = None,
batch_axis: int = None,
*,
axis_names: Optional[Sequence[str]] = None,
):
super().__init__(
value_or_size,
dtype=dtype,
batch_axis=batch_axis,
axis_names=axis_names,
)
class VariableView(Variable):
"""A view of a Variable instance.
This class is used to create a subset view of ``brainpy.math.Variable``.
>>> import brainpy.math as bm
>>> bm.random.seed(123)
>>> origin = bm.Variable(bm.random.random(5))
>>> view = bm.VariableView(origin, slice(None, 2, None)) # origin[:2]
VariableView([0.02920651, 0.19066381], dtype=float32)
``VariableView`` can be used to update the subset of the original
Variable instance, and make operations on this subset of the Variable.
>>> view[:] = 1.
>>> view
VariableView([1., 1.], dtype=float32)
>>> origin
Variable([1. , 1. , 0.5482849, 0.6564884, 0.8446237], dtype=float32)
>>> view + 10
Array([11., 11.], dtype=float32)
>>> view *= 10
VariableView([10., 10.], dtype=float32)
The above example demonstrates that the updating of an ``VariableView`` instance
is actually made in the original ``Variable`` instance.
Moreover, it's worthy to note that ``VariableView`` is not a PyTree.
"""
_need_record = False
def __init__(
self,
value: Variable,
index: Any,
):
self.index = jax.tree_util.tree_map(_as_jax_array_, index, is_leaf=lambda a: isinstance(a, Array))
if not isinstance(value, Variable):
raise ValueError('Must be instance of Variable.')
super().__init__(value.value, batch_axis=value.batch_axis)
self._value = value
def __repr__(self) -> str:
print_code = repr(self._value)
prefix = f'{self.__class__.__name__}'
blank = " " * (len(prefix) + 1)
lines = print_code.split("\n")
lines[0] = prefix + "(" + lines[0]
for i in range(1, len(lines)):
lines[i] = blank + lines[i]
lines[-1] += ","
lines.append(blank + f'index={self.index})')
print_code = "\n".join(lines)
return print_code
@property
def value(self):
return self._value[self.index]
@value.setter
def value(self, v):
int_shape = self.shape
if self.batch_axis is None:
ext_shape = v.shape
else:
ext_shape = v.shape[:self.batch_axis] + v.shape[self.batch_axis + 1:]
int_shape = int_shape[:self.batch_axis] + int_shape[self.batch_axis + 1:]
if ext_shape != int_shape:
error = f"The shape of the original data is {self.shape}, while we got {v.shape}"
if self.batch_axis is None:
error += '. Do you forget to set "batch_axis" when initialize this variable?'
else:
error += f' with batch_axis={self.batch_axis}.'
raise MathError(error)
if v.dtype != self._value.dtype:
raise MathError(f"The dtype of the original data is {self._value.dtype}, "
f"while we got {v.dtype}.")
self._value[self.index] = v.value if isinstance(v, Array) else v
@register_pytree_node_class
class VarList(list):
"""A sequence of :py:class:`~.Variable`, which is compatible with
:py:func:`.vars()` operation in a :py:class:`~.BrainPyObject`.
Actually, :py:class:`~.VarList` is a python list.
:py:class:`~.VarList` is specifically designed to store Variable instances.
"""
def __init__(self, seq=()):
super().__init__()
self.extend(seq)
def append(self, element) -> 'VarList':
if not isinstance(element, Variable):
raise TypeError(f'element must be an instance of {Variable.__name__}.')
super().append(element)
return self
def extend(self, iterable) -> 'VarList':
for element in iterable:
self.append(element)
return self
def __setitem__(self, key, value) -> 'VarList':
"""Override the item setting.
This function ensures that the Variable appended in the :py:class:`~.VarList` will not be overridden,
and only the value can be changed for each element.
>>> import brainpy.math as bm
>>> l = bm.var_list([bm.Variable(1), bm.Variable(2)])
>>> print(id(l[0]), id(l[1]))
2077748389472 2077748389552
>>> l[1] = bm.random.random(2)
>>> l[0] = bm.random.random(1)
>>> print(id(l[0]), id(l[1])) # still the original Variable instances
2077748389472 2077748389552
"""
if isinstance(key, int):
self[key].value = value
else:
super().__setitem__(key, value)
return self
def tree_flatten(self):
return tuple(self), None
@classmethod
def tree_unflatten(cls, aux_data, children):
return cls(children)
var_list = VarList
@register_pytree_node_class
class VarDict(dict):
"""A dictionary of :py:class:`~.Variable`, which is compatible with
:py:func:`.vars()` operation in a :py:class:`~.BrainPyObject`.
Actually, :py:class:`~.VarDict` is a python dict.
:py:class:`~.VarDict` is specifically designed to store Variable instances.
"""
def _check_elem(self, elem):
if not isinstance(elem, Variable):
raise TypeError(f'Element should be {Variable.__name__}, but got {type(elem)}.')
return elem
def __init__(self, *args, **kwargs):
super().__init__()
self.update(*args, **kwargs)
def update(self, *args, **kwargs) -> 'VarDict':
for arg in args:
if isinstance(arg, dict):
for k, v in arg.items():
self[k] = v
elif isinstance(arg, tuple):
assert len(arg) == 2
self[arg[0]] = arg[1]
for k, v in kwargs.items():
self[k] = v
return self
def __setitem__(self, key, value) -> 'VarDict':
"""Override the item setting.
This function ensures that the Variable appended in the :py:class:`~.VarList` will not be overridden.
>>> import brainpy.math as bm
>>> d = bm.var_dict({'a': bm.Variable(1), 'b': bm.Variable(2)})
>>> print(id(d['a']), id(d['b']))
2077667833504 2077748488176
>>> d['b'] = bm.random.random(2)
>>> d['a'] = bm.random.random(1)
>>> print(id(d['a']), id(d['b'])) # still the original Variable instances
2077667833504 2077748488176
"""
if key in self:
self[key].value = value
else:
super().__setitem__(key, self._check_elem(value))
return self
def tree_flatten(self):
return tuple(self.values()), tuple(self.keys())
@classmethod
def tree_unflatten(cls, keys, values):
return cls(jax.util.safe_zip(keys, values))
var_dict = VarDict