Skip to content

utils

utils ¤

InputLayerFactory ¤

Bases: Protocol

The protocol of a factory that constructs input layers.

Source code in cirkit/templates/utils.py
52
53
54
55
56
57
58
59
60
61
62
63
64
class InputLayerFactory(Protocol):  # pylint: disable=too-few-public-methods
    """The protocol of a factory that constructs input layers."""

    def __call__(self, scope: Scope, num_units: int) -> InputLayer:
        """Constructs an input layer.

        Args:
            scope: The scope of the layer.
            num_units: The number of input units composing the layer.

        Returns:
            InputLayer: An input layer.
        """

__call__(scope, num_units) ¤

Constructs an input layer.

Parameters:

Name Type Description Default
scope Scope

The scope of the layer.

required
num_units int

The number of input units composing the layer.

required

Returns:

Name Type Description
InputLayer InputLayer

An input layer.

Source code in cirkit/templates/utils.py
55
56
57
58
59
60
61
62
63
64
def __call__(self, scope: Scope, num_units: int) -> InputLayer:
    """Constructs an input layer.

    Args:
        scope: The scope of the layer.
        num_units: The number of input units composing the layer.

    Returns:
        InputLayer: An input layer.
    """

Parameterization dataclass ¤

The settings for a parameterization: the initialization method, the activation function to use, and the data type of the parameter tensor.

Source code in cirkit/templates/utils.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@dataclass(frozen=True)
class Parameterization:
    """The settings for a parameterization: the initialization method, the activation
    function to use, and the data type of the parameter tensor."""

    initialization: str = "normal"
    """The initialization method. Defaults to 'normal', i.e., sampling from a standard Gaussian."""
    activation: str = "none"
    """The activation function. Defaults to 'none', i.e., no activation."""
    dtype: str = "real"
    """The data type. Defaults to 'real', i.e., real numbers."""
    initialization_kwargs: dict[str, Any] = field(default_factory=dict)
    """Additional arguments to pass to the initializatiot method."""
    activation_kwargs: dict[str, Any] = field(default_factory=dict)
    """Additional arguments to pass to the activation function."""

activation = 'none' class-attribute instance-attribute ¤

The activation function. Defaults to 'none', i.e., no activation.

activation_kwargs = field(default_factory=dict) class-attribute instance-attribute ¤

Additional arguments to pass to the activation function.

dtype = 'real' class-attribute instance-attribute ¤

The data type. Defaults to 'real', i.e., real numbers.

initialization = 'normal' class-attribute instance-attribute ¤

The initialization method. Defaults to 'normal', i.e., sampling from a standard Gaussian.

initialization_kwargs = field(default_factory=dict) class-attribute instance-attribute ¤

Additional arguments to pass to the initializatiot method.

__init__(initialization='normal', activation='none', dtype='real', initialization_kwargs=dict(), activation_kwargs=dict()) ¤

ProductLayerFactory ¤

Bases: Protocol

The protocol of a factory that constructs product layers.

Source code in cirkit/templates/utils.py
82
83
84
85
86
87
88
89
90
91
92
93
94
class ProductLayerFactory(Protocol):  # pylint: disable=too-few-public-methods
    """The protocol of a factory that constructs product layers."""

    def __call__(self, num_input_units: int, arity: int) -> ProductLayer:
        """Constructs a product layer.

        Args:
            num_input_units: The number of units in each layer that is an input.
            arity: The number of input layers.

        Returns:
            ProductLayer: A product layer.
        """

__call__(num_input_units, arity) ¤

Constructs a product layer.

Parameters:

Name Type Description Default
num_input_units int

The number of units in each layer that is an input.

required
arity int

The number of input layers.

required

Returns:

Name Type Description
ProductLayer ProductLayer

A product layer.

Source code in cirkit/templates/utils.py
85
86
87
88
89
90
91
92
93
94
def __call__(self, num_input_units: int, arity: int) -> ProductLayer:
    """Constructs a product layer.

    Args:
        num_input_units: The number of units in each layer that is an input.
        arity: The number of input layers.

    Returns:
        ProductLayer: A product layer.
    """

SumLayerFactory ¤

Bases: Protocol

The protocol of a factory that constructs sum layers.

Source code in cirkit/templates/utils.py
67
68
69
70
71
72
73
74
75
76
77
78
79
class SumLayerFactory(Protocol):  # pylint: disable=too-few-public-methods
    """The protocol of a factory that constructs sum layers."""

    def __call__(self, num_input_units: int, num_output_units: int) -> SumLayer:
        """Constructs a sum layer.

        Args:
            num_input_units: The number of units in each layer that is an input.
            num_output_units: The number of sum units in the layer.

        Returns:
            SumLayer: A sum layer.
        """

__call__(num_input_units, num_output_units) ¤

Constructs a sum layer.

Parameters:

Name Type Description Default
num_input_units int

The number of units in each layer that is an input.

required
num_output_units int

The number of sum units in the layer.

required

Returns:

Name Type Description
SumLayer SumLayer

A sum layer.

Source code in cirkit/templates/utils.py
70
71
72
73
74
75
76
77
78
79
def __call__(self, num_input_units: int, num_output_units: int) -> SumLayer:
    """Constructs a sum layer.

    Args:
        num_input_units: The number of units in each layer that is an input.
        num_output_units: The number of sum units in the layer.

    Returns:
        SumLayer: A sum layer.
    """

name_to_dtype(name) ¤

Retrieves a data type by name.

Parameters:

Name Type Description Default
name str

The name of the data type. It can be either 'integer, 'real' or 'complex'.

required

Returns:

Name Type Description
DataType DataType

The corresponding symbolic data type.

Raises:

Type Description
ValueError

If the given data type name is not known.

Source code in cirkit/templates/utils.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def name_to_dtype(name: str) -> DataType:
    """Retrieves a data type by name.

    Args:
        name: The name of the data type. It can be either 'integer, 'real' or 'complex'.

    Returns:
        DataType: The corresponding symbolic data type.

    Raises:
        ValueError: If the given data type name is not known.
    """
    match name:
        case "integer":
            return DataType.INTEGER
        case "real":
            return DataType.REAL
        case "complex":
            return DataType.COMPLEX
        case _:
            raise ValueError(f"Unknown data type called {name}")

name_to_initializer(name, **kwargs) ¤

Retrieves a symbolic initializer object by name.

Parameters:

Name Type Description Default
name str

The initialization name. It can be one of the following: 'uniform' (in the range 0-1), 'normal' (with mean 0 and standard deviation 1), 'dirichlet' (with concentration parameters 1).

required
**kwargs Any

Optional arguments to pass to the initializer.

{}

Returns:

Name Type Description
Initializer Initializer

The symbolic initializer.

Raises:

Type Description
ValueError

If the given initialization name is not known.

Source code in cirkit/templates/utils.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def name_to_initializer(name: str, **kwargs: Any) -> Initializer:
    """Retrieves a symbolic initializer object by name.

    Args:
        name: The initialization name. It can be one of the following: 'uniform' (in the range 0-1),
            'normal' (with mean 0 and standard deviation 1), 'dirichlet' (with concentration
            parameters 1).
        **kwargs: Optional arguments to pass to the initializer.

    Returns:
        Initializer: The symbolic initializer.

    Raises:
        ValueError: If the given initialization name is not known.
    """
    kwargs = kwargs.copy()
    match name:
        case "uniform":
            if "a" not in kwargs:
                kwargs["a"] = 0.0
            if "b" not in kwargs:
                kwargs["b"] = 1.0
            return UniformInitializer(**kwargs)
        case "normal":
            if "mean" not in kwargs:
                kwargs["mean"] = 0.0
            if "stddev" not in kwargs:
                kwargs["stddev"] = 1.0
            return NormalInitializer(**kwargs)
        case "dirichlet":
            if "alpha" not in kwargs:
                kwargs["alpha"] = 1.0
            return DirichletInitializer(**kwargs)
        case _:
            raise ValueError(f"Unknown initializer called {name}")

name_to_input_layer_factory(name, **kwargs) ¤

Retrieves a factory that constructs symbolic input layers.

Parameters:

Name Type Description Default
name str

The name of the input layer. It can be one of the following: 'embedding', 'categorical', 'gaussian', 'binomial'.

required
**kwargs Any

Arguments to pass to the factory.

{}

Returns:

Name Type Description
InputLayerFactory InputLayerFactory

A symbolic input layer factory.

Raises:

Type Description
ValueError

If the given input layer name is not known.

Source code in cirkit/templates/utils.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def name_to_input_layer_factory(name: str, **kwargs: Any) -> InputLayerFactory:
    """Retrieves a factory that constructs symbolic input layers.

    Args:
        name: The name of the input layer. It can be one of the following:
            'embedding', 'categorical', 'gaussian', 'binomial'.
        **kwargs: Arguments to pass to the factory.

    Returns:
        InputLayerFactory: A symbolic input layer factory.

    Raises:
        ValueError: If the given input layer name is not known.
    """
    match name:
        case "embedding":
            return functools.partial(EmbeddingLayer, **kwargs)
        case "categorical":
            return functools.partial(CategoricalLayer, **kwargs)
        case "binomial":
            return functools.partial(BinomialLayer, **kwargs)
        case "gaussian":
            return functools.partial(GaussianLayer, **kwargs)
        case _:
            raise ValueError(f"Unknown input layer called {name}")

name_to_parameter_activation(name, **kwargs) ¤

Retrieves a symbolic unary parameter operator by name.

Parameters:

Name Type Description Default
name str

The name of the parameter activation. It can be either 'none', 'softmax', 'sigmoid', or 'positive-clamp'.

required
**kwargs Any

Optional arguments to pass to symbolic unary parameter.

{}

Returns:

Name Type Description
None Callable[[tuple[int, ...]], UnaryParameterOp] | None

If name is 'none'

Callable[[tuple[int, ...]], UnaryParameterOp] | None

Callable[[tuple[int, ...]], UnaryParameterOp]: If name is not 'none', then a function that takes the parameter shape and returns a unary parameter operator is given.

Raises:

Type Description
ValueError

If the given activation name is not known.

Source code in cirkit/templates/utils.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def name_to_parameter_activation(
    name: str, **kwargs: Any
) -> Callable[[tuple[int, ...]], UnaryParameterOp] | None:
    """Retrieves a symbolic unary parameter operator by name.

    Args:
        name: The name of the parameter activation. It can be either 'none',
            'softmax', 'sigmoid', or 'positive-clamp'.
        **kwargs: Optional arguments to pass to symbolic unary parameter.

    Returns:
        None: If name is 'none'
        Callable[[tuple[int, ...]], UnaryParameterOp]: If name is not 'none', then a function that
            takes the parameter shape and returns a unary parameter operator is given.

    Raises:
        ValueError: If the given activation name is not known.
    """
    match name:
        case "none":
            return None
        case "softmax":
            return functools.partial(SoftmaxParameter, **kwargs)
        case "sigmoid":
            return functools.partial(SigmoidParameter)
        case "positive-clamp":
            if "vmin" not in kwargs:
                kwargs["vmin"] = 1e-18
            return functools.partial(ClampParameter, **kwargs)
        case "softplus":
            return functools.partial(SoftplusParameter, **kwargs)
        case _:
            raise ValueError

named_parameterizations_to_factories(params) ¤

Given a mapping of parameters names to parameterizations, retrieve a dictionary mapping the same parameters names to symbolic parameter factories.

Parameters:

Name Type Description Default
params Mapping[str, Parameterization]

A mapping from parameter names to parameterization objects.

required

Returns:

Type Description
Mapping[str, ParameterFactory]

Mapping[str, ParameterFactory]: A mapping from parameter names to symbolic parameter factories.

Source code in cirkit/templates/utils.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def named_parameterizations_to_factories(
    params: Mapping[str, Parameterization],
) -> Mapping[str, ParameterFactory]:
    """Given a mapping of parameters names to parameterizations, retrieve a dictionary
        mapping the  same parameters names to symbolic parameter factories.

    Args:
        params: A mapping from parameter names to parameterization objects.

    Returns:
        Mapping[str, ParameterFactory]: A mapping from parameter names to symbolic
            parameter factories.
    """
    return {name + "_factory": parameterization_to_factory(param) for name, param in params.items()}

parameterization_to_factory(param) ¤

Given the settings of a parameterization, retrieves a factory that constructs symbolic parameters with that parameterization.

Parameters:

Name Type Description Default
param Parameterization

The parameterization.

required

Returns:

Name Type Description
ParameterFactory ParameterFactory

A symbolic parameter factory.

Raises:

Type Description
ValueError

If one of the settings in the given parameterization is unknown.

Source code in cirkit/templates/utils.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def parameterization_to_factory(param: Parameterization) -> ParameterFactory:
    """Given the settings of a parameterization, retrieves a factory that constructs
        symbolic parameters with that parameterization.

    Args:
        param: The parameterization.

    Returns:
        ParameterFactory: A symbolic parameter factory.

    Raises:
        ValueError: If one of the settings in the given parameterization is unknown.
    """
    unary_op_factory = name_to_parameter_activation(param.activation, **param.activation_kwargs)
    dtype = name_to_dtype(param.dtype)
    initializer = name_to_initializer(param.initialization, **param.initialization_kwargs)
    return functools.partial(
        _build_tensor_parameter,
        unary_op_factory=unary_op_factory,
        dtype=dtype,
        initializer=initializer,
    )