Repository navigation
Expand file tree
/
Copy pathapi.py
More file actions
1565 lines (1286 loc) · 61.6 KB
/
Copy pathapi.py
File metadata and controls
1565 lines (1286 loc) · 61.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""MAX Engine APIs."""
from __future__ import annotations
import faulthandler
import os
import signal
import sys
import threading
from collections.abc import Iterable, Mapping, Sequence
from enum import Enum, IntEnum, auto
from inspect import Parameter, Signature
from pathlib import Path
from typing import Any, BinaryIO, ClassVar, Literal, NoReturn, cast
import numpy as np
from max import _validation_hooks
from max._core.engine import CompiledModels as _CompiledModels
from max._core.engine import DebugConfig as DebugConfig
from max._core.engine import InferenceSession as _InferenceSession
from max._core.engine import Model as Model
from max._core.engine import PrintStyle
from max._core.engine import TensorSpec as TensorSpec
from max._core.engine import read as _read
from max._core.mlrt import AsyncValue as _AsyncValue
from max._core.profiler import (
set_gpu_profiling_state,
)
from max.driver import CPU, Buffer, Device, DLPackArray, is_virtual_device_mode
from max.engine._compilation_stats import _record_phase
from max.graph import Graph, Module
from max.profiler import traced
from mojo.paths import _build_mojo_source_package, is_mojo_source_package_path
from ._precompiled_mefs import MefStore
# Manually define dlpack compatible types since MyPy isn't aware that ndarray
# implements the protocol
InputShape = list[int | str | None] | None
CustomExtensionType = str | Path
CustomExtensionsType = Sequence[CustomExtensionType] | CustomExtensionType
"""Specifies one or more custom extension libraries to load with an
:class:`InferenceSession`.
It may be a single path or a sequence of paths, where each path is a ``str``
or :class:`~pathlib.Path` pointing to a compiled ``.mojoc`` custom ops
library or a ``.mojo`` source file. When a ``.mojo`` source path is provided,
it's automatically compiled into a package before loading.
"""
# Need to use tuple instead of Union to ensure that Python 3.9 support works
ScalarType = (int, float, bool, np.generic)
InputType = DLPackArray | Buffer | int | float | bool | np.generic
GPUProfilingMode = Literal["off", "on", "detailed"]
"""The supported modes for GPU profiling.
GPU profiling modes control the level of instrumentation when profiling
MAX applications with NVIDIA Nsight Systems or Nsight Compute. Higher
levels provide more detail but may introduce additional overhead.
- ``off`` (default): Disable GPU profiling instrumentation. Incurs no
profiling overhead.
- ``on``: Enable basic GPU profiling. Adds CUDA driver calls and NVTX
markers for correlating kernel executions with host-side code.
- ``detailed``: Enable detailed GPU profiling with additional NVTX
markers from Python code. This mode provides the most visibility into
which Python operations correspond to which GPU kernels, but has the
highest overhead.
See Also:
:meth:`InferenceSession.gpu_profiling`: Method to set the profiling mode.
"""
# TODO(GEX-2071): Remove global lock when parallel compilation is safe.
_COMPILATION_LOCK = threading.Lock()
def _raise_if_not_contiguous(x: InputType) -> None:
should_raise = False
if isinstance(x, bool):
return
elif _is_torch_tensor(x):
# This code does not import torch, so we ignore the type checker here
if not x.is_contiguous(): # type: ignore
should_raise = True
elif isinstance(x, np.ndarray) and not x.flags.c_contiguous:
should_raise = True
elif isinstance(x, Buffer) and not x.is_contiguous:
should_raise = True
if should_raise:
raise ValueError(
"Max does not currently support executing"
" non-contiguous tensors. Before passing these"
" tensors to Max, please make a contiguous copy of them"
" using `.contiguous()` before feeding them into the"
" `execute` or `load` APIs."
)
@traced
def _Model_execute(self: Model, *args: InputType) -> list[Buffer]:
# Original tensor-only execution path
input_impls: list[Buffer] = []
for idx, arg in enumerate(args):
_raise_if_not_contiguous(arg)
# Validate that input is one of supported types and convert if
# necessary.
if isinstance(arg, Buffer):
buffer = arg
elif isinstance(arg, DLPackArray):
buffer = Buffer.from_dlpack(arg)
elif isinstance(arg, ScalarType):
spec = self.input_metadata[idx]
buffer = Buffer.scalar(arg, spec.dtype, self.input_devices[idx])
else:
raise ValueError(
"All positional arguments must be of the type"
" `max.driver.Buffer` or a tensor type"
" implementing the dlpack protocol. We do not"
f" currently support inputs of the type {type(arg)}."
)
input_impls.append(buffer)
_validation_hooks.mark_used(input_impls)
return self._execute_device_tensors(input_impls)
def _Model_call(
self: Model, *args: InputType, **kwargs: InputType
) -> list[Buffer]:
bound = self.signature.bind(*args, **kwargs)
return self.execute(*bound.arguments.values())
def _Model_repr(self: Model) -> str:
return f"Model(inputs={self.input_metadata})"
def _Model_signature(self: Model) -> Signature:
"""Get input signature for model."""
parameters = [
Parameter(input.name, Parameter.POSITIONAL_OR_KEYWORD)
for input in self.input_metadata
]
return Signature(parameters=parameters)
def _normalize_graph_key(graph_key: int) -> int:
if isinstance(graph_key, bool) or not isinstance(graph_key, int):
raise TypeError("graph_key must be an int.")
if graph_key < 0 or graph_key > 2**64 - 1:
raise ValueError("graph_key must be in range [0, 2^64 - 1].")
return graph_key
def _normalize_graph_keys(graph_keys: int | Sequence[int]) -> list[int]:
if isinstance(graph_keys, bool):
raise TypeError("graph_keys must be an int or sequence of ints.")
if isinstance(graph_keys, int):
return [_normalize_graph_key(graph_keys)]
if isinstance(graph_keys, (str, bytes)):
raise TypeError("graph_keys must be a sequence of ints.")
normalized: list[int] = []
for graph_key in graph_keys:
normalized.append(_normalize_graph_key(graph_key))
if not normalized:
raise ValueError("graph_keys must not be empty.")
return normalized
def _Model_capture(
self: Model, graph_keys: int | Sequence[int], *inputs: Buffer
) -> list[Buffer]:
"""Capture execution into a device graph for caller-provided key.
Capture is best-effort and model-dependent. If the model issues
capture-unsafe operations (for example, host-device synchronization),
graph capture may fail. Callers should choose capture-safe execution paths.
"""
if not inputs:
raise ValueError("Model.capture requires input buffers.")
normalized_keys = _normalize_graph_keys(graph_keys)
return self._capture(normalized_keys, list(inputs))
def _Model_replay(
self: Model, graph_keys: int | Sequence[int], *inputs: Buffer
) -> None:
"""Replay the captured device graph for a caller-provided key."""
if not inputs:
raise ValueError("Model.replay requires input buffers.")
normalized_keys = _normalize_graph_keys(graph_keys)
self._replay(normalized_keys, list(inputs))
def _Model_debug_verify_replay(
self: Model, graph_keys: int | Sequence[int], *inputs: Buffer
) -> None:
"""Execute eagerly and verify the launch trace matches the captured graph.
This method validates that graph capture correctly represents eager
execution by running the model and comparing kernel launch sequences
against a previously captured device graph.
For example, capture a graph, verify its replay, then replay it:
.. code-block:: python
model.capture([1, 1], input_tensor)
model.debug_verify_replay([1, 1], input_tensor)
model.replay([1, 1], input_tensor)
Args:
self: The model to debug/verify
graph_keys: Caller-provided graph key or per-device keys identifying
captured graphs.
inputs: Input buffers matching the captured input signature (same
shapes and dtypes used during capture).
Raises:
TypeError: If ``graph_keys`` is neither an int nor a sequence of ints.
ValueError: If any key in ``graph_keys`` is out of uint64 range.
ValueError: If no input buffers are provided.
RuntimeError: If no graph has been captured for ``graph_keys``.
RuntimeError: If the eager execution trace doesn't match the captured graph.
"""
if not inputs:
raise ValueError("Model.debug_verify_replay requires input buffers.")
normalized_keys = _normalize_graph_keys(graph_keys)
self._debug_verify_replay(normalized_keys, list(inputs))
def _Model_release_captured_graph(
self: Model, graph_keys: int | Sequence[int]
) -> None:
"""Releases a previously captured device graph and its working memory.
Drops the runtime-side reference for the given key(s); the underlying
device graph and its captured-time scratch buffers are freed once any
in-flight replay completes. Releasing a key that was never captured is
a no-op.
Note that the caller is still responsible for dropping any output
:class:`Buffer` handles returned by the corresponding
:meth:`Model.capture` call. Those buffers reference device memory that
the runtime cannot reclaim while Python references remain.
For example, capture a graph, drop the output handles, then release the
captured graph:
.. code-block:: python
outputs = model.capture(42, input_tensor)
model.replay(42, input_tensor)
del outputs # Drop Python-side handles first.
model.release_captured_graph(42)
Args:
self: The model whose captured graph should be released.
graph_keys: Caller-provided graph key or per-device keys identifying
captured graphs to release.
Raises:
TypeError: If ``graph_keys`` is neither an int nor a sequence of ints.
ValueError: If any key in ``graph_keys`` is out of uint64 range.
"""
normalized_keys = _normalize_graph_keys(graph_keys)
self._release_captured_graph(normalized_keys)
Model.execute = _Model_execute # type: ignore[method-assign]
Model.__call__ = _Model_call # type: ignore[method-assign]
Model.__repr__ = _Model_repr # type: ignore[assignment, method-assign]
Model.signature = property(_Model_signature) # type: ignore[assignment]
Model.capture = _Model_capture # type: ignore[method-assign]
Model.replay = _Model_replay # type: ignore[method-assign]
Model.debug_verify_replay = _Model_debug_verify_replay # type: ignore[method-assign]
Model.release_captured_graph = _Model_release_captured_graph # type: ignore[method-assign]
def _TensorSpec_str(self: TensorSpec) -> str:
if self.shape is not None:
mlir_shape = [
str(dim) if dim is not None else "-1" for dim in self.shape
]
shape_str = "x".join(mlir_shape)
return f"{shape_str}x{self.dtype.name}"
else:
return f"None x {self.dtype.name}"
def _TensorSpec_repr(self: TensorSpec) -> str:
return (
f"TensorSpec(shape={self.shape}, dtype={self.dtype}, name={self.name})"
)
TensorSpec.__str__ = _TensorSpec_str # type: ignore[assignment, method-assign]
TensorSpec.__repr__ = _TensorSpec_repr # type: ignore[assignment, method-assign]
def _is_torch_tensor(obj: Any) -> bool:
"""Checks if an object is a `torch.Tensor`."""
t = type(obj)
return t.__module__ == "torch" and t.__name__ == "Tensor"
def _process_custom_extensions_object(
custom_extension: CustomExtensionType,
) -> CustomExtensionType:
if is_mojo_source_package_path(Path(custom_extension)):
# Builds the source directory into a .mojoc file.
return _build_mojo_source_package(Path(custom_extension))
# Pass the path through as is.
return custom_extension
def _process_custom_extensions_objects(
custom_extensions: CustomExtensionsType,
) -> list[CustomExtensionType]:
if not isinstance(custom_extensions, Iterable) or isinstance(
custom_extensions, str
):
custom_extensions = [custom_extensions]
return [
_process_custom_extensions_object(custom_extension)
for custom_extension in custom_extensions
]
def _derive_pipeline_name(module: Module) -> str:
"""Concatenate the sym_names of every non-subgraph `mo.graph` in `module`.
Used as the diagnostic ``pipelineName`` passed to
``compile_from_object``; replaces the previous reliance on ``Graph.name``
so the public :class:`Module` overload doesn't need a separate name kwarg.
"""
return "+".join(module.top_level_graph_names())
class SplitKReductionPrecision(IntEnum):
"""Internal use."""
ACCUM = auto()
OUTPUT = auto()
class AssertLevel(str, Enum):
"""Which Mojo asserts are kept in the compiled model.
Set with :meth:`InferenceSession.set_mojo_assert_level`.
"""
NONE = "none"
WARN = "warn"
SAFE = "safe"
ALL = "all"
class LogLevel(str, Enum):
"""Verbosity of Mojo logging in the compiled model.
Set with :meth:`InferenceSession.set_mojo_log_level`.
"""
NOTSET = "notset"
"""No Mojo logging at all."""
TRACE = "trace"
"""Finest-grained logging; more detail than ``DEBUG``."""
DEBUG = "debug"
"""Detailed diagnostic information."""
INFO = "info"
"""Confirmation that things are working as expected."""
WARNING = "warning"
"""A sign that something unexpected happened; execution continues."""
ERROR = "error"
"""A failure in part of the run."""
CRITICAL = "critical"
"""A failure so serious the run cannot continue."""
class CompilationStopped(RuntimeError):
"""Raised by :meth:`InferenceSession.compile` when ``pre_jit`` stopped it.
With :attr:`DebugConfig.pre_jit` set, the graph compiler writes the Mojo
for the graph into :attr:`DebugConfig.ir_output_dir` and stops there, so
there is no compiled artifact to return. This is the requested outcome,
not a failure; callers that only wanted the emitted Mojo catch it and
carry on.
"""
class CompiledModel:
"""A compiled model artifact, ready for initialization with weights.
Returned by :meth:`InferenceSession.compile`. Pass it to
:meth:`InferenceSession.init` or :meth:`InferenceSession.init_all` to
produce executable :class:`Model` instances.
A :class:`CompiledModel` is not directly executable: compilation is
independent of the device-memory allocations performed during
initialization, so a single artifact can be initialized more than once.
"""
# A pending compile() handle, or the plain resolved artifact from read().
_compiled: _AsyncValue[_CompiledModels] | _CompiledModels
_expected_weights: dict[str, Any] | None
# Top-level graph names captured from the source MLIR module when known.
# Empty for path-compiled artifacts (no module to inspect). Used by the
# virtual-device-mode short-circuit in ``init_all``; the non-virtual path
# derives keys from each runtime ``Model.name`` instead.
_graph_names: tuple[str, ...]
def __init__(
self,
compiled: _AsyncValue[_CompiledModels] | _CompiledModels,
expected_weights: dict[str, Any] | None,
) -> None:
# Internal constructor; users obtain instances from
# :meth:`InferenceSession.compile` or :func:`read`.
self._compiled = compiled
self._expected_weights = expected_weights
self._graph_names = ()
def __repr__(self) -> str:
return "CompiledModel()"
def export_mef(self, path: str | Path) -> None:
"""Exports this compiled artifact to a MEF file.
Writes the serialized model straight from the compiled artifact, so
it does not require the model to be initialized on a device. This
makes it usable in cross-compilation / virtual-device scenarios where
the target device may not be attached.
Args:
path: Filesystem path to write the MEF to.
"""
if isinstance(self._compiled, _CompiledModels):
self._compiled.export_mef(str(path))
return
self._compiled.wait()
if (exc := self._compiled.exception()) is not None:
raise exc
self._compiled.result().export_mef(str(path))
class CompileOnlyExecutionError(RuntimeError):
"""A model compiled under virtual devices was asked to do something real."""
class CompileOnlyModel:
"""Stands in for a :class:`Model` compiled under virtual devices.
A virtual device compiles for hardware that is not attached, so the compile
half of a load finishes and the initialize half has nothing to do. Callers
doing exactly that -- cross-compiling, benchmarking a compile -- want the
load to return, so it returns this: an object that carries what was compiled
and raises :class:`CompileOnlyExecutionError` from everything that would
need the device. A stand-in that answered those calls with placeholder
values would move the failure to whatever consumed them.
"""
def __init__(self, name: str, compiled: CompiledModel) -> None:
self.name = name
self.compiled = compiled
def __repr__(self) -> str:
return f"CompileOnlyModel({self.name!r})"
def _refuse(self, what: str) -> NoReturn:
"""Raises, naming what was asked of a model that was never initialized.
Args:
what: The member the caller reached for.
Raises:
CompileOnlyExecutionError: Always.
"""
raise CompileOnlyExecutionError(
f"{what} needs the device that graph {self.name!r} was compiled "
"for, and it was compiled under a virtual device, which stands in "
"for hardware that is not attached. Initialize the compiled "
"artifact on a real device to execute it."
)
def execute(self, *args: object, **kwargs: object) -> NoReturn:
"""Raises: a compile-only stand-in has nothing to execute on."""
self._refuse("execute")
# Explicit, unlike the refusals below, so that this stays callable: a
# caller testing `callable(model)` gets the same answer a Model gives.
__call__ = execute
def __getattr__(self, name: str) -> NoReturn:
"""Refuses any :class:`Model` member this stand-in does not carry.
Every member is refused rather than enumerated, because a load returns
this where a :class:`Model` is expected: one left out answers with an
:class:`AttributeError`, which reads as a broken caller rather than as
the absence of the device, and a member added to :class:`Model` later
would be left out silently.
Args:
name: The member the caller reached for.
Raises:
CompileOnlyExecutionError: If :class:`Model` carries ``name``.
AttributeError: If it does not, as any object would.
"""
if hasattr(Model, name):
self._refuse(name)
raise AttributeError(name)
def read(source: str | os.PathLike[str] | BinaryIO) -> CompiledModel:
"""Reads a previously exported compiled-model artifact (a ``.mef``).
Args:
source: The path to a ``.mef`` file, or a binary file-like
object (anything with ``read()``, such as :class:`io.BytesIO`)
positioned at the start of the artifact.
Returns:
A :class:`CompiledModel` holding the deserialized artifact, ready
to be initialized on any session via :meth:`InferenceSession.init`.
Raises:
RuntimeError: If the artifact is missing or cannot be
deserialized.
"""
if isinstance(source, (str, os.PathLike)):
artifact = _read(source)
else:
artifact = _read(source.read())
return CompiledModel(compiled=artifact, expected_weights=None)
class InferenceSession:
"""Manages an inference session in which you can load and run models.
You need an ``InferenceSession`` instance to load a model as a
:class:`~max.engine.Model` object. For example:
.. code-block:: python
from max.driver import CPU, Accelerator, accelerator_count
from max.dtype import DType
from max.engine import InferenceSession
from max.graph import DeviceRef, Graph, ops
device = Accelerator() if accelerator_count() > 0 else CPU()
device_ref = DeviceRef.from_device(device)
with Graph("add") as graph:
graph.output(
ops.add(
ops.constant([1.0, 2.0], DType.float32, device=device_ref),
ops.constant([3.0, 4.0], DType.float32, device=device_ref),
)
)
session = InferenceSession(devices=[device])
model = session.load(graph)
.. invisible-code-block: python
import numpy as np
assert np.allclose(model.execute()[0].to_numpy(), [4.0, 6.0])
For workflows that need to separate compilation from weight binding,
use :meth:`compile` followed by :meth:`init` or :meth:`init_all`.
For example:
.. code-block:: python
from max.driver import CPU, Accelerator, accelerator_count
from max.dtype import DType
from max.engine import InferenceSession
from max.graph import DeviceRef, Graph, ops
device = Accelerator() if accelerator_count() > 0 else CPU()
device_ref = DeviceRef.from_device(device)
with Graph("add") as graph:
graph.output(
ops.add(
ops.constant([1.0, 2.0], DType.float32, device=device_ref),
ops.constant([3.0, 4.0], DType.float32, device=device_ref),
)
)
session = InferenceSession(devices=[device])
compiled = session.compile(graph)
model = session.init(compiled)
.. invisible-code-block: python
import numpy as np
assert np.allclose(model.execute()[0].to_numpy(), [4.0, 6.0])
Args:
devices: A list of devices on which to run inference. The host CPU
is always included automatically.
num_threads: The number of execution threads. Defaults to ``None``,
which lets the runtime choose automatically.
custom_extensions: The extensions to load for the model. Supports
paths to a ``.mojoc`` custom ops library or a ``.mojo`` source file.
precompiled_mefs: A directory of compiled-graph artifacts written by an
earlier session's ``export_mefs``, or several of them -- a large set
of graphs is often split across producers. Every graph this session
loads is initialized from its artifact instead of being compiled,
which lets the compiling and the executing run happen on different
machines. Raises if a graph has no artifact.
export_mefs: A directory to write a compiled-graph artifact into for
every graph this session loads, alongside a manifest describing
them. Pass the same directory as another session's
``precompiled_mefs`` to reuse them. Mutually exclusive with it.
"""
_impl: _InferenceSession
# DebugConfig is a process-wide singleton. Assigning it as a class
# attribute at import time means both ``InferenceSession.debug`` and
# ``session.debug`` return the same underlying object, and any
# ``MODULAR_DEBUG`` env-var parsing happens exactly once (at import).
debug: DebugConfig = _InferenceSession.debug
default_mef_store: ClassVar[MefStore | None] = None
"""The store a session consults when given neither ``precompiled_mefs``
nor ``export_mefs``.
For a caller that does not construct the session itself -- a test harness
running code that builds its own -- and so has nowhere to pass one. An
explicit ``precompiled_mefs``/``export_mefs`` always wins, and this is read
when a graph is compiled rather than when the session is constructed, so
installing it after a session exists still governs that session.
A process wants exactly one store object here: :meth:`MefStore.write_manifest`
writes the entries of the store it is called on, so artifacts exported
through a store that was swapped out go unnamed by the manifest that
follows.
"""
def __init__(
self,
devices: Iterable[Device] = (),
num_threads: int | None = None,
*,
custom_extensions: CustomExtensionsType | None = None,
precompiled_mefs: str | Path | Iterable[str | Path] | None = None,
export_mefs: str | Path | None = None,
) -> None:
if precompiled_mefs is not None and export_mefs is not None:
raise ValueError(
"pass at most one of precompiled_mefs and export_mefs: a "
"session either reuses artifacts or produces them"
)
# Taken at construction rather than settable later because the store
# tracks its position through the graphs this session loads.
self._mef_store: MefStore | None = None
if precompiled_mefs is not None:
self._mef_store = MefStore.for_import(precompiled_mefs)
elif export_mefs is not None:
self._mef_store = MefStore.for_export(export_mefs)
self.num_threads = num_threads
# Process the provided iterable `devices`.
final_devices: list[Device] = []
seen_devices: set[Device] = set()
for device in devices:
if device not in seen_devices:
final_devices.append(device)
seen_devices.add(device)
host_cpu = CPU()
if host_cpu not in seen_devices:
final_devices.append(host_cpu)
seen_devices.add(host_cpu)
custom_extensions_final = []
if custom_extensions:
custom_extensions_final = _process_custom_extensions_objects(
custom_extensions
)
self._impl = _InferenceSession(
final_devices,
custom_extensions_final,
num_threads or 0,
)
# Register async-safe Python stack trace handler
# This enables Python stack traces in crash reports without GIL deadlocks
try:
faulthandler.register(
signal.SIGUSR2, file=sys.stderr, all_threads=True, chain=False
)
except (OSError, RuntimeError):
# Ignore errors if SIGUSR2 is already registered or unavailable
pass
# Read the op log level from the max-debug.op-log-level config key
# (covers MODULAR_MAX_DEBUG_OP_LOG_LEVEL env var, modular.cfg, and
# InferenceSession.debug.op_log_level Python setter).
if log_level := _InferenceSession.debug.op_log_level:
self.set_mojo_log_level(log_level)
# Read the assert level from the max-debug.assert-level Config key.
if assert_level_str := _InferenceSession.debug.assert_level:
try:
assert_level = AssertLevel[assert_level_str.upper()]
except KeyError as e:
raise TypeError(
f"Invalid assert level ({assert_level_str}). Please use one of: {[x.name for x in AssertLevel]}"
) from e
self.set_mojo_assert_level(assert_level)
if use_fi_topk := os.getenv("USE_FI_TOPK_KERNEL"):
self.use_fi_topk_kernel(use_fi_topk)
if val := os.getenv("ENABLE_PER_TENSOR_FP8_QUANTIZE"):
self.enable_per_tensor_fp8_quantize(val)
# Read the uninit-read check from the max-debug.uninitialized-read-check
# Config key.
if _InferenceSession.debug.uninitialized_read_check:
# The mode picks what a match does: "abort" stops at the first
# one, "report" prints it and keeps running so a single run
# enumerates every offending load, which matters when a run is
# expensive enough that iterating one site at a time is not
# affordable.
mode = _InferenceSession.debug.uninitialized_read_mode or "abort"
if mode not in ("abort", "report"):
raise ValueError(
f"Invalid uninitialized read mode ({mode}). Please use one"
" of: abort, report"
)
# Enable debug allocator poison
existing = os.environ.get("MODULAR_DEBUG_DEVICE_ALLOCATOR", "")
if existing:
if "uninitialized-poison" not in existing:
os.environ["MODULAR_DEBUG_DEVICE_ALLOCATOR"] = (
existing + ",uninitialized-poison"
)
else:
os.environ["MODULAR_DEBUG_DEVICE_ALLOCATOR"] = (
"uninitialized-poison"
)
# Enable compile-time checks
self._set_mojo_define(
"MOJO_STDLIB_SIMD_UNINIT_CHECK",
"report" if mode == "report" else "true",
)
def __repr__(self) -> str:
if self.num_threads:
return f"<modular engine InferenceSession(num_threads={self.num_threads})>"
else:
return "<modular engine InferenceSession>"
def load(
self,
model: str | Path | Graph,
*,
custom_extensions: CustomExtensionsType | None = None,
weights_registry: Mapping[str, DLPackArray] | None = None,
tile_based_fusion: bool = False,
) -> Model:
"""Loads a trained model and compiles it for inference.
.. note::
This method combines compilation and weight binding in a single
call and will be deprecated over time. New code should call
:meth:`compile` followed by :meth:`init` instead, which separates
the two steps and lets you reuse a compiled artifact across
multiple initializations.
Args:
model: A :class:`Graph` instance, or the path to a saved model
file (for example, a ``.mef`` file).
custom_extensions: The extensions to load for the model.
Supports paths to ``.mojoc`` custom ops.
weights_registry: A mapping from model weight names to their
values. The values should be DLPack arrays. If an array is a
read-only NumPy array, you must ensure that its lifetime
extends beyond the lifetime of the model. Although
``weights_registry`` is technically optional, you'll always
need to load weights in practice.
tile_based_fusion: When ``True``, compile the graph under the tile-based
programming model. Only applies when ``model`` is a
:class:`Graph`; ignored for precompiled ``.mef`` paths.
Defaults to ``False``.
Returns:
The loaded model, compiled and ready to execute.
Raises:
RuntimeError: If the path provided is invalid.
"""
models = self.load_all(
model,
custom_extensions=custom_extensions,
weights_registry=weights_registry,
tile_based_fusion=tile_based_fusion,
)
if len(models) != 1:
raise ValueError(
f"Expected exactly one model in the compiled artifact, but "
f"got {len(models)}. Use load_all() to load multi-model artifacts."
)
return next(iter(models.values()))
def load_all(
self,
model: str | Path | Module | Graph,
*,
custom_extensions: CustomExtensionsType | None = None,
weights_registry: Mapping[str, DLPackArray] | None = None,
tile_based_fusion: bool = False,
) -> dict[str, Model]:
"""Loads multiple models and compiles them for inference.
A compiled ``.mef`` artifact may contain more than one model (for
example, a vision encoder and a language model compiled together).
This method returns one :class:`Model` per model encoded in the
artifact, keyed by the ``sym_name`` of the corresponding ``mo.graph``
op (preserved through MEF serialization). For single-model
artifacts, the returned dict has exactly one entry.
.. note::
This method combines compilation and weight binding in a single
call and will be deprecated over time. New code should call
:meth:`compile` followed by :meth:`init_all` instead, which
separates the two steps and lets you reuse a compiled artifact
across multiple initializations.
Args:
model: A :class:`max.graph.Module` containing one or more
``mo.graph`` ops, the path to a saved multi-model file (for
example, a ``.mef`` file), or a single :class:`Graph`.
custom_extensions: The extensions to load for the model.
Supports paths to ``.mojoc`` custom ops.
weights_registry: A mapping from model weight names to their
values. The values should be DLPack arrays. If an array is a
read-only NumPy array, you must ensure that its lifetime
extends beyond the lifetime of the model. Although
``weights_registry`` is technically optional, you'll always
need to load weights in practice.
tile_based_fusion: When ``True``, compile the graph under the tile-based
programming model. Only applies when ``model`` is a
:class:`Graph` or :class:`max.graph.Module`; ignored for
precompiled ``.mef`` paths. Defaults to ``False``.
Returns:
A mapping from each model's ``sym_name`` to its loaded
:class:`Model`, ready to execute.
Raises:
RuntimeError: If the path provided is invalid.
"""
compiled = self.compile_reusing_mefs(
model,
custom_extensions=custom_extensions,
tile_based_fusion=tile_based_fusion,
)
return self.init_all(compiled, weights_registry=weights_registry)
def compile_reusing_mefs(
self,
model: str | Path | Module | Graph,
*,
custom_extensions: CustomExtensionsType | None = None,
tile_based_fusion: bool = False,
) -> CompiledModel:
"""Compiles ``model``, or reuses an artifact if the session has a store.
The compiling half of :meth:`load_all`, split out for callers that trace
a graph and initialize it themselves rather than handing it over -- a
:class:`~max.experimental.nn.Module`, for one, which keeps the compiled
artifact and the input/output plumbing it derived alongside it. Without
this they would call :meth:`compile` and silently bypass the session's
``precompiled_mefs``/``export_mefs``.
Behaves exactly like :meth:`compile` on a session with no store at all,
and only :class:`~max.graph.Graph` models participate: the store
identifies an artifact by a graph's name and signature. A session
constructed with neither consults the process-wide store installed with
:attr:`default_mef_store`, if one is installed; an explicit
``precompiled_mefs``/``export_mefs`` always wins.
Args:
model: As :meth:`compile`.
custom_extensions: As :meth:`compile`. Ignored when reusing an
artifact, which is already compiled.
tile_based_fusion: As :meth:`compile`. Ignored when reusing an
artifact.
Returns:
The compiled artifact, ready for :meth:`init` or :meth:`init_all`.
Raises:
RuntimeError: If reusing and no recorded artifact matches
``model``'s name and signature.
"""
# See `_precompiled_mefs` for why a caller would want this: it lets the
# compile happen somewhere that holds no accelerator.
store = (
self._mef_store
if self._mef_store is not None
else InferenceSession.default_mef_store
)
if store is None or not isinstance(model, Graph):
return self.compile(
model,
custom_extensions=custom_extensions,
tile_based_fusion=tile_based_fusion,
)
if not store.exporting:
artifact = store.claim_import(model)
# A store with nothing to say about this graph declines it, and
# the compile happens here as it would with no store at all.
if artifact is not None:
return self.compile(artifact)
return self.compile(
model,
custom_extensions=custom_extensions,
tile_based_fusion=tile_based_fusion,
)
compiled = self.compile(
model,
custom_extensions=custom_extensions,
tile_based_fusion=tile_based_fusion,
)
compiled.export_mef(store.claim_export(model))
store.write_manifest()
return compiled
def compile_async(
self,
model: str | Path | Module | Graph,
*,
custom_extensions: CustomExtensionsType | None = None,
tile_based_fusion: bool = False,
) -> CompiledModel:
"""Compiles a model without blocking on the compilation finishing.
Returns as soon as the compile is scheduled; the returned
:class:`CompiledModel` wraps a pending compilation that runs on the
runtime's worker pool. Compilation errors are not raised here — they
surface when the artifact is awaited, for example by :meth:`init`,
:meth:`init_all`, or :meth:`CompiledModel.export_mef`. Use
:meth:`compile` for the synchronous variant that blocks and raises.
Compiles are serialized process-wide: if another compile is in
flight (from any session), this call blocks until it resolves
before scheduling this one.
Args:
model: A :class:`Graph` instance, a :class:`max.graph.Module`
containing one or more ``mo.graph`` ops, or the path to a
saved model file (for example, a ``.mef`` file).
custom_extensions: The extensions to load for the model.
Supports paths to ``.mojoc`` custom ops.
tile_based_fusion: When ``True``, compile the graph under the tile-based
programming model, in which the graph compiler selects
tile-based kernels (operating on ``TileTensor`` values instead
of SIMD). Only applies when ``model`` is a :class:`Graph` or