Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add KL Divergence helper #7062

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ jobs:
tests/stats/test_log_likelihood.py
tests/distributions/test_distribution.py
tests/distributions/test_discrete.py
tests/distributions/stats/test_kl_divergence.py

- |
tests/tuning/test_scaling.py
Expand Down
6 changes: 6 additions & 0 deletions pymc/distributions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@
)
from pymc.distributions.truncated import Truncated

# now dispatched stats are being initialized
# isort: off
import pymc.distributions.stats

# isort: on

__all__ = [
"Uniform",
"Flat",
Expand Down
14 changes: 14 additions & 0 deletions pymc/distributions/stats/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Copyright 2024 The PyMC Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pymc.distributions.stats import kl_divergence
35 changes: 35 additions & 0 deletions pymc/distributions/stats/kl_divergence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2024 The PyMC Developers
#
# 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.

import pytensor.tensor as pt

from pymc.distributions.continuous import Normal
from pymc.logprob.abstract import _kl_div


@_kl_div.register(Normal, Normal)
def _normal_normal_kl(
q_dist: Normal,
p_dist: Normal,
q_inputs: list[pt.TensorVariable],
p_inputs: list[pt.TensorVariable],
):
_, _, _, q_mu, q_sigma = q_inputs
_, _, _, p_mu, p_sigma = p_inputs
diff_log_scale = pt.log(q_sigma) - pt.log(p_sigma)
return (

Check warning on line 31 in pymc/distributions/stats/kl_divergence.py

View check run for this annotation

Codecov / codecov/patch

pymc/distributions/stats/kl_divergence.py#L28-L31

Added lines #L28 - L31 were not covered by tests
Copy link
Member

@ricardoV94 ricardoV94 Feb 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May want to broadcast to size, like we do with moment, if someone does kl_div(pm.Normal.dist(shape=5), pm.Normal.dist(mu=1))

0.5 * (q_mu / p_sigma - p_mu / p_sigma) ** 2
+ 0.5 * pt.expm1(2.0 * diff_log_scale)
- diff_log_scale
)
2 changes: 2 additions & 0 deletions pymc/logprob/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from pymc.logprob.basic import (
conditional_logp,
icdf,
kl_div,
logcdf,
logp,
transformed_conditional_logp,
Expand All @@ -58,4 +59,5 @@
"logp",
"logcdf",
"icdf",
"kl_div",
)
25 changes: 25 additions & 0 deletions pymc/logprob/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from collections.abc import Sequence
from functools import singledispatch

from multipledispatch import dispatch as multipledispatch
from pytensor.graph.op import Op
from pytensor.graph.utils import MetaType
from pytensor.tensor import TensorVariable
Expand Down Expand Up @@ -153,3 +154,27 @@


MeasurableVariable.register(MeasurableElemwise)


@multipledispatch(Op, Op)
def _kl_div(
q_dist: Op,
p_dist: Op,
q_inputs: list[TensorVariable],
p_inputs: list[TensorVariable],
) -> TensorVariable:
raise NotImplementedError(f"KL Divergence is not implemented for {q_dist}, {p_dist}")


def _kl_div_helper(
q_rv: TensorVariable,
p_rv: TensorVariable,
) -> TensorVariable:
kl = _kl_div(

Check warning on line 173 in pymc/logprob/abstract.py

View check run for this annotation

Codecov / codecov/patch

pymc/logprob/abstract.py#L173

Added line #L173 was not covered by tests
q_rv.owner.op,
p_rv.owner.op,
q_inputs=q_rv.owner.inputs,
p_inputs=p_rv.owner.inputs,
)
kl.name = f"{q_rv.name}_{p_rv.name}_kl"
return kl

Check warning on line 180 in pymc/logprob/abstract.py

View check run for this annotation

Codecov / codecov/patch

pymc/logprob/abstract.py#L179-L180

Added lines #L179 - L180 were not covered by tests
22 changes: 22 additions & 0 deletions pymc/logprob/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
from pymc.logprob.abstract import (
MeasurableVariable,
_icdf_helper,
_kl_div_helper,
_logcdf_helper,
_logprob,
_logprob_helper,
Expand Down Expand Up @@ -633,6 +634,27 @@
return logp_terms_list


def kl_div(
ferrine marked this conversation as resolved.
Show resolved Hide resolved
q_rv: TensorVariable,
p_rv: TensorVariable,
) -> TensorVariable:
r"""KL Divergence

Parameters
----------
q_rv : TensorVariable
:math:`Q` Distribution
p_rv : TensorVariable
:math:`P` Distribution

Returns
-------
TensorVariable
:math::KL\{Q||P\}
"""
return _kl_div_helper(q_rv, p_rv)

Check warning on line 655 in pymc/logprob/basic.py

View check run for this annotation

Codecov / codecov/patch

pymc/logprob/basic.py#L655

Added line #L655 was not covered by tests


def factorized_joint_logprob(*args, **kwargs):
warnings.warn(
"`factorized_joint_logprob` was renamed to `conditional_logp`. "
Expand Down
2 changes: 1 addition & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ sphinx>=1.5
sphinxext-rediraffe
types-cachetools
typing-extensions>=3.7.4
watermark
watermark
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ arviz>=0.13.0
cachetools>=4.2.1
cloudpickle
fastprogress>=0.2.0
multipledispatch
numpy>=1.15.0
pandas>=0.24.0
pytensor>=2.18.1,<2.19
Expand Down
25 changes: 25 additions & 0 deletions tests/distributions/stats/test_kl_divergence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright 2024 The PyMC Developers
#
# 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.
import numpy as np

import pymc as pm

from pymc.logprob import kl_div


def test_normal_normal():
q = pm.Normal.dist(0, 1)
p = pm.Normal.dist(1, 2)
kl = kl_div(q, p)
np.testing.assert_allclose(kl.eval(), 0.44314718)
Loading