Metadata-Version: 2.4
Name: efax
Version: 1.17.2
Summary: Exponential families for JAX
Project-URL: repository, https://github.com/NeilGirdhar/efax
Author: Neil Girdhar
Author-email: mistersheik@gmail.com
Maintainer: Neil Girdhar
Maintainer-email: mistersheik@gmail.com
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2020, Neil Girdhar
        
           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.
License-File: LICENSE
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: <3.14,>=3.11
Requires-Dist: jax>=0.4.34
Requires-Dist: numpy>=1.23
Requires-Dist: optimistix>=0.0.9
Requires-Dist: scipy>=1.10
Requires-Dist: tensorflow-probability>=0.15
Requires-Dist: tjax>=1.0.1
Requires-Dist: typing-extensions>=4.8
Description-Content-Type: text/x-rst

=================================
EFAX: Exponential Families in JAX
=================================

|pypi| |py_versions|

.. |pypi| image:: https://img.shields.io/pypi/v/efax
   :alt: PyPI - Version

.. |py_versions| image:: https://img.shields.io/pypi/pyversions/efax
   :alt: PyPI - Python Version

.. role:: bash(code)
    :language: bash

.. role:: python(code)
    :language: python

This library provides a set of tools for working with *exponential family distributions* in the
differential programming library `JAX <https://github.com/google/jax/>`_.

The *exponential families* are an important class of probability distributions that include the
normal, gamma, beta, exponential, Poisson, binomial, and Bernoulli distributions.
For an explanation of the fundamental ideas behind this library, see our `overview on exponential
families <https://github.com/NeilGirdhar/efax/blob/master/expfam.pdf>`_.

The main motivation for using EFAX over a library like tensorflow-probability or the basic functions
in JAX is that EFAX provides the two most important parametrizations for each exponential family—the
natural and expectation parametrizations—and a uniform interface to efficient implementations of the
main functions used in machine learning.  An example of why this matters is that the most efficient
way to implement cross entropy between X and Y relies on X being in the expectation parametrization
and Y in the natural parametrization.

----

.. contents::

----

Framework
=========
Representation
--------------
EFAX has a single base class for its objects: :python:`Distribution` whose type encodes the
distribution family.

Each parametrization object has a shape, and so it can store any number of distributions.
Operations on these objects are vectorized.
This is unlike SciPy where each distribution is represented by a single object, and so a thousand
distributions need a thousand objects, and corresponding calls to functions that operate on them.

All parametrization objects are dataclasses using :python:`tjax.dataclass`.  These dataclasses are
a modification of Python's dataclasses to support JAX's “PyTree” type registration.

Each of the fields of a parametrization object stores a parameter over a specified support.
Some parameters are marked as “fixed”, which means that they are fixed with respect to the
exponential family.  An example of a fixed parameter is the failure number of the negative binomial
distribution.

For example:

.. code:: python

    @dataclass
    class MultivariateNormalNP(NaturalParametrization['MultivariateNormalEP']):
        mean_times_precision: RealArray = distribution_parameter(VectorSupport())
        negative_half_precision: RealArray = distribution_parameter(SymmetricMatrixSupport())

In this case, we see that there are two natural parameters for the multivariate normal distribution.
Objects of this type can hold any number of distributions:  if such an object :python:`x` has shape
:python:`s`, then the shape of
:python:`x.mean_times_precision` is :python:`(*s, n)` and the shape of
:python:`x.negative_half_precision` is :python:`(*s, n, n)`.

Parametrizations
----------------
Each exponential family distribution has two special parametrizations: the natural and the
expectation parametrization.  (These are described in the overview pdf.)
Consequently, every distribution has at least two base classes, one inheriting from
:python:`NaturalParametrization` and one from :python:`ExpectationParametrization`.

The motivation for the natural parametrization is combining and scaling independent predictive
evidence.  In the natural parametrization, these operations correspond to scaling and addition.

The motivation for the expectation parametrization is combining independent observations into the
maximum likelihood distribution that could have produced them.  In the expectation parametrization,
this is an expected value.

EFAX provides conversions between the two parametrizations through the
:python:`NaturalParametrization.to_exp` and :python:`ExpectationParametrization.to_nat` methods.

Important methods
-----------------
EFAX aims to provide the main methods used in machine learning.

Every :python:`Distribution` has methods:

- :python:`flattened` and :python:`unflattened` to flatten and unflatten the parameters into a
  single array.  Typically, array-valued signals in a machine learning model would be unflattened
  into a distribution object, operated on, and then flattened before being sent back to the model.
  Flattening is careful with distributions with symmetric (or Hermitian) matrix-valued parameters.
  It only stores the upper triangular elements.  And,
- :python:`shape`, which supports broadcasting.

Every :python:`NaturalParametrization` has methods:

- :python:`to_exp` to convert itself to expectation parameters.
- :python:`sufficient_statistics` to produce the sufficient statistics given an observation (used in
  maximum likelihood estimation),
- :python:`pdf` and :python:`log_pdf`, which is the density or mass function and its logarithm,
- :python:`fisher_information`, which is the Fisher information matrix, and
- :python:`kl_divergence`, which is the KL divergence.

Every :python:`ExpectationParametrization` has methods:

- :python:`to_nat` to convert itself to natural parameters, and
- :python:`kl_divergence`, which is the KL divergence.

Some parametrizations inherit from these interfaces:

- :python:`HasConjugatePrior` can produce the conjugate prior,
- :python:`HasGeneralizedConjugatePrior` can produce a generalization of the conjugate prior,
- :python:`Multidimensional` distributions have a integer number of `dimensions`, and
- :python:`Samplable` distributions support sampling.

Some parametrizations inherit from these public mixins:

- :python:`HasEntropyEP` is an expectation parametrization with an entropy and cross entropy, and
- :python:`HasEntropyNP` is a natural parametrization with an entropy,  (The cross entropy is not
  efficient.)

Some parametrizations inherit from these private mixins:

- :python:`ExpToNat` implements the conversion from expectation to natural parameters when no
  analytical solution is possible.  It uses Newton's method with a Jacobian to invert the gradient
  log-normalizer.
- :python:`TransformedNaturalParametrization` produces a natural parametrization by relating it to
  an existing natural parametrization.  And similarly for
  :python:`TransformedExpectationParametrization`.

Distributions
=============
EFAX supports the following distributions:

- normal:

  - univariate real:

    - with fixed unit variance
    - with arbitrary variance

  - univariate complex

    - with fixed unit variance and zero pseudo-variance
    - with arbitrary variance

  - multivariate real:

    - with fixed unit variance
    - with fixed variance
    - with isotropic variance
    - with diagonal variance
    - with arbitrary variance

  - multivariate complex:

    - with fixed unit variance and zero pseudo-variance
    - circularly symmetric

- on a finite set:

  - Bernoulli
  - multinomial

- on the nonnegative integers:

  - geometric
  - logarithmic
  - negative binomial
  - Poisson

- on the positive reals:

  - chi
  - chi-square
  - exponential
  - gamma
  - Rayleigh
  - Weibull

- on the simplex:

  - beta
  - Dirichlet
  - generalized Dirichlet

- on the n-sphere:

  - von Mises-Fisher

Usage
=====
Basic usage
-----------
A basic use of the two parametrizations:

.. code:: python

    from jax import numpy as jnp

    from efax import BernoulliEP, BernoulliNP

    # p is the expectation parameters of three Bernoulli distributions having probabilities 0.4, 0.5,
    # and 0.6.
    p = BernoulliEP(jnp.array([0.4, 0.5, 0.6]))

    # q is the natural parameters of three Bernoulli distributions having log-odds 0, which is
    # probability 0.5.
    q = BernoulliNP(jnp.zeros(3))

    print(p.cross_entropy(q))
    # [0.6931472 0.6931472 0.6931472]

    # q2 is natural parameters of Bernoulli distributions having a probability of 0.3.
    p2 = BernoulliEP(0.3 * jnp.ones(3))
    q2 = p2.to_nat()

    print(p.cross_entropy(q2))
    # [0.6955941  0.78032386 0.86505365]
    # A Bernoulli distribution with probability 0.3 predicts a Bernoulli observation with probability
    # 0.4 better than the other observations.

Optimization
------------
Using the cross entropy to iteratively optimize a prediction is simple:

.. code:: python

    from __future__ import annotations

    import jax.numpy as jnp
    from jax import grad, lax
    from tjax import JaxBooleanArray, JaxRealArray, jit, print_generic

    from efax import BernoulliEP, BernoulliNP, parameter_dot_product, parameter_map


    def cross_entropy_loss(p: BernoulliEP, q: BernoulliNP) -> JaxRealArray:
        return jnp.sum(p.cross_entropy(q))


    gce = jit(grad(cross_entropy_loss, 1))


    def apply(x: JaxRealArray, x_bar: JaxRealArray) -> JaxRealArray:
        return x - 1e-4 * x_bar


    def body_fun(q: BernoulliNP) -> BernoulliNP:
        q_bar = gce(some_p, q)
        return parameter_map(apply, q, q_bar)


    def cond_fun(q: BernoulliNP) -> JaxBooleanArray:
        q_bar = gce(some_p, q)
        total = jnp.sum(parameter_dot_product(q_bar, q_bar))
        return total > 1e-6  # noqa: PLR2004


    # some_p are expectation parameters of a Bernoulli distribution corresponding
    # to probabilities 0.3, 0.4, and 0.7.
    some_p = BernoulliEP(jnp.asarray([0.3, 0.4, 0.7]))

    # some_q are natural parameters of a Bernoulli distribution corresponding to
    # log-odds 0, which is probability 0.5.
    some_q = BernoulliNP(jnp.zeros(3))

    # Optimize the predictive distribution iteratively, and output the natural parameters of the
    # prediction.
    optimized_q = lax.while_loop(cond_fun, body_fun, some_q)
    print_generic(optimized_q)
    # BernoulliNP
    # └── log_odds=Jax Array (3,) float32
    #     └──  -0.8440 │ -0.4047 │ 0.8440

    # Compare with the true value.
    print_generic(some_p.to_nat())
    # BernoulliNP
    # └── log_odds=Jax Array (3,) float32
    #     └──  -0.8473 │ -0.4055 │ 0.8473

    # Print optimized natural parameters as expectation parameters.
    print_generic(optimized_q.to_exp())
    # BernoulliEP
    # └── probability=Jax Array (3,) float32
    #     └──  0.3007 │ 0.4002 │ 0.6993

Maximum likelihood estimation
-----------------------------
Maximum likelihood estimation is often using the conjugate prior, but this can be done using only
the expectation parametrization (which is equivalent less one parameter that represents the number
of samples).

.. code:: python

    from functools import partial

    import jax.numpy as jnp
    from jax.random import key

    from efax import DirichletNP, parameter_mean

    # Consider a Dirichlet distribution with a given alpha.
    alpha = jnp.asarray([2.0, 3.0, 4.0])
    source_distribution = DirichletNP(alpha_minus_one=alpha - 1.0)

    # Let's sample from it.
    n_samples = 10000
    key_a = key(123)
    samples = source_distribution.sample(key_a, (n_samples,))

    # Now, let's find the maximum likelihood Dirichlet distribution that fits it.
    # First, convert the samples to their sufficient statistics.
    ss = DirichletNP.sufficient_statistics(samples)
    # ss has type DirichletEP.  This is similar to the conjguate prior of the Dirichlet distribution.

    # Take the mean over the first axis.
    ss_mean = parameter_mean(ss, axis=0)  # ss_mean also has type DirichletEP.

    # Convert this back to the natural parametrization.
    estimated_distribution = ss_mean.to_nat()
    print(estimated_distribution.alpha_minus_one + 1.0)  # [1.9849904 3.0065458 3.963935 ]


Contribution guidelines
=======================

Contributions are welcome!

It's not hard to add a new distribution.  The steps are:

- Create an issue for the new distribution.

- Solve for or research the equations needed to fill the blanks in the overview pdf, and put them in
  the issue.  I'll add them to the pdf for you.

- Implement the natural and expectation parametrizations, either:

  - directly like in the Bernoulli distribution, or
  - as a transformation of an existing exponential family like the Rayleigh distribution.

- Implement the conversion from the expectation to the natural parametrization.  If this has no
  analytical solution, then there's a mixin that implements a numerical solution.  This can be seen
  in the Dirichlet distribution.

- Add the new distribution to the tests by adding it to `create_info <https://github.com/NeilGirdhar/efax/blob/master/tests/create_info.py>`_.

Implementation should respect PEP8.
The tests can be run using :bash:`pytest . -n auto`.  Specific distributions can be run with
:bash:`pytest . -n auto --distribution=Gamma` where the names match the class names in
`create_info <https://github.com/NeilGirdhar/efax/blob/master/tests/create_info.py>`_.

There are a few tools to clean and check the source:

- :bash:`ruff check .`
- :bash:`pyright`
- :bash:`mypy`
- :bash:`isort .`
- :bash:`pylint efax tests`
