Skip to content

layers

layers ¤

DEFAULT_LAYER_FUSE_OPT_RULES = {SumCollapsePattern: apply_sum_collapse, TuckerPattern: apply_tucker, CandecompPattern: apply_candecomp} module-attribute ¤

DEFAULT_LAYER_SHATTER_OPT_RULES = {DenseKroneckerPattern: apply_dense_tensordot, TensorDotKroneckerPattern: apply_tensordot_tensordot} module-attribute ¤

CandecompPattern ¤

Bases: LayerOptPatternDefn

Detect combinations of Hadamard and Sum layer to merge as CP-T layers.

Source code in cirkit/backend/torch/optimization/layers.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class CandecompPattern(LayerOptPatternDefn):
    """Detect combinations of Hadamard and Sum layer to merge as CP-T layers."""

    @classmethod
    def is_output(cls) -> bool:
        return False

    @classmethod
    def entries(cls) -> Sequence[type[TorchLayer]]:
        return [TorchSumLayer, TorchHadamardLayer]

    @classmethod
    def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
        return [{} for _ in cls.entries()]

    @classmethod
    def config_patterns(cls) -> list[dict[str, Any]]:
        return [{"arity": 1}, {}]

config_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
85
86
87
@classmethod
def config_patterns(cls) -> list[dict[str, Any]]:
    return [{"arity": 1}, {}]

entries() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
77
78
79
@classmethod
def entries(cls) -> Sequence[type[TorchLayer]]:
    return [TorchSumLayer, TorchHadamardLayer]

is_output() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
73
74
75
@classmethod
def is_output(cls) -> bool:
    return False

sub_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
81
82
83
@classmethod
def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
    return [{} for _ in cls.entries()]

DenseKroneckerPattern ¤

Bases: LayerOptPatternDefn

Detect sum layer which have a Kronecker parameter node as parameter output.

The goal of this pattern is to replace the expensive matrix multiplication from the sum by leveraging the decomposition of the parameters from the kronecker product.

Given \(W=A \otimes B\) the parameters of the sum layer, with \(A\) of shape \((a_1,\dots,a_n)\) and \(B\) of shape \((b_1,\dots,b_n)\) $$ \begin{align} (Wx){kl} &=((A \otimes B) x)\ &= (B (A x)^{T})_{k1}
\end{align
} $$

As \(W\) has shape \((a_1b_1,\dots,\a_nb_n)\), it is significantly less computationally expensive to compute the two inner products instead.

Source code in cirkit/backend/torch/optimization/layers.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class DenseKroneckerPattern(LayerOptPatternDefn):
    r"""Detect sum layer which have a Kronecker parameter node as parameter output.

    The goal of this pattern is to replace the expensive matrix multiplication from
    the sum by leveraging the decomposition of the parameters from the kronecker product.

    Given $W=A \otimes B$ the parameters of the sum layer,
    with $A$ of shape $(a_1,\dots,a_n)$ and $B$ of shape $(b_1,\dots,b_n)$
    $$
        \begin{align*} 
        (Wx)_{kl} &=((A \otimes B) x)_{kl}\\
        &= (B (A x)^{T})_{k1}  
        \end{align*}
    $$

    As $W$ has shape $(a_1b_1,\dots,\a_nb_n)$, it is significantly less computationally
    expensive to compute the two inner products instead.
    """

    @classmethod
    def is_output(cls) -> bool:
        return False

    @classmethod
    def entries(cls) -> Sequence[type[TorchLayer]]:
        return [TorchSumLayer]

    @classmethod
    def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
        return [{"weight": KroneckerOutParameterPattern}]

    @classmethod
    def config_patterns(cls) -> list[dict[str, Any]]:
        return [{"arity": 1}]

config_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
121
122
123
@classmethod
def config_patterns(cls) -> list[dict[str, Any]]:
    return [{"arity": 1}]

entries() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
113
114
115
@classmethod
def entries(cls) -> Sequence[type[TorchLayer]]:
    return [TorchSumLayer]

is_output() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
109
110
111
@classmethod
def is_output(cls) -> bool:
    return False

sub_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
117
118
119
@classmethod
def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
    return [{"weight": KroneckerOutParameterPattern}]

SumCollapsePattern ¤

Bases: LayerOptPatternDefn

Detect adjacent sum layers that could be fused

Source code in cirkit/backend/torch/optimization/layers.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class SumCollapsePattern(LayerOptPatternDefn):
    """Detect adjacent sum layers that could be fused"""

    @classmethod
    def is_output(cls) -> bool:
        return False

    @classmethod
    def entries(cls) -> Sequence[type[TorchLayer]]:
        return [TorchSumLayer, TorchSumLayer]

    @classmethod
    def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
        return [{} for _ in cls.entries()]

    @classmethod
    def config_patterns(cls) -> list[dict[str, Any]]:
        return [{"arity": 1}, {}]

config_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
45
46
47
@classmethod
def config_patterns(cls) -> list[dict[str, Any]]:
    return [{"arity": 1}, {}]

entries() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
37
38
39
@classmethod
def entries(cls) -> Sequence[type[TorchLayer]]:
    return [TorchSumLayer, TorchSumLayer]

is_output() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
33
34
35
@classmethod
def is_output(cls) -> bool:
    return False

sub_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
41
42
43
@classmethod
def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
    return [{} for _ in cls.entries()]

TensorDotKroneckerPattern ¤

Bases: LayerOptPatternDefn

Detect Dot layer which have a Kronecker parameter node as parameter output.

The goal of this pattern is to replace the expensive matrix multiplication from the dot layer by leveraging the decomposition of the parameters from the kronecker product.

Given \(W=A \otimes B\) the parameters of the dot layer, with \(A\) of shape \((a_1,\dots,a_n)\) and \(B\) of shape \((b_1,\dots,b_n)\) $$ \begin{align} (Wx){kl} &=((A \otimes B) x)\ &= (B (A x)^{T})_{k1}
\end{align
} $$

As \(W\) has shape \((a_1b_1,\dots,\a_nb_n)\), it is significantly less computationally expensive to compute the two inner products instead.

Source code in cirkit/backend/torch/optimization/layers.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
class TensorDotKroneckerPattern(LayerOptPatternDefn):
    r"""Detect Dot layer which have a Kronecker parameter node as parameter output.

    The goal of this pattern is to replace the expensive matrix multiplication from
    the dot layer by leveraging the decomposition of the parameters from the kronecker product.

    Given $W=A \otimes B$ the parameters of the dot layer,
    with $A$ of shape $(a_1,\dots,a_n)$ and $B$ of shape $(b_1,\dots,b_n)$
    $$
        \begin{align*} 
        (Wx)_{kl} &=((A \otimes B) x)_{kl}\\
        &= (B (A x)^{T})_{k1}  
        \end{align*}
    $$

    As $W$ has shape $(a_1b_1,\dots,\a_nb_n)$, it is significantly less computationally
    expensive to compute the two inner products instead.
    """

    @classmethod
    def is_output(cls) -> bool:
        return False

    @classmethod
    def entries(cls) -> Sequence[type[TorchLayer]]:
        return [TorchTensorDotLayer]

    @classmethod
    def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
        return [{"weight": KroneckerOutParameterPattern}]

    @classmethod
    def config_patterns(cls) -> list[dict[str, Any]]:
        return [{}]

config_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
157
158
159
@classmethod
def config_patterns(cls) -> list[dict[str, Any]]:
    return [{}]

entries() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
149
150
151
@classmethod
def entries(cls) -> Sequence[type[TorchLayer]]:
    return [TorchTensorDotLayer]

is_output() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
145
146
147
@classmethod
def is_output(cls) -> bool:
    return False

sub_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
153
154
155
@classmethod
def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
    return [{"weight": KroneckerOutParameterPattern}]

TuckerPattern ¤

Bases: LayerOptPatternDefn

Detect combinations of Sum and Kroenecker product to merge in a Tucker layer

Source code in cirkit/backend/torch/optimization/layers.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class TuckerPattern(LayerOptPatternDefn):
    """Detect combinations of Sum and Kroenecker product to merge in a Tucker layer"""

    @classmethod
    def is_output(cls) -> bool:
        return False

    @classmethod
    def entries(cls) -> Sequence[type[TorchLayer]]:
        return [TorchSumLayer, TorchKroneckerLayer]

    @classmethod
    def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
        return [{} for _ in cls.entries()]

    @classmethod
    def config_patterns(cls) -> list[dict[str, Any]]:
        return [{"arity": 1}, {}]

config_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
65
66
67
@classmethod
def config_patterns(cls) -> list[dict[str, Any]]:
    return [{"arity": 1}, {}]

entries() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
57
58
59
@classmethod
def entries(cls) -> Sequence[type[TorchLayer]]:
    return [TorchSumLayer, TorchKroneckerLayer]

is_output() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
53
54
55
@classmethod
def is_output(cls) -> bool:
    return False

sub_patterns() classmethod ¤

Source code in cirkit/backend/torch/optimization/layers.py
61
62
63
@classmethod
def sub_patterns(cls) -> Sequence[dict[str, ParameterOptPattern]]:
    return [{} for _ in cls.entries()]

apply_candecomp(compiler, match) ¤

Construct the CPT layer fusing one Sum and one Hadamard layer.

Parameters:

Name Type Description Default
compiler TorchCompiler

The current compiler doing the optimization.

required
match LayerOptMatch

The match to optimize.

required

Returns:

Type Description
tuple[TorchCPTLayer]

tuple[TorchCPTLayer]: The CPT layer replacing the sum and hadamard layers.

Source code in cirkit/backend/torch/optimization/layers.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def apply_candecomp(compiler: "TorchCompiler", match: LayerOptMatch) -> tuple[TorchCPTLayer]:
    r"""Construct the CPT layer fusing one Sum and one Hadamard layer.

    Args:
        compiler (TorchCompiler): The current compiler doing the optimization.
        match (LayerOptMatch): The match to optimize.

    Returns:
        tuple[TorchCPTLayer]: The CPT layer replacing the sum and hadamard layers.
    """
    dense = cast(TorchSumLayer, match.entries[0])
    hadamard = cast(TorchHadamardLayer, match.entries[1])
    cpt = TorchCPTLayer(
        hadamard.num_input_units,
        dense.num_output_units,
        hadamard.arity,
        weight=dense.weight,
        semiring=compiler.semiring,
    )
    return (cpt,)

apply_dense_tensordot(compiler, match) ¤

Return two Dot Layer corresponding to a Sum parameterized by a Kronecker product

Parameters:

Name Type Description Default
compiler TorchCompiler

The current compiler doing the optimization.

required
match LayerOptMatch

The match to optimize.

required

Returns:

Type Description
tuple[TorchTensorDotLayer, TorchTensorDotLayer]

tuple[TorchTensorDotLayer, TorchTensorDotLayer]: the two dot layer to replace the sum layer.

Source code in cirkit/backend/torch/optimization/layers.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def apply_dense_tensordot(
    compiler: "TorchCompiler", match: LayerOptMatch
) -> tuple[TorchTensorDotLayer, TorchTensorDotLayer]:
    r"""Return two Dot Layer corresponding to a Sum parameterized by a Kronecker product

    Args:
        compiler (TorchCompiler): The current compiler doing the optimization.
        match (LayerOptMatch): The match to optimize.

    Returns:
        tuple[TorchTensorDotLayer, TorchTensorDotLayer]: the two dot layer to
            replace the sum layer.
    """
    dense = cast(TorchSumLayer, match.entries[0])
    weight_patterns = match.sub_entries[0]["weight"]
    kronecker = cast(TorchKroneckerParameter, weight_patterns[0].entries[0])
    return _apply_tensordot_rule(
        compiler, dense.num_input_units, dense.num_output_units, dense.weight, kronecker
    )

apply_sum_collapse(compiler, match) ¤

Fuse two sum nodes together.

This function simply develop the two node into one single sum using matrix multiplication of the two sum's parameters.

Indeed, if we have two sums with parameters \(W_1\), \(W_2\): $\(S_1=W_1X\)$ $\(S_2=W_2S_1\)$ $\(S_2=W_2W_1X\)$

The final sums have weight : \(W_2W_1\)

Parameters:

Name Type Description Default
compiler TorchCompiler

The current compiler

required
match LayerOptMatch

The match to replace

required

Returns:

Type Description
tuple[TorchSumLayer]

tuple[TorchSumLayer]: The sum layer computing the two sum in one sum.

Source code in cirkit/backend/torch/optimization/layers.py
162
163
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
197
198
def apply_sum_collapse(compiler: "TorchCompiler", match: LayerOptMatch) -> tuple[TorchSumLayer]:
    """Fuse two sum nodes together.

    This function simply develop the two node into one
    single sum using matrix multiplication of the two
    sum's parameters.

    Indeed, if we have two sums with parameters $W_1$, $W_2$:
    $$S_1=W_1X$$
    $$S_2=W_2S_1$$
    $$S_2=W_2W_1X$$

    The final sums have weight : $W_2W_1$

    Args:
        compiler (TorchCompiler): The current compiler
        match: The match to replace

    Returns:
       tuple[TorchSumLayer]: The sum layer computing the two sum
            in one sum.
    """
    dense1 = cast(TorchSumLayer, match.entries[0])
    dense2 = cast(TorchSumLayer, match.entries[1])
    weight = TorchParameter.from_binary(
        TorchMatMulParameter(dense1.weight.shape, dense2.weight.shape),
        dense1.weight,
        dense2.weight,
    )
    dense = TorchSumLayer(
        dense2.num_input_units,
        dense1.num_output_units,
        arity=dense2.arity,
        weight=weight,
        semiring=compiler.semiring,
    )
    return (dense,)

apply_tensordot_tensordot(compiler, match) ¤

Return two Dot Layer corresponding to a Dot Layer parameterized by a Kronecker product

Parameters:

Name Type Description Default
compiler TorchCompiler

The current compiler doing the optimization.

required
match LayerOptMatch

The match to optimize.

required

Returns:

Type Description
tuple[TorchTensorDotLayer, TorchTensorDotLayer]

tuple[TorchTensorDotLayer, TorchTensorDotLayer]: the two dot layer to replace the sum layer.

Source code in cirkit/backend/torch/optimization/layers.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
def apply_tensordot_tensordot(
    compiler: "TorchCompiler", match: LayerOptMatch
) -> tuple[TorchTensorDotLayer, TorchTensorDotLayer]:
    r"""Return two Dot Layer corresponding to a Dot Layer parameterized by a Kronecker product

    Args:
        compiler (TorchCompiler): The current compiler doing the optimization.
        match (LayerOptMatch): The match to optimize.

    Returns:
        tuple[TorchTensorDotLayer, TorchTensorDotLayer]: the two dot layer to
            replace the sum layer.
    """

    tdot = cast(TorchTensorDotLayer, match.entries[0])
    weight_patterns = match.sub_entries[0]["weight"]
    kronecker = cast(TorchKroneckerParameter, weight_patterns[0].entries[0])
    return _apply_tensordot_rule(
        compiler, tdot.num_input_units, tdot.num_output_units, tdot.weight, kronecker
    )

apply_tucker(compiler, match) ¤

Create a Tucker layer that compute the sum of a kronecker product.

This optimization consists of rewriting the full operation in a single einsum to avoid computing the intermediary tensor from the kronecker product.

The output of the kronecker product which take the vectors \(x\) and \(y\) of shape \(a\) and \(b\) respectively (no batch or fold for simplicity), can be written as the following einsum:

\[ a,b \rightarrow ab \]

We would then proceed to flatten the output to get a vector \(z\) of size \(i=a \times b\). This vector is then used in the einsum for the sum. Given W the parameter matrix of shape \((o,i)\), the sum \(Wx\) is:

\[ i,oi \rightarrow o \]

Now let's reshape the tensors to re-introduce the \(a\) and \(b\) dimensions. The sum would be written as:

\[ ab, oab \rightarrow o \]

We can finally substitute the results of the kronecker product for the \(x\) and \(y\) vectors:

\[ a,b,oab \rightarrow o \]

Thus avoiding the intermediary Kronecker product. This is exactly what the tucker layer will compute.

Parameters:

Name Type Description Default
compiler TorchCompiler

The current compiler.

required
match LayerOptMatch

The match to replace.

required

Returns:

Type Description
tuple[TorchTuckerLayer]

tuple[TorchTuckerLayer]: The tucker layer merging the two operations.

Source code in cirkit/backend/torch/optimization/layers.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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
257
def apply_tucker(compiler: "TorchCompiler", match: LayerOptMatch) -> tuple[TorchTuckerLayer]:
    r"""Create a Tucker layer that compute the sum of a kronecker product.

    This optimization consists of rewriting the full operation in a single
    einsum to avoid computing the intermediary tensor from the kronecker
    product.

    The output of the kronecker product which take the vectors $x$ and $y$ of shape $a$ and
    $b$ respectively (no batch or fold for simplicity), can be written as the
    following einsum:

    $$
        a,b \rightarrow ab
    $$

    We would then proceed to flatten the output to get a vector $z$ of
    size $i=a \times b$. This vector is then used in the einsum for the sum.
    Given W the parameter matrix of shape $(o,i)$, the sum $Wx$ is:

    $$
        i,oi \rightarrow o
    $$

    Now let's reshape the tensors to re-introduce the $a$ and $b$ dimensions.
    The sum would be written as:

    $$
        ab, oab \rightarrow o
    $$

    We can finally substitute the results of the kronecker product for the $x$
    and $y$ vectors:

    $$
        a,b,oab \rightarrow o
    $$

    Thus avoiding the intermediary Kronecker product.
    This is exactly what the tucker layer will compute.

    Args:
        compiler (TorchCompiler): The current compiler.
        match (LayerOptMatch): The match to replace.

    Returns:
       tuple[TorchTuckerLayer]: The tucker layer merging the two operations.
    """
    dense = cast(TorchSumLayer, match.entries[0])
    kronecker = cast(TorchKroneckerLayer, match.entries[1])
    tucker = TorchTuckerLayer(
        kronecker.num_input_units,
        dense.num_output_units,
        kronecker.arity,
        weight=dense.weight,
        semiring=compiler.semiring,
    )
    return (tucker,)