Compiler & Tracer

lower(expr: Funsor) Funsor[source]

Lower a funsor expression: - eliminate bound variables - convert Contraction to Binary

Parameters

expr (Funsor) – An arbitrary funsor expression.

Returns

A lowered funsor expression.

Return type

Funsor

trace_function(fn, kwargs: dict, *, allow_constants=False)[source]

Traces function to an OpProgram that runs on backend values.

Example:

# Create a function involving ops.
def fn(a, b, x):
    return ops.add(ops.matmul(a, x), b)

# Evaluate via Funsor substitution.
data = dict(a=randn(3, 3), b=randn(3), x=randn(3))
expected = fn(**data)

# Alternatively evaluate via a program.
program = trace_function(expr, data)
actual = program(**data)
assert (acutal == expected).all()
Parameters

expr (Funsor) – A funsor expression to evaluate.

Returns

An op program.

Return type

OpProgram

class OpProgram(constants, inputs, operations)[source]

Bases: object

Backend program for evaluating a symbolic funsor expression.

Programs depend on the funsor library only via funsor.ops and op registrations; program evaluation does not involve funsor interpretation or rewriting. Programs can be pickled and unpickled.

Parameters
  • expr (iterable) – A list of built-in constants (leaves).

  • inputs (iterable) – A list of string names of program inputs (leaves).

  • operations (iterable) – A list of program operations defining non-leaf nodes in the program dag. Each operations is a tuple (op, arg_ids) where op is a funsor op and arg_ids is a tuple of positions of values, starting from zero and counting: constants, inputs, and operation outputs.

as_code(name='program')[source]

Returns Python code text defining a straight-line function equivalent to this program.

Parameters

name (str) – Optional name for the function, defaults to “program”.

Returns

A string defining a python function equivalent to this program.

Return type

str