Skip to content

Engines

src.engines

src.engines.base_engine

Abstract base engine for multi-backend LLM inference.

This module provides the foundation for Erudi's multi-engine architecture, supporting MLX (Apple Silicon), CUDA (NVIDIA GPUs), and CPU fallback. The engine abstraction enables consistent model loading, quantization, and streaming inference across different hardware backends.

Fonctionnalités: - Automatic engine selection based on platform and hardware - Singleton pattern with shared model state across requests - Automatic memory cleanup after idle timeout - Streaming token generation API - Engine-format gate (FORMAT_TAG): only pre-built artefacts are ever loaded

Architecture

BaseEngine (ABC) ├── MLX_Engine (Apple Silicon) ├── CUDA_Engine (NVIDIA GPUs) └── CPU_Engine (Fallback)

Examples:

Get appropriate engine for current platform: from src.engines.base_engine import BaseEngine engine_class = BaseEngine.get_engine() model, tokenizer = engine_class.get_model_and_tokenizer( llm_id="1", llm_local_path="backend/data/models/llama-7b" )

Stream tokens (driven by the agent layer, not the engine): the model handle's base_url is consumed by ChatOpenAI in src.agents.model_factory; the engine only spawns / probes / reaps the OpenAI-compatible server.

BaseEngine()

Bases: ABC

Abstract base class for all LLM inference engines.

Implements singleton pattern with shared model state, automatic cleanup, and platform-aware engine selection. Subclasses must implement backend- specific model loading and inference methods.

Class Attributes

_model: Currently loaded model instance (shared across all engines). _tokenizer: Currently loaded tokenizer instance. _model_id: ID of the currently loaded model. _last_used: Timestamp of last model access for cleanup tracking. _cleanup_task: Async task monitoring idle time. _max_idle_time: Seconds before automatic memory cleanup (default: 300). MODEL_MAPPING: Dictionary mapping model architectures to classes.

Context windows -- two numbers that must never be confused:

  • max_context_tokens() is the declared ceiling: the window the configuration imposes on every spawn (ERUDI_CTX when the user pinned one), or None when nothing is imposed. It exists before any model is loaded and never depends on which model is.
  • effective_context_tokens() is the allocated window: what the CURRENTLY LOADED child actually runs with, read from the live engine handle. It only exists while a child is up, differs per model AND per machine/memory state (llama-server's fit can shrink it below the model's trained window), and is therefore never stored in the database.

Consumers that budget or warn against "the window" (compaction thresholds, the first-token watchdog, the UI's allocated-window display) must read the allocated window; only the sampling resolver's max_tokens_cap reads the declared ceiling, because it describes configuration, not a running child.

Note

Do not instantiate directly. Use get_engine() to obtain the appropriate engine class, then call class methods for operations.

Prevent direct instantiation.

Raises:

Type Description
RuntimeError

Always raised as engines use class methods only.

Source code in backend/src/engines/base_engine.py
def __init__(self):
    """Prevent direct instantiation.

    Raises:
        RuntimeError: Always raised as engines use class methods only.

    """
    raise RuntimeError("Use the methods instead of instantiating")

begin_memory_window() classmethod

Open a measurement window on the loaded child for one turn; the returned token closes it (end_memory_window). No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def begin_memory_window(cls) -> Any:
    """Open a measurement window on the loaded child for one turn; the
    returned token closes it (``end_memory_window``). No-op here."""
    return None

brake_point(point, *, llm_id=None) classmethod

Take the brake's sample at a safe point (turn_start for llm_id, turn_end, idle) and act on it. No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def brake_point(cls, point: str, *, llm_id: Any = None) -> BrakeOutcome:
    """Take the brake's sample at a safe point (``turn_start`` for
    ``llm_id``, ``turn_end``, ``idle``) and act on it. No-op here."""
    return BrakeOutcome()

brake_reload_pending(llm_id) classmethod

Whether the next turn for llm_id reloads a model the brake unloaded (or, on the CPU engine, re-prefills a child it respawned). Never here.

Source code in backend/src/engines/base_engine.py
@classmethod
def brake_reload_pending(cls, llm_id: Any) -> bool:
    """Whether the next turn for ``llm_id`` reloads a model the brake
    unloaded (or, on the CPU engine, re-prefills a child it respawned).
    Never here."""
    return False

chat_template_caps(llm_id=None) classmethod

What the CURRENTLY LOADED child reported about its chat template.

llama.cpp engines stamp the server's chat_template_caps map on the handle during the one /props read at spawn -- nine booleans evaluated by llama.cpp's own symbolic execution of the template, of which supports_reasoning_effort drives the reasoning-effort lever. Engines whose server reports nothing (MLX) return an empty map, and so does a child that is down or serving another model.

llm_id guards exactly that: capabilities belong to the artifact the child was spawned for, so a caller planning a turn for a DIFFERENT model gets nothing rather than the loaded model's answers.

Source code in backend/src/engines/base_engine.py
@classmethod
def chat_template_caps(cls, llm_id: Any = None) -> dict:
    """What the CURRENTLY LOADED child reported about its chat template.

    llama.cpp engines stamp the server's ``chat_template_caps`` map on the
    handle during the one ``/props`` read at spawn -- nine booleans
    evaluated by llama.cpp's own symbolic execution of the template, of
    which ``supports_reasoning_effort`` drives the reasoning-effort lever.
    Engines whose server reports nothing (MLX) return an empty map, and so
    does a child that is down or serving another model.

    ``llm_id`` guards exactly that: capabilities belong to the artifact the
    child was spawned for, so a caller planning a turn for a DIFFERENT
    model gets nothing rather than the loaded model's answers.
    """
    if llm_id is not None and cls._model_id != llm_id:
        return {}
    model = cls._model
    if isinstance(model, dict):
        caps = model.get("chat_template_caps")
        if isinstance(caps, dict):
            return caps
    return {}

claim_prefix(owner) classmethod

Make the loaded child's prefix cache belong to owner (conv:<thread id> or arena), resetting it when it held something else. No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def claim_prefix(cls, owner: str) -> None:
    """Make the loaded child's prefix cache belong to ``owner``
    (``conv:<thread id>`` or ``arena``), resetting it when it held
    something else. No-op here."""
    return None

cleanup() classmethod

Free model and tokenizer from memory, reset state.

Releases GPU/CPU memory occupied by the model and tokenizer, resets all cached state. Called automatically after idle timeout or manually when switching models.

Note

Thread-safe. Can be called explicitly or by cleanup monitor. Calls garbage collector to ensure memory is freed.

Source code in backend/src/engines/base_engine.py
@classmethod
def cleanup(cls) -> None:
    """Free model and tokenizer from memory, reset state.

    Releases GPU/CPU memory occupied by the model and tokenizer,
    resets all cached state. Called automatically after idle timeout
    or manually when switching models.

    Note:
        Thread-safe. Can be called explicitly or by cleanup monitor.
        Calls garbage collector to ensure memory is freed.

    """
    cls._idle_unload = None
    if cls._model or cls._tokenizer:
        import gc

        logger.info(f"Cleaning up model {cls._model_id}")
        cls._model = cls._tokenizer = cls._model_id = cls._last_used = None
        gc.collect()

community_search_kwargs(term) classmethod

HfApi.list_models kwargs to find models in THIS engine's runnable format across ALL of HF (any author), so community fine-tunes surface and are runnable by construction. Searches by the format TAG, not by org — e.g. filter="mlx" catches non-mlx-community quants the org never holds. An empty term is the global pass: filter by format only, ranked by downloads.

expand pulls pipeline_tag + tags (alongside the downloads/likes the quality floor needs) in the one call, so the non-chat task filter (#242) can gate ASR/embedding/OCR/media-gen repos out of the derived catalog, plus gated so a repo the token-less app cannot download is dropped (model_resolver.is_gated).

Source code in backend/src/engines/base_engine.py
@classmethod
def community_search_kwargs(cls, term: str) -> dict:
    """`HfApi.list_models` kwargs to find models in THIS engine's runnable
    format across ALL of HF (any author), so community fine-tunes surface and
    are runnable by construction. Searches by the format TAG, not by org —
    e.g. ``filter="mlx"`` catches non-mlx-community quants the org never holds.
    An empty ``term`` is the global pass: filter by format only, ranked by
    downloads.

    ``expand`` pulls pipeline_tag + tags (alongside the downloads/likes the
    quality floor needs) in the one call, so the non-chat task filter (#242)
    can gate ASR/embedding/OCR/media-gen repos out of the derived catalog,
    plus ``gated`` so a repo the token-less app cannot download is dropped
    (``model_resolver.is_gated``).
    """
    kwargs = {
        "filter": cls.FORMAT_TAG,
        "expand": ["pipeline_tag", "tags", "downloads", "likes", "gated"],
    }
    if term:
        kwargs["search"] = term
    return kwargs

compute_supports_tools(local_path) classmethod

Static tool-calling capability of the model at local_path.

Computed once at post-download time from the model's chat template by differential rendering (see engines.tool_capability): no inference, no runtime probe. Any failure (unreadable artifact, missing template) returns False so the model routes through the systematic KB path — the capability is never assumed.

Source code in backend/src/engines/base_engine.py
@classmethod
def compute_supports_tools(cls, local_path: Union[str, Path]) -> bool:
    """Static tool-calling capability of the model at ``local_path``.

    Computed once at post-download time from the model's chat template by
    differential rendering (see ``engines.tool_capability``): no inference,
    no runtime probe. Any failure (unreadable artifact, missing template)
    returns ``False`` so the model routes through the systematic KB path —
    the capability is never assumed.
    """
    from src.engines.tool_capability import tokenizer_declares_tools

    try:
        tokenizer = cls._load_capability_tokenizer(local_path)
    except Exception:
        # exc_info matters: a missing dependency in the frozen build (the
        # gguf package, #171) is indistinguishable from an unreadable model
        # without the underlying exception in the log.
        logger.warning(
            f"[{cls.__name__}] tool-calling detection: could not load a "
            f"tokenizer for {local_path}; treating as not tool-capable",
            exc_info=True,
        )
        return False
    if tokenizer is None:
        return False
    return tokenizer_declares_tools(tokenizer)

compute_wire_tools(local_path) classmethod

Verified tool-call WIRE capability of the model at local_path (#298).

compute_supports_tools says the chat template DECLARES tools; this says the engine's local server actually parses the model's tool-call output into a structured call the agent executes — a per-model wire property (#273 matrix): a template matching no parser streams the call as raw text (swallowed answer, #295) or leaks JSON to the user.

Engine-specific: MLX runs mlx-vlm's own parser inference on the chat template; llama.cpp engines trust the --jinja generic fallback for any usable template. The base default is None (unverified) so an engine without an implementation never routes a KB turn agentic.

Source code in backend/src/engines/base_engine.py
@classmethod
def compute_wire_tools(cls, local_path: Union[str, Path]) -> Optional[bool]:
    """Verified tool-call WIRE capability of the model at ``local_path`` (#298).

    ``compute_supports_tools`` says the chat template DECLARES tools; this
    says the engine's local server actually parses the model's tool-call
    output into a structured call the agent executes — a per-model wire
    property (#273 matrix): a template matching no parser streams the call
    as raw text (swallowed answer, #295) or leaks JSON to the user.

    Engine-specific: MLX runs mlx-vlm's own parser inference on the chat
    template; llama.cpp engines trust the ``--jinja`` generic fallback for
    any usable template. The base default is ``None`` (unverified) so an
    engine without an implementation never routes a KB turn agentic.
    """
    return None

consume_brake_notice() classmethod

The brake's pending notice for the user, consumed. None here.

Source code in backend/src/engines/base_engine.py
@classmethod
def consume_brake_notice(cls) -> Optional[str]:
    """The brake's pending notice for the user, consumed. None here."""
    return None

effective_context_tokens() classmethod

The ALLOCATED WINDOW: the context window of the CURRENTLY LOADED child, in tokens, or None when no child is up or the window could not be read.

Read from the live engine handle (_model): llama.cpp engines stamp it from the server's /props after boot (the CPU engine's -c, sized from the RAM budget at spawn and reduced by its memory brake; on CUDA, llama-server's own fit, which may shrink it below the model's trained window when memory demands); MLX stamps the trained window it passed at spawn as the preflight bound, then lowers it to the memory bound once the child's base footprint is measured, when memory binds (memory_bound_tokens). Never persisted anywhere -- the same model gets a different window on a different machine or memory state, so the only truthful source is the running child.

Source code in backend/src/engines/base_engine.py
@classmethod
def effective_context_tokens(cls) -> Optional[int]:
    """The ALLOCATED WINDOW: the context window of the CURRENTLY LOADED
    child, in tokens, or ``None`` when no child is up or the window could
    not be read.

    Read from the live engine handle (``_model``): llama.cpp engines stamp
    it from the server's ``/props`` after boot (the CPU engine's ``-c``,
    sized from the RAM budget at spawn and reduced by its memory brake; on
    CUDA, llama-server's own fit, which may shrink it below the model's
    trained window when memory demands); MLX stamps the trained window it passed at spawn as
    the preflight bound, then lowers it to the memory bound once the
    child's base footprint is measured, when memory binds
    (``memory_bound_tokens``). Never persisted anywhere -- the same model
    gets a different window on a different machine or memory state, so the
    only truthful source is the running child."""
    model = cls._model
    if isinstance(model, dict):
        window = model.get("context_tokens")
        if isinstance(window, int) and not isinstance(window, bool) and window > 0:
            return window
    return None

end_memory_window(token, *, abandoned=False, compaction_threshold=None) classmethod

Close the window token opened and record what the turn used, with the compaction threshold of the conversation that ran it (None: an arena turn). No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def end_memory_window(
    cls, token: Any, *, abandoned: bool = False, compaction_threshold: Optional[int] = None
) -> Any:
    """Close the window ``token`` opened and record what the turn used,
    with the compaction threshold of the conversation that ran it
    (``None``: an arena turn). No-op here."""
    return None

generation_guard() async classmethod

Serialize a full generation and suppress idle cleanup for its duration.

The agent layer wraps model resolution + the entire token stream in this guard so that: - concurrent requests for different models can't thrash the single-model engine subprocess (they serialize on one asyncio lock); - the idle-cleanup tick (_cleanup_tick) shares this SAME lock, so it cannot run — let alone reap the model — while a generation is in flight. It waits until the guard exits, by which point the idle clock has been refreshed, so no mid-generation teardown is possible.

This is the engine-level home of the invariant that generate_stream used to carry; it lives here (not in the agent layer) to keep subprocess lifecycle and concurrency inside the engine encapsulation.

The lock is taken through _acquire_generation_lock, which first drains a prefix-cache reset an earlier holder left running.

Source code in backend/src/engines/base_engine.py
@classmethod
@asynccontextmanager
async def generation_guard(cls):
    """Serialize a full generation and suppress idle cleanup for its duration.

    The agent layer wraps model resolution + the entire token stream in this
    guard so that:
      - concurrent requests for different models can't thrash the
        single-model engine subprocess (they serialize on one asyncio lock);
      - the idle-cleanup tick (``_cleanup_tick``) shares this SAME lock, so
        it cannot run — let alone reap the model — while a generation is in
        flight. It waits until the guard exits, by which point the idle
        clock has been refreshed, so no mid-generation teardown is possible.

    This is the engine-level home of the invariant that ``generate_stream``
    used to carry; it lives here (not in the agent layer) to keep subprocess
    lifecycle and concurrency inside the engine encapsulation.

    The lock is taken through ``_acquire_generation_lock``, which first
    drains a prefix-cache reset an earlier holder left running.
    """
    lock = cls._generation_lock_for_running_loop()
    # Contention diagnostic: another generation (or the cleanup tick)
    # holds the lock right now — measure how long this request waits.
    wait_start_s = time.perf_counter()
    contended = lock.locked()
    async with cls._acquire_generation_lock():
        if contended:
            wait_ms = (time.perf_counter() - wait_start_s) * 1000
            logger.debug(
                f"[{cls.__name__}] generation_guard waited {wait_ms:.0f}ms "
                f"for the generation lock (model={cls._model_id})"
            )
        logger.info(f"[{cls.__name__}] generation_guard acquired (model={cls._model_id})")
        held_start_s = time.perf_counter()
        try:
            yield
        finally:
            # Restart the idle clock from the end of the generation.
            cls._last_used = datetime.now()
            held_ms = (time.perf_counter() - held_start_s) * 1000
            logger.info(
                f"[{cls.__name__}] generation_guard released "
                f"(model={cls._model_id}, held {held_ms:.0f}ms)"
            )

get_engine() classmethod

Select and return appropriate engine class for current platform.

Automatically detects OS and hardware to choose the optimal backend: - macOS ARM (M1/M2/M3): MLX_Engine - macOS Intel: CPU_Engine - Linux/Windows with CUDA: CUDA_Engine - Linux/Windows without CUDA: CPU_Engine

Returns:

Type Description
Type[BaseEngine]

The engine class (not an instance) appropriate for this system.

Raises:

Type Description
EngineException

If no suitable engine can be determined.

Examples:

from src.engines.base_engine import BaseEngine engine_class = BaseEngine.get_engine() print(f"Using: {engine_class}") # e.g., "LLM Engine: MLX_Engine"

Source code in backend/src/engines/base_engine.py
@classmethod
def get_engine(cls) -> Type["BaseEngine"]:
    """Select and return appropriate engine class for current platform.

    Automatically detects OS and hardware to choose the optimal backend:
    - macOS ARM (M1/M2/M3): MLX_Engine
    - macOS Intel: CPU_Engine
    - Linux/Windows with CUDA: CUDA_Engine
    - Linux/Windows without CUDA: CPU_Engine

    Returns:
        The engine class (not an instance) appropriate for this system.

    Raises:
        EngineException: If no suitable engine can be determined.

    Examples:
        from src.engines.base_engine import BaseEngine
        engine_class = BaseEngine.get_engine()
        print(f"Using: {engine_class}")  # e.g., "LLM Engine: MLX_Engine"

    """
    from src.engines.mlx_engine import MLX_Engine
    from src.engines.cpu_engine import CPU_Engine
    from src.engines.cuda_engine import CUDA_Engine

    system = platform.system().lower()  # mac, linux, windows
    machine = platform.machine().lower()  # arm64, x86_64, etc.
    llm_engine = None

    try:
        # Testing override: ERUDI_FORCE_CPU=1 bypasses GPU detection entirely.
        # Use this to validate CPU fallback on a GPU machine without disabling hardware.
        if os.environ.get("ERUDI_FORCE_CPU"):
            logger.info("[ERUDI_FORCE_CPU] Forcing CPU_Engine - GPU detection skipped.")
            return CPU_Engine

        if system == "darwin":  # MacOS
            if "arm" in machine:
                llm_engine = MLX_Engine
            elif "x86" in machine:
                llm_engine = CPU_Engine
        elif system in ("linux", "windows"):
            cuda_present = False
            try:
                import pynvml as nv

                nv.nvmlInit()
                cuda_present = nv.nvmlDeviceGetCount() > 0
            except ImportError:
                # A CPU build ships without pynvml: expected, not a defect.
                logger.info("pynvml is not installed; using CPU_Engine.")
            except Exception as e:
                if type(e).__name__ in _NO_NVIDIA_DRIVER_ERRORS:
                    # No NVIDIA driver on this machine: the ordinary way a
                    # CPU-only PC boots, not a fallback worth a warning.
                    logger.info(f"No NVIDIA driver ({e}); using CPU_Engine.")
                else:
                    # A driver that is present but broken. The user lands
                    # on the processor without being told why unless this
                    # record says so.
                    logger.warning(
                        f"NVIDIA detection failed ({type(e).__name__}: {e}); "
                        f"using CPU_Engine.",
                        exc_info=True,
                    )
            if cuda_present:
                llm_engine = CUDA_Engine
            else:
                llm_engine = CPU_Engine
                logger.info(f"System: {system} and CUDA not available.")
        logger.info(f"Engine chosen: {llm_engine}")
        if llm_engine is None:
            raise RuntimeError(f"no engine matches system={system!r} machine={machine!r}")
        return llm_engine
    except Exception as e:
        raise EngineException(
            message="Error selecting the LLM Engine.",
            trace=f"{type(e).__name__}: {e}",
        )

get_flat_hardware_data() abstractmethod classmethod

Get hardware data in flat format compatible with HardwareProfile entity.

Returns hardware specifications as a flat dictionary ready for direct insertion into the HardwareProfile database entity. Combines and flattens data from get_hardware_info() and get_performance_evaluation().

Returns:

Type Description
Dict[str, Any]

Dict with keys matching HardwareProfile columns:

Dict[str, Any]

{

Common fields (all backends)

"backend_type": str, # "mlx", "cuda", "cpu" "cpu_model": str, "total_memory_gb": float, "available_memory_gb": float, "disk_total_gb": float, "disk_available_gb": float, "global_inference_score": float, "global_inference_label": str, "cpu_score": float, "memory_score": float, "gpu_score": float, "system_platform": str, "architecture": Optional[str], "estimated_tflops": Optional[float], "memory_bandwidth_gbs": Optional[float], "cpu_performance_units": Optional[float], "performance_breakdown": dict,

MLX-specific fields

"mlx_chip_model": Optional[str], "mlx_gpu_cores": Optional[int], "mps_available": Optional[bool], "neural_engine_tops": Optional[float], "unified_memory": Optional[bool], "gpu_name": Optional[str],

CUDA-specific fields

"cuda_cores": Optional[int], "cuda_version": Optional[str], "compute_capability": Optional[str], "vram_total_gb": Optional[float], "vram_available_gb": Optional[float],

Dict[str, Any]

}

Raises:

Type Description
EngineException

If hardware data collection fails.

Note

This method provides a single point of access for hardware data in the format expected by the database layer, eliminating the need for manual flattening in service layers.

Examples:

>>> engine = BaseEngine.get_engine()
>>> data = engine.get_flat_hardware_data()
>>> profile = HardwareProfile(**data)  # Direct instantiation
>>> db.add(profile)
Source code in backend/src/engines/base_engine.py
@classmethod
@abstractmethod
def get_flat_hardware_data(cls) -> Dict[str, Any]:
    """Get hardware data in flat format compatible with HardwareProfile entity.

    Returns hardware specifications as a flat dictionary ready for direct
    insertion into the HardwareProfile database entity. Combines and flattens
    data from get_hardware_info() and get_performance_evaluation().

    Returns:
        Dict with keys matching HardwareProfile columns:
        {
            # Common fields (all backends)
            "backend_type": str,  # "mlx", "cuda", "cpu"
            "cpu_model": str,
            "total_memory_gb": float,
            "available_memory_gb": float,
            "disk_total_gb": float,
            "disk_available_gb": float,
            "global_inference_score": float,
            "global_inference_label": str,
            "cpu_score": float,
            "memory_score": float,
            "gpu_score": float,
            "system_platform": str,
            "architecture": Optional[str],
            "estimated_tflops": Optional[float],
            "memory_bandwidth_gbs": Optional[float],
            "cpu_performance_units": Optional[float],
            "performance_breakdown": dict,

            # MLX-specific fields
            "mlx_chip_model": Optional[str],
            "mlx_gpu_cores": Optional[int],
            "mps_available": Optional[bool],
            "neural_engine_tops": Optional[float],
            "unified_memory": Optional[bool],
            "gpu_name": Optional[str],

            # CUDA-specific fields
            "cuda_cores": Optional[int],
            "cuda_version": Optional[str],
            "compute_capability": Optional[str],
            "vram_total_gb": Optional[float],
            "vram_available_gb": Optional[float],
        }

    Raises:
        EngineException: If hardware data collection fails.

    Note:
        This method provides a single point of access for hardware data
        in the format expected by the database layer, eliminating the need
        for manual flattening in service layers.

    Examples:
        >>> engine = BaseEngine.get_engine()
        >>> data = engine.get_flat_hardware_data()
        >>> profile = HardwareProfile(**data)  # Direct instantiation
        >>> db.add(profile)

    """
    pass

get_hardware_info() abstractmethod classmethod

Get comprehensive hardware information for this backend.

Returns detailed hardware specifications including CPU, GPU/accelerator, memory, and platform-specific details. Implementation varies by backend: - MLX: Apple Silicon chip model, unified memory, MPS availability - CUDA: NVIDIA GPU model, CUDA cores, separate VRAM - CPU: Processor model, core count, system RAM

Returns:

Type Description
Dict[str, Any]

Dict containing hardware specifications with the following structure:

Dict[str, Any]

{ "system": { "platform": str, # "Darwin", "Linux", "Windows" "platform_version": Optional[str], "machine": str, # "arm64", "x86_64", etc. "processor": str }, "cpu": { "model": str, "architecture": str, "total_cores": int, "logical_cores": int, "is_apple_silicon": bool, # MLX only "performance_cores": Optional[int], # MLX only "efficiency_cores": Optional[int], # MLX only }, "memory": { "total_memory_gb": float, "available_memory_gb": float, "memory_pressure": float, # 0.0-1.0 "memory_type": str, # "unified" (MLX) or "system" (CPU/CUDA) }, "gpu": { "gpu_name": str, "gpu_cores": Optional[int], # MLX: GPU cores, CUDA: CUDA cores "memory_bandwidth_gbs": Optional[float], "vram_total_gb": Optional[float], # CUDA only "vram_available_gb": Optional[float], # CUDA only "compute_capability": Optional[str], # CUDA only "cuda_version": Optional[str], # CUDA only "mps_supported": Optional[bool], # MLX only "unified_memory": bool, # True for MLX, False for CUDA/CPU }, "accelerator": { # MLX only "neural_engine_tops": Optional[float], "architecture": Optional[str], # "3nm", "5nm", etc. }, "storage": { "total_gb": float, "available_gb": float, "usage_percentage": float }, "backend_type": str, # "mlx", "cuda", or "cpu" "timestamp": float

Dict[str, Any]

}

Raises:

Type Description
EngineException

If hardware detection fails critically.

Note

Implementation should handle errors gracefully and return fallback values rather than raising exceptions for non-critical failures.

Examples:

>>> engine = BaseEngine.get_engine()
>>> hw_info = engine.get_hardware_info()
>>> print(f"GPU: {hw_info['gpu']['gpu_name']}")
>>> print(f"Total Memory: {hw_info['memory']['total_memory_gb']} GB")
Source code in backend/src/engines/base_engine.py
@classmethod
@abstractmethod
def get_hardware_info(cls) -> Dict[str, Any]:
    """Get comprehensive hardware information for this backend.

    Returns detailed hardware specifications including CPU, GPU/accelerator,
    memory, and platform-specific details. Implementation varies by backend:
    - MLX: Apple Silicon chip model, unified memory, MPS availability
    - CUDA: NVIDIA GPU model, CUDA cores, separate VRAM
    - CPU: Processor model, core count, system RAM

    Returns:
        Dict containing hardware specifications with the following structure:
        {
            "system": {
                "platform": str,  # "Darwin", "Linux", "Windows"
                "platform_version": Optional[str],
                "machine": str,  # "arm64", "x86_64", etc.
                "processor": str
            },
            "cpu": {
                "model": str,
                "architecture": str,
                "total_cores": int,
                "logical_cores": int,
                "is_apple_silicon": bool,  # MLX only
                "performance_cores": Optional[int],  # MLX only
                "efficiency_cores": Optional[int],  # MLX only
            },
            "memory": {
                "total_memory_gb": float,
                "available_memory_gb": float,
                "memory_pressure": float,  # 0.0-1.0
                "memory_type": str,  # "unified" (MLX) or "system" (CPU/CUDA)
            },
            "gpu": {
                "gpu_name": str,
                "gpu_cores": Optional[int],  # MLX: GPU cores, CUDA: CUDA cores
                "memory_bandwidth_gbs": Optional[float],
                "vram_total_gb": Optional[float],  # CUDA only
                "vram_available_gb": Optional[float],  # CUDA only
                "compute_capability": Optional[str],  # CUDA only
                "cuda_version": Optional[str],  # CUDA only
                "mps_supported": Optional[bool],  # MLX only
                "unified_memory": bool,  # True for MLX, False for CUDA/CPU
            },
            "accelerator": {  # MLX only
                "neural_engine_tops": Optional[float],
                "architecture": Optional[str],  # "3nm", "5nm", etc.
            },
            "storage": {
                "total_gb": float,
                "available_gb": float,
                "usage_percentage": float
            },
            "backend_type": str,  # "mlx", "cuda", or "cpu"
            "timestamp": float
        }

    Raises:
        EngineException: If hardware detection fails critically.

    Note:
        Implementation should handle errors gracefully and return fallback
        values rather than raising exceptions for non-critical failures.

    Examples:
        >>> engine = BaseEngine.get_engine()
        >>> hw_info = engine.get_hardware_info()
        >>> print(f"GPU: {hw_info['gpu']['gpu_name']}")
        >>> print(f"Total Memory: {hw_info['memory']['total_memory_gb']} GB")

    """
    pass

get_model_and_tokenizer(llm_id, llm_local_path, *args) abstractmethod classmethod

Load or retrieve cached model and tokenizer for inference.

Implements singleton pattern: returns cached model if already loaded for the given llm_id, otherwise loads from disk. Thread-safe.

Parameters:

Name Type Description Default
llm_id str

Unique identifier for the model (used for caching).

required
llm_local_path Union[str, Path]

Path to the model directory on disk.

required
*args

Engine-specific loading arguments (e.g., device, dtype).

()

Returns:

Type Description
Tuple[Any, Any]

Tuple of (model, tokenizer) ready for inference.

Raises:

Type Description
EngineException

If model loading fails.

FileNotFoundError

If model path doesn't exist.

Examples:

from src.engines.base_engine import BaseEngine engine = BaseEngine.get_engine() model, tokenizer = engine.get_model_and_tokenizer( llm_id="1", llm_local_path="backend/data/models/llama-7b" )

Source code in backend/src/engines/base_engine.py
@classmethod
@abstractmethod
def get_model_and_tokenizer(
    cls, llm_id: str, llm_local_path: Union[str, Path], *args
) -> Tuple[Any, Any]:
    """Load or retrieve cached model and tokenizer for inference.

    Implements singleton pattern: returns cached model if already loaded
    for the given llm_id, otherwise loads from disk. Thread-safe.

    Args:
        llm_id: Unique identifier for the model (used for caching).
        llm_local_path: Path to the model directory on disk.
        *args: Engine-specific loading arguments (e.g., device, dtype).

    Returns:
        Tuple of (model, tokenizer) ready for inference.

    Raises:
        EngineException: If model loading fails.
        FileNotFoundError: If model path doesn't exist.

    Examples:
        from src.engines.base_engine import BaseEngine
        engine = BaseEngine.get_engine()
        model, tokenizer = engine.get_model_and_tokenizer(
            llm_id="1",
            llm_local_path="backend/data/models/llama-7b"
        )

    """
    pass

get_performance_evaluation() abstractmethod classmethod

Calculate comprehensive performance metrics and scores for this backend.

Evaluates hardware capabilities and returns performance scores for inference workloads. Scoring methodology varies by backend but results are normalized to 0-100 scale for cross-platform comparison.

Scoring Components
  • Inference Score: Optimized for generation speed and latency. Weights: GPU/accelerator compute (35-60%), memory bandwidth (20-30%), memory capacity (10-30%), CPU (5-10%).

Returns:

Type Description
Dict[str, Any]

Dict containing performance metrics and scores:

Dict[str, Any]

{

Hardware identification

"backend_type": str, # "mlx", "cuda", "cpu" "accelerator_name": str, # GPU/chip model "cpu_model": str,

Memory metrics

"total_memory_gb": float, "available_memory_gb": float, "memory_bandwidth_gbs": Optional[float],

Storage metrics

"disk_total_gb": float, "disk_available_gb": float,

Compute metrics

"estimated_tflops": Optional[float], # GPU compute power "compute_units": Optional[int], # GPU cores or CUDA cores "cpu_performance_units": float,

Backend-specific metrics

"neural_engine_tops": Optional[float], # MLX only "cuda_version": Optional[str], # CUDA only "compute_capability": Optional[str], # CUDA only "architecture": Optional[str], # MLX: "3nm", CUDA: "Ampere"

Performance scores (0-100)

"global_inference_score": float, "global_inference_label": str, # "Very Good", "Good", "Medium", "Poor" "gpu_score": float, "cpu_score": float, "memory_score": float,

Technical details

"unified_memory": bool, "accelerator_available": bool, "system_platform": str,

Performance breakdown for debugging

"performance_breakdown": { "compute_score": float, "memory_bandwidth_score": float, "memory_capacity_score": float, "cpu_performance_score": float, # Backend-specific breakdown }

Dict[str, Any]

}

Raises:

Type Description
EngineException

If evaluation fails critically.

Note

Scores are platform-specific estimates based on hardware specs. Should call warm_up_accelerator() before evaluation for accuracy. Returns fallback scores if evaluation fails rather than raising.

Examples:

>>> engine = BaseEngine.get_engine()
>>> engine.warm_up_accelerator(1.5)
>>> eval_result = engine.get_performance_evaluation()
>>> print(f"Inference: {eval_result['global_inference_score']}/100")
Source code in backend/src/engines/base_engine.py
@classmethod
@abstractmethod
def get_performance_evaluation(cls) -> Dict[str, Any]:
    """Calculate comprehensive performance metrics and scores for this backend.

    Evaluates hardware capabilities and returns performance scores for
    inference workloads. Scoring methodology varies by backend but results
    are normalized to 0-100 scale for cross-platform comparison.

    Scoring Components:
        - **Inference Score**: Optimized for generation speed and latency.
          Weights: GPU/accelerator compute (35-60%), memory bandwidth (20-30%),
          memory capacity (10-30%), CPU (5-10%).

    Returns:
        Dict containing performance metrics and scores:
        {
            # Hardware identification
            "backend_type": str,  # "mlx", "cuda", "cpu"
            "accelerator_name": str,  # GPU/chip model
            "cpu_model": str,

            # Memory metrics
            "total_memory_gb": float,
            "available_memory_gb": float,
            "memory_bandwidth_gbs": Optional[float],

            # Storage metrics
            "disk_total_gb": float,
            "disk_available_gb": float,

            # Compute metrics
            "estimated_tflops": Optional[float],  # GPU compute power
            "compute_units": Optional[int],  # GPU cores or CUDA cores
            "cpu_performance_units": float,

            # Backend-specific metrics
            "neural_engine_tops": Optional[float],  # MLX only
            "cuda_version": Optional[str],  # CUDA only
            "compute_capability": Optional[str],  # CUDA only
            "architecture": Optional[str],  # MLX: "3nm", CUDA: "Ampere"

            # Performance scores (0-100)
            "global_inference_score": float,
            "global_inference_label": str,  # "Very Good", "Good", "Medium", "Poor"
            "gpu_score": float,
            "cpu_score": float,
            "memory_score": float,

            # Technical details
            "unified_memory": bool,
            "accelerator_available": bool,
            "system_platform": str,

            # Performance breakdown for debugging
            "performance_breakdown": {
                "compute_score": float,
                "memory_bandwidth_score": float,
                "memory_capacity_score": float,
                "cpu_performance_score": float,
                # Backend-specific breakdown
            }
        }

    Raises:
        EngineException: If evaluation fails critically.

    Note:
        Scores are platform-specific estimates based on hardware specs.
        Should call warm_up_accelerator() before evaluation for accuracy.
        Returns fallback scores if evaluation fails rather than raising.

    Examples:
        >>> engine = BaseEngine.get_engine()
        >>> engine.warm_up_accelerator(1.5)
        >>> eval_result = engine.get_performance_evaluation()
        >>> print(f"Inference: {eval_result['global_inference_score']}/100")

    """
    pass

is_runnable(link) classmethod

Whether a catalog model (already engine-format by construction, since it came from a filter=FORMAT_TAG search) can actually run. The only exclusion is KNOWN_BROKEN — quants that load-crash on this engine.

Source code in backend/src/engines/base_engine.py
@classmethod
def is_runnable(cls, link: str) -> bool:
    """Whether a catalog model (already engine-format by construction, since it
    came from a filter=FORMAT_TAG search) can actually run. The only exclusion
    is KNOWN_BROKEN — quants that load-crash on this engine."""
    return link not in cls.KNOWN_BROKEN

max_context_tokens() classmethod

The DECLARED CEILING: the configured context window imposed on every spawn, or None when none is configured (the default everywhere).

llama.cpp engines override this to return ERUDI_CTX when the user pinned one (then passed as -c); MLX never imposes one. This is a configuration fact, not a runtime one -- for the window the loaded child actually runs with, read effective_context_tokens(). The per-model sampling resolver (#388) caps max_tokens on this value when it exists.

Source code in backend/src/engines/base_engine.py
@classmethod
def max_context_tokens(cls) -> Optional[int]:
    """The DECLARED CEILING: the configured context window imposed on every
    spawn, or ``None`` when none is configured (the default everywhere).

    llama.cpp engines override this to return ``ERUDI_CTX`` when the user
    pinned one (then passed as ``-c``); MLX never imposes one. This is a
    configuration fact, not a runtime one -- for the window the loaded
    child actually runs with, read ``effective_context_tokens()``. The
    per-model sampling resolver (#388) caps ``max_tokens`` on this value
    when it exists."""
    return None

memory_bound_footprint_bytes() classmethod

What a memory-bound child holds whatever the conversation does (the CPU engine's whole allocation at load: KV, compute, weights), the number the bound memory warning quotes when no per-token accounting exists; None here and on MLX, whose footprint grows with the conversation (MemoryBudget.footprint_bytes).

Source code in backend/src/engines/base_engine.py
@classmethod
def memory_bound_footprint_bytes(cls) -> Optional[int]:
    """What a memory-bound child holds whatever the conversation does
    (the CPU engine's whole allocation at load: KV, compute, weights), the
    number the ``bound`` memory warning quotes when no per-token
    accounting exists; ``None`` here and on MLX, whose footprint grows
    with the conversation (``MemoryBudget.footprint_bytes``)."""
    return None

memory_bound_tokens() classmethod

The window the machine's MEMORY imposed on the loaded child, or None when memory is not what bounds it.

Set by an engine whose child's window memory limits: MLX, which lowers its child's window to the memory ceiling after load, the CPU engine, which sizes -c from the RAM budget at spawn (never for a sliding-window model, whose window the budget over-estimates), and the CUDA engine, which sizes it from the VRAM budget at spawn; it then equals the allocated window. None means the model's own window binds (or the bound could not be applied): no memory notice, no memory wording on an overflow and no memory reason on a compaction apply.

Source code in backend/src/engines/base_engine.py
@classmethod
def memory_bound_tokens(cls) -> Optional[int]:
    """The window the machine's MEMORY imposed on the loaded child, or
    ``None`` when memory is not what bounds it.

    Set by an engine whose child's window memory limits: MLX, which lowers
    its child's window to the memory ceiling after load, the CPU engine,
    which sizes ``-c`` from the RAM budget at spawn (never for a
    sliding-window model, whose window the budget over-estimates), and
    the CUDA engine, which sizes it from the VRAM budget at spawn; it then
    equals the allocated window. ``None`` means the model's own
    window binds (or the bound could not be applied): no memory notice, no
    memory wording on an overflow and no memory reason on a compaction
    apply."""
    return None

model_supports_vision(local_path) classmethod

Whether the model at local_path accepts image input (#133).

Deterministic, no model load: llama.cpp engines look for an mmproj projector, MLX reads config.json. Returns None when the engine cannot decide; the runtime treats None as not vision-capable (#212): images are stripped unless the capability is an explicit True, and the user is notified when the current turn carried an image.

Source code in backend/src/engines/base_engine.py
@classmethod
def model_supports_vision(cls, local_path: Union[str, Path]) -> Optional[bool]:
    """Whether the model at ``local_path`` accepts image input (#133).

    Deterministic, no model load: llama.cpp engines look for an ``mmproj``
    projector, MLX reads ``config.json``. Returns ``None`` when the engine
    cannot decide; the runtime treats ``None`` as not vision-capable (#212):
    images are stripped unless the capability is an explicit ``True``,
    and the user is notified when the current turn carried an image.
    """
    return None

note_call_start(handle, estimated_prompt_tokens) classmethod

A model call bound to handle is about to be sent, with the client's estimate of its size. No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def note_call_start(cls, handle: Any, estimated_prompt_tokens: int) -> None:
    """A model call bound to ``handle`` is about to be sent, with the
    client's estimate of its size. No-op here."""
    return None

note_call_usage(handle, input_tokens, output_tokens, cached_tokens=0, has_images=False) classmethod

One model call's server-reported usage, pushed by the chat client bound to handle. No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def note_call_usage(
    cls,
    handle: Any,
    input_tokens: int,
    output_tokens: int,
    cached_tokens: int = 0,
    has_images: bool = False,
) -> None:
    """One model call's server-reported usage, pushed by the chat client
    bound to ``handle``. No-op here."""
    return None

note_stream_abandoned(handle) classmethod

A model stream against handle (the child it was built for) did not end normally. No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def note_stream_abandoned(cls, handle: Any) -> None:
    """A model stream against ``handle`` (the child it was built for) did
    not end normally. No-op here."""
    return None

on_history_rewritten() classmethod

The conversation history was rewritten (compaction): the cached prefix is garbage. No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def on_history_rewritten(cls) -> None:
    """The conversation history was rewritten (compaction): the cached
    prefix is garbage. No-op here."""
    return None

start_cleanup_task() classmethod

Start the automatic cleanup monitoring task.

Creates an async task that periodically checks for idle models and frees memory. Should be called once during application startup.

Note

Idempotent - calling multiple times has no effect if task already running.

Examples:

from src.engines.base_engine import BaseEngine engine = BaseEngine.get_engine() engine.start_cleanup_task()

Source code in backend/src/engines/base_engine.py
@classmethod
def start_cleanup_task(cls):
    """Start the automatic cleanup monitoring task.

    Creates an async task that periodically checks for idle models
    and frees memory. Should be called once during application startup.

    Note:
        Idempotent - calling multiple times has no effect if task already running.

    Examples:
        from src.engines.base_engine import BaseEngine
        engine = BaseEngine.get_engine()
        engine.start_cleanup_task()

    """
    if cls._cleanup_task is None:
        cls._cleanup_task = asyncio.create_task(cls._cleanup_monitor(), name="idle-cleanup")
        cls._cleanup_task.add_done_callback(_log_monitor_death)
        logger.info("Started cleanup monitor")

start_pressure_task() classmethod

Start the idle memory-pressure monitor. No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
def start_pressure_task(cls) -> None:
    """Start the idle memory-pressure monitor. No-op here."""
    return None

stop_cleanup_task() classmethod

Stop the automatic cleanup monitoring task.

Cancels the cleanup monitor task. Should be called during application shutdown to gracefully stop background tasks.

Note

Idempotent - calling when no task is running has no effect.

Examples:

from src.engines.base_engine import BaseEngine engine = BaseEngine.get_engine() engine.stop_cleanup_task()

Source code in backend/src/engines/base_engine.py
@classmethod
def stop_cleanup_task(cls):
    """Stop the automatic cleanup monitoring task.

    Cancels the cleanup monitor task. Should be called during application
    shutdown to gracefully stop background tasks.

    Note:
        Idempotent - calling when no task is running has no effect.

    Examples:
        from src.engines.base_engine import BaseEngine
        engine = BaseEngine.get_engine()
        engine.stop_cleanup_task()

    """
    if cls._cleanup_task is not None:
        cls._cleanup_task.cancel()
        cls._cleanup_task = None
        logger.info("Stopped cleanup monitor")

stop_pressure_task() async classmethod

Stop the idle memory-pressure monitor and wait for it. No-op here.

Source code in backend/src/engines/base_engine.py
@classmethod
async def stop_pressure_task(cls) -> None:
    """Stop the idle memory-pressure monitor and wait for it. No-op here."""
    return None

take_idle_reload(llm_id) classmethod

Whether this turn reloads llm_id after an idle-timeout reap.

True once (the record is consumed) when the reap unloaded llm_id and nothing is loaded. A record found while a model is loaded is stale (the title request of a new conversation reloaded it first) and is dropped. Identity is llm.id, as in _should_not_reload_model.

Source code in backend/src/engines/base_engine.py
@classmethod
def take_idle_reload(cls, llm_id: Any) -> bool:
    """Whether this turn reloads ``llm_id`` after an idle-timeout reap.

    True once (the record is consumed) when the reap unloaded ``llm_id``
    and nothing is loaded. A record found while a model is loaded is stale
    (the title request of a new conversation reloaded it first) and is
    dropped. Identity is ``llm.id``, as in ``_should_not_reload_model``.
    """
    record = cls._idle_unload
    if not isinstance(record, dict):
        return False
    if cls._model is not None:
        cls._idle_unload = None
        return False
    if record.get("model_id") != llm_id:
        return False
    cls._idle_unload = None
    return True

warm_up_accelerator(duration_seconds=1.0) abstractmethod classmethod

Warm up the hardware accelerator (GPU/Neural Engine) for optimal performance.

Runs compute-intensive operations to bring the accelerator to optimal performance state before benchmarking or inference. Implementation varies: - MLX: Matrix operations on MPS device - CUDA: CUDA kernel warm-up on GPU - CPU: CPU cache warm-up (minimal effect)

Parameters:

Name Type Description Default
duration_seconds float

How long to run warm-up operations (default: 1.0).

1.0

Returns:

Name Type Description
bool bool

True if warm-up completed successfully, False otherwise.

Raises:

Type Description
EngineException

If warm-up fails critically (rare, usually returns False).

Note

This is particularly important for GPUs that dynamically adjust clocks. MLX/MPS benefits significantly from warm-up due to power management. CPU backend may implement minimal warm-up or skip entirely.

Examples:

>>> engine = BaseEngine.get_engine()
>>> success = engine.warm_up_accelerator(1.5)
>>> if success:
...     print("Accelerator ready for benchmarking")
Source code in backend/src/engines/base_engine.py
@classmethod
@abstractmethod
def warm_up_accelerator(cls, duration_seconds: float = 1.0) -> bool:
    """Warm up the hardware accelerator (GPU/Neural Engine) for optimal performance.

    Runs compute-intensive operations to bring the accelerator to optimal
    performance state before benchmarking or inference. Implementation varies:
    - MLX: Matrix operations on MPS device
    - CUDA: CUDA kernel warm-up on GPU
    - CPU: CPU cache warm-up (minimal effect)

    Args:
        duration_seconds: How long to run warm-up operations (default: 1.0).

    Returns:
        bool: True if warm-up completed successfully, False otherwise.

    Raises:
        EngineException: If warm-up fails critically (rare, usually returns False).

    Note:
        This is particularly important for GPUs that dynamically adjust clocks.
        MLX/MPS benefits significantly from warm-up due to power management.
        CPU backend may implement minimal warm-up or skip entirely.

    Examples:
        >>> engine = BaseEngine.get_engine()
        >>> success = engine.warm_up_accelerator(1.5)
        >>> if success:
        ...     print("Accelerator ready for benchmarking")

    """
    pass

EngineMeta

Bases: ABCMeta

Metaclass for Engine classes with custom repr.

__repr__()

Return human-readable engine class name.

Returns:

Type Description

String representation like "LLM Engine: MLX_Engine".

Source code in backend/src/engines/base_engine.py
def __repr__(cls):
    """Return human-readable engine class name.

    Returns:
        String representation like "LLM Engine: MLX_Engine".

    """
    return f"LLM Engine: {cls.__name__}"

drain_pending_reset() async

Wait for an in-flight reset an earlier lock holder left behind.

Called right after acquiring the generation lock, before the new holder does anything, and by the shutdown before it stops the child (src.core.api.lifespan). The reset task's outcome is never re-raised into this unrelated holder; a cancellation of the holder during the wait is re-raised once the reset thread has finished.

Source code in backend/src/engines/base_engine.py
async def drain_pending_reset() -> None:
    """Wait for an in-flight reset an earlier lock holder left behind.

    Called right after acquiring the generation lock, before the new holder
    does anything, and by the shutdown before it stops the child
    (``src.core.api.lifespan``). The reset task's outcome is never re-raised into this
    unrelated holder; a cancellation of the holder during the wait is
    re-raised once the reset thread has finished.
    """
    task = BaseEngine._pending_reset
    if task is None:
        return
    if task.get_loop() is not asyncio.get_running_loop():
        # Left behind by another (closed) event loop: nothing can still run
        # against this loop's child, and it cannot be awaited from here.
        BaseEngine._pending_reset = None
        return
    cancelled = await wait_shielded(task)
    if BaseEngine._pending_reset is task:
        BaseEngine._pending_reset = None
    if cancelled:
        raise asyncio.CancelledError()

run_reset_shielded(fn) async

Run the blocking reset fn in a worker thread, shielded.

Registers the thread's task as BaseEngine._pending_reset for the next lock acquirer to drain, waits for it through wait_shielded (a cancellation never returns early), then re-raises a cancellation that arrived meanwhile. Returns fn's result, or None when it raised (logged once by the done callback). Every prefix-cache reset path -- the claim of a conversation, the compaction reset and the memory brake's samples (brake_point: MLX may reset the cache or move the child's bound, the CPU engine may restart its child) -- goes through here.

Source code in backend/src/engines/base_engine.py
async def run_reset_shielded(fn: Any) -> Any:
    """Run the blocking reset ``fn`` in a worker thread, shielded.

    Registers the thread's task as ``BaseEngine._pending_reset`` for the next
    lock acquirer to drain, waits for it through ``wait_shielded`` (a
    cancellation never returns early), then re-raises a cancellation that
    arrived meanwhile. Returns ``fn``'s result, or ``None`` when it raised
    (logged once by the done callback). Every prefix-cache reset path -- the
    claim of a conversation, the compaction reset and the memory brake's
    samples (``brake_point``: MLX may reset the cache or move the child's
    bound, the CPU engine may restart its child) -- goes through here.
    """
    task = asyncio.get_running_loop().create_task(asyncio.to_thread(fn))
    task.add_done_callback(_log_reset_outcome)
    BaseEngine._pending_reset = task
    cancelled = await wait_shielded(task)
    if BaseEngine._pending_reset is task:
        BaseEngine._pending_reset = None
    if cancelled:
        raise asyncio.CancelledError()
    if task.cancelled() or task.exception() is not None:
        return None
    return task.result()

wait_shielded(task) async

Wait until task is done, whatever cancellation arrives meanwhile.

Returns whether a native cancellation of the CURRENT task was absorbed, so the caller can re-raise it once the wait is over. The task's own outcome is left to the caller (for a reset, _log_reset_outcome owns it). Also used by src.agents.isolated_stream to wait for the task that consumes the agent's LangGraph stream.

Source code in backend/src/engines/base_engine.py
async def wait_shielded(task: "asyncio.Task") -> bool:
    """Wait until ``task`` is done, whatever cancellation arrives meanwhile.

    Returns whether a native cancellation of the CURRENT task was absorbed,
    so the caller can re-raise it once the wait is over. The task's own
    outcome is left to the caller (for a reset, ``_log_reset_outcome`` owns
    it). Also used by ``src.agents.isolated_stream`` to wait for the task
    that consumes the agent's LangGraph stream.
    """
    import anyio

    cancelled = False
    with anyio.CancelScope(shield=True):
        while not task.done():
            try:
                await asyncio.shield(task)
            except asyncio.CancelledError:
                # Ours (the outer wait was cancelled) unless the task itself
                # ended cancelled; either way, keep waiting until it is done.
                if not (task.done() and task.cancelled()):
                    cancelled = True
            except Exception:
                # The task's own failure: the task is done, and the caller
                # reads (or logs) its outcome from it.
                break
    return cancelled

src.engines.cpu_engine

CPU engine for fallback inference using llama.cpp HTTP server.

This module provides a CPU-only backend for systems without GPU acceleration: - Uses llama.cpp server (OpenAI-compatible API) for optimized CPU inference - GGUF model format for quantization (4-bit, 5-bit, 8-bit) - Threading optimization for multi-core CPUs - Fallback when MLX (Mac Silicon) or CUDA (NVIDIA GPU) unavailable - Rosetta support for x86_64 binaries on Apple Silicon

Current Status

FUNCTIONAL - Core features implemented. Performance evaluation pending refinement.

Features
  • Load GGUF quantized models via llama-server subprocess
  • Multi-threaded inference with configurable thread count
  • Context window sized by Erudi at spawn (-c = min(trained window, what 0.75 x RAM affords), see gguf_memory); llama-server's own fit when the GGUF header is unreadable; ERUDI_CTX pins it
  • A memory brake: under memory pressure the child respawns with a smaller window, or is unloaded (memory_brake.llama_step, memory_pressure)
  • Streaming generation via OpenAI-compatible /v1/chat/completions
  • Automatic port selection and server lifecycle management
  • Cross-platform (macOS, Linux, Windows) with Rosetta support
Architecture

CPU Engine (Singleton): ┌───────────────────────────────────────────────────────────┐ │ get_model_and_tokenizer() │ │ └─> Start llama-server → return handle │ └───────────────────────────────────────────────────────────┘ ↓ ┌───────────────────────────────────────────────────────────┐ │ token streaming lives in the agent layer, not the engine: │ │ AgentRunner → ChatOpenAI(base_url) → POST /v1/chat/... │ │ the engine only spawns / probes / reaps the server │ └───────────────────────────────────────────────────────────┘ ↓ ┌───────────────────────────────────────────────────────────┐ │ cleanup() │ │ └─> Terminate server process → free memory │ └───────────────────────────────────────────────────────────┘

Example

::

from src.engines.cpu_engine import CPU_Engine

model, tokenizer = CPU_Engine.get_model_and_tokenizer(
    llm_id="mistral-7b-q4",
    llm_local_path="/path/to/model.gguf"
)

# Token streaming is driven by the agent layer (ChatOpenAI(base_url=...)),
# not the engine; ``model["base_url"]`` is what it connects to.
Note

BaseEngine.get_engine() will automatically select CPU_Engine if: - System is not Mac Silicon (no MLX) - No CUDA-capable GPU detected (no CUDA_Engine)

This ensures graceful degradation for unsupported hardware.

Warning

CPU inference is significantly slower than GPU (10-50x depending on model size). Use only as last resort fallback when GPU acceleration is unavailable. For production deployments, prefer MLX (Mac) or CUDA (NVIDIA) engines.

CPU_Engine()

Bases: BaseLlamaCppEngine

CPU Engine using llama.cpp's HTTP server (llama-server).

Inherits the subprocess + SSE lifecycle from BaseChatServerEngine and the llama-cpp specifics (Popen, GGUF picking, llama-server location) from BaseLlamaCppEngine. CPU-specific here: _build_spawn_argv, the window it sizes itself (_prepare_spawn_context), the memory brake's bindings, and class attrs.

Notes
  • "model" is a dict handle for the running server (pid, port, alias, base_url)
  • "tokenizer" is a placeholder (HTTP server abstracts tokenization)
Source code in backend/src/engines/base_engine.py
def __init__(self):
    """Prevent direct instantiation.

    Raises:
        RuntimeError: Always raised as engines use class methods only.

    """
    raise RuntimeError("Use the methods instead of instantiating")

brake_point(point, *, llm_id=None) classmethod

Take the brake's sample at point and execute its decision. Never raises: a failure is ONE WARNING with the exception's class name, and the sample is lost.

Source code in backend/src/engines/cpu_engine.py
@classmethod
def brake_point(cls, point: str, *, llm_id: Any = None) -> BrakeOutcome:
    """Take the brake's sample at ``point`` and execute its decision.
    Never raises: a failure is ONE WARNING with the exception's class
    name, and the sample is lost."""
    try:
        return cls._llama_brake_point(point, llm_id)
    except Exception as exc:
        logger.warning(
            f"[{cls.__name__}] Memory brake sample failed ({type(exc).__name__}): "
            f"point={point}"
        )
        return BrakeOutcome()

brake_reload_pending(llm_id) classmethod

An unload's record for llm_id (the shared answer), or a brake respawn of its loaded child whose reload state is still owed.

Source code in backend/src/engines/cpu_engine.py
@classmethod
def brake_reload_pending(cls, llm_id: Any) -> bool:
    """An unload's record for ``llm_id`` (the shared answer), or a brake
    respawn of its loaded child whose reload state is still owed."""
    return super().brake_reload_pending(llm_id) or cls._llama_respawn_pending(llm_id)

get_flat_hardware_data() classmethod

Get hardware data in flat format compatible with HardwareProfile entity.

Returns hardware specifications as a flat dictionary ready for database insertion. For CPU backend, get_performance_evaluation() already returns data in the correct flat format.

Returns:

Type Description
Dict[str, Any]

Flat dict with all fields matching HardwareProfile columns.

Raises:

Type Description
HardwareException

If hardware data collection fails.

Source code in backend/src/engines/cpu_engine.py
@classmethod
def get_flat_hardware_data(cls) -> Dict[str, Any]:
    """Get hardware data in flat format compatible with HardwareProfile entity.

    Returns hardware specifications as a flat dictionary ready for database
    insertion. For CPU backend, get_performance_evaluation() already returns
    data in the correct flat format.

    Returns:
        Flat dict with all fields matching HardwareProfile columns.

    Raises:
        HardwareException: If hardware data collection fails.
    """
    # get_performance_evaluation() already returns flat structure
    return cls.get_performance_evaluation()

get_hardware_info() classmethod

Get comprehensive hardware information for CPU-only backend.

Returns detailed hardware specifications including CPU model, system memory, storage capacity, and platform information. No GPU/accelerator data.

Returns:

Type Description
Dict[str, Any]

Dict containing hardware specifications following BaseEngine contract:

Dict[str, Any]

{ "system": {"platform": str, "platform_version": str, ...}, "cpu": {"model": str, "total_cores": int, "architecture": str, ...}, "memory": {"total_memory_gb": float, "available_memory_gb": float, ...}, "storage": {"total_gb": float, "available_gb": float, "usage_percentage": float}, "backend_type": "cpu", "timestamp": float

Dict[str, Any]

}

Note

GPU fields return None/False since this is CPU-only backend. Falls back gracefully if psutil unavailable.

Source code in backend/src/engines/cpu_engine.py
@classmethod
def get_hardware_info(cls) -> Dict[str, Any]:
    """Get comprehensive hardware information for CPU-only backend.

    Returns detailed hardware specifications including CPU model, system memory,
    storage capacity, and platform information. No GPU/accelerator data.

    Returns:
        Dict containing hardware specifications following BaseEngine contract:
        {
            "system": {"platform": str, "platform_version": str, ...},
            "cpu": {"model": str, "total_cores": int, "architecture": str, ...},
            "memory": {"total_memory_gb": float, "available_memory_gb": float, ...},
            "storage": {"total_gb": float, "available_gb": float, "usage_percentage": float},
            "backend_type": "cpu",
            "timestamp": float
        }

    Note:
        GPU fields return None/False since this is CPU-only backend.
        Falls back gracefully if psutil unavailable.
    """
    try:
        # Import optional dependencies for hardware detection
        try:
            import psutil
        except ImportError as e:
            logger.warning(f"Optional hardware detection dependency missing: {e}")
            psutil = None

        # System information
        system = platform.system()
        machine = platform.machine()
        processor = platform.processor() or platform.uname().processor

        # CPU information
        total_cores = psutil.cpu_count(logical=False) if psutil else (os.cpu_count() or 1)
        logical_cores = psutil.cpu_count(logical=True) if psutil else (os.cpu_count() or 1)

        # Enhanced CPU model detection from OS-native sources (no py-cpuinfo
        # multiprocessing child; see src/engines/cpu_brand.py and #282)
        cpu_model = processor
        cpu_brand = get_cpu_brand()
        if cpu_brand:
            cpu_model = cpu_brand

        # Check if Apple Silicon (shouldn't normally reach CPU_Engine on Mac, but handle it)
        is_apple_silicon = system == "Darwin" and "arm" in machine.lower()

        # Memory information
        total_mem = avail_mem = memory_pressure = None
        if psutil:
            vm = psutil.virtual_memory()
            total_mem = round(vm.total / (1024**3), 2)
            avail_mem = round(vm.available / (1024**3), 2)
            memory_pressure = round(1.0 - (vm.available / vm.total), 3) if vm.total > 0 else 0.0

        # Storage information
        disk_total = disk_available = disk_usage_pct = None
        if psutil:
            try:
                disk = psutil.disk_usage(os.path.abspath(os.sep))
                disk_total = round(disk.total / (1024**3), 2)
                disk_available = round(disk.free / (1024**3), 2)
                disk_usage_pct = round(disk.percent, 2)
            except Exception as e:
                logger.warning(f"Failed to get disk info: {e}")

        # Build hardware info dictionary
        info = {
            "system": {
                "platform": system,
                "platform_version": platform.version(),
                "machine": machine,
                "processor": processor,
            },
            "cpu": {
                "model": cpu_model,
                "architecture": machine,
                "total_cores": total_cores,
                "logical_cores": logical_cores,
                "is_apple_silicon": is_apple_silicon,
                "performance_cores": None,  # Not available without Apple Silicon API
                "efficiency_cores": None,
            },
            "memory": {
                "total_memory_gb": total_mem,
                "available_memory_gb": avail_mem,
                "memory_pressure": memory_pressure,
                "memory_type": "system",
            },
            "gpu": {
                "gpu_name": "CPU Only",
                "gpu_cores": None,
                "memory_bandwidth_gbs": None,
                "vram_total_gb": None,
                "vram_available_gb": None,
                "compute_capability": None,
                "cuda_version": None,
                "mps_supported": False,
                "unified_memory": False,
            },
            "accelerator": {
                "neural_engine_tops": None,
                "architecture": None,
            },
            "storage": {
                "total_gb": disk_total,
                "available_gb": disk_available,
                "usage_percentage": disk_usage_pct,
            },
            "backend_type": "cpu",
            "timestamp": time.time(),
        }

        logger.info(
            f"CPU hardware detected: {cpu_model}, {total_cores} cores, {total_mem}GB RAM"
        )
        return info

    except Exception as e:
        logger.exception(f"CPU hardware detection failed: {e}")
        # Return minimal fallback info
        return {
            "system": {
                "platform": platform.system(),
                "platform_version": platform.version(),
                "machine": platform.machine(),
                "processor": "Unknown",
            },
            "cpu": {
                "model": "Unknown CPU",
                "architecture": platform.machine(),
                "total_cores": os.cpu_count() or 1,
                "logical_cores": os.cpu_count() or 1,
                "is_apple_silicon": False,
                "performance_cores": None,
                "efficiency_cores": None,
            },
            "memory": {
                "total_memory_gb": None,
                "available_memory_gb": None,
                "memory_pressure": None,
                "memory_type": "system",
            },
            "gpu": {
                "gpu_name": "CPU Only",
                "gpu_cores": None,
                "memory_bandwidth_gbs": None,
                "vram_total_gb": None,
                "vram_available_gb": None,
                "compute_capability": None,
                "cuda_version": None,
                "mps_supported": False,
                "unified_memory": False,
            },
            "accelerator": {"neural_engine_tops": None, "architecture": None},
            "storage": {"total_gb": None, "available_gb": None, "usage_percentage": None},
            "backend_type": "cpu",
            "timestamp": time.time(),
        }

get_performance_evaluation() classmethod

Calculate comprehensive performance metrics for CPU-only backend.

Evaluates hardware capabilities and returns performance scores for inference workloads. Scoring acknowledges CPU limitations compared to GPU-accelerated backends.

Scoring methodology
  • Inference: CPU cores (40%), memory capacity (30%), memory bandwidth est. (20%), disk (10%)
Normalization
  • CPU cores: 64 cores = 100 points
  • Memory: 128GB = 100 points
  • Memory bandwidth: Estimated from CPU specs, 100GB/s = 100 points
  • Disk: 500GB available = 100 points

Returns:

Type Description
Dict[str, Any]

Dict containing performance metrics and scores (0-100 scale):

Dict[str, Any]

{ "backend_type": "cpu", "cpu_model": str, "total_memory_gb": float, "available_memory_gb": float, "compute_units": int, # CPU cores "cpu_performance_units": int, "global_inference_score": float, "global_inference_label": str, "cpu_score": float, "memory_score": float, "performance_breakdown": PerformanceBreakdown, ...

Dict[str, Any]

}

Note

CPU backend scores are generally lower than GPU backends due to lack of parallel processing capabilities. Scores are calibrated to be realistic about CPU limitations while still differentiating between high-end and low-end CPU systems.

Source code in backend/src/engines/cpu_engine.py
@classmethod
def get_performance_evaluation(cls) -> Dict[str, Any]:
    """Calculate comprehensive performance metrics for CPU-only backend.

    Evaluates hardware capabilities and returns performance scores for
    inference workloads. Scoring acknowledges CPU limitations compared to
    GPU-accelerated backends.

    Scoring methodology:
        - Inference: CPU cores (40%), memory capacity (30%), memory bandwidth est. (20%), disk (10%)

    Normalization:
        - CPU cores: 64 cores = 100 points
        - Memory: 128GB = 100 points
        - Memory bandwidth: Estimated from CPU specs, 100GB/s = 100 points
        - Disk: 500GB available = 100 points

    Returns:
        Dict containing performance metrics and scores (0-100 scale):
        {
            "backend_type": "cpu",
            "cpu_model": str,
            "total_memory_gb": float,
            "available_memory_gb": float,
            "compute_units": int,  # CPU cores
            "cpu_performance_units": int,
            "global_inference_score": float,
            "global_inference_label": str,
            "cpu_score": float,
            "memory_score": float,
            "performance_breakdown": PerformanceBreakdown,
            ...
        }

    Note:
        CPU backend scores are generally lower than GPU backends due to
        lack of parallel processing capabilities. Scores are calibrated
        to be realistic about CPU limitations while still differentiating
        between high-end and low-end CPU systems.
    """
    try:
        # Import optional dependencies
        try:
            import psutil
        except ImportError as e:
            logger.warning(f"Optional hardware detection dependency missing: {e}")
            psutil = None

        # Get hardware info
        hw_info = cls.get_hardware_info()

        # Extract key metrics
        total_cores = hw_info["cpu"]["total_cores"] or 1
        total_memory_gb = hw_info["memory"]["total_memory_gb"] or 0
        available_memory_gb = hw_info["memory"]["available_memory_gb"] or 0
        disk_available_gb = hw_info["storage"]["available_gb"] or 0
        cpu_model = hw_info["cpu"]["model"]

        # === SCORING WEIGHTS ===
        # Inference: CPU (40%), Memory Capacity (30%), Memory BW (20%), Disk (10%)
        INF_WEIGHTS = {
            "cpu": 0.40,
            "memory_capacity": 0.30,
            "memory_bandwidth": 0.20,
            "disk": 0.10,
        }

        # === NORMALIZATION FACTORS ===
        NORM_CPU_CORES = 64.0  # 64 cores = 100 points
        NORM_MEMORY_GB = 128.0  # 128GB RAM = 100 points
        NORM_MEM_BW_GBS = 100.0  # 100GB/s = 100 points (estimated)
        NORM_DISK_GB = 500.0  # 500GB available = 100 points

        # === COMPONENT SCORES (0-100 scale) ===

        # CPU Score: Based on core count
        cpu_score = min(100.0, (total_cores / NORM_CPU_CORES) * 100.0)

        # Memory Score: Based on total memory capacity
        memory_capacity_score = min(100.0, (total_memory_gb / NORM_MEMORY_GB) * 100.0)

        # Memory Bandwidth Score: Estimate based on CPU architecture
        # Modern CPUs: ~50-100 GB/s, older CPUs: ~20-40 GB/s
        estimated_mem_bw = total_cores * 1.5  # Rough heuristic: 1.5 GB/s per core
        memory_bandwidth_score = min(100.0, (estimated_mem_bw / NORM_MEM_BW_GBS) * 100.0)

        # Disk Score: Based on available storage
        disk_score = min(100.0, (disk_available_gb / NORM_DISK_GB) * 100.0)

        # === GLOBAL SCORES ===

        # Inference Score
        inference_score = (
            cpu_score * INF_WEIGHTS["cpu"]
            + memory_capacity_score * INF_WEIGHTS["memory_capacity"]
            + memory_bandwidth_score * INF_WEIGHTS["memory_bandwidth"]
            + disk_score * INF_WEIGHTS["disk"]
        )

        # Round score
        inference_score = round(inference_score, 2)

        # === LABELS ===
        def score_to_label(score: float) -> str:
            """Convert 0-100 score to qualitative label."""
            if score >= 85:
                return "Amazing"
            elif score >= 70:
                return "Excellent"
            elif score >= 55:
                return "Very Good"
            elif score >= 40:
                return "Good"
            elif score >= 25:
                return "Medium"
            elif score >= 10:
                return "Poor"
            else:
                return "Terrible"

        inference_label = score_to_label(inference_score)

        # === BUILD RESULT ===
        result = {
            "backend_type": "cpu",
            "gpu_name": "CPU Only",
            "cpu_model": cpu_model,
            "total_memory_gb": total_memory_gb,
            "available_memory_gb": available_memory_gb,
            "memory_bandwidth_gbs": round(estimated_mem_bw, 2),
            "disk_total_gb": hw_info["storage"]["total_gb"],
            "disk_available_gb": disk_available_gb,
            "estimated_tflops": None,  # Not applicable for CPUs
            "cpu_performance_units": total_cores,
            "neural_engine_tops": None,
            "cuda_version": None,
            "compute_capability": None,
            "architecture": hw_info["cpu"]["architecture"],
            "global_inference_score": inference_score,
            "global_inference_label": inference_label,
            "gpu_score": 0.0,  # No GPU
            "cpu_score": round(cpu_score, 2),
            "memory_score": round(memory_capacity_score, 2),
            "unified_memory": False,
            "system_platform": hw_info["system"]["platform"],
            "performance_breakdown": {
                "compute_score": round(cpu_score, 2),
                "memory_bandwidth_score": round(memory_bandwidth_score, 2),
                "memory_capacity_score": round(memory_capacity_score, 2),
                "cpu_performance_score": round(cpu_score, 2),
                "disk_score": round(disk_score, 2),
            },
        }

        logger.info(
            f"CPU performance evaluated: Inference={inference_score:.1f} ({inference_label})"
        )

        return result

    except Exception as e:
        logger.exception(f"CPU performance evaluation failed: {e}")
        # Return minimal fallback
        cores = os.cpu_count() or 1
        base_score = min(100.0, cores * 5.0)  # 5 points per core
        return {
            "backend_type": "cpu",
            "gpu_name": "CPU Only",
            "cpu_model": platform.processor() or "Unknown CPU",
            "total_memory_gb": None,
            "available_memory_gb": None,
            "memory_bandwidth_gbs": None,
            "disk_total_gb": None,
            "disk_available_gb": None,
            "estimated_tflops": None,
            "cpu_performance_units": cores,
            "neural_engine_tops": None,
            "cuda_version": None,
            "compute_capability": None,
            "architecture": platform.machine(),
            "global_inference_score": round(base_score, 2),
            "global_inference_label": "Poor",
            "gpu_score": 0.0,
            "cpu_score": round(base_score, 2),
            "memory_score": 0.0,
            "unified_memory": False,
            "system_platform": platform.system(),
            "performance_breakdown": {
                "compute_score": round(base_score, 2),
                "memory_bandwidth_score": 0.0,
                "memory_capacity_score": 0.0,
                "cpu_performance_score": round(base_score, 2),
                "disk_score": 0.0,
            },
        }

warm_up_accelerator(duration_seconds=1.0) classmethod

Warm up CPU with compute workload.

Runs lightweight computation loop to bring CPU to stable performance state. Less critical than GPU warm-up but still useful for consistent benchmarking results.

Parameters:

Name Type Description Default
duration_seconds float

How long to run warm-up operations (default: 1.0).

1.0

Returns:

Name Type Description
bool bool

True if warm-up completed successfully, False otherwise.

Note

CPU warm-up is minimal compared to GPU since CPUs don't have dynamic clock management like modern GPUs.

Source code in backend/src/engines/cpu_engine.py
@classmethod
def warm_up_accelerator(cls, duration_seconds: float = 1.0) -> bool:
    """Warm up CPU with compute workload.

    Runs lightweight computation loop to bring CPU to stable performance
    state. Less critical than GPU warm-up but still useful for consistent
    benchmarking results.

    Args:
        duration_seconds: How long to run warm-up operations (default: 1.0).

    Returns:
        bool: True if warm-up completed successfully, False otherwise.

    Note:
        CPU warm-up is minimal compared to GPU since CPUs don't have
        dynamic clock management like modern GPUs.
    """
    try:
        logger.info(f"Warming up CPU for {duration_seconds}s...")
        t0 = time.time()

        # Run bounded compute loop
        n = 0
        iterations = 0
        while time.time() - t0 < max(0.05, float(duration_seconds)):
            # Lightweight integer arithmetic to engage CPU
            for _ in range(10000):
                n += (_ * 7) % 13
            iterations += 1

            # Small sleep to prevent complete CPU saturation
            if iterations % 10 == 0:
                time.sleep(0.001)

        logger.info(f"CPU warm-up completed successfully ({iterations} iterations)")
        return True

    except Exception as e:
        logger.warning(f"CPU warm-up failed: {e}")
        return False

src.engines.cuda_engine

CUDA engine for NVIDIA GPU inference.

This module implements the CUDA backend for local LLM inference on systems with NVIDIA GPUs. It provides: - Hardware detection via PyTorch CUDA and NVML - Performance evaluation for inference - GPU warm-up for optimal benchmarking - Cross-platform support (Windows and Linux)

Architecture

CUDA Engine → PyTorch CUDA + NVML ┌───────────────────────────────────────────────────────────┐ │ get_hardware_info() │ │ └─> Detect GPU, VRAM, compute capability via NVML │ └───────────────────────────────────────────────────────────┘ ↓ ┌───────────────────────────────────────────────────────────┐ │ get_performance_evaluation() │ │ 1. Calculate TFLOPS (FP32, FP16, BF16) │ │ 2. Measure memory bandwidth │ │ 3. Score inference performance │ └───────────────────────────────────────────────────────────┘ ↓ ┌───────────────────────────────────────────────────────────┐ │ warm_up_accelerator() │ │ └─> Matrix operations to boost GPU clocks │ └───────────────────────────────────────────────────────────┘

Hardware Detection
  • CUDA availability: torch.cuda.is_available()
  • GPU information: NVML (pynvml library)
  • Best GPU selection: highest VRAM capacity
  • OS-agnostic: Works on Windows and Linux
Performance Scoring

Inference weights: - GPU compute (40%): Tensor TFLOPS (BF16/FP16) - Memory bandwidth (30%): GB/s throughput - VRAM capacity (15%): GPU memory size - CPU performance (5%): Multi-core GHz - System RAM (5%): Host memory - PCIe bandwidth (5%): Bus capacity

Example

Get CUDA hardware information::

from src.engines.cuda_engine import CUDA_Engine

# Detect hardware
hw_info = CUDA_Engine.get_hardware_info()
print(f"GPU: {hw_info['gpu']['gpu_name']}")
print(f"VRAM: {hw_info['gpu']['vram_total_gb']} GB")

# Warm up GPU
CUDA_Engine.warm_up_accelerator(1.5)

# Evaluate performance
perf = CUDA_Engine.get_performance_evaluation()
print(f"Inference score: {perf['global_inference_score']}/100")
print(f"Label: {perf['global_inference_label']}")

Inference (llama.cpp compiled with CUDA, a llama-server subprocess): - The window (-c) is sized by Erudi at spawn for a FULL offload, against the selected GPU's memory at load (cuda_memory); llama.cpp's fit places the layers (-ngl -1, "auto" while fit is on) with Erudi's margin (-fitt). When the floor window does not fit or the GGUF cannot be modelled, no -c: fit sizes the window and places the layers. - After load the placement is classified (full or partial offload); on Windows a full-offload child carries a memory brake driven by the WDDM spill gauge alone -- its Shared GPU memory above its baseline, the reading at load bounded by the healthy level of its window (memory_brake.llama_step); RAM pressure never drives it. On Linux, which has no spill, the brake has no signal and never acts. A partial or fit-sized child runs brake-off. - One GPU, pinned by UUID (CUDA_VISIBLE_DEVICES), never over a value the user set.

Note
  • Requires torch with CUDA support
  • Requires pynvml for GPU monitoring and the window sizing
  • All methods return fallback values if CUDA unavailable
  • Thread-safe through BaseEngine._lock

CUDA_Engine()

Bases: BaseLlamaCppEngine

Engine for NVIDIA CUDA GPU inference.

Provides hardware detection and performance evaluation for NVIDIA GPUs using PyTorch CUDA backend and NVML monitoring library.

Hardware Specs Reference Tables

CUDA_PER_SM: CUDA cores and Tensor cores per SM by compute capability TC_OPS: Tensor core operations per precision by compute capability

Note

Inference uses a CUDA-compiled llama-server subprocess (same architecture as CPU_Engine). The window is sized for a full offload against the GPU's memory; llama.cpp's fit places the layers.

Source code in backend/src/engines/base_engine.py
def __init__(self):
    """Prevent direct instantiation.

    Raises:
        RuntimeError: Always raised as engines use class methods only.

    """
    raise RuntimeError("Use the methods instead of instantiating")

brake_point(point, *, llm_id=None) classmethod

Take the brake's sample at point and execute its decision -- on Windows only, and only on a child whose window Erudi sized and that loaded in full: a fit-sized or partial child is never sampled (nothing for the law's unload to act on either). Off Windows there is no spill, so no signal: nothing is read and nothing acts (the idle monitor still ticks; its samples return here). Never raises: a failure is ONE WARNING with the exception's class name, and the sample is lost.

Source code in backend/src/engines/cuda_engine.py
@classmethod
def brake_point(cls, point: str, *, llm_id: Any = None) -> BrakeOutcome:
    """Take the brake's sample at ``point`` and execute its decision --
    on Windows only, and only on a child whose window Erudi sized and
    that loaded in full: a fit-sized or partial child is never sampled
    (nothing for the law's unload to act on either). Off Windows there
    is no spill, so no signal: nothing is read and nothing acts (the idle
    monitor still ticks; its samples return here). Never raises: a
    failure is ONE WARNING with the exception's class name, and the
    sample is lost."""
    handle = cls._model
    if (
        not cls._host_is_windows()
        or not isinstance(handle, dict)
        or not handle.get("window_sized")
    ):
        return BrakeOutcome()
    try:
        return cls._llama_brake_point(point, llm_id)
    except Exception as exc:
        logger.warning(
            f"[{cls.__name__}] Memory brake sample failed ({type(exc).__name__}): "
            f"point={point}"
        )
        return BrakeOutcome()

brake_reload_pending(llm_id) classmethod

An unload's record for llm_id (the shared answer), or a brake respawn of its loaded child whose reload state is still owed.

Source code in backend/src/engines/cuda_engine.py
@classmethod
def brake_reload_pending(cls, llm_id: Any) -> bool:
    """An unload's record for ``llm_id`` (the shared answer), or a brake
    respawn of its loaded child whose reload state is still owed."""
    return super().brake_reload_pending(llm_id) or cls._llama_respawn_pending(llm_id)

get_flat_hardware_data() classmethod

Get hardware data in flat format compatible with HardwareProfile entity.

Calls get_performance_evaluation() and strips keys that have no matching column in the HardwareProfile ORM model so the result can be splatted directly into the entity constructor.

Returns:

Type Description
Dict[str, Any]

Flat dict with fields matching HardwareProfile columns.

Raises:

Type Description
HardwareException

If hardware data collection fails.

Source code in backend/src/engines/cuda_engine.py
@classmethod
def get_flat_hardware_data(cls) -> Dict[str, Any]:
    """Get hardware data in flat format compatible with HardwareProfile entity.

    Calls get_performance_evaluation() and strips keys that have no matching
    column in the HardwareProfile ORM model so the result can be splatted
    directly into the entity constructor.

    Returns:
        Flat dict with fields matching HardwareProfile columns.

    Raises:
        HardwareException: If hardware data collection fails.
    """
    data = cls.get_performance_evaluation()
    # Keys produced by get_performance_evaluation() that are NOT columns on
    # HardwareProfile — strip them to avoid "invalid keyword argument".
    _EXTRA_KEYS = {
        "tensor_tflops",
        "sm_clock_ghz",
        "compute_units",
        "accelerator_available",
    }
    for key in _EXTRA_KEYS:
        data.pop(key, None)
    return data

get_hardware_info() classmethod

Get comprehensive hardware information for NVIDIA CUDA backend.

Returns detailed hardware specifications including GPU model, VRAM, compute capability, system resources, and CUDA availability.

Returns:

Type Description
Dict[str, Any]

Dict containing hardware specifications:

Dict[str, Any]

{ "system": { "platform": str, "platform_version": str, "machine": str, "processor": str }, "cpu": { "model": str, "architecture": str, "total_cores": int, "logical_cores": int }, "memory": { "total_memory_gb": float, "available_memory_gb": float, "memory_pressure": float, "memory_type": "system" }, "gpu": { "gpu_name": str, "gpu_index": int, "cuda_cores": int, "vram_total_gb": float, "vram_available_gb": float, "compute_capability": str, "memory_bandwidth_gbs": float, "cuda_available": bool, "unified_memory": False }, "storage": { "total_gb": float, "available_gb": float, "usage_percentage": float }, "backend_type": "cuda", "timestamp": float

Dict[str, Any]

}

Raises:

Type Description
HardwareException

If critical hardware detection fails.

Note

Returns fallback values if CUDA unavailable rather than raising. Safe to call even on systems without NVIDIA GPUs.

Examples:

>>> hw_info = CUDA_Engine.get_hardware_info()
>>> print(f"GPU: {hw_info['gpu']['gpu_name']}")
>>> print(f"VRAM: {hw_info['gpu']['vram_total_gb']} GB")
>>> print(f"Compute: {hw_info['gpu']['compute_capability']}")
Source code in backend/src/engines/cuda_engine.py
@classmethod
def get_hardware_info(cls) -> Dict[str, Any]:
    """Get comprehensive hardware information for NVIDIA CUDA backend.

    Returns detailed hardware specifications including GPU model, VRAM,
    compute capability, system resources, and CUDA availability.

    Returns:
        Dict containing hardware specifications:
        {
            "system": {
                "platform": str,
                "platform_version": str,
                "machine": str,
                "processor": str
            },
            "cpu": {
                "model": str,
                "architecture": str,
                "total_cores": int,
                "logical_cores": int
            },
            "memory": {
                "total_memory_gb": float,
                "available_memory_gb": float,
                "memory_pressure": float,
                "memory_type": "system"
            },
            "gpu": {
                "gpu_name": str,
                "gpu_index": int,
                "cuda_cores": int,
                "vram_total_gb": float,
                "vram_available_gb": float,
                "compute_capability": str,
                "memory_bandwidth_gbs": float,
                "cuda_available": bool,
                "unified_memory": False
            },
            "storage": {
                "total_gb": float,
                "available_gb": float,
                "usage_percentage": float
            },
            "backend_type": "cuda",
            "timestamp": float
        }

    Raises:
        HardwareException: If critical hardware detection fails.

    Note:
        Returns fallback values if CUDA unavailable rather than raising.
        Safe to call even on systems without NVIDIA GPUs.

    Examples:
        >>> hw_info = CUDA_Engine.get_hardware_info()
        >>> print(f"GPU: {hw_info['gpu']['gpu_name']}")
        >>> print(f"VRAM: {hw_info['gpu']['vram_total_gb']} GB")
        >>> print(f"Compute: {hw_info['gpu']['compute_capability']}")
    """
    try:
        # Import required modules
        try:
            import psutil
        except ImportError as e:
            logger.error(f"Required hardware detection dependency missing: {e}")
            raise HardwareException(
                f"Missing dependency for hardware detection: {e}", trace=str(e)
            )

        # Check CUDA availability
        cuda_available = cls._cuda_available()

        # Get system info
        vm = psutil.virtual_memory()
        total_memory_gb = vm.total / (1024**3)
        available_memory_gb = vm.available / (1024**3)
        memory_pressure = 1.0 - (vm.available / vm.total)

        disk = psutil.disk_usage(os.path.abspath(os.sep))
        disk_total_gb = disk.total / (1024**3)
        disk_available_gb = disk.free / (1024**3)
        disk_usage_pct = disk.percent

        cpu_model = get_cpu_brand() or "Unknown CPU"
        total_cores = psutil.cpu_count(logical=False) or 4
        logical_cores = psutil.cpu_count(logical=True) or 8

        # GPU information (if available)
        gpu_info = {
            "gpu_name": "No NVIDIA GPU",
            "gpu_index": -1,
            "cuda_cores": 0,
            "vram_total_gb": 0.0,
            "vram_available_gb": 0.0,
            "compute_capability": "N/A",
            "memory_bandwidth_gbs": 0.0,
            "cuda_available": cuda_available,
            "unified_memory": False,
        }

        if cuda_available:
            gpus = cls._get_nvml_gpus()
            if gpus:
                best_gpu = cls._select_best_gpu(gpus)
                if best_gpu:
                    # Get basic GPU info
                    gpu_info["gpu_name"] = best_gpu["name"]
                    gpu_info["gpu_index"] = best_gpu["id"]
                    gpu_info["vram_total_gb"] = best_gpu["vram_total_mb"] / 1024
                    gpu_info["vram_available_gb"] = best_gpu["vram_free_mb"] / 1024

                    # Get compute capability and CUDA cores
                    device_id = best_gpu["id"]
                    major, minor = cls._get_compute_capability(best_gpu["handle"])
                    compute_cap = f"{major}.{minor}"
                    gpu_info["compute_capability"] = compute_cap

                    cores_per_sm, _ = cls._CUDA_PER_SM.get(major, (64, 0))
                    sm_count = cls._get_sm_count(device_id)
                    gpu_info["cuda_cores"] = sm_count * cores_per_sm

                    # Get memory bandwidth (requires NVML)
                    try:
                        import pynvml as nv

                        handle = best_gpu["handle"]
                        mem_clock_mhz = cls._rated_clock_mhz(nv, handle, nv.NVML_CLOCK_MEM)
                        bus_bits = nv.nvmlDeviceGetMemoryBusWidth(handle)
                        # Bandwidth = 2 * clock * bus_width / 8 (DDR, convert bits to bytes)
                        bandwidth_gbs = 2 * mem_clock_mhz / 1000 * bus_bits / 8
                        gpu_info["memory_bandwidth_gbs"] = round(bandwidth_gbs, 1)
                    except Exception as e:
                        logger.warning(f"Could not get memory bandwidth: {e}")

        # Build complete hardware info
        hardware_info = {
            "system": {
                "platform": platform.system(),
                "platform_version": platform.version(),
                "machine": platform.machine(),
                "processor": platform.processor() or cpu_model,
            },
            "cpu": {
                "model": cpu_model,
                "architecture": platform.machine(),
                "total_cores": total_cores,
                "logical_cores": logical_cores,
            },
            "memory": {
                "total_memory_gb": round(total_memory_gb, 2),
                "available_memory_gb": round(available_memory_gb, 2),
                "memory_pressure": round(memory_pressure, 3),
                "memory_type": "system",
            },
            "gpu": gpu_info,
            "storage": {
                "total_gb": round(disk_total_gb, 2),
                "available_gb": round(disk_available_gb, 2),
                "usage_percentage": round(disk_usage_pct, 2),
            },
            "backend_type": "cuda",
            "timestamp": time.time(),
        }

        logger.info(
            f"CUDA hardware detected: {gpu_info['gpu_name']}, "
            f"{gpu_info['cuda_cores']} CUDA cores, "
            f"{gpu_info['vram_total_gb']:.1f}GB VRAM"
        )

        return hardware_info

    except Exception as e:
        logger.exception(f"CUDA hardware detection failed: {e}")
        raise HardwareException("Failed to detect CUDA hardware", trace=str(e))

get_performance_evaluation() classmethod

Calculate comprehensive performance metrics for NVIDIA CUDA backend.

Evaluates hardware capabilities and returns normalized performance scores for inference workloads. Scoring based on TFLOPS, memory bandwidth, VRAM capacity, and system resources.

Scoring methodology

Inference (0-100 scale): - GPU compute (40%): Tensor TFLOPS (BF16/FP16) - Memory bandwidth (30%): GB/s throughput - VRAM capacity (15%): GPU memory size - CPU performance (5%): Multi-core units - System RAM (5%): Host memory - PCIe capacity (5%): Bus bandwidth

Returns:

Type Description
Dict[str, Any]

Dict containing performance metrics and scores:

Dict[str, Any]

{ "backend_type": "cuda", "gpu_name": str, "cpu_model": str, "total_memory_gb": float, "available_memory_gb": float, "memory_bandwidth_gbs": float, "disk_total_gb": float, "disk_available_gb": float, "estimated_tflops": float, "compute_units": int, "cpu_performance_units": float, "cuda_version": str, "compute_capability": str, "architecture": str, "global_inference_score": float, "global_inference_label": str, "gpu_score": float, "cpu_score": float, "memory_score": float, "unified_memory": False, "accelerator_available": bool, "system_platform": str, "performance_breakdown": dict

Dict[str, Any]

}

Raises:

Type Description
HardwareException

If evaluation fails critically.

Note

Returns fallback scores if CUDA unavailable. Should call warm_up_accelerator() before evaluation for accuracy.

Examples:

>>> CUDA_Engine.warm_up_accelerator(1.5)
>>> eval_result = CUDA_Engine.get_performance_evaluation()
>>> print(f"Inference: {eval_result['global_inference_score']}/100")
>>> print(f"Label: {eval_result['global_inference_label']}")
Source code in backend/src/engines/cuda_engine.py
@classmethod
def get_performance_evaluation(cls) -> Dict[str, Any]:
    """Calculate comprehensive performance metrics for NVIDIA CUDA backend.

    Evaluates hardware capabilities and returns normalized performance scores
    for inference workloads. Scoring based on TFLOPS, memory bandwidth, VRAM
    capacity, and system resources.

    Scoring methodology:
        Inference (0-100 scale):
            - GPU compute (40%): Tensor TFLOPS (BF16/FP16)
            - Memory bandwidth (30%): GB/s throughput
            - VRAM capacity (15%): GPU memory size
            - CPU performance (5%): Multi-core units
            - System RAM (5%): Host memory
            - PCIe capacity (5%): Bus bandwidth

    Returns:
        Dict containing performance metrics and scores:
        {
            "backend_type": "cuda",
            "gpu_name": str,
            "cpu_model": str,
            "total_memory_gb": float,
            "available_memory_gb": float,
            "memory_bandwidth_gbs": float,
            "disk_total_gb": float,
            "disk_available_gb": float,
            "estimated_tflops": float,
            "compute_units": int,
            "cpu_performance_units": float,
            "cuda_version": str,
            "compute_capability": str,
            "architecture": str,
            "global_inference_score": float,
            "global_inference_label": str,
            "gpu_score": float,
            "cpu_score": float,
            "memory_score": float,
            "unified_memory": False,
            "accelerator_available": bool,
            "system_platform": str,
            "performance_breakdown": dict
        }

    Raises:
        HardwareException: If evaluation fails critically.

    Note:
        Returns fallback scores if CUDA unavailable.
        Should call warm_up_accelerator() before evaluation for accuracy.

    Examples:
        >>> CUDA_Engine.warm_up_accelerator(1.5)
        >>> eval_result = CUDA_Engine.get_performance_evaluation()
        >>> print(f"Inference: {eval_result['global_inference_score']}/100")
        >>> print(f"Label: {eval_result['global_inference_label']}")
    """
    try:
        # Get base hardware info
        hw_info = cls.get_hardware_info()

        cuda_available = hw_info["gpu"]["cuda_available"]

        # Initialize scores with fallback values
        gpu_score = 0.0
        mem_bandwidth_score = 0.0
        vram_score = 0.0
        estimated_tflops = 0.0
        cuda_version = "N/A"
        architecture = "N/A"
        tensor_tflops = {}
        sm_clock_ghz = 0.0

        if cuda_available:
            gpus = cls._get_nvml_gpus()
            if gpus:
                best_gpu = cls._select_best_gpu(gpus)
                device_id = best_gpu["id"]
                handle = best_gpu["handle"]

                # Get GPU clocks and specs
                try:
                    import pynvml as nv

                    sm_clock_mhz = cls._rated_clock_mhz(nv, handle, nv.NVML_CLOCK_SM)
                    sm_clock_ghz = sm_clock_mhz / 1000
                    mem_clock_mhz = cls._rated_clock_mhz(nv, handle, nv.NVML_CLOCK_MEM)
                    bus_bits = nv.nvmlDeviceGetMemoryBusWidth(handle)
                    bandwidth_gbs = 2 * mem_clock_mhz / 1000 * bus_bits / 8
                except Exception as e:
                    logger.warning(f"Failed to get GPU clocks: {e}")
                    sm_clock_ghz = 1.5  # Fallback
                    bandwidth_gbs = hw_info["gpu"]["memory_bandwidth_gbs"]

                # Get compute capability and SM count (no torch required)
                compute_cap_major, compute_cap_minor = cls._get_compute_capability(handle)
                sm_count = cls._get_sm_count(device_id)

                # Calculate CUDA cores and tensor cores
                cores_per_sm, tc_per_sm = cls._CUDA_PER_SM.get(compute_cap_major, (64, 0))
                total_cuda_cores = sm_count * cores_per_sm

                # Calculate FP32 TFLOPS
                # 2 ops per CUDA core per clock (FMA = mul + add)
                fp32_tflops = 2 * sm_count * cores_per_sm * sm_clock_ghz / 1000

                # Calculate Tensor TFLOPS (FP16, BF16)
                for precision, (ops_per_tc, min_cc) in cls._TC_OPS.items():
                    if compute_cap_major >= min_cc:
                        tflops = (sm_count * tc_per_sm * ops_per_tc * sm_clock_ghz) / 1000
                        tensor_tflops[precision] = round(tflops, 2)
                    else:
                        tensor_tflops[precision] = 0.0

                # Use best tensor performance for scoring
                estimated_tflops = tensor_tflops.get(
                    "bf16", tensor_tflops.get("fp16", fp32_tflops)
                )

                # Get CUDA version from NVML driver info
                cuda_version = cls._get_cuda_driver_version()

                # Determine architecture
                if compute_cap_major == 7:
                    architecture = "Turing"
                elif compute_cap_major == 8:
                    architecture = "Ampere"
                elif compute_cap_major == 9:
                    architecture = "Ada Lovelace / Hopper"
                else:
                    architecture = f"Compute {compute_cap_major}.{compute_cap_minor}"

                # Calculate component scores
                vram_gb = hw_info["gpu"]["vram_total_gb"]
                vram_score = min(100, (vram_gb / cls._NORM_INFERENCE["vram"]) * 100)
                mem_bandwidth_score = min(
                    100, (bandwidth_gbs / cls._NORM_INFERENCE["bandwidth"]) * 100
                )
                gpu_score = min(100, (estimated_tflops / cls._NORM_INFERENCE["tflops"]) * 100)

        # CPU and system scores
        cpu_perf_units = cls._get_cpu_performance_units()
        cpu_score = min(100, (cpu_perf_units / (cls._NORM_INFERENCE["cpu_ghz"] * 12)) * 100)

        sys_ram_gb = hw_info["memory"]["total_memory_gb"]
        ram_score = min(100, (sys_ram_gb / cls._NORM_INFERENCE["ram"]) * 100)

        # PCIe score
        pcie_score = 50.0  # Default fallback
        if cuda_available and gpus:
            pcie_units = cls._get_pcie_capacity(handle)
            pcie_score = min(100, (pcie_units / cls._NORM_INFERENCE["pcie"]) * 100)

        # Calculate weighted inference score
        inference_score = (
            cls._WEIGHTS_INFERENCE["gpu_compute"] * gpu_score
            + cls._WEIGHTS_INFERENCE["gpu_bw"] * mem_bandwidth_score
            + cls._WEIGHTS_INFERENCE["gpu_vram"] * vram_score
            + cls._WEIGHTS_INFERENCE["cpu_single"] * cpu_score
            + cls._WEIGHTS_INFERENCE["sys_ram"] * ram_score
            + cls._WEIGHTS_INFERENCE["pcie"] * pcie_score
        )

        # Generate labels
        def get_label(score: float) -> str:
            if score >= 90:
                return "Amazing"
            elif score >= 80:
                return "Excellent"
            elif score >= 70:
                return "Very High"
            elif score >= 60:
                return "High"
            elif score >= 50:
                return "Good"
            elif score >= 40:
                return "Medium"
            elif score >= 30:
                return "Bad"
            elif score >= 20:
                return "Very Bad"
            elif score >= 10:
                return "Poor"
            else:
                return "Terrible"

        inference_label = get_label(inference_score)

        # Build performance breakdown
        performance_breakdown = {
            "compute_score": round(gpu_score, 2),
            "memory_bandwidth_score": round(mem_bandwidth_score, 2),
            "memory_capacity_score": round(vram_score, 2),
            "cpu_performance_score": round(cpu_score, 2),
            "system_ram_score": round(ram_score, 2),
            "pcie_score": round(pcie_score, 2),
            "weights_inference": cls._WEIGHTS_INFERENCE,
            "normalization_inference": cls._NORM_INFERENCE,
        }

        # Build complete evaluation result
        eval_result = {
            # Hardware identification
            "backend_type": "cuda",
            "gpu_name": hw_info["gpu"]["gpu_name"],
            "cpu_model": hw_info["cpu"]["model"],
            # Memory metrics
            "total_memory_gb": hw_info["memory"]["total_memory_gb"],
            "available_memory_gb": hw_info["memory"]["available_memory_gb"],
            "memory_bandwidth_gbs": hw_info["gpu"]["memory_bandwidth_gbs"],
            # Storage metrics
            "disk_total_gb": hw_info["storage"]["total_gb"],
            "disk_available_gb": hw_info["storage"]["available_gb"],
            # Compute metrics
            "estimated_tflops": round(estimated_tflops, 2),
            "tensor_tflops": tensor_tflops,
            "compute_units": hw_info["gpu"]["cuda_cores"],
            "cuda_cores": hw_info["gpu"]["cuda_cores"],  # Entity field name
            "cpu_performance_units": round(cpu_perf_units, 1),
            # CUDA specific
            "cuda_version": cuda_version,
            "compute_capability": hw_info["gpu"]["compute_capability"],
            "architecture": architecture,
            "sm_clock_ghz": round(sm_clock_ghz, 3),
            # VRAM (CUDA-specific, from hw_info)
            "vram_total_gb": hw_info["gpu"]["vram_total_gb"],
            "vram_available_gb": hw_info["gpu"]["vram_available_gb"],
            # Performance scores (0-100)
            "global_inference_score": round(inference_score, 2),
            "global_inference_label": inference_label,
            "gpu_score": round(gpu_score, 2),
            "cpu_score": round(cpu_score, 2),
            "memory_score": round(vram_score, 2),
            # Technical details
            "unified_memory": False,
            "accelerator_available": cuda_available,
            "system_platform": hw_info["system"]["platform"],
            # Performance breakdown
            "performance_breakdown": performance_breakdown,
        }

        logger.info(
            f"Performance evaluation: Inference={inference_score:.1f}/100 ({inference_label})"
        )

        return eval_result

    except Exception as e:
        logger.exception(f"Performance evaluation failed: {e}")
        raise HardwareException("Failed to evaluate CUDA performance", trace=str(e))

warm_up_accelerator(duration_seconds=1.0) classmethod

Warm up NVIDIA GPU to boost clock speeds for benchmarking.

Runs matrix multiplication operations on GPU to bring it to optimal performance state before measurements. Important for GPUs with dynamic clock management.

Parameters:

Name Type Description Default
duration_seconds float

How long to run warm-up operations (default: 1.0).

1.0

Returns:

Name Type Description
bool bool

True if warm-up completed successfully, False otherwise.

Note

Silently returns False if CUDA unavailable rather than raising. Uses 4096x4096 matrix multiplications on primary GPU.

Examples:

>>> success = CUDA_Engine.warm_up_accelerator(1.5)
>>> if success:
...     print("GPU ready for benchmarking")
Source code in backend/src/engines/cuda_engine.py
@classmethod
def warm_up_accelerator(cls, duration_seconds: float = 1.0) -> bool:
    """Warm up NVIDIA GPU to boost clock speeds for benchmarking.

    Runs matrix multiplication operations on GPU to bring it to optimal
    performance state before measurements. Important for GPUs with
    dynamic clock management.

    Args:
        duration_seconds: How long to run warm-up operations (default: 1.0).

    Returns:
        bool: True if warm-up completed successfully, False otherwise.

    Note:
        Silently returns False if CUDA unavailable rather than raising.
        Uses 4096x4096 matrix multiplications on primary GPU.

    Examples:
        >>> success = CUDA_Engine.warm_up_accelerator(1.5)
        >>> if success:
        ...     print("GPU ready for benchmarking")
    """
    if not cls._cuda_available():
        logger.warning("CUDA not available, skipping GPU warm-up")
        return False

    # GPU warm-up via torch matmul is skipped — the packaged build uses
    # CPU-only torch.  llama-server warms up its own CUDA context on first
    # inference, so this has no effect on LLM performance.
    logger.info("GPU warm-up skipped (not required for llama-server inference)")
    return False

src.engines.cuda_compatibility

Can this NVIDIA GPU actually run the CUDA llama-server Erudi ships?

BaseEngine.get_engine() picks CUDA_Engine as soon as NVML reports one NVIDIA device. That is the right default, but it is not sufficient: the CUDA build we ship targets a fixed architecture list, so a card below it -- or a driver too old to JIT the PTX in it -- crashes on the first chat message with a raw GGML_ABORT instead of running on the CPU it would run on perfectly well.

This module holds the two halves of the answer, both free of NVML imports at module scope so it stays importable everywhere:

  • :func:cuda_preflight_notice -- two NVML reads at startup (compute capability, CUDA driver version), turned into an engine_notice payload the frontend renders as a decision. It never raises.
  • :func:classify_cuda_failure -- the runtime half: the tail a dead child printed, matched against the fixed strings ggml emits, so the chat stream's error event carries a code instead of a wall of text.

Neither half ever switches the engine on its own: the CPU fallback is PROPOSED, and only the persisted user_settings.inference_backend preference (or a reinstall with the CPU build) applies it.

classify_cuda_failure(child_output)

Map a dead child's captured output to a CUDA failure code.

Parameters:

Name Type Description Default
child_output Optional[str]

The tail the drainer collected before the child exited. None or empty is fine.

required

Returns:

Type Description
Optional[str]

One of :data:CUDA_FAILURE_CODES, or None when the output shows no

Optional[str]

CUDA failure at all -- a missing GGUF, a corrupt model, a port clash.

Optional[str]

None is what keeps a non-CUDA crash on the generic error path.

Source code in backend/src/engines/cuda_compatibility.py
def classify_cuda_failure(child_output: Optional[str]) -> Optional[str]:
    """Map a dead child's captured output to a CUDA failure code.

    Args:
        child_output: The tail the drainer collected before the child exited.
            ``None`` or empty is fine.

    Returns:
        One of :data:`CUDA_FAILURE_CODES`, or ``None`` when the output shows no
        CUDA failure at all -- a missing GGUF, a corrupt model, a port clash.
        ``None`` is what keeps a non-CUDA crash on the generic error path.
    """
    if not child_output:
        return None
    for signature, code in _SIGNATURES:
        if signature in child_output:
            return code
    if _CUDA_ERROR_MARKER in child_output:
        return "CUDA_ERROR"
    return None

cuda_preflight_notice()

Verdict on the selected NVIDIA GPU, as an engine_notice payload.

Reads the first NVML device's compute capability and the system's CUDA driver version through CUDA_Engine's existing helpers, and returns:

  • CUDA_COMPUTE_CAPABILITY_TOO_LOW when the card is below CUDA 12's own floor -- there is no driver that fixes it;
  • CUDA_DRIVER_TOO_OLD when the card is fine but the driver is below the version it needs (see :func:required_cuda_version);
  • None when the machine can run the bundled build, when a reading is unavailable, or when NVML fails.

An unreadable value yields None on purpose: guessing from a failed read is how a healthy card gets told its driver is too old. Never raises -- startup must not fail because a diagnostic could not run.

Source code in backend/src/engines/cuda_compatibility.py
def cuda_preflight_notice() -> Optional[dict]:
    """Verdict on the selected NVIDIA GPU, as an ``engine_notice`` payload.

    Reads the first NVML device's compute capability and the system's CUDA
    driver version through ``CUDA_Engine``'s existing helpers, and returns:

    - ``CUDA_COMPUTE_CAPABILITY_TOO_LOW`` when the card is below CUDA 12's own
      floor -- there is no driver that fixes it;
    - ``CUDA_DRIVER_TOO_OLD`` when the card is fine but the driver is below the
      version it needs (see :func:`required_cuda_version`);
    - ``None`` when the machine can run the bundled build, when a reading is
      unavailable, or when NVML fails.

    An unreadable value yields ``None`` on purpose: guessing from a failed read
    is how a healthy card gets told its driver is too old. Never raises --
    startup must not fail because a diagnostic could not run.
    """
    try:
        from src.engines.cuda_engine import CUDA_Engine

        gpus = CUDA_Engine._get_nvml_gpus()
        if not gpus:
            logger.warning("CUDA pre-flight skipped: NVML reported no device.")
            return None
        gpu = gpus[0]
        capability = tuple(CUDA_Engine._get_compute_capability(gpu.get("handle")))
        driver_version = CUDA_Engine._get_cuda_driver_version_int()
    except Exception as e:
        logger.warning(f"CUDA pre-flight skipped: {e}", exc_info=True)
        return None

    if capability == (0, 0):
        logger.warning("CUDA pre-flight skipped: compute capability is unreadable.")
        return None
    if not driver_version:
        logger.warning("CUDA pre-flight skipped: CUDA driver version is unreadable.")
        return None

    gpu_name = gpu.get("name") or "NVIDIA GPU"
    needed = required_cuda_version(capability)
    notice = {
        "event": "engine_notice",
        "gpu_name": gpu_name,
        "compute_capability": _format_compute_capability(capability),
        "driver_cuda_version": format_cuda_version(driver_version),
        "required_cuda_version": format_cuda_version(needed),
    }

    if capability < MIN_COMPUTE_CAPABILITY:
        floor = _format_compute_capability(MIN_COMPUTE_CAPABILITY)
        notice["code"] = "CUDA_COMPUTE_CAPABILITY_TOO_LOW"
        notice["raw"] = (
            f"{gpu_name} has compute capability {notice['compute_capability']}; "
            f"the bundled CUDA build requires {floor} or newer."
        )
        logger.warning(
            f"CUDA pre-flight: compute capability {notice['compute_capability']} "
            f"is below the {floor} floor of the bundled CUDA build."
        )
        return notice

    if driver_version < needed:
        notice["code"] = "CUDA_DRIVER_TOO_OLD"
        notice["raw"] = (
            f"{gpu_name} (compute capability {notice['compute_capability']}) needs a driver "
            f"providing CUDA {notice['required_cuda_version']} or newer; this system reports "
            f"CUDA {notice['driver_cuda_version']}."
        )
        logger.warning(
            f"CUDA pre-flight: driver CUDA {notice['driver_cuda_version']} is below the "
            f"{notice['required_cuda_version']} this GPU needs."
        )
        return notice

    logger.info(
        f"CUDA pre-flight ok: compute capability {notice['compute_capability']}, "
        f"driver CUDA {notice['driver_cuda_version']}."
    )
    return None

format_cuda_version(version)

Render an NVML CUDA version int (12080) for display ("12.8").

Source code in backend/src/engines/cuda_compatibility.py
def format_cuda_version(version: int) -> str:
    """Render an NVML CUDA version int (``12080``) for display (``"12.8"``)."""
    major, minor = divmod(version, 1000)
    return f"{major}.{minor // 10}"

required_cuda_version(capability)

The driver's CUDA version this card needs to run the bundled binary.

A card with native SASS in the binary only needs the runtime baseline; a card that depends on the PTX needs the toolkit's own driver family.

Source code in backend/src/engines/cuda_compatibility.py
def required_cuda_version(capability: tuple[int, int]) -> int:
    """The driver's CUDA version this card needs to run the bundled binary.

    A card with native SASS in the binary only needs the runtime baseline; a
    card that depends on the PTX needs the toolkit's own driver family.
    """
    if capability in NATIVE_SASS_ARCHITECTURES:
        return CUDA_RUNTIME_BASELINE
    return CUDA_PTX_DRIVER_FLOOR

src.engines.mlx_engine

MLX engine for Apple Silicon inference via mlx_vlm.server subprocess.

Inference is delegated to an out-of-process mlx_vlm.server HTTP server (OpenAI-compatible), spawned by multiprocessing.Process and reached over loopback HTTP — exactly aligned with the CPU/CUDA pattern that wraps the llama-server binary. mlx-vlm is a superset of mlx-lm (it depends on it): it serves plain text models, carries a working tool-calling parser (no mlx_lm.server EOS-flush drop, so agentic tools fire), and accepts image input. Apple Silicon hardware detection remains in-process: it doesn't need the server and would only inflate cold-start time if it did.

Architecture

MLX_Engine (singleton) ┌───────────────────────────────────────────────────────────────┐ │ get_model_and_tokenizer(llm_id, path) │ │ 1. Pick free TCP port (27300+) │ │ 2. Spawn child: mp.Process(target=run_mlx_vlm_server) │ │ 3. Poll GET /health until 200 (≤120s) │ │ 4. atexit.register(terminate) │ │ 5. Cache handle {pid,proc,port,base_url,alias,model_path} │ └───────────────────────────────────────────────────────────────┘ ↓ ┌───────────────────────────────────────────────────────────────┐ │ token streaming lives in the agent layer, not the engine: │ │ AgentRunner → Erudi_Chat_OpenAI(base_url) → POST /v1/... │ │ carries delta.content AND delta.reasoning (#554) │ └───────────────────────────────────────────────────────────────┘ ↓ ┌───────────────────────────────────────────────────────────────┐ │ cleanup() — override │ │ └─> SIGTERM child → join(5s) → SIGKILL if needed │ │ → wait_port_closed → super().cleanup() │ └───────────────────────────────────────────────────────────────┘

The memory brake (brake_point, see the section below) gives memory back under macOS memory pressure, at turn boundaries and from an idle monitor.

Where the child's output goes: An mp.Process has no output pipe, so the child redirects its own stdout and stderr into logs/mlx-child-<port>.log (mlx_child_log, wired in _mlx_vlm_server_runner). _read_child_output quotes the tail of that file in every crash report and probe timeout, exactly where the llama-cpp engines quote their drainer.

Why multiprocessing instead of subprocess.Popen([sys.executable, "-m", ...])? In a PyInstaller frozen build, sys.executable is the launcher binary, not a Python interpreter, so the -m flag is a no-op. mp.spawn (already configured in backend/run.py:143-160 via mp.freeze_support() + set_start_method("spawn", force=True)) re-executes the binary in child mode and reconstitutes the import graph — the same run_mlx_vlm_server target works in dev (real Python) and in prod (frozen).

Why the <|channel>thought ... <channel|> manual filter is gone: mlx-vlm's native server-side split owns the reasoning markers (#554): the child spawns with --enable-thinking (thinking on by default) and streams chain-of-thought in the dedicated delta.reasoning field (mirrored into delta.reasoning_content on the pinned 0.6.17), which Erudi_Chat_OpenAI re-attaches to the message chunks and the runner emits as thinking events — symmetric to llama-server's default --reasoning-format auto on the CPU/CUDA path. The runner's ThinkSplitter stays as the inline fallback for families whose markers the server split does not know.

Why the _MLX_EXECUTOR thread bottleneck is gone: Generation now runs in a separate OS process; the GPU stream is initialised inside that child, fully isolated from the FastAPI parent. The Stream(gpu, 0) crash that motivated the persistent thread executor (commits cefdc7a, 40fb55e) is structurally impossible from the parent.

Model format

The engine only ever loads pre-built MLX repos (HF library tag mlx, see FORMAT_TAG): the catalog and the HF search are filtered on that tag and a by-link download is refused up front when the repo lacks it. There is no local HF -> MLX conversion (#408).

Example

::

from src.engines.mlx_engine import MLX_Engine

model, tokenizer = MLX_Engine.get_model_and_tokenizer(
    llm_id="mistral-7b",
    llm_local_path="/path/to/mlx/model"
)
# Token streaming is driven by the agent layer (ChatOpenAI(base_url=...)),
# not the engine; ``model["base_url"]`` is what it connects to.
MLX_Engine.cleanup()
Warning

Only use on Apple Silicon. On other platforms, BaseEngine.get_engine() will select CUDA_Engine or CPU_Engine instead.

MLX_Engine()

Bases: BaseChatServerEngine

Singleton Engine for MLX models and tokenizers runtimes. Built for Apple Silicon Backends.

Source code in backend/src/engines/base_engine.py
def __init__(self):
    """Prevent direct instantiation.

    Raises:
        RuntimeError: Always raised as engines use class methods only.

    """
    raise RuntimeError("Use the methods instead of instantiating")

begin_memory_window() classmethod

Open the turn's measurement window on the loaded child; returns the (handle, pid, window) token end_memory_window closes it with (window numbers the turn's window on this child: a token of an earlier window never closes a later one).

Source code in backend/src/engines/mlx_engine.py
@classmethod
def begin_memory_window(cls) -> Any:
    """Open the turn's measurement window on the loaded child; returns the
    ``(handle, pid, window)`` token ``end_memory_window`` closes it with
    (``window`` numbers the turn's window on this child: a token of an
    earlier window never closes a later one)."""
    from src.engines import process_footprint

    handle = cls._model
    if not isinstance(handle, dict) or not handle.get("pid"):
        return None
    pid = handle["pid"]
    # Every turn opens a window, abandoned ones included: the brake sees
    # the turn (no unload across it). The previous turn's largest request
    # stands until this one's window closes with a size of its own.
    state = handle.get("brake")
    if isinstance(state, BrakeState):
        state.turn_happened = True
    previous = handle.get("memory_window") or {}
    base = handle.get("base_footprint_bytes")
    current = process_footprint.footprint(pid)
    window_id = int(previous.get("window", 0)) + 1
    handle["memory_window"] = {
        "window": window_id,
        "seq": int(previous.get("seq", 0)) + 1,
        "open": True,
        # What the previous request left behind above base (the prefix
        # cache, plus any buffers MLX still pools): it can raise this
        # turn's peak.
        "residue_at_start_bytes": (
            current - base if current is not None and base is not None else None
        ),
        "swapouts_start": process_footprint.swapouts(),
        "pressure_start": process_footprint.pressure_level(),
        "spi_started": process_footprint.begin_peak_window(pid),
        "calls": [],
    }
    return (handle, pid, window_id)

brake_point(point, *, llm_id=None) classmethod

Take the brake's sample at point and execute its decision.

turn_start samples only when the loaded child is the one the turn for llm_id will use. Never raises: a failure is ONE WARNING with the exception's class name, and the sample is lost.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def brake_point(cls, point: str, *, llm_id: Any = None) -> BrakeOutcome:
    """Take the brake's sample at ``point`` and execute its decision.

    ``turn_start`` samples only when the loaded child is the one the turn
    for ``llm_id`` will use. Never raises: a failure is ONE WARNING with
    the exception's class name, and the sample is lost.
    """
    try:
        return cls._brake_point(point, llm_id)
    except Exception as exc:
        logger.warning(
            f"[MLX_Engine] Memory brake sample failed ({type(exc).__name__}): point={point}"
        )
        return BrakeOutcome()

claim_prefix(owner) classmethod

Make the prefix cache belong to owner, resetting it if needed.

Same owner: nothing to do. A fresh child: its pool is empty, so the owner is recorded without a reset. Anything else (another owner, a previous reset that failed -- <dirty> -- or no owner at all): reset, then record the owner. A failed reset leaves the owner <dirty> so the next claim retries; it never fails the turn.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def claim_prefix(cls, owner: str) -> None:
    """Make the prefix cache belong to ``owner``, resetting it if needed.

    Same owner: nothing to do. A fresh child: its pool is empty, so the
    owner is recorded without a reset. Anything else (another owner, a
    previous reset that failed -- ``<dirty>`` -- or no owner at all): reset,
    then record the owner. A failed reset leaves the owner ``<dirty>`` so
    the next claim retries; it never fails the turn.
    """
    handle = cls._model
    if not isinstance(handle, dict):
        return
    current = handle.get("prefix_owner")
    if current == owner:
        return
    if current == cls._PREFIX_OWNER_FRESH:
        handle["prefix_owner"] = owner
        return
    reason = "arena" if owner == "arena" else "conversation_change"
    if cls._reset_prefix_cache(handle, reason=reason):
        handle["prefix_owner"] = owner

compute_wire_tools(llm_local_path) classmethod

Verified tool-call wire capability on the mlx-vlm server (#298).

Runs mlx-vlm's OWN parser inference (_infer_tool_parser) on the model's chat template: the server picks its tool parser from exactly that function at load time, so this executes the same code the server executes — the verdict is exact by construction for the pinned mlx-vlm (0.6.13). A template matching no parser entry means the server streams the model's tool-call output as raw text (#295), hence wire False.

Tokenizer-level only (_load_capability_tokenizer: local files, no weights, no server). Any failure to load mlx-vlm or the tokenizer returns None (unverified) rather than a wrong verdict.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def compute_wire_tools(cls, llm_local_path: Union[str, Path]) -> Optional[bool]:
    """Verified tool-call wire capability on the mlx-vlm server (#298).

    Runs mlx-vlm's OWN parser inference (``_infer_tool_parser``) on the
    model's chat template: the server picks its tool parser from exactly
    that function at load time, so this executes the same code the server
    executes — the verdict is exact by construction for the pinned mlx-vlm
    (0.6.13). A template matching no parser entry means the server streams
    the model's tool-call output as raw text (#295), hence wire False.

    Tokenizer-level only (``_load_capability_tokenizer``: local files, no
    weights, no server). Any failure to load mlx-vlm or the tokenizer
    returns ``None`` (unverified) rather than a wrong verdict.
    """
    try:
        from mlx_vlm.tool_parsers import _infer_tool_parser
    except Exception:
        logger.warning(
            f"[MLX_Engine] wire tool detection unavailable (mlx_vlm import failed) "
            f"for {llm_local_path}"
        )
        return None
    try:
        tokenizer = cls._load_capability_tokenizer(llm_local_path)
    except Exception:
        logger.warning(
            f"[MLX_Engine] wire tool detection: could not load a tokenizer "
            f"for {llm_local_path}"
        )
        return None
    try:
        template = getattr(tokenizer, "chat_template", None)
        parser = _infer_tool_parser(template)
    except Exception:
        logger.warning(
            f"[MLX_Engine] wire tool detection: parser inference failed "
            f"for {llm_local_path}"
        )
        return None
    if parser is None:
        logger.info(
            f"[MLX_Engine] wire tools NOT verified for {llm_local_path}: "
            f"chat template matches no mlx-vlm tool parser"
        )
        return False
    logger.info(
        f"[MLX_Engine] wire tools verified for {llm_local_path}: "
        f"mlx-vlm inferred parser {parser}"
    )
    return True

end_memory_window(token, *, abandoned=False, compaction_threshold=None) classmethod

Close the window and record the turn's observation; returns it, or None when nothing could be recorded.

Recorded only on a MEASURED base (never the weights-on-disk fallback) and a window that really started. A child that died during the window is recorded too, child_died and no peak: it is the ground truth of an under-prediction. An ABANDONED turn whose call was cut before its usage arrived is recorded with n_est (the client's estimate of the call in flight) and no measured n; an estimate never raises the exceeded-prediction WARNING.

Whatever is recorded, the turn's largest request is written to handle["last_request_tokens"] first: the measured n, else the estimate of the call in flight (n_est: an abandoned turn, or one that recovered from an error before any usage arrived, such as a first-chunk timeout); a turn with neither keeps the previous value. compaction_threshold -- the threshold of the conversation that sent it, None for an arena turn -- is written beside it, to handle["last_request_threshold"], and only then: the pair stays the request of one turn and the trigger it is judged against. The memory brake shrinks the window only when the next turn would compact under it, and a missing SPI or base must not hide that.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def end_memory_window(
    cls, token: Any, *, abandoned: bool = False, compaction_threshold: Optional[int] = None
) -> Optional[Dict[str, Any]]:
    """Close the window and record the turn's observation; returns it, or
    ``None`` when nothing could be recorded.

    Recorded only on a MEASURED base (never the weights-on-disk fallback)
    and a window that really started. A child that died during the window
    is recorded too, ``child_died`` and no peak: it is the ground truth of
    an under-prediction. An ABANDONED turn whose call was cut before its
    usage arrived is recorded with ``n_est`` (the client's estimate of the
    call in flight) and no measured ``n``; an estimate never raises the
    exceeded-prediction WARNING.

    Whatever is recorded, the turn's largest request is written to
    ``handle["last_request_tokens"]`` first: the measured ``n``, else the
    estimate of the call in flight (``n_est``: an abandoned turn, or one
    that recovered from an error before any usage arrived, such as a
    first-chunk timeout); a turn with neither keeps the previous value.
    ``compaction_threshold`` -- the threshold of the conversation that
    sent it, ``None`` for an arena turn -- is written beside it, to
    ``handle["last_request_threshold"]``, and only then: the pair stays
    the request of one turn and the trigger it is judged against.
    The memory brake shrinks the window only when the next turn would
    compact under it, and a missing SPI or base must not hide that."""
    import time
    import uuid

    from src.engines import memory_observations, process_footprint
    from src.engines._mlx_vlm_server_runner import APC_BLOCK_SIZE_TOKENS
    from src.engines.memory_budget import MLX_BUFFER_CACHE_LIMIT, MemoryBudget, prior_scale

    if not token:
        return None
    handle, pid, window_id = token
    window = handle.get("memory_window") if isinstance(handle, dict) else None
    if (
        not isinstance(window, dict)
        or not window.get("open")
        or handle.get("pid") != pid
        or window.get("window") != window_id
    ):
        return None
    window["open"] = False
    calls = [call for call in window["calls"] if call["seq"] == window["seq"]]
    in_flight = window.get("in_flight")
    n_est = (
        in_flight.get("n_est")
        if isinstance(in_flight, dict) and in_flight.get("seq") == window["seq"]
        else None
    )
    if calls:
        largest = max(calls, key=lambda call: call["n_in"] + call["n_out"])
    else:
        largest = {"n_in": None, "n_out": None, "cached": None}
    n = (
        largest["n_in"] + largest["n_out"]
        if largest["n_in"] is not None and largest["n_out"] is not None
        else None
    )
    largest_request = n if n is not None else n_est
    if largest_request is not None:
        handle["last_request_tokens"] = largest_request
        handle["last_request_threshold"] = compaction_threshold
    base = handle.get("base_footprint_bytes")
    if not window.get("spi_started") or base is None:
        return None
    peak = process_footprint.peak_since(pid, True)
    child_died = peak is None and not cls._proc_is_alive(handle.get("proc"))
    measured = bool(calls) or child_died or (abandoned and n_est is not None)
    if (peak is None and not child_died) or not measured:
        return None
    budget = MemoryBudget.from_handle(cls, handle)
    scale = prior_scale()
    size = n if n is not None else n_est
    predicted = budget.predict(size) if size is not None else None
    if predicted is not None and scale != 1.0:
        predicted = int(predicted * scale)
    swap_start, swap_end = window.get("swapouts_start"), process_footprint.swapouts()
    pressures = [
        level
        for level in (window.get("pressure_start"), process_footprint.pressure_level())
        if level is not None
    ]
    has_images = any(call["has_images"] for call in calls)
    observation = {
        "id": uuid.uuid4().hex,
        "at": time.time(),
        "n": n,
        "n_est": n_est,
        "n_in": largest["n_in"],
        "n_out": largest["n_out"],
        "y_bytes": peak - base if peak is not None else None,
        "predicted_bytes": predicted,
        "cache_read": largest["cached"],
        "has_images": has_images,
        "abandoned": bool(abandoned),
        "residue_at_start_bytes": window.get("residue_at_start_bytes"),
        "pressure_level": max(pressures) if pressures else None,
        "swapouts": (
            swap_end - swap_start if swap_start is not None and swap_end is not None else None
        ),
        "spi_started": True,
        "child_died": child_died,
    }
    if scale != 1.0:
        observation["prior_scale"] = scale
    facts = handle.get("memory_facts") or {}
    components = memory_observations.key_components(
        model=facts.get("model_type"),
        artifact_bytes=facts.get("weights_bytes"),
        working_set_bytes=facts.get("working_set_bytes"),
        runtime={
            "apc_block_size": APC_BLOCK_SIZE_TOKENS,
            "prefill_step": facts.get("prefill_step"),
            "buffer_cache_limit": MLX_BUFFER_CACHE_LIMIT,
        },
    )
    try:
        memory_observations.record(components, base, observation)
    except Exception:
        # The observation is lost, nothing else: the turn already ended.
        logger.warning("[MLX_Engine] Recording a memory observation failed", exc_info=True)
    # The warning sets aside what the previous turn left in the child at
    # this turn's start: right after a large turn (a conversation switch
    # resets the prefix cache with no barrier) the OS reclaims that residue
    # over a few seconds (0.3-2.2 GiB measured, cache limit 0), and a small
    # turn would otherwise exceed ``predict`` at its own size (Qwen3-4B, 512
    # tokens after 8192: 2.93 GiB above base against 2.01 GiB predicted)
    # while the absolute footprint stayed far below the prediction of the
    # large turn the window was admitted for. The record keeps both raw.
    residue = observation["residue_at_start_bytes"]
    own_bytes = (
        observation["y_bytes"] - (residue if residue is not None and residue > 0 else 0)
        if observation["y_bytes"] is not None
        else None
    )
    if (
        predicted is not None
        and n is not None
        and not has_images
        and (own_bytes is not None and own_bytes > predicted)
    ):
        warned = handle.setdefault("memory_exceeded_warned", set())
        key = memory_observations.entry_key(components)
        if key not in warned:
            warned.add(key)
            model = str(facts.get("model_type")).encode("ascii", "backslashreplace").decode()
            logger.warning(
                f"Memory prediction exceeded on this machine (the app's memory estimate "
                f"was wrong here; nothing is corrected automatically): model={model}, "
                f"n_in={largest['n_in']}, n_out={largest['n_out']}, "
                f"peak_above_base_bytes={observation['y_bytes']}, "
                f"predicted_bytes={predicted}, "
                f"residue_bytes={observation['residue_at_start_bytes']}"
            )
    return observation

get_flat_hardware_data() classmethod

Get hardware data in flat format compatible with HardwareProfile entity.

Returns hardware specifications as a flat dictionary ready for database insertion. For MLX backend, get_performance_evaluation() already returns data in the correct flat format.

Returns:

Type Description
Dict[str, Any]

Flat dict with all fields matching HardwareProfile columns.

Raises:

Type Description
HardwareException

If hardware data collection fails.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def get_flat_hardware_data(cls) -> Dict[str, Any]:
    """Get hardware data in flat format compatible with HardwareProfile entity.

    Returns hardware specifications as a flat dictionary ready for database
    insertion. For MLX backend, get_performance_evaluation() already returns
    data in the correct flat format.

    Returns:
        Flat dict with all fields matching HardwareProfile columns.

    Raises:
        HardwareException: If hardware data collection fails.
    """
    # get_performance_evaluation() already returns flat structure
    return cls.get_performance_evaluation()

get_hardware_info() classmethod

Get comprehensive hardware information for Apple Silicon.

Returns detailed hardware specifications including Apple chip model, unified memory, MPS availability, and Neural Engine specs.

Returns:

Type Description
Dict[str, Any]

Dict containing hardware specifications following BaseEngine contract:

Dict[str, Any]

{ "system": {"platform": "Darwin", ...}, "cpu": {"model": str, "is_apple_silicon": True, ...}, "memory": {"total_memory_gb": float, "memory_type": "unified", ...}, "gpu": {"gpu_name": str, "mlx_gpu_cores": int, "unified_memory": True, ...}, "accelerator": {"neural_engine_tops": float, "architecture": str}, "storage": {"total_gb": float, "available_gb": float}, "backend_type": "mlx", "timestamp": float

Dict[str, Any]

}

Raises:

Type Description
HardwareException

If critical hardware detection fails.

Note

Returns fallback values on non-critical failures rather than raising.

Examples:

>>> hw_info = MLX_Engine.get_hardware_info()
>>> print(f"Chip: {hw_info['cpu']['model']}")
>>> print(f"GPU Cores: {hw_info['gpu']['mlx_gpu_cores']}")
Source code in backend/src/engines/mlx_engine.py
@classmethod
def get_hardware_info(cls) -> Dict[str, Any]:
    """Get comprehensive hardware information for Apple Silicon.

    Returns detailed hardware specifications including Apple chip model,
    unified memory, MPS availability, and Neural Engine specs.

    Returns:
        Dict containing hardware specifications following BaseEngine contract:
        {
            "system": {"platform": "Darwin", ...},
            "cpu": {"model": str, "is_apple_silicon": True, ...},
            "memory": {"total_memory_gb": float, "memory_type": "unified", ...},
            "gpu": {"gpu_name": str, "mlx_gpu_cores": int, "unified_memory": True, ...},
            "accelerator": {"neural_engine_tops": float, "architecture": str},
            "storage": {"total_gb": float, "available_gb": float},
            "backend_type": "mlx",
            "timestamp": float
        }

    Raises:
        HardwareException: If critical hardware detection fails.

    Note:
        Returns fallback values on non-critical failures rather than raising.

    Examples:
        >>> hw_info = MLX_Engine.get_hardware_info()
        >>> print(f"Chip: {hw_info['cpu']['model']}")
        >>> print(f"GPU Cores: {hw_info['gpu']['mlx_gpu_cores']}")
    """
    try:
        # Import required modules for hardware detection
        try:
            import psutil
            import cpuinfo
        except ImportError as e:
            logger.warning(f"Optional hardware detection dependency missing: {e}")

        # Detect chip model
        chip_model = cls._detect_apple_silicon_chip()

        # Get unified memory info
        vm = psutil.virtual_memory()
        total_memory_gb = vm.total / (1024**3)
        available_memory_gb = vm.available / (1024**3)
        memory_pressure = 1.0 - (vm.available / vm.total)

        # Get storage info
        disk = psutil.disk_usage(os.path.abspath(os.sep))
        disk_total_gb = disk.total / (1024**3)
        disk_available_gb = disk.free / (1024**3)
        disk_usage_pct = disk.percent

        # Get CPU info
        cpu_info_data = cpuinfo.get_cpu_info()
        cpu_model = cpu_info_data.get("brand_raw", "Apple Silicon CPU")
        total_cores = psutil.cpu_count(logical=False)
        logical_cores = psutil.cpu_count(logical=True)

        # Get chip specifications
        specs = cls._APPLE_SILICON_SPECS.get(chip_model, {}) if chip_model else {}
        gpu_cores = specs.get("gpu_cores", 0)
        memory_bandwidth = specs.get("memory_bandwidth", 0.0)
        neural_engine_tops = specs.get("neural_engine_tops", 0.0)
        architecture = specs.get("architecture", "Unknown")
        max_memory = specs.get("max_memory", 0)
        cpu_cores_breakdown = specs.get("cpu_cores", {})

        # Estimate TFLOPS (Apple doesn't publish official values)
        estimated_tflops = gpu_cores * 0.35 if gpu_cores else 0.0

        # Check MPS availability
        mps_supported = cls._mps_available()

        # Build hardware info dictionary
        hardware_info = {
            "system": {
                "platform": platform.system(),
                "platform_version": platform.version(),
                "machine": platform.machine(),
                "processor": platform.processor(),
            },
            "cpu": {
                "model": cpu_model,
                "architecture": platform.machine(),
                "total_cores": total_cores,
                "logical_cores": logical_cores,
                "is_apple_silicon": True,
                "performance_cores": cpu_cores_breakdown.get("performance"),
                "efficiency_cores": cpu_cores_breakdown.get("efficiency"),
            },
            "memory": {
                "total_memory_gb": round(total_memory_gb, 2),
                "available_memory_gb": round(available_memory_gb, 2),
                "memory_pressure": round(memory_pressure, 3),
                "memory_type": "unified",
            },
            "gpu": {
                "gpu_name": f"Apple {chip_model} GPU" if chip_model else "Apple GPU",
                "mlx_gpu_cores": gpu_cores,
                "memory_bandwidth_gbs": memory_bandwidth,
                "mps_supported": mps_supported,
                "unified_memory": True,
                "estimated_tflops": round(estimated_tflops, 2),
            },
            "accelerator": {
                "neural_engine_tops": neural_engine_tops,
                "architecture": architecture,
            },
            "storage": {
                "total_gb": round(disk_total_gb, 2),
                "available_gb": round(disk_available_gb, 2),
                "usage_percentage": round(disk_usage_pct, 2),
            },
            "backend_type": "mlx",
            "mlx_chip_model": chip_model,
            "timestamp": time.time(),
        }

        logger.info(
            f"MLX hardware detected: {chip_model}, {gpu_cores} GPU cores, {total_memory_gb:.1f}GB unified memory"
        )
        return hardware_info

    except Exception as e:
        logger.exception(f"MLX hardware detection failed: {e}")
        raise HardwareException("Failed to detect Apple Silicon hardware", trace=str(e))

get_performance_evaluation() classmethod

Calculate comprehensive performance metrics for Apple Silicon.

Evaluates hardware capabilities and returns performance scores for inference workloads. Scoring optimized for Apple Silicon unified memory architecture.

Scoring methodology
  • Inference: GPU compute (35%), memory bandwidth (30%), memory (20%), Neural Engine (10%), CPU (5%)

Returns:

Type Description
Dict[str, Any]

Dict containing performance metrics and scores (0-100 scale):

Dict[str, Any]

{ "backend_type": "mlx", "gpu_name": str, "cpu_model": str, "total_memory_gb": float, "available_memory_gb": float, "memory_bandwidth_gbs": float, "disk_total_gb": float, "disk_available_gb": float, "estimated_tflops": float, "mlx_gpu_cores": int, "cpu_performance_units": float, "neural_engine_tops": float, "architecture": str, "global_inference_score": float, "global_inference_label": str, "gpu_score": float, "cpu_score": float, "memory_score": float, "unified_memory": True, "mps_available": bool, "system_platform": "Darwin", "mlx_chip_model": str, "performance_breakdown": dict

Dict[str, Any]

}

Raises:

Type Description
HardwareException

If evaluation fails critically.

Examples:

>>> eval_result = MLX_Engine.get_performance_evaluation()
>>> print(f"Inference: {eval_result['global_inference_score']}/100")
>>> print(f"Label: {eval_result['global_inference_label']}")
Source code in backend/src/engines/mlx_engine.py
@classmethod
def get_performance_evaluation(cls) -> Dict[str, Any]:
    """Calculate comprehensive performance metrics for Apple Silicon.

    Evaluates hardware capabilities and returns performance scores for
    inference workloads. Scoring optimized for Apple Silicon unified memory
    architecture.

    Scoring methodology:
        - Inference: GPU compute (35%), memory bandwidth (30%), memory (20%),
          Neural Engine (10%), CPU (5%)

    Returns:
        Dict containing performance metrics and scores (0-100 scale):
        {
            "backend_type": "mlx",
            "gpu_name": str,
            "cpu_model": str,
            "total_memory_gb": float,
            "available_memory_gb": float,
            "memory_bandwidth_gbs": float,
            "disk_total_gb": float,
            "disk_available_gb": float,
            "estimated_tflops": float,
            "mlx_gpu_cores": int,
            "cpu_performance_units": float,
            "neural_engine_tops": float,
            "architecture": str,
            "global_inference_score": float,
            "global_inference_label": str,
            "gpu_score": float,
            "cpu_score": float,
            "memory_score": float,
            "unified_memory": True,
            "mps_available": bool,
            "system_platform": "Darwin",
            "mlx_chip_model": str,
            "performance_breakdown": dict
        }

    Raises:
        HardwareException: If evaluation fails critically.

    Examples:
        >>> eval_result = MLX_Engine.get_performance_evaluation()
        >>> print(f"Inference: {eval_result['global_inference_score']}/100")
        >>> print(f"Label: {eval_result['global_inference_label']}")
    """
    try:
        # Get base hardware info
        hw_info = cls.get_hardware_info()

        # Extract key metrics
        chip_model = hw_info.get("mlx_chip_model")
        gpu_cores = hw_info["gpu"]["mlx_gpu_cores"]
        estimated_tflops = hw_info["gpu"]["estimated_tflops"]
        memory_bandwidth = hw_info["gpu"]["memory_bandwidth_gbs"]
        neural_engine_tops = hw_info["accelerator"]["neural_engine_tops"]
        total_memory_gb = hw_info["memory"]["total_memory_gb"]
        available_memory_gb = hw_info["memory"]["available_memory_gb"]
        total_cores = hw_info["cpu"]["total_cores"]
        perf_cores = hw_info["cpu"].get("performance_cores", 4)

        # Calculate component scores (0-100 scale)

        # GPU/Accelerator score based on TFLOPS and GPU cores
        gpu_score = min(100, (estimated_tflops / 20.0) * 100)  # Normalize to 20 TFLOPS

        # Memory bandwidth score
        mem_bandwidth_score = min(
            100, (memory_bandwidth / 400.0) * 100
        )  # Normalize to 400 GB/s

        # Memory capacity score
        memory_capacity_score = min(100, (total_memory_gb / 64.0) * 100)  # Normalize to 64GB

        # Neural Engine score
        neural_score = min(100, (neural_engine_tops / 20.0) * 100)  # Normalize to 20 TOPS

        # CPU score based on performance cores
        cpu_performance_units = perf_cores * 2.5  # Weight performance cores higher
        cpu_score = min(100, (cpu_performance_units / 20.0) * 100)  # Normalize to 20 units

        # Calculate weighted inference score
        inference_score = (
            gpu_score * 0.35
            + mem_bandwidth_score * 0.30
            + memory_capacity_score * 0.20
            + neural_score * 0.10
            + cpu_score * 0.05
        )

        # Generate labels based on scores
        def get_label(score: float) -> str:
            if score >= 80:
                return "Excellent"
            elif score >= 60:
                return "Good"
            elif score >= 40:
                return "Fair"
            elif score >= 20:
                return "Poor"
            else:
                return "Weak"

        inference_label = get_label(inference_score)

        # Build performance breakdown
        performance_breakdown = {
            "compute_score": round(gpu_score, 2),
            "memory_bandwidth_score": round(mem_bandwidth_score, 2),
            "memory_capacity_score": round(memory_capacity_score, 2),
            "neural_engine_score": round(neural_score, 2),
            "cpu_performance_score": round(cpu_score, 2),
            "weights_inference": {
                "gpu_compute": 0.35,
                "memory_bandwidth": 0.30,
                "memory_capacity": 0.20,
                "neural_engine": 0.10,
                "cpu": 0.05,
            },
        }

        # Build complete evaluation result
        eval_result = {
            # Hardware identification
            "backend_type": "mlx",
            "gpu_name": hw_info["gpu"]["gpu_name"],
            "cpu_model": hw_info["cpu"]["model"],
            # Memory metrics
            "total_memory_gb": total_memory_gb,
            "available_memory_gb": available_memory_gb,
            "memory_bandwidth_gbs": memory_bandwidth,
            # Storage metrics
            "disk_total_gb": hw_info["storage"]["total_gb"],
            "disk_available_gb": hw_info["storage"]["available_gb"],
            # Compute metrics
            "estimated_tflops": estimated_tflops,
            "mlx_gpu_cores": gpu_cores,
            "cpu_performance_units": cpu_performance_units,
            # Apple Silicon specific
            "neural_engine_tops": neural_engine_tops,
            "architecture": hw_info["accelerator"]["architecture"],
            "mlx_chip_model": chip_model,
            # Performance scores (0-100)
            "global_inference_score": round(inference_score, 2),
            "global_inference_label": inference_label,
            "gpu_score": round(gpu_score, 2),
            "cpu_score": round(cpu_score, 2),
            "memory_score": round(memory_capacity_score, 2),
            # Technical details
            "unified_memory": True,
            "mps_available": hw_info["gpu"]["mps_supported"],
            "system_platform": hw_info["system"]["platform"],
            # Performance breakdown
            "performance_breakdown": performance_breakdown,
        }

        logger.info(
            f"Performance evaluation: Inference={inference_score:.1f}/100 ({inference_label})"
        )
        return eval_result

    except Exception as e:
        logger.exception(f"Performance evaluation failed: {e}")
        raise HardwareException("Failed to evaluate Apple Silicon performance", trace=str(e))

The GPU's usable working set in bytes, or None if unavailable.

On Apple Silicon Metal caps the GPU at a recommended working set well below total unified memory (~74 % of RAM; mlx-vlm pins the wired limit to it on every generation). That working set -- not total RAM -- is the hard ceiling the memory accounting plans against, so memory_budget.total_memory_bytes reads it here (#601), and the recorded memory observations carry it as part of their key.

Kept deliberately off get_flat_hardware_data / get_performance_evaluation: this fact does not belong in the persisted HardwareProfile schema; a dedicated method keeps the hardware knowledge in the engine without polluting the profile.

The mlx import is lazy (nothing at module import time may require mlx) and any failure answers None -- this may be called on a host where the query is unavailable.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def max_recommended_working_set_bytes(cls) -> Optional[int]:
    """The GPU's usable working set in bytes, or ``None`` if unavailable.

    On Apple Silicon Metal caps the GPU at a recommended working set well
    below total unified memory (~74 % of RAM; mlx-vlm pins the wired limit
    to it on every generation). That working set -- not total RAM -- is the
    hard ceiling the memory accounting plans against, so
    ``memory_budget.total_memory_bytes`` reads it here (#601), and the
    recorded memory observations carry it as part of their key.

    Kept deliberately off ``get_flat_hardware_data`` /
    ``get_performance_evaluation``: this fact does not belong in the
    persisted HardwareProfile schema; a dedicated method keeps the hardware
    knowledge in the engine without polluting the profile.

    The ``mlx`` import is lazy (nothing at module import time may require
    mlx) and any failure answers ``None`` -- this may be called on a host
    where the query is unavailable.
    """
    try:
        import mlx.core as mx

        return int(mx.device_info()["max_recommended_working_set_size"])
    except Exception:
        # No record here on purpose: the caller
        # (memory_budget.total_memory_bytes) writes the single degraded
        # record and simply leaves the memory accounting off when this is None.
        return None

memory_bound_tokens() classmethod

The memory bound applied to the loaded child, or None.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def memory_bound_tokens(cls) -> Optional[int]:
    """The memory bound applied to the loaded child, or ``None``."""
    handle = cls._model
    if not isinstance(handle, dict):
        return None
    bound = handle.get("memory_bound_tokens")
    if isinstance(bound, int) and not isinstance(bound, bool) and bound > 0:
        return bound
    return None

model_supports_vision(llm_local_path) classmethod

An MLX model is vision-capable iff its config.json declares vision.

Reads the directory's config.json only (no weights, no server) and defers the decision to config_declares_vision. Unreadable/absent config -> None (permissive).

Source code in backend/src/engines/mlx_engine.py
@classmethod
def model_supports_vision(cls, llm_local_path: Union[str, Path]) -> Optional[bool]:
    """An MLX model is vision-capable iff its ``config.json`` declares vision.

    Reads the directory's ``config.json`` only (no weights, no server) and
    defers the decision to ``config_declares_vision``. Unreadable/absent
    config -> ``None`` (permissive).
    """
    import json

    from src.engines.vision_capability import config_declares_vision

    try:
        model_dir = cls._resolve_model_artifact(llm_local_path)
        config = json.loads((model_dir / "config.json").read_text(encoding="utf-8"))
        return config_declares_vision(config)
    except Exception as exc:
        # Permissive fallback (the model stays usable, vision unverified):
        # a WARNING, with what went wrong -- an absent config and a corrupt
        # one are the same verdict here but not the same defect.
        logger.warning(
            f"[MLX_Engine] vision detection failed for {llm_local_path}: "
            f"{type(exc).__name__}: {exc}"
        )
        return None

note_call_start(handle, estimated_prompt_tokens) classmethod

A call is in flight: its estimated size, until its usage arrives.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def note_call_start(cls, handle: Any, estimated_prompt_tokens: int) -> None:
    """A call is in flight: its estimated size, until its usage arrives."""
    window = handle.get("memory_window") if isinstance(handle, dict) else None
    if not isinstance(window, dict) or not window.get("open"):
        return
    window["in_flight"] = {"seq": window["seq"], "n_est": int(estimated_prompt_tokens or 0)}

note_call_usage(handle, input_tokens, output_tokens, cached_tokens=0, has_images=False) classmethod

One call's usage, with the window's sequence number at push time.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def note_call_usage(
    cls,
    handle: Any,
    input_tokens: int,
    output_tokens: int,
    cached_tokens: int = 0,
    has_images: bool = False,
) -> None:
    """One call's usage, with the window's sequence number at push time."""
    window = handle.get("memory_window") if isinstance(handle, dict) else None
    if not isinstance(window, dict) or not window.get("open"):
        return
    window.pop("in_flight", None)
    window["calls"].append(
        {
            "seq": window["seq"],
            "n_in": int(input_tokens or 0),
            "n_out": int(output_tokens or 0),
            "cached": int(cached_tokens or 0),
            "has_images": bool(has_images),
        }
    )

note_stream_abandoned(handle) classmethod

Flag handle -- the child the stream was BUILT against, never the one loaded now -- so its next reset sends a barrier first.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def note_stream_abandoned(cls, handle: Any) -> None:
    """Flag ``handle`` -- the child the stream was BUILT against, never the
    one loaded now -- so its next reset sends a barrier first."""
    if isinstance(handle, dict):
        handle["abandoned"] = True

on_history_rewritten() classmethod

Compaction rewrote the history: the cached prefix is garbage, and the turn's memory measurement restarts (the summary call's peak and the hops before it never count).

Source code in backend/src/engines/mlx_engine.py
@classmethod
def on_history_rewritten(cls) -> None:
    """Compaction rewrote the history: the cached prefix is garbage, and
    the turn's memory measurement restarts (the summary call's peak and
    the hops before it never count)."""
    handle = cls._model
    if not isinstance(handle, dict):
        return
    cls._reset_prefix_cache(handle, reason="compaction")
    cls._restart_memory_window(handle)

validate_local_artifact(llm_local_path) classmethod

Integrity gate for an MLX snapshot (#88).

An MLX model is loadable iff its directory ships config.json + a tokenizer file + at least one weights file, each non-empty. Raises :class:EngineException with a curated, user-facing message on the first missing/empty essential. Backs both the download-completion gate and the pre-spawn load gate.

Source code in backend/src/engines/mlx_engine.py
@classmethod
def validate_local_artifact(cls, llm_local_path: Union[str, Path]) -> None:
    """Integrity gate for an MLX snapshot (#88).

    An MLX model is loadable iff its directory ships ``config.json`` + a
    tokenizer file + at least one weights file, each non-empty. Raises
    :class:`EngineException` with a curated, user-facing message on the
    first missing/empty essential. Backs both the download-completion gate
    and the pre-spawn load gate.
    """
    from src.engines import integrity

    integrity.validate_hf_snapshot(llm_local_path)

warm_up_accelerator(duration_seconds=1.0) classmethod

Warm up Apple Silicon GPU using Metal Performance Shaders.

Runs matrix operations on MPS device to bring GPU to optimal performance state before benchmarking or inference.

Parameters:

Name Type Description Default
duration_seconds float

How long to run warm-up operations (default: 1.0).

1.0

Returns:

Name Type Description
bool bool

True if warm-up completed successfully, False otherwise.

Note

Particularly important for Apple Silicon due to dynamic clock management.

Examples:

>>> success = MLX_Engine.warm_up_accelerator(1.5)
>>> if success:
...     print("MPS device ready")
Source code in backend/src/engines/mlx_engine.py
@classmethod
def warm_up_accelerator(cls, duration_seconds: float = 1.0) -> bool:
    """Warm up Apple Silicon GPU using Metal Performance Shaders.

    Runs matrix operations on MPS device to bring GPU to optimal performance
    state before benchmarking or inference.

    Args:
        duration_seconds: How long to run warm-up operations (default: 1.0).

    Returns:
        bool: True if warm-up completed successfully, False otherwise.

    Note:
        Particularly important for Apple Silicon due to dynamic clock management.

    Examples:
        >>> success = MLX_Engine.warm_up_accelerator(1.5)
        >>> if success:
        ...     print("MPS device ready")
    """
    if not cls._mps_available():
        logger.warning("MPS not available, skipping GPU warm-up")
        return False

    try:
        # Import required modules for hardware detection
        try:
            import torch
        except ImportError as e:
            logger.warning(f"Optional hardware detection dependency missing: {e}")

        logger.info(f"Warming up MPS device for {duration_seconds}s...")
        start_time = time.time()

        # Create tensors on MPS device
        device = torch.device("mps")
        size = 4096

        while (time.time() - start_time) < duration_seconds:
            # Matrix multiplication on GPU
            a = torch.randn(size, size, device=device)
            b = torch.randn(size, size, device=device)
            c = torch.matmul(a, b)

            # Small sleep to prevent CPU overload
            time.sleep(0.05)

        logger.info("MPS warm-up completed successfully")
        return True

    except Exception as e:
        logger.exception(f"MPS warm-up failed: {e}")
        return False