Neural Compiler V2 (Beta)#
Beta
Neural Compiler V2 is in beta and its API may still change between releases. The existing NeuralCompiler class remains the default.
NeuralCompilerV2 compiles Neural Network model(s) into a Dataflow Program (DFP). The compile method runs the full pipeline in one call:
from memryx import NeuralCompilerV2
nc = NeuralCompilerV2()
dfp = nc.compile("mobilenet.h5", num_chips=4, dfp_fname="mobilenet.dfp")
The pipeline has four stages, and each one is also available as its own method. Each stage returns a result object that is passed to the next stage, so custom logic can be run in between. The following is equivalent to the compile call above:
from memryx import NeuralCompilerV2
nc = NeuralCompilerV2()
loaded = nc.load("mobilenet.h5")
graphs = nc.graph(loaded)
mapped = nc.map(graphs, num_chips=4)
dfp = nc.assemble(mapped, dfp_fname="mobilenet.dfp")
- class NeuralCompilerV2(verbose: int = 0)#
The MemryX Neural Compiler.
The Neural Compiler compiles Neural Network model(s) into a Dataflow Program (DFP) which can be used to program and perform inference using MemryX Accelerators (MXA).
The high-level
compile()method runs the full pipeline (load → graph → map → assemble) in one call. The staged methodsload(),graph(),map(), andassemble()expose individual stages so callers can interleave their own logic — for example, inspecting or modifying anMxGraphbetweengraph()andmap().- Parameters:
- verboseint, default=0
Verbosity level. Higher values produce more diagnostic output. The CLI maps repeated
-vflags onto this argument.
Examples
from memryx import NeuralCompilerV2 nc = NeuralCompilerV2() dfp = nc.compile("mobilenet.keras", num_chips=4, dfp_fname="mobilenet.dfp")
- compile(models: str | Path | Any | Sequence[str | Path | Any], autocrop: bool = False, input_shapes: dict | list[dict] | None = None, inputs: str | None = None, outputs: str | None = None, io_file: str | Path | None = None, wbtable: str | Path | None = None, extensions: str | Path | Sequence[str | Path] = (), allow_unsigned_extensions: bool = False, hpoc: list[int] | None = None, hpoc_file: str | Path | None = None, exp_auto_dp: bool = False, effort: Literal['lazy', 'normal', 'hard', 'closed_loop'] = 'normal', split_number: int = -1, num_chips: int = 4, target_fps: int | float = inf, visualize_mapping: bool = False, dfp_fname: str | None = None, no_sim_dfp: bool = True, save_all_splits: bool = False, num_processes: int = 1, device_id: int = 0)#
Compile one or more models into a DFP.
Convenience entry point that runs the full pipeline (
load()→graph()→map()→assemble()) and returns aDfpready for deployment on a MemryX accelerator.Parameters here are grouped by the stage that owns them; see the listed stage method for full descriptions.
- Parameters:
- models, autocrop, input_shapes, inputs, outputs, io_file, wbtable
Model loading and cropping. See
load().- extensions, allow_unsigned_extensions, hpoc, hpoc_file, exp_auto_dp, effort, split_number
Graph construction and quantization. See
graph().- num_chips, target_fps, visualize_mapping
Mapping onto the MXA design. See
map().- dfp_fname, no_sim_dfp, save_all_splits, device_id
DFP assembly and output. See
assemble().- num_processes
Worker processes for every stage that parallelizes over sweeps. See
graph(),map(), andassemble().
- Returns:
- Dfp
The compiled Dataflow Program, ready to deploy or save.
- Raises:
- ValueError
If both
hpocandhpoc_fileare provided.
Examples
from memryx import NeuralCompilerV2 nc = NeuralCompilerV2() dfp = nc.compile("mobilenet.keras", num_chips=4, effort="hard", dfp_fname="mobilenet.dfp")
- load(models: str | Path | Any | Sequence[str | Path | Any], autocrop: bool = False, input_shapes: dict | list[dict] | None = None, inputs: str | None = None, outputs: str | None = None, io_file: str | Path | None = None, wbtable: str | Path | None = None, crop_fname: str | None = None) LoadResult#
Load and parse models, optionally with autocrop applied.
Stage 1 of the compile pipeline.
- Parameters:
- modelspath, model object, or list of either
Neural Network model(s) to compile. Can be a path to a model file, a loaded model object, or a list of either. Supported framework formats:
Framework
strorpathlib.Pathobject
onnx
.onnxonnx.ModelPrototflite
.tflitebytes(loaded flatbuf)keras / tf_keras
.keras,.h5,.jsonkeras.Modeltensorflow
.pbor.metaN/A
Pass a list to co-compile multiple models simultaneously (multi-model). Frameworks can be mixed.
- autocropbool, default=False
Automatically crop pre- and post-processing layers from the input model(s). When enabled, the model is split into up to three pieces (preprocessing, core, postprocessing); only the core is compiled for the MXA. The pieces are saved as
<name>_crop.<ext>,<name>_pre.<ext>and<name>_post.<ext>(pre/post only when present), where<name>is thecrop_fnamestem or the model name and<ext>matches the model’s framework. Multi-model files are prefixed withmodel_<i>_. The pre/post pieces can be attached at runtime withset_preprocessing_model/set_postprocessing_modelonSyncAccl/AsyncAccl.- input_shapesdict or list of lists, optional
Explicit input shapes per model. Only required when shapes cannot be inferred from the model itself. Keys are model indices into
models; values are a shape or list of shapes. Shapes are channel-last and include the batch dimension.# One model with one input input_shapes = {0: [1, 300, 300, 3]} # One model with two inputs input_shapes = {0: [[1, 300, 300, 3], [1, 400, 400, 3]]} # Two models, with shapes only for the second input_shapes = {1: [1, 300, 300, 3]} # Shorthand for one model with two inputs input_shapes = [[1, 300, 300, 3], [1, 400, 400, 3]]
- inputsstr, optional
Names of input layer(s). Delimit multiple inputs of one model with
,; separate per-model entries with|. Overridesio_file.- outputsstr, optional
Names of output layer(s). Same delimiter rules as
inputs. Overridesio_file.- io_filestr or Path, optional
Path to a JSON file specifying input and output layer names. Useful for extracting a subgraph from the full graph, for example to strip pre/post processing.
- wbtablestr, Path, or dict, optional
Per-layer weight quantization configuration. Valid precisions are 4, 8, and 16 bits. Pass a JSON path or an equivalent dict. Use the
__DEFAULT__key to set a global precision for all layers. See the weight-precision spec for the file format.- crop_fnamestr, optional
When
autocropis enabled, the base filename used when writing cropped pieces to disk. Defaults to the model’s own name.
- Returns:
- LoadResult
Wraps the loaded models and their source paths.
- graph(models: LoadResult, extensions: str | Path | Sequence[str | Path] = (), allow_unsigned_extensions: bool = False, hpoc: list[int] | None = None, hpoc_file: str | Path | None = None, exp_auto_dp: bool = False, effort: Literal['lazy', 'normal', 'hard', 'closed_loop'] = 'normal', split_number: int = -1, num_processes: int = 1) GraphResult#
Build MxGraph(s) from loaded models.
Stage 2 of the compile pipeline. Accepts the output of
load()and runs the graph engine sweeps required by the mapper.- Parameters:
- modelsLoadResult
Output of
load().- extensionsstr, Path, or sequence of either, default=()
One or more paths to
.nceextension files that extend compiler functionality at runtime. Official MemryX extensions are signed; passallow_unsigned_extensions=Trueto load unsigned ones.- allow_unsigned_extensionsbool, default=False
Allow loading of unsigned extensions. An extension may execute arbitrary code — only enable this for sources you trust.
- hpoclist of int, optional
High-precision output channels: list of final-layer output channel indices to compute at higher precision. Only handles the simple case where the model has a single output or every output shares the same channel count. For more flexibility (multi-model or multi-output), use
hpoc_fileinstead. Mutually exclusive withhpoc_file.- hpoc_filestr, Path, or dict, optional
HPOC configuration for the complex case: per-layer / per-model channel selections. Pass a JSON path or an equivalent dict. See the HPOC spec for the file format. Mutually exclusive with
hpoc.- exp_auto_dpbool, default=False
Experimental double-precision mode. Auto-selects layers to run at 16 bits while the rest use 8 bits. The selected layers are set to 16 bits even if
wbtable(passed toload()) assigns them a different precision.- effort{“lazy”, “normal”, “hard”, “closed_loop”}, default=”normal”
Mapping effort. Controls how much time the compiler spends searching for an efficient mapping.
lazy: compile very quickly, but with low inference performance (FPS).normal: balances compile time and inference performance.hard: best inference performance, much longer compile time.closed_loop: feedback-driven search for the highest achievable FPS; longest compile time.
- split_numberint, default=-1
Compile only the selected original effort split: 0-29 for
hardandclosed_loop, only 0 forlazyandnormal. An out-of-range value raisesCompilerError. The default of-1runs every split and keeps the best one. The selected split number is stored in the resulting DFP metadata.- num_processesint, default=1
Number of worker processes used to run graph-processing sweeps in parallel. Only has an effect when
effortishardorclosed_loop(30 sweeps each); the other levels run a single sweep.
- Returns:
- GraphResult
Wraps the compiled MxGraph(s) along with quantization settings.
- Raises:
- ValueError
If both
hpocandhpoc_fileare provided.
- map(graph: GraphResult, num_chips: int = 4, target_fps: int | float = inf, visualize_mapping: bool = False, num_processes: int = 1) MapResult#
Map graph(s) onto the MXA design.
Stage 3 of the compile pipeline. Runs the mapper sweeps and returns all successful mappings, with the winner first outside closed-loop effort.
- Parameters:
- graphGraphResult
Output of
graph().- num_chipsint, default=4
Number of MXAs to target. Determines the size of the compiled DFP.
- target_fpsint or float, default=inf
Target frames-per-second for the mapping optimizer. The default (
inf) tells the optimizer to maximize performance.- visualize_mappingbool, default=False
Animate the mapper’s optimization steps. Useful for debugging mapping decisions.
- num_processesint, default=1
Number of worker processes used to run mapper sweeps in parallel. Only has an effect when the upstream
effortishardorclosed_loop; the other levels produce a single sweep.
- Returns:
- MapResult
Wraps the resulting MPU graphs and the target design parameters.
- assemble(graphs: MapResult, no_sim_dfp: bool = True, dfp_fname: str | None = None, num_processes: int = 1, device_id: int = 0, save_all_splits: bool = False) Dfp#
Assemble mapped graph(s) into a DFP.
Stage 4 (final) of the compile pipeline. Produces the deployable DFP.
- Parameters:
- graphsMapResult
Output of
map().- no_sim_dfpbool, default=True
Skip embedding Simulator info in the
.dfpfile. Disabling (False) produces a larger DFP that the Simulator can consume without the original model.- dfp_fnamestr, optional
File path to save the compiled DFP. The
.dfpextension is appended automatically if missing. WhenNone(the default) the DFP is saved in the current directory as<model_name>.dfpfor a single model loaded from disk, andmodels.dfpotherwise.- device_idint, default=0
Device ID to use when benchmarking DFP candidates for
effort="closed_loop". Requires a connected MXA.- num_processesint, default=1
Number of worker processes used to assemble mappings in parallel. Only has an effect when more than one mapping is assembled: for
effort="closed_loop", oreffort="hard"withsave_all_splits=True.- save_all_splitsbool, default=False
Save every successful candidate DFP for hard and closed-loop efforts as
<dfp_stem>_splits/<dfp_stem>_split_<N>.dfp, alongside the winning DFP. The directory is replaced on each run. Ignored forlazyandnormal. The sameMapResultcan be assembled again with this option enabled or disabled.
- Returns:
- Dfp
The compiled Dataflow Program.
Result Objects#
Each stage returns an object that holds its output along with the information needed by the following stages.
- class LoadResult(models: list[Model], model_paths: list[Path | None])#
Output of
NeuralCompilerV2.load().- Attributes:
- modelslist of Model
Loaded model objects, in the same order as the input
models.- model_pathslist of (Path or None)
Source path for each model when loaded from disk, or
Nonewhen loaded from memory.
- class GraphResult(mxgraphs: list[FlatMxGraph], nbits: int, effort: Literal['lazy', 'normal', 'hard', 'closed_loop'], model_paths: list[Path | None], split_numbers: list[int])#
Output of
NeuralCompilerV2.graph().- Attributes:
- mxgraphslist of FlatMxGraph
One graph per mapper sweep produced by the graph engine.
- nbitsint
Number of quantization bits.
- effort{“lazy”, “normal”, “hard”, “closed_loop”}
Mapping effort that produced this graph set.
- model_pathslist of (Path or None)
Carried through from
LoadResult.- split_numberslist of int
Original effort-sweep indices, in the same order as
mxgraphs.
- class MapResult(mpugraphs: list[list[MpuGraph]], design_parameters: DesignParameters, nbits: int, effort: Literal['lazy', 'normal', 'hard', 'closed_loop'], model_paths: list[Path | None], split_numbers: list[int])#
Output of
NeuralCompilerV2.map().- Attributes:
- mpugraphslist of Mapping
Mapper results, one per successful sweep. The winner is first for non-closed-loop effort; closed-loop assembly selects it by benchmarking.
- design_parametersDesignParameters
MXA design parameters used for mapping.
- nbitsint
Carried through from
GraphResult.- effort{“lazy”, “normal”, “hard”, “closed_loop”}
Carried through from
GraphResult.- model_pathslist of (Path or None)
Carried through from
GraphResult.- split_numberslist of int
Original effort-sweep indices, in the same order as
mpugraphs.
