brainstate 0.2.1__py2.py3-none-any.whl → 0.2.2__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- brainstate/__init__.py +167 -169
- brainstate/_compatible_import.py +340 -340
- brainstate/_compatible_import_test.py +681 -681
- brainstate/_deprecation.py +210 -210
- brainstate/_deprecation_test.py +2297 -2319
- brainstate/_error.py +45 -45
- brainstate/_state.py +2157 -1652
- brainstate/_state_test.py +1129 -52
- brainstate/_utils.py +47 -47
- brainstate/environ.py +1495 -1495
- brainstate/environ_test.py +1223 -1223
- brainstate/graph/__init__.py +22 -22
- brainstate/graph/_node.py +240 -240
- brainstate/graph/_node_test.py +589 -589
- brainstate/graph/_operation.py +1620 -1624
- brainstate/graph/_operation_test.py +1147 -1147
- brainstate/mixin.py +1447 -1433
- brainstate/mixin_test.py +1017 -1017
- brainstate/nn/__init__.py +146 -137
- brainstate/nn/_activations.py +1100 -1100
- brainstate/nn/_activations_test.py +354 -354
- brainstate/nn/_collective_ops.py +635 -633
- brainstate/nn/_collective_ops_test.py +774 -774
- brainstate/nn/_common.py +226 -226
- brainstate/nn/_common_test.py +134 -154
- brainstate/nn/_conv.py +2010 -2010
- brainstate/nn/_conv_test.py +849 -849
- brainstate/nn/_delay.py +575 -575
- brainstate/nn/_delay_test.py +243 -243
- brainstate/nn/_dropout.py +618 -618
- brainstate/nn/_dropout_test.py +480 -477
- brainstate/nn/_dynamics.py +870 -1267
- brainstate/nn/_dynamics_test.py +53 -67
- brainstate/nn/_elementwise.py +1298 -1298
- brainstate/nn/_elementwise_test.py +829 -829
- brainstate/nn/_embedding.py +408 -408
- brainstate/nn/_embedding_test.py +156 -156
- brainstate/nn/_event_fixedprob.py +233 -233
- brainstate/nn/_event_fixedprob_test.py +115 -115
- brainstate/nn/_event_linear.py +83 -83
- brainstate/nn/_event_linear_test.py +121 -121
- brainstate/nn/_exp_euler.py +254 -254
- brainstate/nn/_exp_euler_test.py +377 -377
- brainstate/nn/_linear.py +744 -744
- brainstate/nn/_linear_test.py +475 -475
- brainstate/nn/_metrics.py +1070 -1070
- brainstate/nn/_metrics_test.py +611 -611
- brainstate/nn/_module.py +391 -384
- brainstate/nn/_module_test.py +40 -40
- brainstate/nn/_normalizations.py +1334 -1334
- brainstate/nn/_normalizations_test.py +699 -699
- brainstate/nn/_paddings.py +1020 -1020
- brainstate/nn/_paddings_test.py +722 -722
- brainstate/nn/_poolings.py +2239 -2239
- brainstate/nn/_poolings_test.py +952 -952
- brainstate/nn/_rnns.py +946 -946
- brainstate/nn/_rnns_test.py +592 -592
- brainstate/nn/_utils.py +216 -216
- brainstate/nn/_utils_test.py +401 -401
- brainstate/nn/init.py +809 -809
- brainstate/nn/init_test.py +180 -180
- brainstate/random/__init__.py +270 -270
- brainstate/random/{_rand_funs.py → _fun.py} +3938 -3938
- brainstate/random/{_rand_funs_test.py → _fun_test.py} +638 -640
- brainstate/random/_impl.py +672 -0
- brainstate/random/{_rand_seed.py → _seed.py} +675 -675
- brainstate/random/{_rand_seed_test.py → _seed_test.py} +48 -48
- brainstate/random/{_rand_state.py → _state.py} +1320 -1617
- brainstate/random/{_rand_state_test.py → _state_test.py} +551 -551
- brainstate/transform/__init__.py +56 -59
- brainstate/transform/_ad_checkpoint.py +176 -176
- brainstate/transform/_ad_checkpoint_test.py +49 -49
- brainstate/transform/_autograd.py +1025 -1025
- brainstate/transform/_autograd_test.py +1289 -1289
- brainstate/transform/_conditions.py +316 -316
- brainstate/transform/_conditions_test.py +220 -220
- brainstate/transform/_error_if.py +94 -94
- brainstate/transform/_error_if_test.py +52 -52
- brainstate/transform/_find_state.py +200 -0
- brainstate/transform/_find_state_test.py +84 -0
- brainstate/transform/_jit.py +399 -399
- brainstate/transform/_jit_test.py +143 -143
- brainstate/transform/_loop_collect_return.py +675 -675
- brainstate/transform/_loop_collect_return_test.py +58 -58
- brainstate/transform/_loop_no_collection.py +283 -283
- brainstate/transform/_loop_no_collection_test.py +50 -50
- brainstate/transform/_make_jaxpr.py +2176 -2016
- brainstate/transform/_make_jaxpr_test.py +1634 -1510
- brainstate/transform/_mapping.py +607 -529
- brainstate/transform/_mapping_test.py +104 -194
- brainstate/transform/_progress_bar.py +255 -255
- brainstate/transform/_unvmap.py +256 -256
- brainstate/transform/_util.py +286 -286
- brainstate/typing.py +837 -837
- brainstate/typing_test.py +780 -780
- brainstate/util/__init__.py +27 -27
- brainstate/util/_others.py +1024 -1024
- brainstate/util/_others_test.py +962 -962
- brainstate/util/_pretty_pytree.py +1301 -1301
- brainstate/util/_pretty_pytree_test.py +675 -675
- brainstate/util/_pretty_repr.py +462 -462
- brainstate/util/_pretty_repr_test.py +696 -696
- brainstate/util/filter.py +945 -945
- brainstate/util/filter_test.py +911 -911
- brainstate/util/struct.py +910 -910
- brainstate/util/struct_test.py +602 -602
- {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/METADATA +108 -108
- brainstate-0.2.2.dist-info/RECORD +111 -0
- {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/licenses/LICENSE +202 -202
- brainstate/transform/_eval_shape.py +0 -145
- brainstate/transform/_eval_shape_test.py +0 -38
- brainstate/transform/_random.py +0 -171
- brainstate-0.2.1.dist-info/RECORD +0 -111
- {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/WHEEL +0 -0
- {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/top_level.txt +0 -0
brainstate/nn/_utils.py
CHANGED
@@ -1,216 +1,216 @@
|
|
1
|
-
# Copyright 2025 BrainX Ecosystem Limited. All Rights Reserved.
|
2
|
-
#
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
-
# you may not use this file except in compliance with the License.
|
5
|
-
# You may obtain a copy of the License at
|
6
|
-
#
|
7
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
-
#
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
-
# See the License for the specific language governing permissions and
|
13
|
-
# limitations under the License.
|
14
|
-
# ==============================================================================
|
15
|
-
|
16
|
-
# -*- coding: utf-8 -*-
|
17
|
-
|
18
|
-
from brainstate._state import ParamState
|
19
|
-
from ._module import Module
|
20
|
-
from functools import partial
|
21
|
-
|
22
|
-
import jax
|
23
|
-
import jax.numpy as jnp
|
24
|
-
|
25
|
-
from brainstate.typing import PyTree
|
26
|
-
|
27
|
-
__all__ = [
|
28
|
-
"count_parameters",
|
29
|
-
"clip_grad_norm",
|
30
|
-
]
|
31
|
-
|
32
|
-
|
33
|
-
def _format_parameter_count(num_params, precision=2):
|
34
|
-
if num_params < 1000:
|
35
|
-
return str(num_params)
|
36
|
-
|
37
|
-
suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E']
|
38
|
-
magnitude = 0
|
39
|
-
while abs(num_params) >= 1000:
|
40
|
-
magnitude += 1
|
41
|
-
num_params /= 1000.0
|
42
|
-
|
43
|
-
format_string = '{:.' + str(precision) + 'f}{}'
|
44
|
-
formatted_value = format_string.format(num_params, suffixes[magnitude])
|
45
|
-
|
46
|
-
# 检查是否接近 1000,如果是,尝试使用更大的基数
|
47
|
-
if magnitude < len(suffixes) - 1 and num_params >= 1000 * (1 - 10 ** (-precision)):
|
48
|
-
magnitude += 1
|
49
|
-
num_params /= 1000.0
|
50
|
-
formatted_value = format_string.format(num_params, suffixes[magnitude])
|
51
|
-
|
52
|
-
return formatted_value
|
53
|
-
|
54
|
-
|
55
|
-
def count_parameters(
|
56
|
-
module: Module,
|
57
|
-
precision: int = 2,
|
58
|
-
return_table: bool = False,
|
59
|
-
):
|
60
|
-
"""
|
61
|
-
Count and display the number of trainable parameters in a neural network model.
|
62
|
-
|
63
|
-
This function iterates through all the parameters of the given model,
|
64
|
-
counts the number of parameters for each module, and displays them in a table.
|
65
|
-
It also calculates and returns the total number of trainable parameters.
|
66
|
-
|
67
|
-
Parameters:
|
68
|
-
-----------
|
69
|
-
model : brainstate.nn.Module
|
70
|
-
The neural network model for which to count parameters.
|
71
|
-
|
72
|
-
Returns:
|
73
|
-
--------
|
74
|
-
int
|
75
|
-
The total number of trainable parameters in the model.
|
76
|
-
|
77
|
-
Prints:
|
78
|
-
-------
|
79
|
-
A pretty-formatted table showing the number of parameters for each module,
|
80
|
-
followed by the total number of trainable parameters.
|
81
|
-
"""
|
82
|
-
assert isinstance(module, Module), "Input must be a neural network module" # noqa: E501
|
83
|
-
from prettytable import PrettyTable # noqa: E501
|
84
|
-
table = PrettyTable(["Modules", "Parameters"])
|
85
|
-
total_params = 0
|
86
|
-
for name, parameter in module.states(ParamState).items():
|
87
|
-
param = parameter.numel()
|
88
|
-
table.add_row([name, _format_parameter_count(param, precision=precision)])
|
89
|
-
total_params += param
|
90
|
-
table.add_row(["Total", _format_parameter_count(total_params, precision=precision)])
|
91
|
-
print(table)
|
92
|
-
if return_table:
|
93
|
-
return table, total_params
|
94
|
-
return total_params
|
95
|
-
|
96
|
-
|
97
|
-
def clip_grad_norm(
|
98
|
-
grad: PyTree,
|
99
|
-
max_norm: float | jax.Array,
|
100
|
-
norm_type: int | float | str | None = 2.0,
|
101
|
-
return_norm: bool = False,
|
102
|
-
) -> PyTree | tuple[PyTree, jax.Array]:
|
103
|
-
"""
|
104
|
-
Clip gradient norm of a PyTree of parameters.
|
105
|
-
|
106
|
-
The norm is computed over all gradients together, as if they were
|
107
|
-
concatenated into a single vector. Gradients are scaled if their
|
108
|
-
norm exceeds the specified maximum.
|
109
|
-
|
110
|
-
Parameters
|
111
|
-
----------
|
112
|
-
grad : PyTree
|
113
|
-
A PyTree structure (nested dict, list, tuple, etc.) containing
|
114
|
-
JAX arrays representing gradients to be normalized.
|
115
|
-
max_norm : float or jax.Array
|
116
|
-
Maximum allowed norm of the gradients. If the computed norm
|
117
|
-
exceeds this value, gradients will be scaled down proportionally.
|
118
|
-
norm_type : int, float, str, or None, optional
|
119
|
-
Type of the p-norm to compute. Default is 2.0 (L2 norm).
|
120
|
-
Can be:
|
121
|
-
|
122
|
-
- float: p-norm for any p >= 1
|
123
|
-
- 'inf' or jnp.inf: infinity norm (maximum absolute value)
|
124
|
-
- '-inf' or -jnp.inf: negative infinity norm (minimum absolute value)
|
125
|
-
- int: integer p-norm
|
126
|
-
- None: defaults to 2.0 (Euclidean norm)
|
127
|
-
return_norm : bool, optional
|
128
|
-
If True, returns a tuple (clipped_grad, total_norm).
|
129
|
-
If False, returns only clipped_grad. Default is False.
|
130
|
-
|
131
|
-
Returns
|
132
|
-
-------
|
133
|
-
clipped_grad : PyTree
|
134
|
-
The input gradient structure with norms clipped to max_norm.
|
135
|
-
total_norm : jax.Array, optional
|
136
|
-
The computed norm of the gradients before clipping.
|
137
|
-
Only returned if return_norm=True.
|
138
|
-
|
139
|
-
Notes
|
140
|
-
-----
|
141
|
-
The gradient clipping is performed as:
|
142
|
-
|
143
|
-
.. math::
|
144
|
-
g_{\\text{clipped}} = g \\cdot \\min\\left(1, \\frac{\\text{max\\_norm}}{\\|g\\|_p}\\right)
|
145
|
-
|
146
|
-
where :math:`\\|g\\|_p` is the p-norm of the concatenated gradient vector.
|
147
|
-
|
148
|
-
Examples
|
149
|
-
--------
|
150
|
-
.. code-block:: python
|
151
|
-
|
152
|
-
>>> import jax.numpy as jnp
|
153
|
-
>>> import brainstate
|
154
|
-
|
155
|
-
>>> # Simple gradient clipping without returning norm
|
156
|
-
>>> grads = {'w': jnp.array([3.0, 4.0]), 'b': jnp.array([12.0])}
|
157
|
-
>>> clipped_grads = brainstate.nn.clip_grad_norm(grads, max_norm=5.0)
|
158
|
-
>>> print(f"Clipped w: {clipped_grads['w']}")
|
159
|
-
Clipped w: [1.1538461 1.5384616]
|
160
|
-
|
161
|
-
>>> # Gradient clipping with norm returned
|
162
|
-
>>> grads = {'w': jnp.array([3.0, 4.0]), 'b': jnp.array([12.0])}
|
163
|
-
>>> clipped_grads, norm = brainstate.nn.clip_grad_norm(grads, max_norm=5.0, return_norm=True)
|
164
|
-
>>> print(f"Original norm: {norm:.2f}")
|
165
|
-
Original norm: 13.00
|
166
|
-
|
167
|
-
>>> # Using different norm types
|
168
|
-
>>> grads = {'layer1': jnp.array([[-2.0, 3.0], [1.0, -4.0]])}
|
169
|
-
>>>
|
170
|
-
>>> # L2 norm (default)
|
171
|
-
>>> clipped_l2, norm_l2 = brainstate.nn.clip_grad_norm(grads, max_norm=3.0, norm_type=2, return_norm=True)
|
172
|
-
>>> print(f"L2 norm: {norm_l2:.2f}")
|
173
|
-
L2 norm: 5.48
|
174
|
-
>>>
|
175
|
-
>>> # L1 norm
|
176
|
-
>>> clipped_l1, norm_l1 = brainstate.nn.clip_grad_norm(grads, max_norm=5.0, norm_type=1, return_norm=True)
|
177
|
-
>>> print(f"L1 norm: {norm_l1:.2f}")
|
178
|
-
L1 norm: 10.00
|
179
|
-
>>>
|
180
|
-
>>> # Infinity norm
|
181
|
-
>>> clipped_inf, norm_inf = brainstate.nn.clip_grad_norm(grads, max_norm=2.0, norm_type='inf', return_norm=True)
|
182
|
-
>>> print(f"Inf norm: {norm_inf:.2f}")
|
183
|
-
Inf norm: 4.00
|
184
|
-
"""
|
185
|
-
if norm_type is None:
|
186
|
-
norm_type = 2.0
|
187
|
-
|
188
|
-
# Convert string 'inf' to jnp.inf for compatibility
|
189
|
-
if norm_type == 'inf':
|
190
|
-
norm_type = jnp.inf
|
191
|
-
elif norm_type == '-inf':
|
192
|
-
norm_type = -jnp.inf
|
193
|
-
|
194
|
-
# Get all gradient leaves
|
195
|
-
grad_leaves = jax.tree.leaves(grad)
|
196
|
-
|
197
|
-
# Handle empty PyTree
|
198
|
-
if not grad_leaves:
|
199
|
-
if return_norm:
|
200
|
-
return grad, jnp.array(0.0)
|
201
|
-
return grad
|
202
|
-
|
203
|
-
# Compute norm over flattened gradient values
|
204
|
-
norm_fn = partial(jnp.linalg.norm, ord=norm_type)
|
205
|
-
flat_grads = jnp.concatenate([g.ravel() for g in grad_leaves])
|
206
|
-
total_norm = norm_fn(flat_grads)
|
207
|
-
|
208
|
-
# Compute scaling factor
|
209
|
-
clip_factor = jnp.minimum(1.0, max_norm / (total_norm + 1e-6))
|
210
|
-
|
211
|
-
# Apply clipping
|
212
|
-
clipped_grad = jax.tree.map(lambda g: g * clip_factor, grad)
|
213
|
-
|
214
|
-
if return_norm:
|
215
|
-
return clipped_grad, total_norm
|
216
|
-
return clipped_grad
|
1
|
+
# Copyright 2025 BrainX Ecosystem Limited. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
# -*- coding: utf-8 -*-
|
17
|
+
|
18
|
+
from brainstate._state import ParamState
|
19
|
+
from ._module import Module
|
20
|
+
from functools import partial
|
21
|
+
|
22
|
+
import jax
|
23
|
+
import jax.numpy as jnp
|
24
|
+
|
25
|
+
from brainstate.typing import PyTree
|
26
|
+
|
27
|
+
__all__ = [
|
28
|
+
"count_parameters",
|
29
|
+
"clip_grad_norm",
|
30
|
+
]
|
31
|
+
|
32
|
+
|
33
|
+
def _format_parameter_count(num_params, precision=2):
|
34
|
+
if num_params < 1000:
|
35
|
+
return str(num_params)
|
36
|
+
|
37
|
+
suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E']
|
38
|
+
magnitude = 0
|
39
|
+
while abs(num_params) >= 1000:
|
40
|
+
magnitude += 1
|
41
|
+
num_params /= 1000.0
|
42
|
+
|
43
|
+
format_string = '{:.' + str(precision) + 'f}{}'
|
44
|
+
formatted_value = format_string.format(num_params, suffixes[magnitude])
|
45
|
+
|
46
|
+
# 检查是否接近 1000,如果是,尝试使用更大的基数
|
47
|
+
if magnitude < len(suffixes) - 1 and num_params >= 1000 * (1 - 10 ** (-precision)):
|
48
|
+
magnitude += 1
|
49
|
+
num_params /= 1000.0
|
50
|
+
formatted_value = format_string.format(num_params, suffixes[magnitude])
|
51
|
+
|
52
|
+
return formatted_value
|
53
|
+
|
54
|
+
|
55
|
+
def count_parameters(
|
56
|
+
module: Module,
|
57
|
+
precision: int = 2,
|
58
|
+
return_table: bool = False,
|
59
|
+
):
|
60
|
+
"""
|
61
|
+
Count and display the number of trainable parameters in a neural network model.
|
62
|
+
|
63
|
+
This function iterates through all the parameters of the given model,
|
64
|
+
counts the number of parameters for each module, and displays them in a table.
|
65
|
+
It also calculates and returns the total number of trainable parameters.
|
66
|
+
|
67
|
+
Parameters:
|
68
|
+
-----------
|
69
|
+
model : brainstate.nn.Module
|
70
|
+
The neural network model for which to count parameters.
|
71
|
+
|
72
|
+
Returns:
|
73
|
+
--------
|
74
|
+
int
|
75
|
+
The total number of trainable parameters in the model.
|
76
|
+
|
77
|
+
Prints:
|
78
|
+
-------
|
79
|
+
A pretty-formatted table showing the number of parameters for each module,
|
80
|
+
followed by the total number of trainable parameters.
|
81
|
+
"""
|
82
|
+
assert isinstance(module, Module), "Input must be a neural network module" # noqa: E501
|
83
|
+
from prettytable import PrettyTable # noqa: E501
|
84
|
+
table = PrettyTable(["Modules", "Parameters"])
|
85
|
+
total_params = 0
|
86
|
+
for name, parameter in module.states(ParamState).items():
|
87
|
+
param = parameter.numel()
|
88
|
+
table.add_row([name, _format_parameter_count(param, precision=precision)])
|
89
|
+
total_params += param
|
90
|
+
table.add_row(["Total", _format_parameter_count(total_params, precision=precision)])
|
91
|
+
print(table)
|
92
|
+
if return_table:
|
93
|
+
return table, total_params
|
94
|
+
return total_params
|
95
|
+
|
96
|
+
|
97
|
+
def clip_grad_norm(
|
98
|
+
grad: PyTree,
|
99
|
+
max_norm: float | jax.Array,
|
100
|
+
norm_type: int | float | str | None = 2.0,
|
101
|
+
return_norm: bool = False,
|
102
|
+
) -> PyTree | tuple[PyTree, jax.Array]:
|
103
|
+
"""
|
104
|
+
Clip gradient norm of a PyTree of parameters.
|
105
|
+
|
106
|
+
The norm is computed over all gradients together, as if they were
|
107
|
+
concatenated into a single vector. Gradients are scaled if their
|
108
|
+
norm exceeds the specified maximum.
|
109
|
+
|
110
|
+
Parameters
|
111
|
+
----------
|
112
|
+
grad : PyTree
|
113
|
+
A PyTree structure (nested dict, list, tuple, etc.) containing
|
114
|
+
JAX arrays representing gradients to be normalized.
|
115
|
+
max_norm : float or jax.Array
|
116
|
+
Maximum allowed norm of the gradients. If the computed norm
|
117
|
+
exceeds this value, gradients will be scaled down proportionally.
|
118
|
+
norm_type : int, float, str, or None, optional
|
119
|
+
Type of the p-norm to compute. Default is 2.0 (L2 norm).
|
120
|
+
Can be:
|
121
|
+
|
122
|
+
- float: p-norm for any p >= 1
|
123
|
+
- 'inf' or jnp.inf: infinity norm (maximum absolute value)
|
124
|
+
- '-inf' or -jnp.inf: negative infinity norm (minimum absolute value)
|
125
|
+
- int: integer p-norm
|
126
|
+
- None: defaults to 2.0 (Euclidean norm)
|
127
|
+
return_norm : bool, optional
|
128
|
+
If True, returns a tuple (clipped_grad, total_norm).
|
129
|
+
If False, returns only clipped_grad. Default is False.
|
130
|
+
|
131
|
+
Returns
|
132
|
+
-------
|
133
|
+
clipped_grad : PyTree
|
134
|
+
The input gradient structure with norms clipped to max_norm.
|
135
|
+
total_norm : jax.Array, optional
|
136
|
+
The computed norm of the gradients before clipping.
|
137
|
+
Only returned if return_norm=True.
|
138
|
+
|
139
|
+
Notes
|
140
|
+
-----
|
141
|
+
The gradient clipping is performed as:
|
142
|
+
|
143
|
+
.. math::
|
144
|
+
g_{\\text{clipped}} = g \\cdot \\min\\left(1, \\frac{\\text{max\\_norm}}{\\|g\\|_p}\\right)
|
145
|
+
|
146
|
+
where :math:`\\|g\\|_p` is the p-norm of the concatenated gradient vector.
|
147
|
+
|
148
|
+
Examples
|
149
|
+
--------
|
150
|
+
.. code-block:: python
|
151
|
+
|
152
|
+
>>> import jax.numpy as jnp
|
153
|
+
>>> import brainstate
|
154
|
+
|
155
|
+
>>> # Simple gradient clipping without returning norm
|
156
|
+
>>> grads = {'w': jnp.array([3.0, 4.0]), 'b': jnp.array([12.0])}
|
157
|
+
>>> clipped_grads = brainstate.nn.clip_grad_norm(grads, max_norm=5.0)
|
158
|
+
>>> print(f"Clipped w: {clipped_grads['w']}")
|
159
|
+
Clipped w: [1.1538461 1.5384616]
|
160
|
+
|
161
|
+
>>> # Gradient clipping with norm returned
|
162
|
+
>>> grads = {'w': jnp.array([3.0, 4.0]), 'b': jnp.array([12.0])}
|
163
|
+
>>> clipped_grads, norm = brainstate.nn.clip_grad_norm(grads, max_norm=5.0, return_norm=True)
|
164
|
+
>>> print(f"Original norm: {norm:.2f}")
|
165
|
+
Original norm: 13.00
|
166
|
+
|
167
|
+
>>> # Using different norm types
|
168
|
+
>>> grads = {'layer1': jnp.array([[-2.0, 3.0], [1.0, -4.0]])}
|
169
|
+
>>>
|
170
|
+
>>> # L2 norm (default)
|
171
|
+
>>> clipped_l2, norm_l2 = brainstate.nn.clip_grad_norm(grads, max_norm=3.0, norm_type=2, return_norm=True)
|
172
|
+
>>> print(f"L2 norm: {norm_l2:.2f}")
|
173
|
+
L2 norm: 5.48
|
174
|
+
>>>
|
175
|
+
>>> # L1 norm
|
176
|
+
>>> clipped_l1, norm_l1 = brainstate.nn.clip_grad_norm(grads, max_norm=5.0, norm_type=1, return_norm=True)
|
177
|
+
>>> print(f"L1 norm: {norm_l1:.2f}")
|
178
|
+
L1 norm: 10.00
|
179
|
+
>>>
|
180
|
+
>>> # Infinity norm
|
181
|
+
>>> clipped_inf, norm_inf = brainstate.nn.clip_grad_norm(grads, max_norm=2.0, norm_type='inf', return_norm=True)
|
182
|
+
>>> print(f"Inf norm: {norm_inf:.2f}")
|
183
|
+
Inf norm: 4.00
|
184
|
+
"""
|
185
|
+
if norm_type is None:
|
186
|
+
norm_type = 2.0
|
187
|
+
|
188
|
+
# Convert string 'inf' to jnp.inf for compatibility
|
189
|
+
if norm_type == 'inf':
|
190
|
+
norm_type = jnp.inf
|
191
|
+
elif norm_type == '-inf':
|
192
|
+
norm_type = -jnp.inf
|
193
|
+
|
194
|
+
# Get all gradient leaves
|
195
|
+
grad_leaves = jax.tree.leaves(grad)
|
196
|
+
|
197
|
+
# Handle empty PyTree
|
198
|
+
if not grad_leaves:
|
199
|
+
if return_norm:
|
200
|
+
return grad, jnp.array(0.0)
|
201
|
+
return grad
|
202
|
+
|
203
|
+
# Compute norm over flattened gradient values
|
204
|
+
norm_fn = partial(jnp.linalg.norm, ord=norm_type)
|
205
|
+
flat_grads = jnp.concatenate([g.ravel() for g in grad_leaves])
|
206
|
+
total_norm = norm_fn(flat_grads)
|
207
|
+
|
208
|
+
# Compute scaling factor
|
209
|
+
clip_factor = jnp.minimum(1.0, max_norm / (total_norm + 1e-6))
|
210
|
+
|
211
|
+
# Apply clipping
|
212
|
+
clipped_grad = jax.tree.map(lambda g: g * clip_factor, grad)
|
213
|
+
|
214
|
+
if return_norm:
|
215
|
+
return clipped_grad, total_norm
|
216
|
+
return clipped_grad
|