Metadata-Version: 2.4
Name: intel-npu-server
Version: 0.3.0
Summary: Local OpenAI-compatible server for OpenVINO GenAI models (primarily on Intel NPU)
Author: Alex Spirin
License-Expression: MIT
Requires-Dist: fastapi>=0.115,<1
Requires-Dist: huggingface-hub>=0.34,<2
Requires-Dist: openvino-genai==2026.4.1.0
Requires-Dist: pydantic>=2.10,<3
Requires-Dist: transformers==5.20.0
Requires-Dist: uvicorn[standard]>=0.34,<1
Requires-Dist: optimum-intel>=2.0.0
Requires-Python: >=3.12, <3.13
Description-Content-Type: text/markdown

# LLM on Intel NPU / OpenVINO GenAI / OpenAI-compatible API

Modular local inference server for OpenCode. The project uses Python 3.12 and `uv`; no PowerShell or batch scripts are required. LFM3 is the default checkpoint, but any exportable OpenVINO model works (see section 4.1).

## Project layout

```text
.
|-- pyproject.toml
|-- uv.lock                    # generated by uv lock / uv sync
|-- model_configuration.json   # generated automatically
|-- opencode.jsonc
`-- npu_server/
    |-- __main__.py            # thin entry point
    |-- tool_call_parsers.py
    |-- cli/
    |   |-- arguments_cli.py     # ModelArgumentsParser
    |   |-- model_config_cli.py  # ModelConfig
    |   `-- server_cli.py        # CommandLineInterface
    |-- generation/
    |   |-- events.py            # StreamEvent, GenerationRequest, GenerationOutcome
    |   |-- streaming.py         # ToolSafeStreamBuffer, TokenStreamCallback
    |   `-- engine.py            # GenerationEngine
    |-- load_model/
    |   |-- runtime.py           # GenerationError, ModelRuntime, RuntimeLengths
    |   |-- preparer.py          # OpenvinoModelPreparer (download + IR export)
    |   `-- loader.py            # OpenvinoModelLoader (pipeline compilation)
    `-- server/
        |-- openai_schemas.py    # CompletionResult, ChatCompletionChunkBuilder
        |-- message_normalizer.py# ChatMessageNormalizer
        |-- http_app.py          # NpuServer (routes + uvicorn)
```

`model_dir` defaults to `Path.cwd().parent / "model"`. The resolved path is written into `model_configuration.json` even when `--model-dir` is omitted. This ensures that a later `serve` command opens the same exported model directory.

Each model lives in its own subfolder named after `model_name`, so several models can share one `model_dir`:

```
model/
`-- lfm3-uncensored/
    |-- checkpoint/        # source Hugging Face checkpoint (downloaded once)
    `-- exported/          # OpenVINO IR, tokenizer files, model_manifest.json
```

The global Hugging Face cache is never used. A legacy flat layout (`model_dir\<files>` + `model_dir\checkpoint`) is migrated automatically on the first start of the new version.

## 1. Install and synchronize

Install `uv` once using the official installer for your operating system. Then, from the project root:

```powershell
uv python install 3.12
uv sync
```

The `optimum-intel` dependency is installed from the author's `lfm3` development branch, and `transformers==5.20.0` is used as required by the LFM3 support PR. The package metadata on that branch may still declare an older upper bound, so `tool.uv.override-dependencies` explicitly overrides it. This resolves the dependency solver conflict; it does not itself guarantee runtime compatibility.

## 2. Run the server

First launch:

```powershell
uv run python -m npu_server run
```

The `run` command:

1. Reads the configuration file and applies command-line overrides.
2. Migrates a legacy flat model layout if one is found.
3. Downloads the Hugging Face checkpoint into `model_dir\<model_name>\checkpoint` (unless `--model-id` points to a local directory).
4. Loads the tokenizer from that checkpoint.
5. Invokes the Optimum Intel Python CLI entry point in-process to export OpenVINO IR using INT4 symmetric weight compression and group size 128.
6. Saves the tokenizer into `model_dir\<model_name>\exported` next to the IR files.
7. Compiles/loads `openvino_genai.LLMPipeline` on the selected device. With the default `auto` lengths on NPU it tries `MAX_PROMPT_LEN=8192, MIN_RESPONSE_LEN=1024` first and falls back down the ladder `4096/1024 -> 2048/512 -> 1024/256` when the device refuses to compile; explicit `--max-prompt-len`/`--min-response-len` values disable the ladder.
8. Starts the HTTP server and keeps the model in memory until the process is stopped with Ctrl+C. On shutdown (Ctrl+C or uvicorn graceful exit) the pipeline reference is dropped and garbage-collected, releasing the model and its memory from the device before the process exits.

Subsequent `run` calls reuse an existing `.xml` + `.bin` IR export and the saved tokenizer.

## 3. Individual commands

Export only:

```powershell
uv run python -m npu_server prepare
```

Run the HTTP server using an existing IR export:

```powershell
uv run python -m npu_server serve
```

Check the local OpenVINO installation and device visibility:

```powershell
uv run python -m npu_server doctor
```

Force a fresh export:

```powershell
uv run python -m npu_server run --force-export
```

## 4. Configuration overrides

All values can be stored in `model_configuration.json` or passed as command-line arguments. Command-line arguments take precedence over the JSON file. If a value is omitted, the value from JSON is used; otherwise the `ModelConfig` default is used.

`model_id` and `device` are required: they must be present in `model_configuration.json` or passed as command-line arguments, otherwise startup fails with an error. `model_name` defaults to `model_id` when omitted.

```powershell
uv run python -m npu_server run `
  --model-id OpenIntelligenceNet/LFM3-1.7B-Uncensored `
  --model-dir ..\model `
  --device NPU `
  --host 127.0.0.1 `
  --port 8000 `
  --max-prompt-len 1024 `
  --min-response-len 128 `
  --max-output-tokens 128
```

`--model-dir` is optional. If omitted, it defaults to the resolved path `Path.cwd().parent / "model"`, and that value is persisted in `model_configuration.json`.

Length parameters accept either a positive integer or `auto`. On NPU, `auto` resolves to safe defaults (`MAX_PROMPT_LEN=8192`, `MIN_RESPONSE_LEN=1024`) with an automatic fallback ladder when the device refuses to compile. On CPU/GPU, `auto` omits the corresponding OpenVINO property so shapes stay dynamic; `max_output_tokens=auto` leaves the generation-length limit to the library default. For tight NPU memory budgets set the lengths explicitly.

## 4.1. Other models

The server works with any Hugging Face checkpoint that Optimum Intel can export to OpenVINO IR; LFM3 is only the default. Pass `--model-id <repo>`, set `--model-name`, and match the tool-call format if the model supports tools:

`--tool-parser` selects the converter for the model's tool-call markup:

| value | markup |
| --- | --- |
| `auto` | guess from the model id/name: `lfm*` -> lfm3, `qwen`/`hermes`/`glm` -> hermes, otherwise none |
| `lfm3` | LFM2/LFM3 XML-ish `<function=...><parameter=...>` blocks |
| `hermes` | JSON payloads `{"name": ..., "arguments": ...}` (Qwen/Hermes style) |
| `none` | no tool-call parsing (text-only) |

`--enable-thinking` / `--no-enable-thinking` controls the `enable_thinking` chat-template flag for thinking-capable models.

`--full-attention-only` converts `sliding_attention` layers to `full_attention` in the downloaded checkpoint before export (removes `sliding_window`, keeps the `full_attention` RoPE group). Intel NPU (NPUW) fails to compile hybrid sliding/full attention models with `NPUW: conflicting attention mask detection for the same SDPA node`; this flag unifies the attention pattern. It changes the attention semantics of the sliding layers (RoPE theta reverts to the `full_attention` group), so use it only when the NPU compile fails without it. The flag is persisted in `model_configuration.json`, recorded in `model_manifest.json`, and requires `--force-export` to re-export an existing IR.

## 5. HTTP API

The server binds to `127.0.0.1:8000` by default and exposes:

- `GET /health`
- `GET /v1/models`
- `POST /v1/chat/completions`

Example health request:

```powershell
curl.exe http://127.0.0.1:8000/health
```

The API applies the Hugging Face tokenizer's chat template and converts the model's tool-call markup into OpenAI-compatible `tool_calls`. Streaming responses are emitted token-by-token through an OpenVINO GenAI streamer; fragments that might belong to a tool-call block are withheld by a holdback buffer and flushed after generation, so tool calls parse reliably.

## 6. OpenCode

Merge the contents of `opencode.jsonc` into your OpenCode configuration. The configured model is `local/lfm3-npu` and the base URL is `http://127.0.0.1:8000/v1`.

## Technical notes

- OpenVINO's current NPU guidance recommends 4-bit symmetric compression and group-wise quantization (group size 128 for smaller models). The exporter uses these settings.
- NPU pipeline configuration uses `CACHE_DIR` always; `MAX_PROMPT_LEN`/`MIN_RESPONSE_LEN` default to 8192/1024 on NPU (`auto`) and are compiled with a fallback ladder; explicit values disable the ladder.
- Works with any checkpoint Optimum Intel can export; match `--tool-parser` to the model's tool-call markup. Validate export, tokenizer behavior, tool calls, and long-context behavior on the target device.
- `trust_remote_code=True` permits repository-provided Python code to run locally. Use it only with a repository whose code you trust.
- `uv.lock` is machine-generated; create it after reviewing the project dependencies with `uv lock`.
