Skip to content

Hardware Domain

Hardware detection and inference scoring for the three engine backends: MLX (Apple Silicon), CUDA (NVIDIA) and CPU fallback.

Overview

Detection is delegated to the engine selected at startup by BaseEngine.get_engine(); the domain only persists the result and serves it. The engine that ends up selected can differ from what detection chose: user_settings.inference_backend pins the CPU engine when the user asked for it, and the CUDA pre-flight (src/engines/cuda_compatibility.py) reports — without changing anything — a GPU the bundled CUDA build cannot drive. See Hardware Detection.

Endpoints -> Service -> Repository -> HardwareProfile entity -> PostgreSQL
                 |
             Engine (MLX / CUDA / CPU)

The profile is a singleton row. Only an inference score is computed and stored — there is no fine-tuning or training score anywhere in the codebase.

API endpoints

The router is mounted with the /hardware prefix under the app-wide /erudi prefix, so the full paths are /erudi/hardware/....

GET /erudi/hardware/app_startup

Minimal payload consumed by the renderer on boot (HardwareAppStartupInfo in schemas.py). All six fields are required.

{
  "backend_type": "mlx",
  "global_inference_score": 92.0,
  "global_inference_label": "Excellent",
  "raw_inference_score": 72.0,
  "recommended_param_min": 4.0,
  "recommended_param_max": 14.0
}
  • global_inference_score is the boosted score, raw_inference_score the engine output.
  • recommended_param_min / recommended_param_max are the model-size window (in billions of parameters) that drives the "Models For You" list on the model page.

GET /erudi/hardware/detailed

Full diagnostics (DetailedHardwareInfo): the backend-specific hardware block, the typed performance breakdown, and the boosted score.

{
  "hardware": { "backend_type": "mlx", "...": "backend-specific fields" },
  "performance_breakdown": {
    "compute_score": 95.0,
    "memory_bandwidth_score": 92.0,
    "memory_capacity_score": 88.0,
    "cpu_performance_score": 75.0,
    "disk_score": 75.0
  },
  "boosted_inference_score": 92.0
}

The raw score stays available inside hardware.raw_inference_score.

POST /erudi/hardware/refresh

Re-runs detection through the engine and updates the stored profile. No request body.

{
  "message": "Hardware profile refreshed successfully",
  "backend_type": "mlx"
}

Useful after a hardware change, or to refresh the dynamic fields (available_memory_gb, disk_available_gb) without restarting the app.

Schemas

hardware/schemas.py builds the response types from a discriminated union keyed on backend_type:

  • BaseHardwareInfo — fields every backend provides (CPU model, memory, disk, raw_inference_score, global_inference_label, cpu_score, memory_score).
  • MLXHardwareInfo — adds mlx_chip_model, mlx_gpu_cores, mps_available, neural_engine_tops, estimated_tflops, memory_bandwidth_gbs, gpu_score, unified_memory.
  • CUDAHardwareInfo — adds gpu_name, cuda_cores, cuda_version, compute_capability, vram_total_gb, vram_available_gb, estimated_tflops, memory_bandwidth_gbs, gpu_score.
  • CPUHardwareInfo — adds compute_units, cpu_performance_units, accelerator_available; gpu_score is always 0.0.
  • PerformanceBreakdown — typed component scores (compute_score, memory_bandwidth_score, memory_capacity_score, cpu_performance_score, optional disk_score).

Scoring

Each engine implements get_performance_evaluation() and returns a single 0-100 inference score built from normalized component scores.

MLX (engines/mlx_engine.py)

Component Weight Normalization (= 100 points)
GPU compute 35 % 20 TFLOPS
Memory bandwidth 30 % 400 GB/s
Memory capacity 20 % 64 GB
Neural Engine 10 % 20 TOPS
CPU 5 % 20 CPU units (performance cores x 2.5)

CUDA (engines/cuda_engine.py)

Weights live in _WEIGHTS_INFERENCE, normalization factors in _NORM_INFERENCE.

Component Weight Normalization (= 100 points)
GPU compute (gpu_compute) 40 % 80 TFLOPS (BF16/FP16)
Memory bandwidth (gpu_bw) 30 % 500 GB/s
VRAM (gpu_vram) 15 % 12 GB
CPU single-core (cpu_single) 5 % 3.6 GHz
System RAM (sys_ram) 5 % 24 GB
PCIe (pcie) 5 % 32 (Gen3 x16 / Gen4 x8)

CPU (engines/cpu_engine.py)

Weights live in INF_WEIGHTS. Memory bandwidth is estimated, not measured: 1.5 GB/s per core.

Component Weight Normalization (= 100 points)
CPU cores 40 % 64 cores
Memory capacity 30 % 128 GB
Memory bandwidth 20 % 100 GB/s (estimated)
Disk 10 % 500 GB available

Display boost and labels

Hardware_Service.calculate_boosted_scores() returns both the raw score and a boosted one for the UI:

boosted_inf = min(100.0, raw_inf + 20.0)

The label is derived from the boosted score by Hardware_Service._get_label():

Boosted score Label
>= 80 Excellent
>= 60 Good
>= 40 Fair
>= 20 Poor
< 20 Weak

Service layer

from src.domains.hardware.services import Hardware_Service

service = Hardware_Service(repository)

profile = service.get_or_create_profile()   # cached singleton, detects on first call
scores = service.calculate_boosted_scores(profile)
service.warm_up(duration_seconds=5)         # warm the accelerator before benchmarking
profile = service.refresh_profile()         # force re-detection
db.commit()

Engine contract

Every engine implements the same three hardware class methods:

@classmethod
def get_hardware_info(cls) -> Dict[str, Any]: ...

@classmethod
def warm_up_accelerator(cls, duration_seconds: float) -> bool: ...

@classmethod
def get_performance_evaluation(cls) -> Dict[str, Any]: ...

get_flat_hardware_data() flattens the nested detection dict into the columns the entity stores.

Database entity

HardwareProfile (entities/HardwareProfile.py) is a singleton row with backend-specific columns left nullable. It stores global_inference_score and global_inference_label (no fine-tuning columns) plus the JSON performance_breakdown.

It has no compute_units column: the CPU count is stored in cpu_performance_units and cast to an int when the endpoint builds CPUHardwareInfo.

Frontend

frontend/src/utils/hardwareTransform.js exports a single helper, transformAppStartupInfo, used to normalize the /erudi/hardware/app_startup payload for the renderer.

Troubleshooting

Stale hardware data — force a re-detection:

curl -X POST http://127.0.0.1:27182/erudi/hardware/refresh

Missing backend-specific fields — branch on the backend_type discriminator before reading mlx_*, cuda_* or CPU-only fields; each backend only populates its own.

Code reference

src.domains.hardware.endpoints

REST API endpoints for backend-agnostic hardware information.

Provides hardware detection, scoring, and monitoring endpoints across all backends (MLX/Apple Silicon, CUDA/NVIDIA, CPU fallback). Uses discriminated unions and transparent score boosting for optimal type safety and user experience.

Endpoints

GET /hardware/app_startup: Minimal UI data with boosted scores GET /hardware/detailed: Comprehensive diagnostics with raw/boosted scores POST /hardware/refresh: Force hardware re-detection

Architecture

Endpoints → Service → Repository → Entity → Database

get_app_startup_info(db=Depends(get_db))

Get minimal performance scores for application startup dashboard.

Returns boosted scores (+20 points, capped at 100) for user-friendly display alongside raw scores for transparency. This endpoint is optimized for quick loading on app startup.

Response structure

{ "backend_type": "cuda", "global_inference_score": 100.0, # Boosted, capped at 100 "global_inference_label": "Excellent", "raw_inference_score": 82.0 # Actual hardware score }

Raises:

Type Description
HTTPException

500 if hardware detection fails

Source code in backend/src/domains/hardware/endpoints.py
@router.get("/app_startup", response_model=HardwareAppStartupInfo)
def get_app_startup_info(db: Session = Depends(get_db)):
    """Get minimal performance scores for application startup dashboard.

    Returns boosted scores (+20 points, capped at 100) for user-friendly display
    alongside raw scores for transparency. This endpoint is optimized for quick
    loading on app startup.

    Response structure:
        {
            "backend_type": "cuda",
            "global_inference_score": 100.0,     # Boosted, capped at 100
            "global_inference_label": "Excellent",
            "raw_inference_score": 82.0          # Actual hardware score
        }

    Raises:
        HTTPException: 500 if hardware detection fails
    """
    try:
        service = _get_service(db)
        profile = service.get_or_create_profile()
        scores = service.calculate_boosted_scores(profile)

        response = HardwareAppStartupInfo(
            backend_type=profile.backend_type,
            global_inference_score=scores["boosted_inference_score"],
            global_inference_label=scores["global_inference_label"],
            raw_inference_score=scores["raw_inference_score"],
            recommended_param_min=scores["recommended_param_min"],
            recommended_param_max=scores["recommended_param_max"],
        )

        db.commit()
        logger.info(
            f"App startup info retrieved: backend={profile.backend_type}, "
            f"boosted_inf={scores['boosted_inference_score']:.1f}, "
            f"raw_inf={scores['raw_inference_score']:.1f}"
        )
        return response

    except (HardwareException, DatabaseException) as e:
        # Already logged with its traceback where it was raised (services /
        # repository); a second record here would show one failure twice.
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        db.rollback()
        logger.exception(f"Unexpected error in get_app_startup_info: {e}")
        raise HTTPException(status_code=500, detail="Internal server error")

get_detailed_hardware_info(db=Depends(get_db))

Get comprehensive hardware diagnostics with raw/boosted score comparison.

Returns complete backend-specific hardware profile plus performance breakdown and both raw/boosted scores for debugging and diagnostics.

Response structure

{ "hardware": { ...full backend-specific fields... }, "performance_breakdown": { ...typed scores... }, "boosted_inference_score": 85.0 }

Note

Raw score available in hardware.raw_inference_score

Raises:

Type Description
HTTPException

500 if hardware detection fails

Source code in backend/src/domains/hardware/endpoints.py
@router.get("/detailed", response_model=DetailedHardwareInfo)
def get_detailed_hardware_info(db: Session = Depends(get_db)):
    """Get comprehensive hardware diagnostics with raw/boosted score comparison.

    Returns complete backend-specific hardware profile plus performance breakdown
    and both raw/boosted scores for debugging and diagnostics.

    Response structure:
        {
            "hardware": { ...full backend-specific fields... },
            "performance_breakdown": { ...typed scores... },
            "boosted_inference_score": 85.0
        }

    Note:
        Raw score available in hardware.raw_inference_score

    Raises:
        HTTPException: 500 if hardware detection fails
    """
    try:
        service = _get_service(db)
        profile = service.get_or_create_profile()
        scores = service.calculate_boosted_scores(profile)

        backend_schema = _build_backend_specific_schema(profile, scores)
        perf_breakdown = _build_performance_breakdown(profile)

        response = DetailedHardwareInfo(
            hardware=backend_schema,
            performance_breakdown=perf_breakdown,
            boosted_inference_score=scores["boosted_inference_score"],
        )

        db.commit()
        logger.info(f"Detailed hardware info retrieved: backend={profile.backend_type}")
        return response

    except (HardwareException, DatabaseException) as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        db.rollback()
        logger.exception(f"Unexpected error in get_detailed_hardware_info: {e}")
        raise HTTPException(status_code=500, detail="Internal server error")

refresh_hardware_profile(db=Depends(get_db))

Force hardware re-detection and update cached profile.

Performs fresh hardware detection through engine and updates database profile. Useful for detecting hardware changes (RAM upgrade, new GPU) or refreshing dynamic fields (available_memory_gb, disk_available_gb) without app restart.

Returns:

Name Type Description
dict

Confirmation message with backend_type

Example response

{ "message": "Hardware profile refreshed successfully", "backend_type": "mlx" }

Raises:

Type Description
HTTPException

500 if refresh fails

Source code in backend/src/domains/hardware/endpoints.py
@router.post("/refresh")
def refresh_hardware_profile(db: Session = Depends(get_db)):
    """Force hardware re-detection and update cached profile.

    Performs fresh hardware detection through engine and updates database profile.
    Useful for detecting hardware changes (RAM upgrade, new GPU) or refreshing
    dynamic fields (available_memory_gb, disk_available_gb) without app restart.

    Returns:
        dict: Confirmation message with backend_type

    Example response:
        {
            "message": "Hardware profile refreshed successfully",
            "backend_type": "mlx"
        }

    Raises:
        HTTPException: 500 if refresh fails
    """
    try:
        service = _get_service(db)
        profile = service.refresh_profile()
        db.commit()

        logger.info(f"Hardware profile refreshed: backend={profile.backend_type}")
        return {
            "message": "Hardware profile refreshed successfully",
            "backend_type": profile.backend_type,
        }

    except (HardwareException, DatabaseException) as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        db.rollback()
        logger.exception(f"Unexpected error in refresh_hardware_profile: {e}")
        raise HTTPException(status_code=500, detail="Internal server error")

src.domains.hardware.schemas

Pydantic validation schemas for backend-agnostic hardware information.

Defines response schemas for hardware detection endpoints across all backends (MLX/CUDA/CPU). Uses discriminated unions and inheritance to reduce duplication while maintaining type safety for backend-specific fields.

Architecture
  • BaseHardwareInfo: Common fields shared by all backends
  • MLXHardwareInfo/CUDAHardwareInfo/CPUHardwareInfo: Backend-specific extensions
  • PerformanceBreakdown: Typed performance metrics (replaces Dict[str, Any])
  • Endpoint-specific views: Training, AppStartup, Detailed
Example

Training endpoint returns full backend-specific schema::

{
    "backend_type": "mlx",
    "mlx_chip_model": "M3 Max",
    "mlx_gpu_cores": 40,
    ...
}

App startup returns minimal UI data::

{
    "backend_type": "cuda",
    "raw_inference_score": 82.5,
    "boosted_inference_score": 100.0,
    ...
}

BaseHardwareInfo

Bases: BaseModel

Common fields shared by all backends.

All engines must provide these fields. Backend-specific fields defined in subclasses.

CPUHardwareInfo

Bases: BaseHardwareInfo

CPU-only backend (fallback) hardware fields.

CUDAHardwareInfo

Bases: BaseHardwareInfo

NVIDIA CUDA specific hardware fields.

DetailedHardwareInfo

Bases: BaseModel

Comprehensive hardware profile for debugging and diagnostics.

Returns full backend-specific data plus performance breakdown and raw/boosted score comparison.

HardwareAppStartupInfo

Bases: BaseModel

Essential performance metrics for application startup dashboard.

Returns minimal UI data with transparent score boosting for user-friendly display. Raw scores preserved for debugging.

MLXHardwareInfo

Bases: BaseHardwareInfo

Apple Silicon (MLX) specific hardware fields.

PerformanceBreakdown

Bases: BaseModel

Typed performance breakdown replacing Dict[str, Any].

Scores are normalized 0-100 scale representing component contributions to overall performance.

src.domains.hardware.services

Business logic layer for hardware domain.

Implements Service pattern for hardware operations. Handles hardware detection, profile management, score calculation, and labeling logic.

Architecture

Endpoints → Service → Repository → Entity → Database

Key Responsibilities
  • Orchestrate hardware detection through LLM_Engine
  • Manage hardware profile lifecycle (get_or_create pattern)
  • Calculate boosted scores for UI display (+20 points)
  • Generate performance labels (Excellent, Good, Fair, Poor, Weak)
  • Format performance_breakdown structure
Example

from src.domains.hardware.services import Hardware_Service from src.domains.hardware.repository import Hardware_Repository from src.database.core import SessionLocal

db = SessionLocal() repo = Hardware_Repository(db) service = Hardware_Service(repo)

profile = service.get_or_create_profile() boosted = service.calculate_boosted_scores(profile) db.commit()

Hardware_Service(repository)

Service layer for hardware domain business logic.

Orchestrates hardware detection, profile management, and score calculations. Separates business logic from data access and API concerns.

Attributes:

Name Type Description
repository

Hardware_Repository for data access operations.

Note

Service methods do NOT commit. Commits are handled at endpoint level. Uses repository for all database operations.

Example

service = Hardware_Service(Hardware_Repository(db)) profile = service.get_or_create_profile() boosted = service.calculate_boosted_scores(profile) print(boosted["global_inference_score"]) # +20 boost 85.0

Initialize service with repository.

Parameters:

Name Type Description Default
repository Hardware_Repository

Hardware_Repository instance for data access.

required
Source code in backend/src/domains/hardware/services.py
def __init__(self, repository: Hardware_Repository):
    """Initialize service with repository.

    Args:
        repository: Hardware_Repository instance for data access.
    """
    self.repository = repository
    logger.debug("Initializing Hardware_Service")

calculate_boosted_scores(profile)

Calculate UI-friendly scores with +20 boost for frontend display.

Returns both raw scores (actual hardware capability) and boosted scores (UI-friendly display with +20 point boost, capped at 100). This makes the boost transparent while maintaining user-friendly presentation.

Parameters:

Name Type Description Default
profile HardwareProfile

HardwareProfile entity with original scores.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Dictionary with both raw and boosted scores/labels.

Example

profile = service.get_or_create_profile() scores = service.calculate_boosted_scores(profile) print(scores) { "raw_inference_score": 65.0, "boosted_inference_score": 85.0, # min(65 + 20, 100) "global_inference_label": "Excellent", # Based on boosted ... }

Source code in backend/src/domains/hardware/services.py
def calculate_boosted_scores(self, profile: HardwareProfile) -> Dict[str, Any]:
    """Calculate UI-friendly scores with +20 boost for frontend display.

    Returns both raw scores (actual hardware capability) and boosted scores
    (UI-friendly display with +20 point boost, capped at 100). This makes
    the boost transparent while maintaining user-friendly presentation.

    Args:
        profile: HardwareProfile entity with original scores.

    Returns:
        Dict[str, Any]: Dictionary with both raw and boosted scores/labels.

    Example:
        >>> profile = service.get_or_create_profile()
        >>> scores = service.calculate_boosted_scores(profile)
        >>> print(scores)
        {
            "raw_inference_score": 65.0,
            "boosted_inference_score": 85.0,  # min(65 + 20, 100)
            "global_inference_label": "Excellent",  # Based on boosted
            ...
        }
    """
    logger.debug("Calculating raw and boosted scores")

    # Raw score (actual hardware capability)
    raw_inf = profile.global_inference_score

    # Boosted score for UI (+ 20 points, capped at 100)
    boosted_inf = min(100.0, raw_inf + 20.0)

    result = {
        # Raw score (engine output, no modification)
        "raw_inference_score": raw_inf,
        # Boosted score for UI display
        "boosted_inference_score": boosted_inf,
        "global_inference_score": boosted_inf,  # Alias for backward compat
        # Label based on boosted score
        "global_inference_label": self._get_label(boosted_inf),
        # Component scores (raw, no boost needed for internal metrics)
        "cpu_score": profile.cpu_score,
        "memory_score": profile.memory_score,
        "gpu_score": profile.gpu_score if profile.gpu_score is not None else 0.0,
    }

    # Hardware-fit model size window (billions of params) for the UI's
    # "Models For You" recommendations (#86), derived from real usable memory.
    param_min, param_max = recommended_param_range(profile)
    result["recommended_param_min"] = param_min
    result["recommended_param_max"] = param_max

    logger.debug(f"Scores calculated: raw_inf={raw_inf:.1f}, boosted_inf={boosted_inf:.1f}")
    return result

get_or_create_profile()

Get cached hardware profile or detect new one.

Retrieves existing hardware profile from database. If none exists or if the cached profile backend doesn't match the current engine, performs hardware detection and creates new profile.

Returns:

Name Type Description
HardwareProfile HardwareProfile

Existing or newly created profile.

Raises:

Type Description
HardwareException

If hardware detection or profile creation fails.

Note

Does NOT commit. Caller must commit transaction.

Example

service = Hardware_Service(repo) profile = service.get_or_create_profile() print(profile.backend_type) # "mlx", "cuda", or "cpu"

Source code in backend/src/domains/hardware/services.py
def get_or_create_profile(self) -> HardwareProfile:
    """Get cached hardware profile or detect new one.

    Retrieves existing hardware profile from database. If none exists or
    if the cached profile backend doesn't match the current engine,
    performs hardware detection and creates new profile.

    Returns:
        HardwareProfile: Existing or newly created profile.

    Raises:
        HardwareException: If hardware detection or profile creation fails.

    Note:
        Does NOT commit. Caller must commit transaction.

    Example:
        >>> service = Hardware_Service(repo)
        >>> profile = service.get_or_create_profile()
        >>> print(profile.backend_type)  # "mlx", "cuda", or "cpu"
    """
    try:
        logger.info("Getting or creating hardware profile")

        # Try to get existing profile
        profile = self.repository.get_profile()

        # Extract backend type from current engine name
        current_backend = config.LLM_Engine.__name__.lower().replace("_engine", "")

        if profile:
            stored_version = getattr(profile, "profiling_version", None)
            if profile.backend_type != current_backend:
                # No profile exists or backend mismatch, detect hardware
                logger.info(
                    f"Backend mismatch: cached={profile.backend_type}, current={current_backend}. Re-detecting."
                )
                self.repository.delete_profile(profile)
            elif stored_version != PROFILING_LOGIC_VERSION:
                # Same machine, but the numbers were produced by profiling
                # logic we have since corrected (#365). Redo them, otherwise
                # the fix never reaches anyone who already ran the app.
                logger.info(
                    f"Profiling logic changed: cached=v{stored_version}, "
                    f"current=v{PROFILING_LOGIC_VERSION}. Re-detecting."
                )
                self.repository.delete_profile(profile)
            else:
                logger.info(f"Using cached hardware profile: backend={profile.backend_type}")
                return profile
        else:
            logger.info("No cached profile found, detecting hardware")

        hardware_data = self._detect_hardware()

        # Create new profile
        profile = self.repository.create_profile(hardware_data)
        logger.info(f"Hardware profile created: backend={profile.backend_type}")

        return profile

    except HardwareException:
        raise  # logged where it was raised
    except Exception as e:
        logger.exception(f"Failed to get or create hardware profile: {e}")
        raise HardwareException("Failed to retrieve hardware information", trace=str(e))

refresh_profile()

Re-detect hardware and update existing profile.

Performs fresh hardware detection and updates existing profile with new data. Useful for detecting hardware changes or refreshing dynamic fields (available_memory_gb, disk_available_gb).

Returns:

Name Type Description
HardwareProfile HardwareProfile

Updated profile entity.

Raises:

Type Description
HardwareException

If refresh fails.

Note

Does NOT commit. Caller must commit transaction.

Example

service = Hardware_Service(repo) profile = service.refresh_profile() db.commit()

Source code in backend/src/domains/hardware/services.py
def refresh_profile(self) -> HardwareProfile:
    """Re-detect hardware and update existing profile.

    Performs fresh hardware detection and updates existing profile with
    new data. Useful for detecting hardware changes or refreshing dynamic
    fields (available_memory_gb, disk_available_gb).

    Returns:
        HardwareProfile: Updated profile entity.

    Raises:
        HardwareException: If refresh fails.

    Note:
        Does NOT commit. Caller must commit transaction.

    Example:
        >>> service = Hardware_Service(repo)
        >>> profile = service.refresh_profile()
        >>> db.commit()
    """
    try:
        logger.info("Refreshing hardware profile")

        # Detect current hardware state
        hardware_data = self._detect_hardware()

        # Get existing profile
        profile = self.repository.get_profile()
        if not profile:
            # No profile exists, create new
            logger.info("No profile to refresh, creating new")
            profile = self.repository.create_profile(hardware_data)
        else:
            # Update existing profile
            logger.info(f"Updating existing profile: id={profile.id}")
            profile = self.repository.update_profile(profile, hardware_data)

        logger.info("Hardware profile refreshed successfully")
        return profile

    except HardwareException:
        raise  # logged where it was raised
    except Exception as e:
        logger.exception(f"Failed to refresh hardware profile: {e}")
        raise HardwareException("Failed to refresh hardware profile", trace=str(e))

warm_up(duration_seconds=5)

Warm up hardware accelerator (GPU/MPS/CUDA).

Delegates to LLM_Engine's warm_up_accelerator() method. Useful before benchmarking or first inference to ensure accurate performance.

Parameters:

Name Type Description Default
duration_seconds int

How long to run warm-up routine.

5

Returns:

Name Type Description
bool bool

True if warm-up succeeded, False otherwise.

Raises:

Type Description
HardwareException

If warm-up fails critically.

Example

service = Hardware_Service(repo) success = service.warm_up(duration_seconds=5) if success: ... print("Accelerator ready")

Source code in backend/src/domains/hardware/services.py
def warm_up(self, duration_seconds: int = 5) -> bool:
    """Warm up hardware accelerator (GPU/MPS/CUDA).

    Delegates to LLM_Engine's warm_up_accelerator() method. Useful before
    benchmarking or first inference to ensure accurate performance.

    Args:
        duration_seconds: How long to run warm-up routine.

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

    Raises:
        HardwareException: If warm-up fails critically.

    Example:
        >>> service = Hardware_Service(repo)
        >>> success = service.warm_up(duration_seconds=5)
        >>> if success:
        ...     print("Accelerator ready")
    """
    try:
        logger.info(f"Starting hardware warm-up: duration={duration_seconds}s")

        if not config.LLM_Engine:
            logger.warning("LLM_Engine not initialized, skipping warm-up")
            return False

        success = config.LLM_Engine.warm_up_accelerator(duration_seconds)

        if success:
            logger.info("Hardware warm-up completed successfully")
        else:
            logger.warning("Hardware warm-up failed or not available")

        return success

    except Exception as e:
        logger.exception(f"Hardware warm-up failed: {e}")
        raise HardwareException("Failed to warm up hardware accelerator", trace=str(e))

recommended_param_range(profile)

Recommended model size window (billions of params) this machine runs comfortably at 4-bit: the smaller of what fits and what runs fast enough.

Source code in backend/src/domains/hardware/services.py
def recommended_param_range(profile: HardwareProfile) -> tuple[float, float]:
    """Recommended model size window (billions of params) this machine runs
    comfortably at 4-bit: the smaller of what fits and what runs fast enough."""
    usable_gb = _usable_inference_memory_gb(profile)
    weight_budget_gb = max(0.0, usable_gb - _INFERENCE_OVERHEAD_RESERVE_GB)
    max_params = weight_budget_gb / _GB_PER_BILLION_PARAMS_Q4

    bandwidth_cap = _bandwidth_param_cap(profile)
    if bandwidth_cap is not None:
        max_params = min(max_params, bandwidth_cap)

    max_params = max(_MIN_PARAM_FLOOR, min(max_params, _MAX_PARAM_CEILING))
    min_params = min(max_params * 0.5, _MAX_RECOMMENDED_MIN_PARAMS)
    min_params = max(_MIN_PARAM_FLOOR, min(min_params, max_params))
    return (round(min_params, 1), round(max_params, 1))