Skip to content
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Added MMD gradient flow for pseudo-coresets, with weighted targets, configurable Optax optimisers and optional scheduled gradient noise.
(https://github.com/gchq/coreax/issues/1105)
- Added `Metric.compute_on_coreset`, `WeightsOptimiser.solve_on_coreset` and immutable
`AbstractCoreset.with_weights`. The coreset-level `compute_metric` and `solve_weights`
methods remain as deprecated compatibility wrappers until 2.0.0.
(https://github.com/gchq/coreax/issues/1023)

- Support for Python 3.14. (...)
- Unit tests workflow now runs the test suite with both the `lowest` and `highest` supported direct and transitive
Expand Down
6 changes: 3 additions & 3 deletions benchmark/blobs_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,9 @@ def compute_solver_metrics(
unweighted_ksd = float(ksd_metric.compute(dataset, coresubset.points))

# Weighted metrics
weighted_coresubset = coresubset.solve_weights(weights_optimiser)
weighted_mmd = float(weighted_coresubset.compute_metric(mmd_metric))
weighted_ksd = float(weighted_coresubset.compute_metric(ksd_metric))
weighted_coresubset = weights_optimiser.solve_on_coreset(coresubset)
weighted_mmd = float(mmd_metric.compute_on_coreset(weighted_coresubset))
weighted_ksd = float(ksd_metric.compute_on_coreset(weighted_coresubset))

end_time = time.perf_counter()
elapsed_time = end_time - start_time
Expand Down
68 changes: 55 additions & 13 deletions coreax/coreset.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

"""Module for defining coreset data structures."""

import warnings
from abc import abstractmethod
from typing import (
TYPE_CHECKING,
Expand All @@ -29,12 +30,13 @@
from typing_extensions import Self, override

from coreax.data import Data, SupervisedData, as_data
from coreax.metrics import Metric
from coreax.weights import WeightsOptimiser

if TYPE_CHECKING:
from typing import Any # noqa: F401

from coreax.metrics import Metric
from coreax.weights import WeightsOptimiser

# `_co` is a well-established suffix for covariant TypeVars
# pylint: disable=invalid-name
_TPointsData_co = TypeVar("_TPointsData_co", Data, SupervisedData, covariant=True)
Expand Down Expand Up @@ -66,14 +68,56 @@ def points(self) -> _TPointsData_co:
def pre_coreset_data(self) -> _TOriginalData_co:
"""The original data that this coreset is based on."""

@abstractmethod
def solve_weights(self, solver: WeightsOptimiser[Data], **solver_kwargs) -> Self:
"""Return a copy of 'self' with weights solved by 'solver'."""
def with_weights(self, weights: Shaped[Array, " n"]) -> Self:
"""
Return a copy with replacement coreset weights.

Subclasses should implement this without changing the original dataset.

:param weights: Replacement weight for each coreset point
:return: A new coreset of the same type
"""
raise NotImplementedError("Coreset subclasses must implement with_weights.")

def solve_weights(self, solver: "WeightsOptimiser[Data]", **solver_kwargs) -> Self:
"""
Return a re-weighted copy using the deprecated coreset interface.

Use :meth:`~coreax.weights.WeightsOptimiser.solve_on_coreset` instead.
This compatibility method will be removed in version 2.0.0.

:param solver: Weight optimiser to use
:param solver_kwargs: Keyword arguments passed to the optimiser
:return: A new coreset with optimised weights
"""
warnings.warn(
"Coreset.solve_weights is deprecated; use "
"WeightsOptimiser.solve_on_coreset instead. Removal is planned for 2.0.0.",
DeprecationWarning,
stacklevel=2,
)
weights = solver.solve(self.pre_coreset_data, self.points, **solver_kwargs)
return self.with_weights(weights)

def compute_metric(
self, metric: Metric[Data], **metric_kwargs
self, metric: "Metric[Data]", **metric_kwargs
) -> Shaped[Array, ""]:
"""Return metric-distance between `self.pre_coreset_data` and `self.coreset`."""
"""
Evaluate a metric using the deprecated coreset interface.

Use :meth:`~coreax.metrics.Metric.compute_on_coreset` instead.
This compatibility method will be removed in version 2.0.0.

:param metric: Metric to compute
:param metric_kwargs: Keyword arguments passed to the metric
:return: The metric value
"""
warnings.warn(
"Coreset.compute_metric is deprecated; use Metric.compute_on_coreset "
"instead. Removal is planned for 2.0.0.",
DeprecationWarning,
stacklevel=2,
)
return metric.compute(self.pre_coreset_data, self.points, **metric_kwargs)

def __len__(self) -> int:
Expand Down Expand Up @@ -191,9 +235,8 @@ def pre_coreset_data(self):
return self._pre_coreset_data

@override
def solve_weights(self, solver: WeightsOptimiser[Data], **solver_kwargs) -> Self:
"""Return a copy of 'self' with weights solved by 'solver'."""
weights = solver.solve(self.pre_coreset_data, self.points, **solver_kwargs)
def with_weights(self, weights: Shaped[Array, " n"]) -> Self:
"""Return a copy with new weights, retaining the original data."""
return eqx.tree_at(lambda x: x.points.weights, self, weights)


Expand Down Expand Up @@ -323,7 +366,6 @@ def indices(self) -> Data:
return self._indices

@override
def solve_weights(self, solver: WeightsOptimiser[Data], **solver_kwargs) -> Self:
"""Return a copy of 'self' with weights solved by 'solver'."""
weights = solver.solve(self.pre_coreset_data, self.points, **solver_kwargs)
def with_weights(self, weights: Shaped[Array, " n"]) -> Self:
"""Return a copy with new weights, retaining the original data."""
return eqx.tree_at(lambda x: x.indices.weights, self, weights)
17 changes: 16 additions & 1 deletion coreax/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from abc import abstractmethod
from itertools import product
from typing import Any, Generic, TypeVar
from typing import Any, Generic, TypeVar, cast

import equinox as eqx
import jax
Expand All @@ -34,6 +34,7 @@
from jaxtyping import Array, Shaped

import coreax.util
from coreax.coreset import AbstractCoreset
from coreax.data import Data, SupervisedData
from coreax.kernels import ScalarValuedKernel
from coreax.score_matching import ScoreMatching, convert_stein_kernel
Expand All @@ -44,6 +45,20 @@
class Metric(eqx.Module, Generic[_Data]):
"""Base class for calculating metrics."""

def compute_on_coreset(
self, coreset: AbstractCoreset[_Data, _Data], **kwargs: Any
) -> Shaped[Array, ""]:
"""
Compare a coreset with its original dataset.

:param coreset: The coreset to evaluate
:param kwargs: Keyword arguments passed to :meth:`compute`
:return: The metric value as a zero-dimensional array
"""
return self.compute(
cast(_Data, coreset.pre_coreset_data), cast(_Data, coreset.points), **kwargs
)

@abstractmethod
def compute(
self, reference_data: _Data, comparison_data: _Data, **kwargs
Expand Down
21 changes: 20 additions & 1 deletion coreax/weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,19 @@
"""

from abc import abstractmethod
from typing import Generic, TypeVar
from typing import Any, Generic, TypeVar, cast

import equinox as eqx
import jax.numpy as jnp
from jaxopt import OSQP
from jaxtyping import Array, Shaped

from coreax.coreset import AbstractCoreset
from coreax.data import Data, as_data
from coreax.kernels import ScalarValuedKernel

_Data = TypeVar("_Data", bound=Data)
_Coreset = TypeVar("_Coreset", bound=AbstractCoreset[Data, Data])

INVALID_KERNEL_DATA_COMBINATION = (
"Invalid combination of 'kernel' and 'dataset' or 'coreset'; if solving weights for"
Expand Down Expand Up @@ -153,6 +155,23 @@ def _prepare_kernel_system(
class WeightsOptimiser(eqx.Module, Generic[_Data]):
r"""Base class for optimising weights."""

def solve_on_coreset(self, coreset: _Coreset, **kwargs: Any) -> _Coreset:
"""
Return a copy of a coreset with optimised weights.

The original dataset, point ordering and coreset type are preserved.
Custom coresets should implement
:meth:`~coreax.coreset.AbstractCoreset.with_weights`.

:param coreset: The coreset to re-weight
:param kwargs: Keyword arguments passed to :meth:`solve`
:return: A new coreset with optimised weights
"""
weights = self.solve(
cast(_Data, coreset.pre_coreset_data), cast(_Data, coreset.points), **kwargs
)
return coreset.with_weights(weights)

@abstractmethod
def solve(
self,
Expand Down
21 changes: 21 additions & 0 deletions documentation/source/coresets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,24 @@ video is preserved. Run :mod:`examples.pounce` to replicate.
- Coreset
* - .. image:: ../../examples/pounce/pounce.gif
- .. image:: ../../examples/pounce/pounce_coreset.gif

Metrics and weights
-------------------

Metrics and weight optimisers accept a coreset directly::

metric_value = metric.compute_on_coreset(coreset)
re_weighted_coreset = weights_optimiser.solve_on_coreset(coreset, epsilon=1e-6)

Both methods forward keyword arguments to the underlying ``compute`` or ``solve``
method. Weight optimisation returns a new coreset of the same type. It preserves the
original dataset, subset indices and any supervision arrays.

To replace weights that have already been computed, use::

re_weighted_coreset = coreset.with_weights(weights)

Custom coreset classes should implement ``with_weights`` to update their own weight
storage without changing the original dataset. The older ``coreset.compute_metric``
and ``coreset.solve_weights`` calls continue to work, but emit a
``DeprecationWarning`` and are scheduled for removal in version 2.0.0.
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@
herding_coreset, _ = herding_solver.reduce(data)

# Determine optimal weights for the coreset
re_weighted_herding_coreset = herding_coreset.solve_weights(weights_optimiser)
re_weighted_herding_coreset = weights_optimiser.solve_on_coreset(herding_coreset)
4 changes: 2 additions & 2 deletions examples/david_map_reduce_weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,11 @@ def main(

# Compute the MMD between the original data and the coreset generated via herding
mmd_metric = MMD(kernel=mmd_kernel)
herding_mmd = herding_coreset.compute_metric(mmd_metric, block_size=block_size)
herding_mmd = mmd_metric.compute_on_coreset(herding_coreset, block_size=block_size)

# Compute the MMD between the original data and the coreset generated via random
# sampling
random_mmd = random_coreset.compute_metric(mmd_metric, block_size=block_size)
random_mmd = mmd_metric.compute_on_coreset(random_coreset, block_size=block_size)

# Print the MMD values
print(f"Random sampling coreset MMD: {random_mmd}")
Expand Down
4 changes: 2 additions & 2 deletions examples/herding_approximate_gram_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,11 @@ def main(out_path: Path | None = None) -> tuple[float, float]:

# Compute the MMD between the original data and the coreset generated via herding
mmd_metric = MMD(kernel=mmd_kernel)
herding_mmd = herding_coreset.compute_metric(mmd_metric)
herding_mmd = mmd_metric.compute_on_coreset(herding_coreset)

# Compute the MMD between the original data and the coreset generated via random
# sampling
random_mmd = random_coreset.compute_metric(mmd_metric)
random_mmd = mmd_metric.compute_on_coreset(random_coreset)

# Print the MMD values
print(f"Random sampling coreset MMD: {random_mmd}")
Expand Down
8 changes: 4 additions & 4 deletions examples/herding_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,17 +133,17 @@ def main(out_path: Path | None = None) -> tuple[float, float, float, float]:

# Compute the MMD between the original data and the coreset generated via herding
mmd_metric = MMD(kernel=mmd_kernel)
herding_mmd = herding_coreset.compute_metric(mmd_metric)
herding_mmd = mmd_metric.compute_on_coreset(herding_coreset)

# Compute the MMD between the original data and the coreset generated via ST
stein_mmd = stein_coreset.compute_metric(mmd_metric)
stein_mmd = mmd_metric.compute_on_coreset(stein_coreset)

# Compute the MMD between the original data and the coreset generated via RPC
rpc_mmd = rpc_coreset.compute_metric(mmd_metric)
rpc_mmd = mmd_metric.compute_on_coreset(rpc_coreset)

# Compute the MMD between the original data and the coreset generated via random
# sampling
random_mmd = random_coreset.compute_metric(mmd_metric)
random_mmd = mmd_metric.compute_on_coreset(random_coreset)

# Print the MMD values
print(f"Random sampling coreset MMD: {random_mmd}")
Expand Down
14 changes: 7 additions & 7 deletions examples/herding_basic_weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def main(out_path: Path | None = None) -> tuple[float, float, float, float]:
sample_key, rpc_key, stein_key = jr.split(jr.key(random_seed), num=3)
herding_solver = KernelHerding(coreset_size, kernel)
herding_coreset, _ = eqx.filter_jit(herding_solver.reduce)(data)
re_weighted_herding_coreset = herding_coreset.solve_weights(weights_optimiser)
re_weighted_herding_coreset = weights_optimiser.solve_on_coreset(herding_coreset)

print("Computing Stein thinning coreset...")
# Compute a coreset using Stein thinning with a PCIMQ base kernel.
Expand All @@ -115,13 +115,13 @@ def main(out_path: Path | None = None) -> tuple[float, float, float, float]:
stein_kernel = SteinKernel(base_kernel, estimated_score_function)
stein_solver = SteinThinning(coreset_size, kernel=stein_kernel)
stein_coreset, _ = eqx.filter_jit(stein_solver.reduce)(data)
re_weighted_stein_coreset = stein_coreset.solve_weights(weights_optimiser)
re_weighted_stein_coreset = weights_optimiser.solve_on_coreset(stein_coreset)

print("Computing RPC coreset...")
# Compute a coreset using RPC with a squared exponential kernel.
rpc_solver = RPCholesky(coreset_size, rpc_key, kernel=kernel)
rpc_coreset, _ = eqx.filter_jit(rpc_solver.reduce)(data)
re_weighted_rpc_coreset = rpc_coreset.solve_weights(weights_optimiser)
re_weighted_rpc_coreset = weights_optimiser.solve_on_coreset(rpc_coreset)

print("Choosing random subset...")
# Generate a coreset via uniform random sampling for comparison
Expand All @@ -138,16 +138,16 @@ def main(out_path: Path | None = None) -> tuple[float, float, float, float]:

# Compute the MMD between the original data and the coreset generated via herding
mmd_metric = MMD(kernel=mmd_kernel)
herding_mmd = re_weighted_herding_coreset.compute_metric(mmd_metric)
herding_mmd = mmd_metric.compute_on_coreset(re_weighted_herding_coreset)

# Compute the MMD between the original data and the coreset generated via RPC
rpc_mmd = re_weighted_rpc_coreset.compute_metric(mmd_metric)
rpc_mmd = mmd_metric.compute_on_coreset(re_weighted_rpc_coreset)

# Compute the MMD between the original data and the coreset generated via ST
stein_mmd = re_weighted_stein_coreset.compute_metric(mmd_metric)
stein_mmd = mmd_metric.compute_on_coreset(re_weighted_stein_coreset)
# Compute the MMD between the original data and the coreset generated via random
# sampling
random_mmd = random_coreset.compute_metric(mmd_metric)
random_mmd = mmd_metric.compute_on_coreset(random_coreset)

# Print the MMD values
print(f"Random sampling coreset MMD: {random_mmd}")
Expand Down
4 changes: 2 additions & 2 deletions examples/herding_duo_composite_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ def main(out_path: Path | None = None) -> tuple[float, float]:

# Compute the MMD between the original data and the coreset generated via herding
mmd_metric = MMD(kernel=mmd_kernel)
herding_mmd = herding_coreset.compute_metric(mmd_metric)
herding_mmd = mmd_metric.compute_on_coreset(herding_coreset)

# Compute the MMD between the original data and the coreset generated via random
# sampling
random_mmd = random_coreset.compute_metric(mmd_metric)
random_mmd = mmd_metric.compute_on_coreset(random_coreset)

# Print the MMD values
print(f"Random sampling coreset MMD: {random_mmd}")
Expand Down
Loading