Skip to content

Base¤

The Base module provides the foundational Base class which is the core of Zodiax's path-based pytree interface. This class allows for operations and functions to be applied to leaves specified by their paths, enabling a flexible and powerful way to manipulate complex data structures.

zodiax.base ¤

Base ¤

Bases: Module

Extend the Equinox.Module class to give a user-friendly 'param based' API for working with pytrees by adding a series of methods used to interface with the leaves of the pytree using parameters.

Source code in zodiax/base.py
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
class Base(eqx.Module):
    """
    Extend the Equinox.Module class to give a user-friendly 'param based' API
    for working with pytrees by adding a series of methods used to interface
    with the leaves of the pytree using parameters.
    """

    def get(self: PyTree, parameters: Params) -> Any:
        """
        Get the leaf specified by param.

        Parameters
        ----------
        parameters : Params
            Parameter selector. Supported forms are:
            - ``"param"`` (single path string)
            - ``["param", "b.param"]`` (list of path strings)
            - ``("param", "b.param")`` (tuple of path strings)
            - Interleaved list/tuple nesting of path strings.

        Returns
        -------
        leaf, leaves : Any, list
            The leaf or list of leaves specified by parameters.
        """
        new_parameters = _format(parameters)
        values = _get_leaves(self, new_parameters)
        return values[0] if len(new_parameters) == 1 else values

    def set(
        self: PyTree,
        parameters: Params = None,
        values: Values = None,
        /,
        **updates,
    ) -> PyTree:
        """
        Set the leaves specified by parameters with values.

        Parameters
        ----------
        parameters : Params, optional
            Parameter selector for positional style. Supported forms are:
            - ``"param"``
            - list/tuple of path strings
            - interleaved list/tuple nesting of path strings
            - a mapping ``{path: value}`` (dictionary style)
        values : Values, optional
            Values for positional style ``set(parameters, values)``.
            Can be a scalar, list, or tuple matching ``parameters``.
        **updates
            Keyword update style, e.g. ``set(param=1.0)`` and nested via
            ``set(**{"b.param": 2.0})``.

        Returns
        -------
        pytree : PyTree
            The pytree with leaves specified by parameters updated with values.
        """
        parameters, values = _normalise_mutation_inputs(
            parameters,
            values,
            updates=updates,
            method_name="set",
        )

        # Allow explicit None values
        if values is None:
            values = [None]
            if isinstance(parameters, str):
                parameters = [parameters]
        new_parameters, new_values = _format(parameters, values)

        # Define 'where' function and update pytree
        def leaves_fn(pytree):
            return _get_leaves(pytree, new_parameters)

        return eqx.tree_at(
            leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
        )

    def add(
        self: PyTree,
        parameters: Params = None,
        values: Values = None,
        /,
        **updates,
    ) -> PyTree:
        """
        Add to the leaves specified by parameters with values.

        Parameters
        ----------
        parameters : Params, optional
            Parameter selector or mapping. Supported forms are:
            - path string
            - list/tuple (including interleaved nesting) of path strings
            - mapping ``{path: value}``
        values : Values, optional
            Values for positional style ``add(parameters, values)``.
        **updates
            Keyword update style, e.g. ``add(param=1.0)`` and nested via
            ``add(**{"b.param": 2.0})``.

        Returns
        -------
        pytree : PyTree
            The pytree with values added to leaves specified by parameters.
        """
        parameters, values = _normalise_mutation_inputs(
            parameters,
            values,
            updates=updates,
            method_name="add",
            require_values=True,
        )
        new_parameters, new_values = _format(parameters, values)
        new_values = [
            leaf + value
            for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
        ]

        # Define 'where' function and update pytree
        def leaves_fn(pytree):
            return _get_leaves(pytree, new_parameters)

        return eqx.tree_at(
            leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
        )

    def multiply(
        self: PyTree,
        parameters: Params = None,
        values: Values = None,
        /,
        **updates,
    ) -> PyTree:
        """
        Multiplies the leaves specified by parameters with values.

        Parameters
        ----------
        parameters : Params, optional
            Parameter selector or mapping (string, list/tuple paths, nested
            list/tuple paths, or ``{path: value}``).
        values : Values, optional
            Values for positional style ``multiply(parameters, values)``.
        **updates
            Keyword update style, e.g. ``multiply(param=2.0)`` and nested via
            ``multiply(**{"b.param": 3.0})``.

        Returns
        -------
        pytree : PyTree
            The pytree with values multiplied by leaves specified by parameters.
        """
        parameters, values = _normalise_mutation_inputs(
            parameters,
            values,
            updates=updates,
            method_name="multiply",
            require_values=True,
        )
        new_parameters, new_values = _format(parameters, values)
        new_values = [
            leaf * value
            for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
        ]

        # Define 'where' function and update pytree
        def leaves_fn(pytree):
            return _get_leaves(pytree, new_parameters)

        return eqx.tree_at(
            leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
        )

    def divide(
        self: PyTree,
        parameters: Params = None,
        values: Values = None,
        /,
        **updates,
    ) -> PyTree:
        """
        Divides the leaves specified by parameters with values.

        Parameters
        ----------
        parameters : Params, optional
            Parameter selector or mapping (string, list/tuple paths, nested
            list/tuple paths, or ``{path: value}``).
        values : Values, optional
            Values for positional style ``divide(parameters, values)``.
        **updates
            Keyword update style, e.g. ``divide(param=2.0)`` and nested via
            ``divide(**{"b.param": 4.0})``.

        Returns
        -------
        pytree : PyTree
            The pytree with values divided by leaves specified by parameters.
        """
        parameters, values = _normalise_mutation_inputs(
            parameters,
            values,
            updates=updates,
            method_name="divide",
            require_values=True,
        )
        new_parameters, new_values = _format(parameters, values)
        new_values = [
            leaf / value
            for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
        ]

        # Define 'where' function and update pytree
        def leaves_fn(pytree):
            return _get_leaves(pytree, new_parameters)

        return eqx.tree_at(
            leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
        )

    def power(
        self: PyTree,
        parameters: Params = None,
        values: Values = None,
        /,
        **updates,
    ) -> PyTree:
        """
        Raises the leaves specified by parameters to the power of values.

        Parameters
        ----------
        parameters : Params, optional
            Parameter selector or mapping (string, list/tuple paths, nested
            list/tuple paths, or ``{path: value}``).
        values : Values, optional
            Values for positional style ``power(parameters, values)``.
        **updates
            Keyword update style, e.g. ``power(param=3.0)`` and nested via
            ``power(**{"b.param": 2.0})``.

        Returns
        -------
        pytree : PyTree
            The pytree with the leaves specified by parameters raised to the power
            of values.
        """
        parameters, values = _normalise_mutation_inputs(
            parameters,
            values,
            updates=updates,
            method_name="power",
            require_values=True,
        )
        new_parameters, new_values = _format(parameters, values)
        new_values = [
            leaf**value
            for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
        ]

        # Define 'where' function and update pytree
        def leaves_fn(pytree):
            return _get_leaves(pytree, new_parameters)

        return eqx.tree_at(
            leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
        )

    def min(
        self: PyTree,
        parameters: Params = None,
        values: Values = None,
        /,
        **updates,
    ) -> PyTree:
        """
        Updates the leaves specified by parameters with the minimum value of the
        leaves and values.

        Parameters
        ----------
        parameters : Params, optional
            Parameter selector or mapping (string, list/tuple paths, nested
            list/tuple paths, or ``{path: value}``).
        values : Values, optional
            Values for positional style ``min(parameters, values)``.
        **updates
            Keyword update style, e.g. ``min(param=0.5)`` and nested via
            ``min(**{"b.param": 3.0})``.

        Returns
        -------
        pytree : PyTree
            The pytree with the leaves specified by parameters updated with the
            minimum value of the leaf and values.
        """
        parameters, values = _normalise_mutation_inputs(
            parameters,
            values,
            updates=updates,
            method_name="min",
            require_values=True,
        )
        new_parameters, new_values = _format(parameters, values)
        new_values = [
            np.minimum(leaf, value)
            for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
        ]

        # Define 'where' function and update pytree
        def leaves_fn(pytree):
            return _get_leaves(pytree, new_parameters)

        return eqx.tree_at(
            leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
        )

    def max(
        self: PyTree,
        parameters: Params = None,
        values: Values = None,
        /,
        **updates,
    ) -> PyTree:
        """
        Updates the leaves specified by parameters with the maximum value of the
        leaves and values.


        Parameters
        ----------
        parameters : Params, optional
            Parameter selector or mapping (string, list/tuple paths, nested
            list/tuple paths, or ``{path: value}``).
        values : Values, optional
            Values for positional style ``max(parameters, values)``.
        **updates
            Keyword update style, e.g. ``max(param=10.0)`` and nested via
            ``max(**{"b.param": 1.0})``.

        Returns
        -------
        pytree : PyTree
            The pytree with the leaves specified by parameters updated with the
            maximum value of the leaf and values.
        """
        parameters, values = _normalise_mutation_inputs(
            parameters,
            values,
            updates=updates,
            method_name="max",
            require_values=True,
        )
        new_parameters, new_values = _format(parameters, values)
        new_values = [
            np.maximum(leaf, value)
            for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
        ]

        # Define 'where' function and update pytree
        def leaves_fn(pytree):
            return _get_leaves(pytree, new_parameters)

        return eqx.tree_at(
            leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
        )

add(parameters=None, values=None, /, **updates) ¤

Add to the leaves specified by parameters with values.

Parameters:

Name Type Description Default
parameters Params

Parameter selector or mapping. Supported forms are: - path string - list/tuple (including interleaved nesting) of path strings - mapping {path: value}

None
values Values

Values for positional style add(parameters, values).

None
**updates

Keyword update style, e.g. add(param=1.0) and nested via add(**{"b.param": 2.0}).

{}

Returns:

Name Type Description
pytree PyTree

The pytree with values added to leaves specified by parameters.

Source code in zodiax/base.py
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
def add(
    self: PyTree,
    parameters: Params = None,
    values: Values = None,
    /,
    **updates,
) -> PyTree:
    """
    Add to the leaves specified by parameters with values.

    Parameters
    ----------
    parameters : Params, optional
        Parameter selector or mapping. Supported forms are:
        - path string
        - list/tuple (including interleaved nesting) of path strings
        - mapping ``{path: value}``
    values : Values, optional
        Values for positional style ``add(parameters, values)``.
    **updates
        Keyword update style, e.g. ``add(param=1.0)`` and nested via
        ``add(**{"b.param": 2.0})``.

    Returns
    -------
    pytree : PyTree
        The pytree with values added to leaves specified by parameters.
    """
    parameters, values = _normalise_mutation_inputs(
        parameters,
        values,
        updates=updates,
        method_name="add",
        require_values=True,
    )
    new_parameters, new_values = _format(parameters, values)
    new_values = [
        leaf + value
        for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
    ]

    # Define 'where' function and update pytree
    def leaves_fn(pytree):
        return _get_leaves(pytree, new_parameters)

    return eqx.tree_at(
        leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
    )

divide(parameters=None, values=None, /, **updates) ¤

Divides the leaves specified by parameters with values.

Parameters:

Name Type Description Default
parameters Params

Parameter selector or mapping (string, list/tuple paths, nested list/tuple paths, or {path: value}).

None
values Values

Values for positional style divide(parameters, values).

None
**updates

Keyword update style, e.g. divide(param=2.0) and nested via divide(**{"b.param": 4.0}).

{}

Returns:

Name Type Description
pytree PyTree

The pytree with values divided by leaves specified by parameters.

Source code in zodiax/base.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
def divide(
    self: PyTree,
    parameters: Params = None,
    values: Values = None,
    /,
    **updates,
) -> PyTree:
    """
    Divides the leaves specified by parameters with values.

    Parameters
    ----------
    parameters : Params, optional
        Parameter selector or mapping (string, list/tuple paths, nested
        list/tuple paths, or ``{path: value}``).
    values : Values, optional
        Values for positional style ``divide(parameters, values)``.
    **updates
        Keyword update style, e.g. ``divide(param=2.0)`` and nested via
        ``divide(**{"b.param": 4.0})``.

    Returns
    -------
    pytree : PyTree
        The pytree with values divided by leaves specified by parameters.
    """
    parameters, values = _normalise_mutation_inputs(
        parameters,
        values,
        updates=updates,
        method_name="divide",
        require_values=True,
    )
    new_parameters, new_values = _format(parameters, values)
    new_values = [
        leaf / value
        for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
    ]

    # Define 'where' function and update pytree
    def leaves_fn(pytree):
        return _get_leaves(pytree, new_parameters)

    return eqx.tree_at(
        leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
    )

get(parameters) ¤

Get the leaf specified by param.

Parameters:

Name Type Description Default
parameters Params

Parameter selector. Supported forms are: - "param" (single path string) - ["param", "b.param"] (list of path strings) - ("param", "b.param") (tuple of path strings) - Interleaved list/tuple nesting of path strings.

required

Returns:

Type Description
leaf, leaves : Any, list

The leaf or list of leaves specified by parameters.

Source code in zodiax/base.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def get(self: PyTree, parameters: Params) -> Any:
    """
    Get the leaf specified by param.

    Parameters
    ----------
    parameters : Params
        Parameter selector. Supported forms are:
        - ``"param"`` (single path string)
        - ``["param", "b.param"]`` (list of path strings)
        - ``("param", "b.param")`` (tuple of path strings)
        - Interleaved list/tuple nesting of path strings.

    Returns
    -------
    leaf, leaves : Any, list
        The leaf or list of leaves specified by parameters.
    """
    new_parameters = _format(parameters)
    values = _get_leaves(self, new_parameters)
    return values[0] if len(new_parameters) == 1 else values

max(parameters=None, values=None, /, **updates) ¤

Updates the leaves specified by parameters with the maximum value of the leaves and values.

Parameters:

Name Type Description Default
parameters Params

Parameter selector or mapping (string, list/tuple paths, nested list/tuple paths, or {path: value}).

None
values Values

Values for positional style max(parameters, values).

None
**updates

Keyword update style, e.g. max(param=10.0) and nested via max(**{"b.param": 1.0}).

{}

Returns:

Name Type Description
pytree PyTree

The pytree with the leaves specified by parameters updated with the maximum value of the leaf and values.

Source code in zodiax/base.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
def max(
    self: PyTree,
    parameters: Params = None,
    values: Values = None,
    /,
    **updates,
) -> PyTree:
    """
    Updates the leaves specified by parameters with the maximum value of the
    leaves and values.


    Parameters
    ----------
    parameters : Params, optional
        Parameter selector or mapping (string, list/tuple paths, nested
        list/tuple paths, or ``{path: value}``).
    values : Values, optional
        Values for positional style ``max(parameters, values)``.
    **updates
        Keyword update style, e.g. ``max(param=10.0)`` and nested via
        ``max(**{"b.param": 1.0})``.

    Returns
    -------
    pytree : PyTree
        The pytree with the leaves specified by parameters updated with the
        maximum value of the leaf and values.
    """
    parameters, values = _normalise_mutation_inputs(
        parameters,
        values,
        updates=updates,
        method_name="max",
        require_values=True,
    )
    new_parameters, new_values = _format(parameters, values)
    new_values = [
        np.maximum(leaf, value)
        for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
    ]

    # Define 'where' function and update pytree
    def leaves_fn(pytree):
        return _get_leaves(pytree, new_parameters)

    return eqx.tree_at(
        leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
    )

min(parameters=None, values=None, /, **updates) ¤

Updates the leaves specified by parameters with the minimum value of the leaves and values.

Parameters:

Name Type Description Default
parameters Params

Parameter selector or mapping (string, list/tuple paths, nested list/tuple paths, or {path: value}).

None
values Values

Values for positional style min(parameters, values).

None
**updates

Keyword update style, e.g. min(param=0.5) and nested via min(**{"b.param": 3.0}).

{}

Returns:

Name Type Description
pytree PyTree

The pytree with the leaves specified by parameters updated with the minimum value of the leaf and values.

Source code in zodiax/base.py
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
def min(
    self: PyTree,
    parameters: Params = None,
    values: Values = None,
    /,
    **updates,
) -> PyTree:
    """
    Updates the leaves specified by parameters with the minimum value of the
    leaves and values.

    Parameters
    ----------
    parameters : Params, optional
        Parameter selector or mapping (string, list/tuple paths, nested
        list/tuple paths, or ``{path: value}``).
    values : Values, optional
        Values for positional style ``min(parameters, values)``.
    **updates
        Keyword update style, e.g. ``min(param=0.5)`` and nested via
        ``min(**{"b.param": 3.0})``.

    Returns
    -------
    pytree : PyTree
        The pytree with the leaves specified by parameters updated with the
        minimum value of the leaf and values.
    """
    parameters, values = _normalise_mutation_inputs(
        parameters,
        values,
        updates=updates,
        method_name="min",
        require_values=True,
    )
    new_parameters, new_values = _format(parameters, values)
    new_values = [
        np.minimum(leaf, value)
        for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
    ]

    # Define 'where' function and update pytree
    def leaves_fn(pytree):
        return _get_leaves(pytree, new_parameters)

    return eqx.tree_at(
        leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
    )

multiply(parameters=None, values=None, /, **updates) ¤

Multiplies the leaves specified by parameters with values.

Parameters:

Name Type Description Default
parameters Params

Parameter selector or mapping (string, list/tuple paths, nested list/tuple paths, or {path: value}).

None
values Values

Values for positional style multiply(parameters, values).

None
**updates

Keyword update style, e.g. multiply(param=2.0) and nested via multiply(**{"b.param": 3.0}).

{}

Returns:

Name Type Description
pytree PyTree

The pytree with values multiplied by leaves specified by parameters.

Source code in zodiax/base.py
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def multiply(
    self: PyTree,
    parameters: Params = None,
    values: Values = None,
    /,
    **updates,
) -> PyTree:
    """
    Multiplies the leaves specified by parameters with values.

    Parameters
    ----------
    parameters : Params, optional
        Parameter selector or mapping (string, list/tuple paths, nested
        list/tuple paths, or ``{path: value}``).
    values : Values, optional
        Values for positional style ``multiply(parameters, values)``.
    **updates
        Keyword update style, e.g. ``multiply(param=2.0)`` and nested via
        ``multiply(**{"b.param": 3.0})``.

    Returns
    -------
    pytree : PyTree
        The pytree with values multiplied by leaves specified by parameters.
    """
    parameters, values = _normalise_mutation_inputs(
        parameters,
        values,
        updates=updates,
        method_name="multiply",
        require_values=True,
    )
    new_parameters, new_values = _format(parameters, values)
    new_values = [
        leaf * value
        for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
    ]

    # Define 'where' function and update pytree
    def leaves_fn(pytree):
        return _get_leaves(pytree, new_parameters)

    return eqx.tree_at(
        leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
    )

power(parameters=None, values=None, /, **updates) ¤

Raises the leaves specified by parameters to the power of values.

Parameters:

Name Type Description Default
parameters Params

Parameter selector or mapping (string, list/tuple paths, nested list/tuple paths, or {path: value}).

None
values Values

Values for positional style power(parameters, values).

None
**updates

Keyword update style, e.g. power(param=3.0) and nested via power(**{"b.param": 2.0}).

{}

Returns:

Name Type Description
pytree PyTree

The pytree with the leaves specified by parameters raised to the power of values.

Source code in zodiax/base.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def power(
    self: PyTree,
    parameters: Params = None,
    values: Values = None,
    /,
    **updates,
) -> PyTree:
    """
    Raises the leaves specified by parameters to the power of values.

    Parameters
    ----------
    parameters : Params, optional
        Parameter selector or mapping (string, list/tuple paths, nested
        list/tuple paths, or ``{path: value}``).
    values : Values, optional
        Values for positional style ``power(parameters, values)``.
    **updates
        Keyword update style, e.g. ``power(param=3.0)`` and nested via
        ``power(**{"b.param": 2.0})``.

    Returns
    -------
    pytree : PyTree
        The pytree with the leaves specified by parameters raised to the power
        of values.
    """
    parameters, values = _normalise_mutation_inputs(
        parameters,
        values,
        updates=updates,
        method_name="power",
        require_values=True,
    )
    new_parameters, new_values = _format(parameters, values)
    new_values = [
        leaf**value
        for value, leaf in zip(new_values, _get_leaves(self, new_parameters))
    ]

    # Define 'where' function and update pytree
    def leaves_fn(pytree):
        return _get_leaves(pytree, new_parameters)

    return eqx.tree_at(
        leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
    )

set(parameters=None, values=None, /, **updates) ¤

Set the leaves specified by parameters with values.

Parameters:

Name Type Description Default
parameters Params

Parameter selector for positional style. Supported forms are: - "param" - list/tuple of path strings - interleaved list/tuple nesting of path strings - a mapping {path: value} (dictionary style)

None
values Values

Values for positional style set(parameters, values). Can be a scalar, list, or tuple matching parameters.

None
**updates

Keyword update style, e.g. set(param=1.0) and nested via set(**{"b.param": 2.0}).

{}

Returns:

Name Type Description
pytree PyTree

The pytree with leaves specified by parameters updated with values.

Source code in zodiax/base.py
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
def set(
    self: PyTree,
    parameters: Params = None,
    values: Values = None,
    /,
    **updates,
) -> PyTree:
    """
    Set the leaves specified by parameters with values.

    Parameters
    ----------
    parameters : Params, optional
        Parameter selector for positional style. Supported forms are:
        - ``"param"``
        - list/tuple of path strings
        - interleaved list/tuple nesting of path strings
        - a mapping ``{path: value}`` (dictionary style)
    values : Values, optional
        Values for positional style ``set(parameters, values)``.
        Can be a scalar, list, or tuple matching ``parameters``.
    **updates
        Keyword update style, e.g. ``set(param=1.0)`` and nested via
        ``set(**{"b.param": 2.0})``.

    Returns
    -------
    pytree : PyTree
        The pytree with leaves specified by parameters updated with values.
    """
    parameters, values = _normalise_mutation_inputs(
        parameters,
        values,
        updates=updates,
        method_name="set",
    )

    # Allow explicit None values
    if values is None:
        values = [None]
        if isinstance(parameters, str):
            parameters = [parameters]
    new_parameters, new_values = _format(parameters, values)

    # Define 'where' function and update pytree
    def leaves_fn(pytree):
        return _get_leaves(pytree, new_parameters)

    return eqx.tree_at(
        leaves_fn, self, new_values, is_leaf=lambda leaf: leaf is None
    )

EquinoxWrapper ¤

Bases: Base

A wrapper class designed to store an Equinox model (typically a neural network) in a way that makes it easily compatible within the Zodiax framework. This is necessary as Equinox operates on whole models, where as Zodiax operates on model leaves. This class is designed to bridge that gap.

This class should not need to be interacted with directly, and is designed to be held within the WrapperHolder class.

Source code in zodiax/base.py
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
class EquinoxWrapper(Base):
    """
    A wrapper class designed to store an Equinox model (typically a neural network)
    in a way that makes it easily compatible within the Zodiax framework. This is
    necessary as Equinox operates on _whole_ models, where as Zodiax operates on
    model _leaves_. This class is designed to bridge that gap.

    This class should not need to be interacted with directly, and is designed to be
    held within the `WrapperHolder` class.
    """

    static: eqx.Module
    shapes: list
    sizes: list
    starts: list
    tree_def: None

    def __init__(self, static, leaves, tree_def):
        self.static = static
        self.tree_def = tree_def
        self.shapes = [v.shape for v in leaves]
        self.sizes = [int(v.size) for v in leaves]
        self.starts = [int(i) for i in np.cumsum(np.array([0] + self.sizes))]

    def inject(self, values):
        leaves = [
            lax.dynamic_slice(values, (start,), (size,)).reshape(shape)
            for start, size, shape in zip(self.starts, self.sizes, self.shapes)
        ]
        return eqx.combine(jtu.unflatten(self.tree_def, leaves), self.static)

WrapperHolder ¤

Bases: Base

A class designed to hold an Equinox model, its structure and values. This helps it operate smoothly within the Zodiax framework.

To apply transformations to the Equinox model values, operate on the values leaf of this class. To build the model, call the build property, and the Equinox model will be constructed with the stored values and be able to be used as if it were a regular Equinox model.

This class is designed to be instantiated by the build_wrapper function.

Example

import equinox as eqx import zodiax as zdx import jax.numpy as np import jax.random as jr

eqx_model = eqx.nn.MLP( in_size=16, out_size=16, width_size=32, depth=1, key=jr.PRNGKey(0) )

class Foo(zdx.WrapperHolder):

def __init__(self, nn):
    values, structure = zdx.build_wrapper(nn)
    self.values = values
    self.structure = structure

def __call__(self, x):
    return self.build(x)

x = np.ones(16) foo = Foo(eqx_model)

Now we can use the model as if it were a regular Equinox model print(foo(x))

[ 0.1767296 0.15628047 -0.63250038 -0.01583058 0.39692974 0.4556041 0.33121592 -0.3183221 -0.75008567 -0.32724514 0.28351735 -0.03595607 -0.53921278 -0.20966474 -0.33641739 -0.28726151]

We can also apply Zodiax transformations to the model! print(foo.multiply("values", 0.)(x))

[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

Source code in zodiax/base.py
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
class WrapperHolder(Base):
    """
    A class designed to hold an Equinox model, its structure and values. This helps it
    operate smoothly within the Zodiax framework.

    To apply transformations to the Equinox model values, operate on the `values` leaf
    of this class. To build the model, call the `build` property, and the Equinox model
    will be constructed with the stored values and be able to be used as if it
    were a regular Equinox model.

    This class is designed to be instantiated by the `build_wrapper` function.

    Example
    -------

    import equinox as eqx
    import zodiax as zdx
    import jax.numpy as np
    import jax.random as jr

    eqx_model = eqx.nn.MLP(
        in_size=16, out_size=16, width_size=32, depth=1, key=jr.PRNGKey(0)
    )

    class Foo(zdx.WrapperHolder):

        def __init__(self, nn):
            values, structure = zdx.build_wrapper(nn)
            self.values = values
            self.structure = structure

        def __call__(self, x):
            return self.build(x)

    x = np.ones(16)
    foo = Foo(eqx_model)

    Now we can use the model as if it were a regular Equinox model
    print(foo(x))

    `[ 0.1767296   0.15628047 -0.63250038 -0.01583058  0.39692974  0.4556041
    0.33121592 -0.3183221  -0.75008567 -0.32724514  0.28351735 -0.03595607
    -0.53921278 -0.20966474 -0.33641739 -0.28726151]`

    We can also apply Zodiax transformations to the model!
    print(foo.multiply("values", 0.)(x))

    `[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]`
    """

    values: Array
    structure: EquinoxWrapper

    @property
    def build(self):
        """
        Builds the Equinox model with the stored values and structure.
        """
        return self.structure.inject(self.values)

    def __getattr__(self, name):
        if hasattr(self.structure, name):
            return getattr(self.structure, name)
        raise AttributeError(f"Attribute {name} not found in {self.__class__.__name__}")

build property ¤

Builds the Equinox model with the stored values and structure.

build_wrapper(pytree, filter_fn=eqx.is_array) ¤

Deconstructs an equinox model into its values and structure, and returns a WrapperHolder object that can be used to interact with the model in a way that is compatible with the Zodiax framework.

Parameters:

Name Type Description Default
pytree PyTree

The pytree to deconstruct.

required
filter_fn callable

A function that takes a leaf of the pytree and returns a boolean value

is_array

Returns:

Name Type Description
values Array

The values of the model, flattened and concatenated.

structure EquinoxWrapper

The structure of the model, stored in a EquinoxWrapper object.

Source code in zodiax/base.py
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
def build_wrapper(pytree: PyTree, filter_fn: callable = eqx.is_array):
    """
    Deconstructs an equinox model into its values and structure, and returns a
    `WrapperHolder` object that can be used to interact with the model in a way
    that is compatible with the Zodiax framework.

    Parameters
    ----------
    pytree : PyTree
        The pytree to deconstruct.
    filter_fn : callable, optional
        A function that takes a leaf of the pytree and returns a boolean value

    Returns
    -------
    values : Array
        The values of the model, flattened and concatenated.
    structure : EquinoxWrapper
        The structure of the model, stored in a `EquinoxWrapper` object.
    """
    arr_mask = jtu.map(lambda leaf: filter_fn(leaf), pytree)
    dyn, static = eqx.partition(pytree, arr_mask)
    leaves, tree_def = jtu.flatten(dyn)
    values = np.concatenate([val.flatten() for val in leaves])
    return values, EquinoxWrapper(static, leaves, tree_def)