107
108
109
110
111
112
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
199
200
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
258
259
260
261
262
263 | class TorchCompiler(AbstractCompiler):
def __init__(self, semiring: str = "sum-product", fold: bool = False, optimize: bool = False):
super().__init__(
CompilerLayerRegistry(DEFAULT_LAYER_COMPILATION_RULES),
CompilerParameterRegistry(DEFAULT_PARAMETER_COMPILATION_RULES),
CompilerInitializerRegistry(DEFAULT_INITIALIZER_COMPILATION_RULES),
fold=fold,
optimize=optimize,
)
# The semiring being used at compile time
self._semiring: Semiring = SemiringImpl.from_name(semiring)
# The state of the compiler
self._state = TorchCompilerState()
# The registry of optimization rules
self._optimization_registry = {
"parameter": ParameterOptRegistry(DEFAULT_PARAMETER_OPT_RULES),
"layer_fuse": LayerOptRegistry(DEFAULT_LAYER_FUSE_OPT_RULES),
"layer_shatter": LayerOptRegistry(DEFAULT_LAYER_SHATTER_OPT_RULES),
}
def compile_pipeline(self, sc: Circuit) -> AbstractTorchCircuit:
# Compile the circuits following the topological ordering of the pipeline.
for sci in pipeline_topological_ordering([sc]):
# Check if the circuit in the pipeline has already been compiled
if self.is_compiled(sci):
continue
# Compile the circuit
self._compile_circuit(sci)
# Return the compiled circuit (i.e., the output of the circuit pipeline)
return self.get_compiled_circuit(sc)
@property
def semiring(self) -> Semiring:
return self._semiring
@property
def is_fold_enabled(self) -> bool:
return self._flags["fold"]
@property
def is_optimize_enabled(self) -> bool:
return self._flags["optimize"]
@property
def state(self) -> TorchCompilerState:
return self._state
def compile_layer(self, layer: Layer) -> TorchLayer:
signature = type(layer)
rule = self.retrieve_layer_rule(signature)
return cast(TorchLayer, rule(self, layer))
def compile_parameter(self, parameter: Parameter) -> TorchParameter:
# A map from symbolic to compiled parameters
compiled_nodes_map: dict[ParameterNode, TorchParameterNode] = {}
# The parameter nodes, and their inputs
nodes: list[TorchParameterNode] = []
in_nodes: dict[TorchParameterNode, list[TorchParameterNode]] = {}
# Compile the parameter by following the topological ordering
for p in parameter.topological_ordering():
# Compile the parameter node and make the connections
compiled_p = self._compile_parameter_node(p)
in_compiled_nodes = [compiled_nodes_map[pi] for pi in parameter.node_inputs(p)]
in_nodes[compiled_p] = in_compiled_nodes
compiled_nodes_map[p] = compiled_p
nodes.append(compiled_p)
# Build the parameter's computational graph
outputs = [compiled_nodes_map[parameter.output]]
return TorchParameter(nodes, in_nodes, outputs)
def compile_initializer(self, initializer: Initializer) -> Callable[[Tensor], Tensor]:
# Retrieve the rule for the given initializer and compile it
signature = type(initializer)
rule = self.retrieve_initializer_rule(signature)
return cast(Callable[[Tensor], Tensor], rule(self, initializer))
def retrieve_optimization_registry(self, kind: str) -> CompilerRegistry:
return cast(CompilerRegistry, self._optimization_registry[kind])
def retrieve_optimization_rule(self, kind: str, pattern: GraphOptPattern) -> Callable:
registry = self.retrieve_optimization_registry(kind)
return registry.retrieve_rule(pattern)
def _compile_parameter_node(self, node: ParameterNode) -> TorchParameterNode:
signature = type(node)
rule = self.retrieve_parameter_rule(signature)
return cast(TorchParameterNode, rule(self, node))
def _compile_circuit(self, sc: Circuit) -> AbstractTorchCircuit:
# A map from symbolic to compiled layers
compiled_layers_map: dict[Layer, TorchLayer] = {}
# The inputs of each layer
in_layers: dict[TorchLayer, list[TorchLayer]] = {}
# Compile layers by following the topological ordering
for sl in sc.topological_ordering():
# Compile the layer, for any layer types
layer = self.compile_layer(sl)
# Build the connectivity between compiled layers
ins = [compiled_layers_map[sli] for sli in sc.layer_inputs(sl)]
in_layers[layer] = ins
compiled_layers_map[sl] = layer
# If the symbolic circuit being compiled has empty scope,
# then return a 'constant circuit' whose interface does not require inputs
cc_cls = TorchCircuit if sc.scope else TorchConstantCircuit
# Construct the sequence of output layers
outputs = [compiled_layers_map[sl] for sl in sc.outputs]
# Construct the tensorized circuit
layers = list(compiled_layers_map.values())
cc = cc_cls(
sc.scope,
sc.num_channels,
layers=layers,
in_layers=in_layers,
outputs=outputs,
properties=sc.properties,
)
# Post-process the compiled circuit, i.e.,
# optionally apply optimizations to it and then fold it
cc = self._post_process_circuit(cc)
# Allocate & initialize the parameters
cc.reset_parameters()
# Register the compiled circuit
self.register_compiled_circuit(sc, cc)
# Signal the end of the circuit compilation to the state
self._state.finish_compilation()
return cc
def _post_process_circuit(self, cc: AbstractTorchCircuit) -> AbstractTorchCircuit:
if self.is_optimize_enabled:
# Optimize the circuit computational graph
opt_cc = _optimize_circuit(self, cc, max_opt_steps=5)
del cc
cc = opt_cc
if self.is_fold_enabled:
# Optimize the circuit by folding it
opt_cc = _fold_circuit(self, cc)
del cc
cc = opt_cc
return cc
|