Local LLM Inference Stability on Windows: A Practical Guide to Crash Handling

    This guide explains how to tell floating-point errors from memory access violations when running large local language models, and why language-level error handling alone is not enough. It covers process supervision with automatic restarts and crash dumps, process and API design for desktop apps, Windows installation checks and DLL lookup order, and CLI documentation with a structured index.

    1. Two Types of Crashes: Floating-Point Errors and Memory Access Violations

    Process crashes are common when running local models with tens of billions of parameters, but they have different causes. Identify the type of crash before you start debugging.

    Floating-point errors are numerical errors. They include overflow to infinity (Inf) in FP16, propagation of not-a-number (NaN) values, and division by zero. The maximum representable value in FP16 is about 65504. If an intermediate result in an attention score or in the variance calculation of LayerNorm exceeds this range, it becomes Inf, and later operations then produce NaN. BF16 uses the same exponent width as FP32, so it has a larger dynamic range. In some cases it overflows less often than FP16, but its precision is lower. Choose between them based on benchmarks on your model and hardware.

    Memory access violations occur when a program accesses a memory address it does not own. They usually appear as segmentation faults. Common causes include pointer arithmetic errors in custom operators, incorrect buffer length calculations, and type mismatches in FFI calls. These problems are not related to numerical values, so changing the clipping logic for values will not fix them.

    The two types require different debugging methods. For numerical problems, check whether tensors are finite at key points:

    1. import torch
    2. def check_finite(tensor: torch.Tensor, name: str) -> torch.Tensor:
    3. mask = ~torch.isfinite(tensor)
    4. if mask.any():
    5. count = int(mask.sum().item())
    6. raise ValueError(f"{name} contains {count} non-finite values (NaN or Inf)")
    7. return tensor

    Keep these checks in debug or canary environments only. Running a full check at every step in production noticeably slows down inference.

    For memory access violations, enable AddressSanitizer (ASan) at compile time, and use compute-sanitizer to locate illegal accesses on the GPU side. When debugging, set the environment variable CUDA_LAUNCH_BLOCKING=1. This maps errors to the kernel call that actually failed. Without it, GPU asynchronous execution makes the stack trace point to unrelated code that runs later.

    Numerical clipping also has costs. Clipping extreme values to a valid range prevents crashes, but it changes the computed results, and output quality may drop. Before release, compare perplexity or task accuracy before and after the change on a fixed evaluation set, and record the differences. Do not judge the change only by whether the process keeps running.

    2. Language-Level Error Handling: Narrower Than Often Assumed

    Some articles claim that writing an inference engine in Rust or Go prevents crashes. This claim needs qualification.

    In Rust, recoverable errors should be returned as Result values and propagated upward with the ? operator. A panic can be caught with std::panic::catch_unwind, but only if the build is configured with panic = "unwind". If the build uses panic = "abort", a panic terminates the process immediately and cannot be caught. In addition, segmentation faults in unsafe code and FFI calls are not converted into panics, so catch_unwind cannot intercept them.

    In Go, recover only catches a panic inside a defer function in the same goroutine. Concurrent writes to the same map, stack overflow, and memory exhaustion are fatal runtime errors. recover cannot catch them, and the process exits immediately.

    Language-level error handling therefore covers only some failures. It reduces crashes caused by foreseeable errors, but it cannot replace process-level supervision.

    3. Process Supervision as a Fallback: Automatic Recovery After Crashes

    Run the inference engine as a separate child process, and let a supervisor program monitor it. The supervisor needs to do four things: detect the child process’s exit code, save logs from before and after the crash, restart the process according to a backoff policy, and stop restarting and alert the user after repeated failures exceed a threshold.

    An exponential backoff policy works well for restarts. For example, wait 2 seconds before the first retry, then 4 seconds, then 8 seconds, and retry up to 5 times. If the engine still fails after that, stop retrying and keep the last error message. Frequent restarts reload the model over and over. This fills up VRAM and slows down the whole system.

    Crash dump collection must be configured in advance. On Linux, run ulimit -c unlimited to enable core file generation, then load the executable and the core file in gdb to analyze the call stack. On Windows, you can collect dumps through Windows Error Reporting (WER), or call the MiniDumpWriteDump function from the dbghelp library in your program to write a dump file when an exception occurs.

    4. Process and Interface Design for Desktop Apps

    The desktop app and the inference engine should have a controller-and-worker relationship. The controller starts, pauses, and stops the engine process. The frontend only reads the engine’s status and does not hold model weights directly. This way, if the UI crashes, the inference process can keep running independently or be shut down safely.

    Bind the local API to the loopback address 127.0.0.1 so that other machines on the local network cannot reach it. If you need authentication, generate a random token at startup and pass it to frontend components that call the API through an environment variable or a startup argument. Never write the token to logs or configuration files.

    The health check endpoint can return the engine’s status in a consistent format. Example:

    1. {
    2. "status": "ready",
    3. "model": "demo-7b-q4",
    4. "uptime_seconds": 3620,
    5. "last_error": null
    6. }

    Verify cross-platform behavior separately. System tray implementations differ widely across Linux desktop environments, and notification permissions are requested differently on Windows and macOS. Test these features on each target system, and do not assume they behave the same way.

    5. Windows Installation and Path Lookup: Actionable Checks

    Before launching the inference engine, the Windows installation script should check three kinds of dependencies: the Visual C++ runtime, the GPU driver, and the dynamic link libraries that the executable depends on. If a dependency is missing, the script should print a clear message with a download link, instead of only reporting an error code that users cannot interpret.

    Here is a PowerShell check example:

    1. # Check for the Visual C++ runtime
    2. if (-not (Test-Path "$env:SystemRoot\System32\vcruntime140.dll")) {
    3. Write-Host "The Visual C++ runtime is missing. Please install vc_redist.x64.exe first."
    4. exit 1
    5. }
    6. # Check whether the NVIDIA driver is available
    7. if (-not (Get-Command nvidia-smi -ErrorAction SilentlyContinue)) {
    8. Write-Host "nvidia-smi was not found. The engine will run in CPU mode."
    9. }

    Handle installation permissions as well. If the user does not have administrator rights, the installer should fall back to a user directory under %LOCALAPPDATA% instead of forcing a write to Program Files. Installations that fail due to insufficient permissions are among the most common complaints from Windows users.

    Search for the engine’s executable and dynamic libraries in a fixed order. The recommended fallback sequence is:

    1. The path specified in the startup arguments.
    2. The directory pointed to by the MODEL_ENGINE_HOME environment variable.
    3. The bin subdirectory of the application’s install directory.
    4. A backup directory under %LOCALAPPDATA% in the user’s profile.
    5. The path read from the App Paths registry entry, if the installer wrote one.

    Place the dependent DLLs in the same directory as the executable when possible. The default DLL search order on Windows checks the executable’s directory first. This reduces reliance on the system PATH and prevents loading an outdated DLL with a mismatched version.

    The test matrix should cover the main combinations of operating systems and hardware. This is a minimal example:

    OS Version Architecture Acceleration Hardware Key Validation
    Windows 10 22H2 x64 CPU only Installation, startup, basic inference
    Windows 11 23H2 x64 CPU only Installation, startup, basic inference
    Windows 11 23H2 x64 NVIDIA GPU Driver detection, VRAM usage, inference output
    Windows 11 23H2 ARM64 CPU only Installer architecture match, dependency library loading
    Windows 11 23H2 x64 Integrated GPU or NPU Whether it falls back to CPU when acceleration is unavailable

    Each cell passes only if all four checks succeed: installation, startup, one completed inference, and uninstallation. If a combination is not supported, state that clearly in the documentation. Do not leave the cell empty.

    6. CLI Documentation and Structured Index

    Document each CLI subcommand separately. Each entry should list the parameter names, types, default values, whether the parameter is required, a typical command, and sample output. For example, the quantize command can be written as:

    1. engine-cli quantize --input ./models/demo.bin --bits 4 --output ./models/demo-q4.bin

    To support parsing by IDE plugins or automation pipelines, you can also provide a structured index based on JSON Schema. The minimal example for the quantize command is:

    ```json
    {
    “$sch