braintools 0.0.1__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.
@@ -0,0 +1,834 @@
1
+ """Shared neural network activations and other functions."""
2
+
3
+ import operator
4
+ from functools import partial
5
+ from typing import Any, Union, Sequence
6
+
7
+ import jax
8
+ import jax.numpy as jnp
9
+ import numpy as np
10
+ from jax import custom_jvp
11
+ from jax import lax
12
+ from jax.scipy.special import logsumexp
13
+ from jax.typing import ArrayLike
14
+
15
+ __all__ = [
16
+ "relu",
17
+ "squareplus",
18
+ "softplus",
19
+ "soft_sign",
20
+ "sigmoid",
21
+ "silu",
22
+ "swish",
23
+ "log_sigmoid",
24
+ "elu",
25
+ "leaky_relu",
26
+ "hard_tanh",
27
+ "celu",
28
+ "selu",
29
+ "gelu",
30
+ "glu",
31
+ "logsumexp",
32
+ "log_softmax",
33
+ "softmax",
34
+ "standardize",
35
+ "one_hot",
36
+ "relu6",
37
+ "hard_sigmoid",
38
+ "hard_silu",
39
+ "hard_swish",
40
+ 'hard_shrink',
41
+ 'rrelu',
42
+ 'mish',
43
+ 'soft_shrink',
44
+ 'prelu',
45
+ 'tanh_shrink',
46
+ 'softmin',
47
+ ]
48
+
49
+
50
+ def softmin(x, axis=-1):
51
+ r"""Applies the Softmin function to an n-dimensional input Tensor
52
+ rescaling them so that the elements of the n-dimensional output Tensor
53
+ lie in the range `[0, 1]` and sum to 1.
54
+
55
+ Softmin is defined as:
56
+
57
+ .. math::
58
+ \text{Softmin}(x_{i}) = \frac{\exp(-x_i)}{\sum_j \exp(-x_j)}
59
+
60
+ Shape:
61
+ - Input: :math:`(*)` where `*` means, any number of additional
62
+ dimensions
63
+ - Output: :math:`(*)`, same shape as the input
64
+
65
+ Args:
66
+ axis (int): A dimension along which Softmin will be computed (so every slice
67
+ along dim will sum to 1).
68
+ """
69
+ unnormalized = jnp.exp(-x)
70
+ return unnormalized / unnormalized.sum(axis, keepdims=True)
71
+
72
+
73
+ def tanh_shrink(x):
74
+ r"""Applies the element-wise function:
75
+
76
+ .. math::
77
+ \text{Tanhshrink}(x) = x - \tanh(x)
78
+ """
79
+ return x - jnp.tanh(x)
80
+
81
+
82
+ def prelu(x, a=0.25):
83
+ r"""Applies the element-wise function:
84
+
85
+ .. math::
86
+ \text{PReLU}(x) = \max(0,x) + a * \min(0,x)
87
+
88
+ or
89
+
90
+ .. math::
91
+ \text{PReLU}(x) =
92
+ \begin{cases}
93
+ x, & \text{ if } x \geq 0 \\
94
+ ax, & \text{ otherwise }
95
+ \end{cases}
96
+
97
+ Here :math:`a` is a learnable parameter. When called without arguments, `nn.PReLU()` uses a single
98
+ parameter :math:`a` across all input channels. If called with `nn.PReLU(nChannels)`,
99
+ a separate :math:`a` is used for each input channel.
100
+ """
101
+ return jnp.where(x >= 0., x, a * x)
102
+
103
+
104
+ def soft_shrink(x, lambd=0.5):
105
+ r"""Applies the soft shrinkage function elementwise:
106
+
107
+ .. math::
108
+ \text{SoftShrinkage}(x) =
109
+ \begin{cases}
110
+ x - \lambda, & \text{ if } x > \lambda \\
111
+ x + \lambda, & \text{ if } x < -\lambda \\
112
+ 0, & \text{ otherwise }
113
+ \end{cases}
114
+
115
+ Args:
116
+ lambd: the :math:`\lambda` (must be no less than zero) value for the Softshrink formulation. Default: 0.5
117
+
118
+ Shape:
119
+ - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
120
+ - Output: :math:`(*)`, same shape as the input.
121
+ """
122
+ return jnp.where(x > lambd, x - lambd, jnp.where(x < -lambd, x + lambd, 0.))
123
+
124
+
125
+ def mish(x):
126
+ r"""Applies the Mish function, element-wise.
127
+
128
+ Mish: A Self Regularized Non-Monotonic Neural Activation Function.
129
+
130
+ .. math::
131
+ \text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))
132
+
133
+ .. note::
134
+ See `Mish: A Self Regularized Non-Monotonic Neural Activation Function <https://arxiv.org/abs/1908.08681>`_
135
+
136
+ Shape:
137
+ - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
138
+ - Output: :math:`(*)`, same shape as the input.
139
+ """
140
+ return x * jnp.tanh(softplus(x))
141
+
142
+
143
+ def rrelu(key, x, lower=0.125, upper=0.3333333333333333):
144
+ r"""Applies the randomized leaky rectified liner unit function, element-wise,
145
+ as described in the paper:
146
+
147
+ `Empirical Evaluation of Rectified Activations in Convolutional Network`_.
148
+
149
+ The function is defined as:
150
+
151
+ .. math::
152
+ \text{RReLU}(x) =
153
+ \begin{cases}
154
+ x & \text{if } x \geq 0 \\
155
+ ax & \text{ otherwise }
156
+ \end{cases}
157
+
158
+ where :math:`a` is randomly sampled from uniform distribution
159
+ :math:`\mathcal{U}(\text{lower}, \text{upper})`.
160
+
161
+ See: https://arxiv.org/pdf/1505.00853.pdf
162
+
163
+ Args:
164
+ lower: lower bound of the uniform distribution. Default: :math:`\frac{1}{8}`
165
+ upper: upper bound of the uniform distribution. Default: :math:`\frac{1}{3}`
166
+
167
+ Shape:
168
+ - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
169
+ - Output: :math:`(*)`, same shape as the input.
170
+
171
+ .. _`Empirical Evaluation of Rectified Activations in Convolutional Network`:
172
+ https://arxiv.org/abs/1505.00853
173
+ """
174
+ x = jnp.asarray(x)
175
+ a = jax.random.uniform(key, x.shape, x.dtype, lower, upper)
176
+ return jnp.where(x >= 0., x, a * x)
177
+
178
+
179
+ def hard_shrink(x, lambd=0.5):
180
+ r"""Applies the Hard Shrinkage (Hardshrink) function element-wise.
181
+
182
+ Hardshrink is defined as:
183
+
184
+ .. math::
185
+ \text{HardShrink}(x) =
186
+ \begin{cases}
187
+ x, & \text{ if } x > \lambda \\
188
+ x, & \text{ if } x < -\lambda \\
189
+ 0, & \text{ otherwise }
190
+ \end{cases}
191
+
192
+ Args:
193
+ lambd: the :math:`\lambda` value for the Hardshrink formulation. Default: 0.5
194
+
195
+ Shape:
196
+ - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
197
+ - Output: :math:`(*)`, same shape as the input.
198
+
199
+ """
200
+ return jnp.where(x > lambd, x, jnp.where(x < -lambd, x, 0.))
201
+
202
+
203
+ def canonicalize_axis(axis, num_dims) -> int:
204
+ """Canonicalize an axis in [-num_dims, num_dims) to [0, num_dims)."""
205
+ axis = operator.index(axis)
206
+ if not -num_dims <= axis < num_dims:
207
+ raise ValueError(f"axis {axis} is out of bounds for array of dimension {num_dims}")
208
+ if axis < 0:
209
+ axis = axis + num_dims
210
+ return axis
211
+
212
+
213
+ # activations
214
+
215
+ @custom_jvp
216
+ @jax.jit
217
+ def relu(x: ArrayLike) -> jax.Array:
218
+ r"""Rectified linear unit activation function.
219
+
220
+ Computes the element-wise function:
221
+
222
+ .. math::
223
+ \mathrm{relu}(x) = \max(x, 0)
224
+
225
+ except under differentiation, we take:
226
+
227
+ .. math::
228
+ \nabla \mathrm{relu}(0) = 0
229
+
230
+ For more information see
231
+ `Numerical influence of ReLU’(0) on backpropagation
232
+ <https://openreview.net/forum?id=urrcVI-_jRm>`_.
233
+
234
+ Args:
235
+ x : input array
236
+
237
+ Returns:
238
+ An array.
239
+
240
+ Example:
241
+ >>> jax.nn.relu(jax.numpy.array([-2., -1., -0.5, 0, 0.5, 1., 2.]))
242
+ Array([0. , 0. , 0. , 0. , 0.5, 1. , 2. ], dtype=float32)
243
+
244
+ See also:
245
+ :func:`relu6`
246
+
247
+ """
248
+ return jnp.maximum(x, 0)
249
+
250
+
251
+ # For behavior at 0, see https://openreview.net/forum?id=urrcVI-_jRm
252
+ relu.defjvps(lambda g, ans, x: lax.select(x > 0, g, lax.full_like(g, 0)))
253
+
254
+
255
+ @jax.jit
256
+ def squareplus(x: ArrayLike, b: ArrayLike = 4) -> jax.Array:
257
+ r"""Squareplus activation function.
258
+
259
+ Computes the element-wise function
260
+
261
+ .. math::
262
+ \mathrm{squareplus}(x) = \frac{x + \sqrt{x^2 + b}}{2}
263
+
264
+ as described in https://arxiv.org/abs/2112.11687.
265
+
266
+ Args:
267
+ x : input array
268
+ b : smoothness parameter
269
+ """
270
+ x = jnp.asarray(x)
271
+ b = jnp.asarray(b)
272
+ y = x + jnp.sqrt(jnp.square(x) + b)
273
+ return y / 2
274
+
275
+
276
+ @jax.jit
277
+ def softplus(x: ArrayLike) -> jax.Array:
278
+ r"""Softplus activation function.
279
+
280
+ Computes the element-wise function
281
+
282
+ .. math::
283
+ \mathrm{softplus}(x) = \log(1 + e^x)
284
+
285
+ Args:
286
+ x : input array
287
+ """
288
+ return jnp.logaddexp(x, 0)
289
+
290
+
291
+ @jax.jit
292
+ def soft_sign(x: ArrayLike) -> jax.Array:
293
+ r"""Soft-sign activation function.
294
+
295
+ Computes the element-wise function
296
+
297
+ .. math::
298
+ \mathrm{soft\_sign}(x) = \frac{x}{|x| + 1}
299
+
300
+ Args:
301
+ x : input array
302
+ """
303
+ x_arr = jnp.asarray(x)
304
+ return x_arr / (jnp.abs(x_arr) + 1)
305
+
306
+
307
+ @partial(jax.jit, inline=True)
308
+ def sigmoid(x: ArrayLike) -> jax.Array:
309
+ r"""Sigmoid activation function.
310
+
311
+ Computes the element-wise function:
312
+
313
+ .. math::
314
+ \mathrm{sigmoid}(x) = \frac{1}{1 + e^{-x}}
315
+
316
+ Args:
317
+ x : input array
318
+
319
+ Returns:
320
+ An array.
321
+
322
+ See also:
323
+ :func:`log_sigmoid`
324
+
325
+ """
326
+ return lax.logistic(x)
327
+
328
+
329
+ @jax.jit
330
+ def silu(x: ArrayLike) -> jax.Array:
331
+ r"""SiLU (a.k.a. swish) activation function.
332
+
333
+ Computes the element-wise function:
334
+
335
+ .. math::
336
+ \mathrm{silu}(x) = x \cdot \mathrm{sigmoid}(x) = \frac{x}{1 + e^{-x}}
337
+
338
+ :func:`swish` and :func:`silu` are both aliases for the same function.
339
+
340
+ Args:
341
+ x : input array
342
+
343
+ Returns:
344
+ An array.
345
+
346
+ See also:
347
+ :func:`sigmoid`
348
+ """
349
+ x_arr = jnp.asarray(x)
350
+ return x_arr * sigmoid(x_arr)
351
+
352
+
353
+ swish = silu
354
+
355
+
356
+ @jax.jit
357
+ def log_sigmoid(x: ArrayLike) -> jax.Array:
358
+ r"""Log-sigmoid activation function.
359
+
360
+ Computes the element-wise function:
361
+
362
+ .. math::
363
+ \mathrm{log\_sigmoid}(x) = \log(\mathrm{sigmoid}(x)) = -\log(1 + e^{-x})
364
+
365
+ Args:
366
+ x : input array
367
+
368
+ Returns:
369
+ An array.
370
+
371
+ See also:
372
+ :func:`sigmoid`
373
+ """
374
+ x_arr = jnp.asarray(x)
375
+ return -softplus(-x_arr)
376
+
377
+
378
+ @jax.jit
379
+ def elu(x: ArrayLike, alpha: ArrayLike = 1.0) -> jax.Array:
380
+ r"""Exponential linear unit activation function.
381
+
382
+ Computes the element-wise function:
383
+
384
+ .. math::
385
+ \mathrm{elu}(x) = \begin{cases}
386
+ x, & x > 0\\
387
+ \alpha \left(\exp(x) - 1\right), & x \le 0
388
+ \end{cases}
389
+
390
+ Args:
391
+ x : input array
392
+ alpha : scalar or array of alpha values (default: 1.0)
393
+
394
+ Returns:
395
+ An array.
396
+
397
+ See also:
398
+ :func:`selu`
399
+ """
400
+ x_arr = jnp.asarray(x)
401
+ return jnp.where(x_arr > 0,
402
+ x_arr,
403
+ alpha * jnp.expm1(jnp.where(x_arr > 0, 0., x_arr)))
404
+
405
+
406
+ @jax.jit
407
+ def leaky_relu(x: ArrayLike, negative_slope: ArrayLike = 1e-2) -> jax.Array:
408
+ r"""Leaky rectified linear unit activation function.
409
+
410
+ Computes the element-wise function:
411
+
412
+ .. math::
413
+ \mathrm{leaky\_relu}(x) = \begin{cases}
414
+ x, & x \ge 0\\
415
+ \alpha x, & x < 0
416
+ \end{cases}
417
+
418
+ where :math:`\alpha` = :code:`negative_slope`.
419
+
420
+ Args:
421
+ x : input array
422
+ negative_slope : array or scalar specifying the negative slope (default: 0.01)
423
+
424
+ Returns:
425
+ An array.
426
+
427
+ See also:
428
+ :func:`relu`
429
+ """
430
+ x_arr = jnp.asarray(x)
431
+ return jnp.where(x_arr >= 0, x_arr, negative_slope * x_arr)
432
+
433
+
434
+ @jax.jit
435
+ def hard_tanh(x: ArrayLike) -> jax.Array:
436
+ r"""Hard :math:`\mathrm{tanh}` activation function.
437
+
438
+ Computes the element-wise function:
439
+
440
+ .. math::
441
+ \mathrm{hard\_tanh}(x) = \begin{cases}
442
+ -1, & x < -1\\
443
+ x, & -1 \le x \le 1\\
444
+ 1, & 1 < x
445
+ \end{cases}
446
+
447
+ Args:
448
+ x : input array
449
+
450
+ Returns:
451
+ An array.
452
+ """
453
+ x_arr = jnp.asarray(x)
454
+ return jnp.where(x_arr > 1, 1, jnp.where(x_arr < -1, -1, x_arr))
455
+
456
+
457
+ @jax.jit
458
+ def celu(x: ArrayLike, alpha: ArrayLike = 1.0) -> jax.Array:
459
+ r"""Continuously-differentiable exponential linear unit activation.
460
+
461
+ Computes the element-wise function:
462
+
463
+ .. math::
464
+ \mathrm{celu}(x) = \begin{cases}
465
+ x, & x > 0\\
466
+ \alpha \left(\exp(\frac{x}{\alpha}) - 1\right), & x \le 0
467
+ \end{cases}
468
+
469
+ For more information, see
470
+ `Continuously Differentiable Exponential Linear Units
471
+ <https://arxiv.org/pdf/1704.07483.pdf>`_.
472
+
473
+ Args:
474
+ x : input array
475
+ alpha : array or scalar (default: 1.0)
476
+
477
+ Returns:
478
+ An array.
479
+ """
480
+ return jnp.maximum(x, 0.0) + alpha * jnp.expm1(jnp.minimum(x, 0.0) / alpha)
481
+
482
+
483
+ @jax.jit
484
+ def selu(x: ArrayLike) -> jax.Array:
485
+ r"""Scaled exponential linear unit activation.
486
+
487
+ Computes the element-wise function:
488
+
489
+ .. math::
490
+ \mathrm{selu}(x) = \lambda \begin{cases}
491
+ x, & x > 0\\
492
+ \alpha e^x - \alpha, & x \le 0
493
+ \end{cases}
494
+
495
+ where :math:`\lambda = 1.0507009873554804934193349852946` and
496
+ :math:`\alpha = 1.6732632423543772848170429916717`.
497
+
498
+ For more information, see
499
+ `Self-Normalizing Neural Networks
500
+ <https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf>`_.
501
+
502
+ Args:
503
+ x : input array
504
+
505
+ Returns:
506
+ An array.
507
+
508
+ See also:
509
+ :func:`elu`
510
+ """
511
+ alpha = 1.6732632423543772848170429916717
512
+ scale = 1.0507009873554804934193349852946
513
+ return scale * elu(x, alpha)
514
+
515
+
516
+ def gelu(x: ArrayLike, approximate: bool = True) -> jax.Array:
517
+ r"""Gaussian error linear unit activation function.
518
+
519
+ If ``approximate=False``, computes the element-wise function:
520
+
521
+ .. math::
522
+ \mathrm{gelu}(x) = \frac{x}{2} \left(1 + \mathrm{erf} \left(
523
+ \frac{x}{\sqrt{2}} \right) \right)
524
+
525
+ If ``approximate=True``, uses the approximate formulation of GELU:
526
+
527
+ .. math::
528
+ \mathrm{gelu}(x) = \frac{x}{2} \left(1 + \mathrm{tanh} \left(
529
+ \sqrt{\frac{2}{\pi}} \left(x + 0.044715 x^3 \right) \right) \right)
530
+
531
+ For more information, see `Gaussian Error Linear Units (GELUs)
532
+ <https://arxiv.org/abs/1606.08415>`_, section 2.
533
+
534
+ Args:
535
+ x : input array
536
+ approximate: whether to use the approximate or exact formulation.
537
+ """
538
+ from jax._src.numpy import util as numpy_util
539
+ [x_arr] = numpy_util.promote_args_inexact("gelu", x)
540
+
541
+ if approximate:
542
+ sqrt_2_over_pi = np.sqrt(2 / np.pi).astype(x_arr.dtype)
543
+ cdf = 0.5 * (1.0 + jnp.tanh(sqrt_2_over_pi * (x_arr + 0.044715 * (x_arr ** 3))))
544
+ return x_arr * cdf
545
+ else:
546
+ sqrt_2 = np.sqrt(2).astype(x_arr.dtype)
547
+ return jnp.array(x_arr * (lax.erf(x_arr / sqrt_2) + 1) / 2, dtype=x_arr.dtype)
548
+
549
+
550
+ @partial(jax.jit, static_argnames=("axis",))
551
+ def glu(x: ArrayLike, axis: int = -1) -> jax.Array:
552
+ r"""Gated linear unit activation function.
553
+
554
+ Computes the function:
555
+
556
+ .. math::
557
+ \mathrm{glu}(x) = x\left[\ldots, 0:\frac{n}{2}, \ldots\right] \cdot
558
+ \mathrm{sigmoid} \left( x\left[\ldots, \frac{n}{2}:n, \ldots\right]
559
+ \right)
560
+
561
+ where the array is split into two along ``axis``. The size of the ``axis``
562
+ dimension must be divisible by two.
563
+
564
+ Args:
565
+ x : input array
566
+ axis: the axis along which the split should be computed (default: -1)
567
+
568
+ Returns:
569
+ An array.
570
+
571
+ See also:
572
+ :func:`sigmoid`
573
+ """
574
+ x_arr = jnp.asarray(x)
575
+ size = x_arr.shape[axis]
576
+ assert size % 2 == 0, "axis size must be divisible by 2"
577
+ x1, x2 = jnp.split(x_arr, 2, axis)
578
+ return x1 * sigmoid(x2)
579
+
580
+
581
+ @partial(jax.jit, static_argnames=("axis",))
582
+ def log_softmax(x: ArrayLike,
583
+ axis: int | tuple[int, ...] | None = -1,
584
+ where: ArrayLike | None = None,
585
+ initial: ArrayLike | None = None) -> jax.Array:
586
+ r"""Log-Softmax function.
587
+
588
+ Computes the logarithm of the :code:`softmax` function, which rescales
589
+ elements to the range :math:`[-\infty, 0)`.
590
+
591
+ .. math ::
592
+ \mathrm{log\_softmax}(x)_i = \log \left( \frac{\exp(x_i)}{\sum_j \exp(x_j)}
593
+ \right)
594
+
595
+ Args:
596
+ x : input array
597
+ axis: the axis or axes along which the :code:`log_softmax` should be
598
+ computed. Either an integer or a tuple of integers.
599
+ where: Elements to include in the :code:`log_softmax`.
600
+ initial: The minimum value used to shift the input array. Must be present
601
+ when :code:`where` is not None.
602
+
603
+ Returns:
604
+ An array.
605
+
606
+ See also:
607
+ :func:`softmax`
608
+ """
609
+ x_arr = jnp.asarray(x)
610
+ x_max = jnp.max(x_arr, axis, where=where, initial=initial, keepdims=True)
611
+ x_safe = x_arr if where is None else jnp.where(where, x_arr, initial)
612
+ shifted = x_safe - lax.stop_gradient(x_max)
613
+ shifted_logsumexp = jnp.log(
614
+ jnp.sum(jnp.exp(shifted), axis, where=where, keepdims=True))
615
+ result = shifted - shifted_logsumexp
616
+ if where is not None:
617
+ return jnp.where(where, result, -jnp.inf)
618
+ return result
619
+
620
+
621
+ def softmax(x: ArrayLike,
622
+ axis: int | tuple[int, ...] | None = -1,
623
+ where: ArrayLike | None = None,
624
+ initial: ArrayLike | None = None) -> jax.Array:
625
+ r"""Softmax function.
626
+
627
+ Computes the function which rescales elements to the range :math:`[0, 1]`
628
+ such that the elements along :code:`axis` sum to :math:`1`.
629
+
630
+ .. math ::
631
+ \mathrm{softmax}(x) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
632
+
633
+ Args:
634
+ x : input array
635
+ axis: the axis or axes along which the softmax should be computed. The
636
+ softmax output summed across these dimensions should sum to :math:`1`.
637
+ Either an integer or a tuple of integers.
638
+ where: Elements to include in the :code:`softmax`.
639
+ initial: The minimum value used to shift the input array. Must be present
640
+ when :code:`where` is not None.
641
+
642
+ Returns:
643
+ An array.
644
+
645
+ See also:
646
+ :func:`log_softmax`
647
+ """
648
+ return _softmax(x, axis, where, initial) # type: ignore[return-value]
649
+
650
+
651
+ @partial(jax.custom_jvp, nondiff_argnums=(1,))
652
+ def _softmax(
653
+ x: ArrayLike,
654
+ axis: int | tuple[int, ...] | None = -1,
655
+ where: ArrayLike | None = None,
656
+ initial: ArrayLike | None = None
657
+ ) -> jax.Array:
658
+ x_max = jnp.max(x, axis, where=where, initial=initial, keepdims=True)
659
+ x_safe = x if where is None else jnp.where(where, x, initial)
660
+ unnormalized = jnp.exp(x_safe - x_max)
661
+ result = unnormalized / jnp.sum(unnormalized, axis, where=where, keepdims=True)
662
+ if where is not None:
663
+ result = jnp.where(where, result, 0)
664
+ return result
665
+
666
+
667
+ @_softmax.defjvp
668
+ def _softmax_jvp(axis, primals, tangents):
669
+ (x, where, initial), (x_dot, _, _) = primals, tangents
670
+ y = _softmax(x, axis, where, initial)
671
+ return y, y * (x_dot - (y * x_dot).sum(axis, where=where, keepdims=True))
672
+
673
+
674
+ @partial(jax.jit, static_argnames=("axis",))
675
+ def standardize(x: ArrayLike,
676
+ axis: int | tuple[int, ...] | None = -1,
677
+ variance: ArrayLike | None = None,
678
+ epsilon: ArrayLike = 1e-5,
679
+ where: ArrayLike | None = None) -> jax.Array:
680
+ r"""Normalizes an array by subtracting ``mean`` and dividing by :math:`\sqrt{\mathrm{variance}}`."""
681
+ mean = jnp.mean(x, axis, keepdims=True, where=where)
682
+ if variance is None:
683
+ # this definition is traditionally seen as less accurate than jnp.var's
684
+ # mean((x - mean(x))**2) but may be faster and even, given typical
685
+ # activation distributions and low-precision arithmetic, more accurate
686
+ # when used in neural network normalization layers
687
+ variance = jnp.mean(
688
+ jnp.square(x), axis, keepdims=True, where=where) - jnp.square(mean)
689
+ return jnp.subtract(x, jnp.asarray(mean)) * lax.rsqrt(jnp.asarray(variance) + epsilon)
690
+
691
+
692
+ @partial(jax.jit, static_argnames=("num_classes", "dtype", "axis"))
693
+ def _one_hot(x: Any,
694
+ num_classes: int, *,
695
+ dtype: Any,
696
+ axis: Union[int, Sequence[int]]) -> jax.Array:
697
+ num_classes = jax.core.concrete_dim_or_error(
698
+ num_classes,
699
+ "The error arose in jax.nn.one_hot argument `num_classes`.")
700
+ dtype = jax.dtypes.canonicalize_dtype(dtype)
701
+ x_arr = jnp.asarray(x)
702
+ try:
703
+ output_pos_axis = canonicalize_axis(axis, x_arr.ndim + 1)
704
+ except TypeError:
705
+ axis_size = lax.psum(1, axis)
706
+ if num_classes != axis_size:
707
+ raise ValueError(f"Expected num_classes to match the size of axis {axis}, "
708
+ f"but {num_classes} != {axis_size}") from None
709
+ axis_idx = lax.axis_index(axis)
710
+ return jnp.asarray(x_arr == axis_idx, dtype=dtype)
711
+ axis = operator.index(axis) # type: ignore[arg-type]
712
+ lhs = lax.expand_dims(x_arr, (axis,))
713
+ rhs_shape = [1] * x_arr.ndim
714
+ rhs_shape.insert(output_pos_axis, num_classes)
715
+ rhs = lax.broadcasted_iota(x_arr.dtype, rhs_shape, output_pos_axis)
716
+ return jnp.asarray(lhs == rhs, dtype=dtype)
717
+
718
+
719
+ def one_hot(x: Any,
720
+ num_classes: int, *,
721
+ dtype: Any = jnp.float_,
722
+ axis: Union[int, Sequence[int]] = -1) -> jax.Array:
723
+ """One-hot encodes the given indices.
724
+
725
+ Each index in the input ``x`` is encoded as a vector of zeros of length
726
+ ``num_classes`` with the element at ``index`` set to one::
727
+
728
+ >>> jax.nn.one_hot(jnp.array([0, 1, 2]), 3)
729
+ Array([[1., 0., 0.],
730
+ [0., 1., 0.],
731
+ [0., 0., 1.]], dtype=float32)
732
+
733
+ Indices outside the range [0, num_classes) will be encoded as zeros::
734
+
735
+ >>> jax.nn.one_hot(jnp.array([-1, 3]), 3)
736
+ Array([[0., 0., 0.],
737
+ [0., 0., 0.]], dtype=float32)
738
+
739
+ Args:
740
+ x: A tensor of indices.
741
+ num_classes: Number of classes in the one-hot dimension.
742
+ dtype: optional, a float dtype for the returned values (default :obj:`jnp.float_`).
743
+ axis: the axis or axes along which the function should be
744
+ computed.
745
+ """
746
+ num_classes = jax.core.concrete_dim_or_error(
747
+ num_classes,
748
+ "The error arose in jax.nn.one_hot argument `num_classes`.")
749
+ return _one_hot(x, num_classes, dtype=dtype, axis=axis)
750
+
751
+
752
+ @jax.custom_jvp
753
+ @jax.jit
754
+ def relu6(x: ArrayLike) -> jax.Array:
755
+ r"""Rectified Linear Unit 6 activation function.
756
+
757
+ Computes the element-wise function
758
+
759
+ .. math::
760
+ \mathrm{relu6}(x) = \min(\max(x, 0), 6)
761
+
762
+ except under differentiation, we take:
763
+
764
+ .. math::
765
+ \nabla \mathrm{relu}(0) = 0
766
+
767
+ and
768
+
769
+ .. math::
770
+ \nabla \mathrm{relu}(6) = 0
771
+
772
+ Args:
773
+ x : input array
774
+
775
+ Returns:
776
+ An array.
777
+
778
+ See also:
779
+ :func:`relu`
780
+ """
781
+ return jnp.minimum(jnp.maximum(x, 0), 6.)
782
+
783
+
784
+ relu6.defjvps(lambda g, ans, x:
785
+ lax.select((x > 0) & (x < 6), g, lax.full_like(g, 0)))
786
+
787
+
788
+ @jax.jit
789
+ def hard_sigmoid(x: ArrayLike) -> jax.Array:
790
+ r"""Hard Sigmoid activation function.
791
+
792
+ Computes the element-wise function
793
+
794
+ .. math::
795
+ \mathrm{hard\_sigmoid}(x) = \frac{\mathrm{relu6}(x + 3)}{6}
796
+
797
+ Args:
798
+ x : input array
799
+
800
+ Returns:
801
+ An array.
802
+
803
+ See also:
804
+ :func:`relu6`
805
+ """
806
+ return relu6(x + 3.) / 6.
807
+
808
+
809
+ @jax.jit
810
+ def hard_silu(x: ArrayLike) -> jax.Array:
811
+ r"""Hard SiLU (swish) activation function
812
+
813
+ Computes the element-wise function
814
+
815
+ .. math::
816
+ \mathrm{hard\_silu}(x) = x \cdot \mathrm{hard\_sigmoid}(x)
817
+
818
+ Both :func:`hard_silu` and :func:`hard_swish` are aliases for the same
819
+ function.
820
+
821
+ Args:
822
+ x : input array
823
+
824
+ Returns:
825
+ An array.
826
+
827
+ See also:
828
+ :func:`hard_sigmoid`
829
+ """
830
+ x_arr = jnp.asarray(x)
831
+ return x_arr * hard_sigmoid(x_arr)
832
+
833
+
834
+ hard_swish = hard_silu