pyro-ppl / funsor

Functional tensors for probabilistic programming
https://funsor.pyro.ai
Apache License 2.0
236 stars 20 forks source link

Support Python immutable datatypes without subclassing Funsor #526

Open fritzo opened 3 years ago

fritzo commented 3 years ago

Alternative to #525

The problem

Funsor computations rely on metadata stored as Funsor attributes (including .inputs, .output, .input_vars, .fresh, .bound) and rely on special behavior accessed via methods FunsorMeta.__call__() and Funsor.__call__(). One problem with relying on attributes and methods is that computations are then restricted to funsor-owned custom datatypes, namely subclasses of the base Funsor class. These restrictions make it cumbersome to perform funsor computations on non-Funsor immutable data such as tuples or frozensets of Funsors. Moreover these restrictions prevent interaction with 3rd-party libraries that define their own immutable datatypes.

Proposed solution

Consider moving all funsor metadata to a new metadata layer, say via a funsor.meta(-) function that looks up an immutable Metadata object with attributies .inputs, .output, .input_vars, .fresh, .bound etc. All Metadata instances are stored in a single global WeakKeyDictionary keyed on the immutable data which implements .__hash__().

Further consider supporting non-Funsor-types by replacing:

  1. FunsorMeta.__call__()reinterpret(-) or a new funsor.make(-), thereby supporting hash-consing and reinterpretation for non-Funsor-subclass types.
  2. Funsor.__call__()substitute(-, -) or Subs(-, -) or a new funsor.subs(arg, **kwargs), thereby supporting substitution for non-`Funsor.

This new type-agnostic interface for funsor data mechanics would be something like:

Complications

  1. str, tuple, and subclasses thereof do not support weak referencing: they cannot be used as keys in a WeakKeyDictionary and cannot be registered via weakref.finalize(-,-).

Tasks