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")
graph LR start([NN Model]) --> ld["load()"] ld --> gp["graph()"] gp --> mp["map()"] mp --> as["assemble()"] as --> stop([DFP]) style start fill:#CFE8FD, stroke:#595959 style ld fill:#FFE699, stroke:#595959 style gp fill:#FFE699, stroke:#595959 style mp fill:#FFE699, stroke:#595959 style as fill:#FFE699, stroke:#595959 style stop fill:#A9D18E, stroke:#595959
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 methods load(), graph(), map(), and assemble() expose individual stages so callers can interleave their own logic — for example, inspecting or modifying an MxGraph between graph() and map().

Parameters:
verboseint, default=0

Verbosity level. Higher values produce more diagnostic output. The CLI maps repeated -v flags 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 a Dfp ready 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(), and assemble().

Returns:
Dfp

The compiled Dataflow Program, ready to deploy or save.

Raises:
ValueError

If both hpoc and hpoc_file are 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

str or pathlib.Path

object

onnx

.onnx

onnx.ModelProto

tflite

.tflite

bytes (loaded flatbuf)

keras / tf_keras

.keras, .h5, .json

keras.Model

tensorflow

.pb or .meta

N/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 the crop_fname stem or the model name and <ext> matches the model’s framework. Multi-model files are prefixed with model_<i>_. The pre/post pieces can be attached at runtime with set_preprocessing_model / set_postprocessing_model on SyncAccl / 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 |. Overrides io_file.

outputsstr, optional

Names of output layer(s). Same delimiter rules as inputs. Overrides io_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 autocrop is 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 .nce extension files that extend compiler functionality at runtime. Official MemryX extensions are signed; pass allow_unsigned_extensions=True to 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_file instead. Mutually exclusive with hpoc_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 to load()) 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 hard and closed_loop, only 0 for lazy and normal. An out-of-range value raises CompilerError. The default of -1 runs 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 effort is hard or closed_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 hpoc and hpoc_file are 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 effort is hard or closed_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 .dfp file. 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 .dfp extension is appended automatically if missing. When None (the default) the DFP is saved in the current directory as <model_name>.dfp for a single model loaded from disk, and models.dfp otherwise.

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", or effort="hard" with save_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 for lazy and normal. The same MapResult can 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 None when 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.