Inspect · Source & workspace
Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0001–#0002
echo <val>ls -l -a <path> <n> > <path>ls -l -a <val>echo <flag>ls -l -a <path> <path>cat <path>Claude Opus 5 · Serving
OpenBuild Qwen3-8B serving 1dev · Open Build
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentClaude Opus 5 · 135 visible calls
02 / EVENT SEQUENCE
Requests are grouped by agent, activity and topic. Delegations open into child branches. Summaries describe visible requests; tool errors and missing responses are flagged. A recorded response does not establish command success or a performance improvement.
Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.
Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0001–#0002
echo <val>ls -l -a <path> <n> > <path>ls -l -a <val>echo <flag>ls -l -a <path> <path>cat <path>Requested file and log inspection related to task requirements.
2 calls · #0003–#0004
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0005–#0005
Read <path>Requested file and log inspection and workspace inspection related to task requirements.
1 call · #0006–#0006
cd <val>cat <path>echo <val>ls -l -a <val> <val> <val> <val> <path>Requested file and log inspection related to source & workspace.
1 call · #0007–#0007
cd <path><command> <args>cat <val>Requested environment setup or inspection, source searches and script or workload execution related to dependencies & build setup.
2 calls · #0008–#0009
envgrep -i -E <val>sortecho <val>which <val> <val>python3 -Vpython3 -m <module> <val> <n> > <path>head -n <n>sed -n <val>Requested file and log inspection and workspace inspection related to task requirements.
1 call · #0010–#0010
cd <val>echo <val>cat <path>echols -l -a <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0011–#0011
cat <path> <path>echo <val>cat <path>Requested file and log inspection and source searches related to source & workspace.
6 calls · #0012–#0017
cd <path>wc -l <path>grep -n <val> <path>head -n <n>Read <path>Requested runtime inspection and file and log inspection related to device memory.
1 call · #0018–#0018
free -gecho <val>df -h <path> <path> <n> > <path>npu-smi info <n> >& <path>head -n <n><command> <args>Requested script or workload execution and file and log inspection related to attention kernels.
1 call · #0019–#0019
cd <path>timeout <n> <val> -c <val> <n> >& <path>tail -n <n>Requested script or workload execution and source searches related to attention kernels.
4 calls · #0020–#0023
cd <path>timeout <n> <val> -c <val> <n> >& <path>grep -v <val>Requested file and log inspection and source searches related to attention kernels.
1 call · #0024–#0024
cd <path><command> <args>tail <flag>echo <val>grep -r -n <val> <val> --include <path> --include <val>head -n <n>Requested environment setup or inspection, workspace inspection and file and log inspection related to source & workspace.
1 call · #0025–#0025
env <vars>ls -d <val> <n> > <path><command> <args>tail <flag>echo <val>ls <val>headgrep -r -n <val> <val> --include <val> --include <path> <n> > <path>head -n <n>Requested environment setup or inspection, file and log inspection and source searches related to attention kernels.
3 calls · #0026–#0028
env <vars>sed -n <val> <path>echo <val>grep -r -n <val> <path> <n> > <path>head -n <n>grep -n <val> -A <n> <path> <n> > <path>ls <path>cd <path>timeout <n> <val> -c <val> <n> >& <path>grep -v <val>Requested code edits related to source & workspace.
1 call · #0029–#0029
Write <path>Requested script or workload execution and source searches related to benchmark & validation setup.
1 call · #0030–#0030
cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested code edits related to source & workspace.
1 call · #0031–#0031
Write <path>Requested script or workload execution and source searches related to parallelism & communication.
1 call · #0032–#0032
cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>grep -v -i -E <val>Requested code edits related to source & workspace.
1 call · #0033–#0033
Write <path>Requested script or workload execution, source searches and environment setup or inspection related to source & workspace.
1 call · #0034–#0034
cd <path>echo <val>timeout <n> <val> <path> <n> >& <path>grep -v <val>grep -v -i -E <val>env <vars> timeout <n> <val> <path> <n> >& <path>Requested environment setup or inspection, file and log inspection and source searches related to attention kernels.
2 calls · #0035–#0036
env <vars>wc -l <val>grep -n <val> <val>head -n <n>sed -n <val> <val>Requested code edits related to source & workspace.
1 call · #0037–#0037
Write <path>Requested script or workload execution and source searches related to source & workspace.
2 calls · #0038–#0039
cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>grep -v -i -E <val>python3 - <script>nohup <val> <n> <val> <path> > <path> <n> >& <path>echo <val>Requested workspace file updates, script or workload execution and source searches related to runtime processes.
1 call · #0040–#0040
mkdir -p <path>cd <path>timeout <n> <val> -c <path> <n> >& <path>grep -v <val>Requested script or workload execution and source searches related to source & workspace.
1 call · #0041–#0041
cd <path>timeout <n> <val> -c <path> <n> >& <path>grep -v <val>Requested code edits related to task requirements.
1 call · #0042–#0042
Write <path>Requested file and log inspection and source searches related to source & workspace.
1 call · #0043–#0043
cat <path> <n> > <path>grep -v <val>grep -v -i -E <val>tail -n <n>Requested source searches and file and log inspection related to latency & request handling.
1 call · #0044–#0044
cd <path>grep -n <val> <path>sed -n <val>Requested file and log inspection related to source & workspace.
1 call · #0045–#0045
cd <path>sed -n <val> <path>Requested source searches and file and log inspection related to benchmark & validation setup.
1 call · #0046–#0046
cd <path>grep -n <val> <path>head -n <n>echo <val>Requested code edits related to runtime processes.
11 calls · #0047–#0057
Write <path>Edit <path>Requested script or workload execution related to source & workspace.
1 call · #0058–#0058
cd <path>python -c <script>Requested code edits related to runtime processes.
1 call · #0059–#0059
Write <path>Requested script or workload execution and source searches related to runtime processes.
1 call · #0060–#0060
cd <path>python -c <script> <n> >& <path>grep -v <val>Requested code edits related to runtime processes.
4 calls · #0061–#0064
Write <path>Edit <path>Requested workspace inspection, source searches and file and log inspection related to source & workspace.
2 calls · #0065–#0066
ls -l -a <path> <n> >& <path>echo <flag>grep -n <val> <path> <n> > <path>head -n <n>envgrep -i -E <val>grep -n <val> <path>Requested code edits related to source & workspace.
1 call · #0067–#0067
Write <path>Requested environment setup or inspection, source searches and file and log inspection related to source & workspace.
1 call · #0068–#0068
envgrep -i -E <val>sed <path>head -n <n>echo <flag>ls <path> <path> <n> >& <path>Requested code edits related to runtime processes.
1 call · #0069–#0069
Write <path>Requested workspace file updates, workspace inspection and environment setup or inspection related to runtime processes.
1 call · #0070–#0070
cd <path>chmod <val> <path> <path>ls -l <path> <path>export <vars>nohup <path> > <path> <n> >& <path>sleep <n>tail -n <n> <path>Requested execution waits and file and log inspection related to runtime processes.
1 call · #0071–#0071
sleep <n>tail -n <n> <path>echo <flag><command> <args>echo <val>head -c <n>Requested script or workload execution related to task requirements.
1 call · #0072–#0072
cd <path>python - <script>Requested script or workload execution related to task requirements.
1 call · #0073–#0073
python -c <script>Requested file and log inspection, source searches and service requests related to runtime processes.
1 call · #0074–#0074
tail -n <n> <path>grep -v <val>echo <val>curl -s -m <n> <url>head -c <n>echotimeout <n> <val> -s -m <n> <url> -H <path> -d <path>Requested process termination, execution waits and file and log inspection related to batching & scheduling.
1 call · #0075–#0075
pkill -f <val>sleep <n>cat > <path> <script>cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>Requested runtime inspection, file and log inspection and source searches related to device memory.
1 call · #0076–#0076
pgrep <flag> <args>npu-smi info <n> > <path>sed -n <val>grep -E <val>head -n <n>echo <val>cd <path><command> <args>echo <val> >> <path>sleep <n>grep -v <val> <path>tail -n <n>Requested process termination, execution waits and runtime inspection related to device memory.
1 call · #0077–#0077
kill <flag> <args>sleep <n>pgrep <flag> <args>echo <val>npu-smi info <n> > <path>grep -E <val>Requested code edits related to source & workspace.
1 call · #0078–#0078
Write <path>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0079–#0079
cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -v <val> <path>tail -n <n>Requested code edits related to runtime processes.
1 call · #0080–#0080
Edit <path>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0081–#0081
cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -v <val> <path>grep -v <val>tail -n <n>Requested code edits related to runtime processes.
1 call · #0082–#0082
Edit <path>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0083–#0083
cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -v <val> <path>grep -v <val>tail -n <n>Requested script or workload execution and file and log inspection related to benchmark & validation setup.
1 call · #0084–#0084
date -upython -c <script>echo <val>cat <path>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0085–#0085
timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -v <val> <path>tail -n <n>Requested workspace inspection and source searches related to source & workspace.
1 call · #0086–#0086
ls <path>echo <flag>grep -n <val> <path>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0087–#0087
timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -v <val> <path>tail -n <n>Requested file and log inspection related to source & workspace.
1 call · #0088–#0088
cat <path>echo <val>Requested environment setup or inspection, source searches and file and log inspection related to benchmark & validation setup.
2 calls · #0089–#0090
env <vars> timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -v <val> <path>tail -n <n>Requested script or workload execution, execution waits and source searches related to benchmark & validation setup.
2 calls · #0091–#0092
nohup <val> <val> <val> <path> > <path> <n> >& <path>echo <val>sleep <n>grep -v <val> <path>tail -n <n>ls -l -a <val> <n> > <path>pgrep <flag> <args>head -n <n>Requested script or workload execution related to latency & request handling.
1 call · #0093–#0093
cd <val>python - <script>Requested execution waits, workspace inspection and runtime inspection related to benchmark & validation setup.
2 calls · #0094–#0095
sleep <n>date -u <val>ls <path> <n> > <path>xargs <flag> <args>echo <val>pgrep -c -f <path>grep -E <val>grep -v <val> <path> <n> > <path>tail -n <n>Requested script or workload execution and runtime inspection related to batching & scheduling.
1 call · #0096–#0096
cd <val>python -c <script>echo <val>pgrep -c -f <path>Requested execution waits, workspace inspection and runtime inspection related to benchmark & validation setup.
2 calls · #0097–#0098
sleep <n>date -u <val>ls <path> <n> > <path>xargs <flag> <args>echo <val>pgrep -c -f <path>Requested script or workload execution and runtime inspection related to runtime processes.
1 call · #0099–#0099
cd <val>python -c <script>echo <val>pgrep -c -f <path>Requested execution waits, workspace inspection and runtime inspection related to benchmark & validation setup.
2 calls · #0100–#0101
sleep <n>date -u <val>ls <path> <n> > <path>xargs <flag> <args>echo <val>pgrep -c -f <path>Requested script or workload execution and runtime inspection related to runtime processes.
1 call · #0102–#0102
cd <val>python -c <script>echo <val>pgrep -c -f <path>date -u <val>Requested execution waits, workspace inspection and runtime inspection related to benchmark & validation setup.
3 calls · #0103–#0105
sleep <n>date -u <val>ls <path> <n> > <path>echo <val>xargs <flag> <args>pgrep -c -f <path>ls <val>grep -c <val>grep -v <val> <path>tail -n <n>Requested script or workload execution related to latency & request handling.
1 call · #0106–#0106
cd <val>python - <script>Requested workspace inspection, source searches and file and log inspection related to latency & request handling.
1 call · #0107–#0107
cd <val>lsgrep <val>headecho <val>python - <script>Requested script or workload execution related to latency & request handling.
1 call · #0108–#0108
cd <val>python - <script>Requested code edits related to runtime processes.
3 calls · #0109–#0111
Edit <path>Requested script or workload execution, source searches and file and log inspection related to attention kernels.
1 call · #0112–#0112
cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -E <val> <path>head -n <n>date -u <val>Requested environment setup or inspection, source searches and script or workload execution related to benchmark & validation setup.
1 call · #0113–#0113
env <vars> timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -v <val> <path>python -c <script>date -u <val>Requested workspace file updates and script or workload execution related to benchmark & validation setup.
1 call · #0114–#0114
cp <path> <path> <n> > <path>echo <val>nohup <val> <val> <val> <path> > <path> <n> >& <path>date -u <val>Requested execution waits and script or workload execution related to latency & request handling.
1 call · #0115–#0115
sleep <n>date -u <val>cd <val>python - <script>Requested execution waits, workspace inspection and file and log inspection related to benchmark & validation setup.
3 calls · #0116–#0118
sleep <n>date -u <val>cd <val>ls -l <flag> <args>awk <val>echo <val>pgrep -c -f <path>grep -v <val> <path>tail -n <n>rm -f <val> <val> <val> <val> <val> <val>lshead -n <n>nohup <val> <val> <val> <path> > <path> <n> >& <path>Requested execution waits, script or workload execution and source searches related to latency & request handling.
3 calls · #0119–#0121
sleep <n>date -u <val>echo <val>cd <val>python - <script>grep -v <val> <path>grep -i -E <val>tail -n <n>Requested source searches, file and log inspection and workspace file updates related to benchmark & validation setup.
2 calls · #0122–#0123
date -u <val>grep -v <val> <path>tail -n <n>cd <val>rm -f <val>lstr <val> <val>echoecho <val>nohup <val> <val> <val> <path> > <path> <n> >& <path>sleep <n>Requested execution waits and script or workload execution related to latency & request handling.
6 calls · #0124–#0129
sleep <n>date -u <val>echo <val>cd <val>python - <script>Requested execution waits, script or workload execution and workspace inspection related to benchmark & validation setup.
6 calls · #0130–#0135
sleep <n>date -u <val>echo <val>cd <val>python - <script>ls <val> <n> > <path>wc -lecho <path>ls -l <flag> <args>awk <val>grep -v <val> <path>grep -E <val>tail -n <n>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: 8f62ee8f410c38ae7cd90305300afd08f0fdb098
@@ -0,0 +1,87 @@+#!/usr/bin/env bash+# Offline, idempotent bootstrap.+#+# Nothing is installed: every dependency this solution needs (torch, torch_npu,+# transformers, starlette, uvicorn, orjson, uvloop, safetensors) is already in+# the base image, and touching the base distribution surface is forbidden. The+# useful work here is verification plus warming the OS page cache for the model+# shards, which cuts weight-load time on every subsequent launch.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"+ENV_DIR="${OPENBUILD_ENV_DIR:-${SOLUTION_DIR}/.env}"+MODEL_PATH="${OPENBUILD_MODEL_PATH:?OPENBUILD_MODEL_PATH is required}"++mkdir -p "${ENV_DIR}"+log() { printf '[bootstrap] %s\n' "$*"; }++log "solution=${SOLUTION_DIR}"+log "env=${ENV_DIR}"+log "model=${MODEL_PATH}"++# ---------------------------------------------------------------- dependencies+python - <<'PY'+import importlib, importlib.metadata as md, sys++required = ["torch", "torch_npu", "transformers", "safetensors",+ "starlette", "uvicorn", "orjson", "numpy"]+missing = []+for name in required:+ try:+ importlib.import_module(name)+ except Exception as exc: # noqa: BLE001+ missing.append(f"{name} ({exc})")+if missing:+ sys.exit("[bootstrap] missing required dependencies: " + ", ".join(missing))++for name in required:+ try:+ print(f"[bootstrap] {name} {md.version(name)}")+ except Exception: # noqa: BLE001+ print(f"[bootstrap] {name} (version unknown)")+PY++# ------------------------------------------------------------- model integrity+python - <<'PY'+import json, os, pathlib, sys++root = pathlib.Path(os.environ["OPENBUILD_MODEL_PATH"])+need = ["config.json", "tokenizer.json", "tokenizer_config.json"]+for rel in need:+ if not (root / rel).is_file():+ sys.exit(f"[bootstrap] model is missing {rel}")++cfg = json.loads((root / "config.json").read_text(encoding="utf-8"))+shards = sorted(root.glob("*.safetensors"))+if not shards:+ sys.exit("[bootstrap] no safetensors shards found")+total = sum(p.stat().st_size for p in shards)+print(f"[bootstrap] arch={cfg.get('architectures')} layers={cfg['num_hidden_layers']} "+ f"hidden={cfg['hidden_size']} dtype={cfg.get('torch_dtype')}")+print(f"[bootstrap] {len(shards)} shard(s), {total / (1 << 30):.2f} GiB")+PY++# ------------------------------------------------------- warm the page cache+# Reading the shards once leaves them in the (very large) page cache, so the+# mmap-based loader in launch.sh is bounded by H2D copy rather than disk.+log "warming page cache for model shards"+warm_start=$(date +%s)+for shard in "${MODEL_PATH}"/*.safetensors; do+ [ -e "${shard}" ] || continue+ dd if="${shard}" of=/dev/null bs=16M status=none 2>/dev/null || true+done+log "page cache warm in $(( $(date +%s) - warm_start ))s"++# ----------------------------------------------------------- record run state+cat > "${ENV_DIR}/bootstrap.json" <<EOF+{+ "solution_dir": "${SOLUTION_DIR}",+ "env_dir": "${ENV_DIR}",+ "model_path": "${MODEL_PATH}",+ "completed_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",+ "installed_packages": []+}+EOF++log "ok"+exit 0@@ -0,0 +1,40 @@+#!/usr/bin/env bash+# Foreground launcher: becomes the HTTP server process via exec, so the process+# that touches the NPU is this process group's root and a plain SIGTERM to the+# group tears everything down and releases the port.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"+cd "${SOLUTION_DIR}"++# CANN / ATB runtime. Normally already exported by the image; re-source only if+# the ATB op library is not on the path yet.+if [ -z "${ATB_HOME_PATH:-}" ]; then+ # shellcheck disable=SC1091+ [ -f /usr/local/Ascend/ascend-toolkit/set_env.sh ] && source /usr/local/Ascend/ascend-toolkit/set_env.sh+ # shellcheck disable=SC1091+ [ -f /usr/local/Ascend/nnal/atb/set_env.sh ] && source /usr/local/Ascend/nnal/atb/set_env.sh+fi++# Device selection: honour the assignment handed to us.+if [ -n "${OPENBUILD_DEVICE_IDS:-}" ]; then+ export ASCEND_RT_VISIBLE_DEVICES="${OPENBUILD_DEVICE_IDS}"+fi++export PYTHONPATH="${SOLUTION_DIR}${PYTHONPATH:+:${PYTHONPATH}}"+export PYTHONUNBUFFERED=1+export TOKENIZERS_PARALLELISM=false+export HF_HUB_OFFLINE=1+export TRANSFORMERS_OFFLINE=1++# Host-side dispatch is the decode bottleneck on this device: TASK_QUEUE_ENABLE=2+# moves op enqueue onto a secondary thread, CPU_AFFINITY_CONF pins the dispatch+# threads near the device's NUMA node, and expandable segments keep the caching+# allocator from re-mapping as batch shapes change.+export TASK_QUEUE_ENABLE="${TASK_QUEUE_ENABLE:-2}"+export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1}"+export PYTORCH_NPU_ALLOC_CONF="${PYTORCH_NPU_ALLOC_CONF:-expandable_segments:True}"+export ASCEND_LAUNCH_BLOCKING=0+export ACL_OP_INIT_MODE="${ACL_OP_INIT_MODE:-1}"++exec python -m openbuild_serve@@ -0,0 +1,10 @@+{+ "schema_version": 1,+ "kind": "openbuild_solution",+ "task_id": "openbuild_serving_qwen3_8b_1dev_v1",+ "model": "Qwen/Qwen3-8B",+ "framework": "openbuild-serve (custom continuous-batching Ascend NPU engine)",+ "bootstrap": "bootstrap.sh",+ "launch": "launch.sh",+ "offline_replay": true+}@@ -0,0 +1,5 @@+"""openbuild-serve: a minimal continuous-batching OpenAI-compatible server for+Qwen3-8B on a single Ascend NPU."""++__all__ = ["__version__"]+__version__ = "1.0.0"@@ -0,0 +1,57 @@+"""Foreground entrypoint.++Order matters: the engine loads weights and warms the device *before* uvicorn+binds the port, so the first successful ``GET /v1/models`` also means the first+real request will not pay a compile or load cost. SIGTERM is handled by uvicorn;+the engine thread is joined afterwards and the process exits, releasing the port.+"""+from __future__ import annotations++import os+import sys+import time+++def main() -> int:+ os.environ.setdefault("PYTORCH_NPU_ALLOC_CONF", "expandable_segments:True")+ os.environ.setdefault("TASK_QUEUE_ENABLE", "2")+ os.environ.setdefault("CPU_AFFINITY_CONF", "1")+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")++ import torch # noqa: F401 (import order: torch before torch_npu)+ import uvicorn++ from .config import ServeConfig+ from .server import build++ torch.set_grad_enabled(False)+ try:+ import uvloop+ uvloop.install()+ loop_impl = "uvloop"+ except Exception: # noqa: BLE001+ loop_impl = "asyncio"++ cfg = ServeConfig.from_env()+ star, app = build(cfg)++ t0 = time.perf_counter()+ app.engine.start()+ app.engine.wait_ready(timeout=float(os.environ.get("OPENBUILD_INIT_TIMEOUT", "900")))+ print(f"[openbuild-serve] ready in {time.perf_counter() - t0:.1f}s "+ f"slots={app.engine.num_slots} max_len={app.engine.max_len} "+ f"loop={loop_impl}", flush=True)++ server = uvicorn.Server(uvicorn.Config(+ star, host=cfg.host, port=cfg.port, log_level="warning",+ access_log=False, loop="none", timeout_keep_alive=600,+ h11_max_incomplete_event_size=64 * 1024 * 1024))+ try:+ server.run()+ finally:+ app.engine.shutdown()+ return 0+++if __name__ == "__main__":+ sys.exit(main())@@ -0,0 +1,94 @@+"""Static model / runtime configuration for the Qwen3-8B Ascend serving engine."""+from __future__ import annotations++import json+import os+from dataclasses import dataclass+from pathlib import Path+++@dataclass(frozen=True)+class ModelConfig:+ hidden_size: int+ intermediate_size: int+ num_layers: int+ num_heads: int+ num_kv_heads: int+ head_dim: int+ vocab_size: int+ rms_norm_eps: float+ rope_theta: float+ max_position_embeddings: int+ eos_token_ids: tuple[int, ...]++ @property+ def q_size(self) -> int:+ return self.num_heads * self.head_dim++ @property+ def kv_size(self) -> int:+ return self.num_kv_heads * self.head_dim+++def load_model_config(model_path: str | Path) -> ModelConfig:+ root = Path(model_path)+ cfg = json.loads((root / "config.json").read_text(encoding="utf-8"))+ eos: list[int] = []+ gen_path = root / "generation_config.json"+ if gen_path.is_file():+ gen = json.loads(gen_path.read_text(encoding="utf-8"))+ raw = gen.get("eos_token_id")+ if isinstance(raw, int):+ eos = [raw]+ elif isinstance(raw, list):+ eos = [int(v) for v in raw if isinstance(v, int)]+ if not eos:+ raw = cfg.get("eos_token_id")+ eos = [int(raw)] if isinstance(raw, int) else [int(v) for v in (raw or [])]+ head_dim = int(cfg.get("head_dim") or cfg["hidden_size"] // cfg["num_attention_heads"])+ return ModelConfig(+ hidden_size=int(cfg["hidden_size"]),+ intermediate_size=int(cfg["intermediate_size"]),+ num_layers=int(cfg["num_hidden_layers"]),+ num_heads=int(cfg["num_attention_heads"]),+ num_kv_heads=int(cfg["num_key_value_heads"]),+ head_dim=head_dim,+ vocab_size=int(cfg["vocab_size"]),+ rms_norm_eps=float(cfg["rms_norm_eps"]),+ rope_theta=float(cfg["rope_theta"]),+ max_position_embeddings=int(cfg["max_position_embeddings"]),+ eos_token_ids=tuple(eos),+ )+++@dataclass(frozen=True)+class ServeConfig:+ model_path: str+ tokenizer_path: str+ served_model: str+ host: str+ port: int+ max_model_len: int+ max_num_seqs: int+ max_prefill_tokens: int+ max_prefill_seqs: int+ hbm_reserve_gib: float++ @staticmethod+ def from_env() -> "ServeConfig":+ model = os.environ.get("OPENBUILD_MODEL_PATH") or ""+ tokenizer = os.environ.get("OPENBUILD_TOKENIZER_PATH") or model+ if not model:+ raise RuntimeError("OPENBUILD_MODEL_PATH is required")+ return ServeConfig(+ model_path=model,+ tokenizer_path=tokenizer or model,+ served_model=os.environ.get("OPENBUILD_SERVED_MODEL", "Qwen/Qwen3-8B"),+ host=os.environ.get("OPENBUILD_HOST", "127.0.0.1"),+ port=int(os.environ.get("OPENBUILD_PORT", "8000")),+ max_model_len=int(os.environ.get("OPENBUILD_MAX_MODEL_LEN", "3072")),+ max_num_seqs=int(os.environ.get("OPENBUILD_MAX_NUM_SEQS", "80")),+ max_prefill_tokens=int(os.environ.get("OPENBUILD_MAX_PREFILL_TOKENS", "8192")),+ max_prefill_seqs=int(os.environ.get("OPENBUILD_MAX_PREFILL_SEQS", "24")),+ hbm_reserve_gib=float(os.environ.get("OPENBUILD_HBM_RESERVE_GIB", "3.5")),+ )@@ -0,0 +1,257 @@+"""Continuous-batching scheduler.++One engine thread owns the device. HTTP handlers submit ``Request`` objects and+consume generated token ids from a per-request asyncio queue; detokenization+happens on the asyncio side so the engine thread only does device dispatch.++Scheduling policy: prefill-priority with a token budget. Waiting requests are+packed into one variable-length prefill batch (up to ``max_prefill_tokens``),+then every admitted sequence advances one token per decode step. Slots are+allocated lowest-free-first so a decode step is a dense slice ``[0, high)``.+"""+from __future__ import annotations++import asyncio+import itertools+import threading+import time+from dataclasses import dataclass, field++import torch++from .config import ModelConfig, ServeConfig, load_model_config+from .kvcache import KVCache, plan_capacity+from .model import Qwen3Runner+from .weights import load_weights++_ids = itertools.count(1)+++@dataclass+class Request:+ prompt: list[int]+ max_tokens: int+ ignore_eos: bool+ stop_token_ids: set[int]+ queue: asyncio.Queue+ loop: asyncio.AbstractEventLoop+ rid: int = field(default_factory=lambda: next(_ids))+ slot: int = -1+ cached: int = 0+ produced: int = 0+ last_token: int = 0+ pending: list[int] = field(default_factory=list)+ finish: str | None = None+ aborted: bool = False++ @property+ def prompt_len(self) -> int:+ return len(self.prompt)+++class Engine:+ def __init__(self, cfg: ServeConfig):+ self.cfg = cfg+ self.model_cfg: ModelConfig = load_model_config(cfg.model_path)+ self._waiting: list[Request] = []+ self._active: dict[int, Request] = {} # slot -> request+ self._lock = threading.Lock()+ self._wake = threading.Event()+ self._stop = threading.Event()+ self._ready = threading.Event()+ self._thread: threading.Thread | None = None+ self._err: BaseException | None = None+ self.stats = {"prompt_tokens": 0, "generated_tokens": 0, "requests": 0}++ # ------------------------------------------------------------------ startup+ def start(self) -> None:+ self._thread = threading.Thread(target=self._run, name="engine", daemon=True)+ self._thread.start()++ def wait_ready(self, timeout: float = 900.0) -> None:+ if not self._ready.wait(timeout):+ raise RuntimeError("engine failed to become ready")+ if self._err is not None:+ raise RuntimeError(f"engine init failed: {self._err}")++ def shutdown(self) -> None:+ self._stop.set()+ self._wake.set()+ t = self._thread+ if t is not None:+ t.join(timeout=15.0)++ def _init_device(self) -> None:+ torch.npu.set_device(0)+ mc = self.model_cfg+ max_len = min(self.cfg.max_model_len, mc.max_position_embeddings)+ self.max_len = max_len+ self.weights = load_weights(self.cfg.model_path, mc)+ slots = plan_capacity(mc, max_len, self.cfg.max_num_seqs,+ self.cfg.hbm_reserve_gib)+ self.cache = KVCache(mc, slots, max_len)+ self.num_slots = slots+ self.runner = Qwen3Runner(mc, self.weights, self.cache)+ self._eos = set(mc.eos_token_ids)+ self._warmup()++ def _warmup(self) -> None:+ """Touch every shape family so the first real request is not a compile."""+ probe = [1, 2, 3, 4, 5, 6, 7, 8]+ slot = self.cache.alloc()+ self.runner.prefill([(slot, probe)])+ self.runner.decode(slot + 1, [1], [len(probe)], [len(probe) + 1])+ self.cache.free(slot)+ for rows in (2, 8, 32):+ rows = min(rows, self.cache.free_slots)+ if rows <= 0:+ break+ slots = [self.cache.alloc() for _ in range(rows)]+ self.runner.prefill([(s, probe) for s in slots])+ hi = max(slots) + 1+ self.runner.decode(hi, [1] * hi, [len(probe)] * hi,+ [len(probe) + 1] * hi)+ for s in slots:+ self.cache.free(s)+ for t in self.cache.flat_k + self.cache.flat_v:+ t.zero_()+ torch.npu.synchronize()++ # ---------------------------------------------------------------- submission+ def submit(self, req: Request) -> None:+ with self._lock:+ self._waiting.append(req)+ self.stats["requests"] += 1+ self.stats["prompt_tokens"] += req.prompt_len+ self._wake.set()++ def abort(self, req: Request) -> None:+ req.aborted = True+ self._wake.set()++ @property+ def capacity(self) -> int:+ return self.num_slots++ # -------------------------------------------------------------------- loop+ def _run(self) -> None:+ try:+ self._init_device()+ except BaseException as exc: # noqa: BLE001 - surfaced to the HTTP layer+ self._err = exc+ self._ready.set()+ return+ self._ready.set()+ try:+ while not self._stop.is_set():+ if not self._step():+ self._wake.wait(0.05)+ self._wake.clear()+ except BaseException as exc: # noqa: BLE001+ self._err = exc+ self._fail_all(exc)++ def _fail_all(self, exc: BaseException) -> None:+ with self._lock:+ pend = list(self._active.values()) + self._waiting+ self._active.clear()+ self._waiting.clear()+ for r in pend:+ self._emit(r, [], "error")++ def _step(self) -> bool:+ self._reap_aborted()+ did = False+ if self._waiting and self.cache.free_slots:+ did = self._do_prefill()+ if self._active:+ self._do_decode()+ did = True+ return did++ def _reap_aborted(self) -> None:+ with self._lock:+ self._waiting = [r for r in self._waiting if not r.aborted]+ dead = [s for s, r in self._active.items() if r.aborted]+ for s in dead:+ self._active.pop(s, None)+ self.cache.free(s)++ # ----------------------------------------------------------------- prefill+ def _do_prefill(self) -> bool:+ budget = self.cfg.max_prefill_tokens+ picked: list[Request] = []+ with self._lock:+ while (self._waiting and len(picked) < self.cfg.max_prefill_seqs+ and self.cache.free_slots > 0):+ nxt = self._waiting[0]+ need = nxt.prompt_len+ if picked and need > budget:+ break+ self._waiting.pop(0)+ nxt.slot = self.cache.alloc()+ picked.append(nxt)+ budget -= need+ if budget <= 0:+ break+ if not picked:+ return False+ batch = [(r.slot, r.prompt) for r in picked]+ ids = self.runner.prefill(batch)+ now = time.perf_counter()+ for r, tok in zip(picked, ids):+ r.cached = r.prompt_len+ self._accept(r, tok, now)+ return True++ # ------------------------------------------------------------------ decode+ def _do_decode(self) -> None:+ active = self._active+ hi = max(active) + 1+ tokens = [0] * hi+ cached = [0] * hi+ kv = [1] * hi+ for slot, r in active.items():+ tokens[slot] = r.last_token+ cached[slot] = r.cached+ kv[slot] = r.cached + 1+ ids = self.runner.decode(hi, tokens, cached, kv)+ now = time.perf_counter()+ for slot in list(active):+ r = active.get(slot)+ if r is not None:+ r.cached += 1+ self._accept(r, ids[slot], now)++ # ----------------------------------------------------------------- accept+ def _accept(self, r: Request, tok: int, now: float) -> None:+ r.last_token = tok+ r.produced += 1+ self.stats["generated_tokens"] += 1+ is_eos = tok in self._eos and not r.ignore_eos+ is_stop = tok in r.stop_token_ids and not r.ignore_eos+ if is_eos or is_stop:+ finish = "stop"+ elif r.produced >= r.max_tokens or r.cached + 1 >= self.max_len:+ r.pending.append(tok)+ finish = "length"+ else:+ r.pending.append(tok)+ self._active[r.slot] = r+ self._emit(r, r.pending, None)+ r.pending = []+ return+ r.finish = finish+ self._active.pop(r.slot, None)+ self.cache.free(r.slot)+ self._emit(r, r.pending, finish)+ r.pending = []++ def _emit(self, r: Request, toks: list[int], finish: str | None) -> None:+ if r.aborted:+ return+ payload = (list(toks), finish)+ try:+ r.loop.call_soon_threadsafe(r.queue.put_nowait, payload)+ except RuntimeError:+ r.aborted = True@@ -0,0 +1,68 @@+"""Slot-contiguous KV cache.++Each sequence owns one slot of `max_len` contiguous token positions per layer.+This trades a little HBM for two properties that matter on this device:++ * decode attention reads a plain ``[slots, max_len, kv_heads*head_dim]``+ tensor, so it runs through ``npu_fused_infer_attention_score`` with nothing+ but a per-slot length list -- no block table, no gather;+ * cache writes are a single ``index_copy_`` per layer.++Slots are handed out lowest-free-first so the active set stays packed near+index 0 and every decode step can slice ``[0:high_water)``.+"""+from __future__ import annotations++import heapq++import torch++from .config import ModelConfig+++class KVCache:+ def __init__(self, cfg: ModelConfig, num_slots: int, max_len: int,+ device: str = "npu:0", dtype: torch.dtype = torch.bfloat16):+ self.cfg = cfg+ self.num_slots = num_slots+ self.max_len = max_len+ kv_dim = cfg.num_kv_heads * cfg.head_dim+ rows = num_slots * max_len+ # flat_*: [slots*max_len, kv_heads, head_dim] for index_copy_ writes+ # view_*: [slots, max_len, kv_heads*head_dim] for BSH attention reads+ self.flat_k: list[torch.Tensor] = []+ self.flat_v: list[torch.Tensor] = []+ self.view_k: list[torch.Tensor] = []+ self.view_v: list[torch.Tensor] = []+ for _ in range(cfg.num_layers):+ k = torch.zeros((rows, kv_dim), dtype=dtype, device=device)+ v = torch.zeros((rows, kv_dim), dtype=dtype, device=device)+ self.flat_k.append(k.view(rows, cfg.num_kv_heads, cfg.head_dim))+ self.flat_v.append(v.view(rows, cfg.num_kv_heads, cfg.head_dim))+ self.view_k.append(k.view(num_slots, max_len, kv_dim))+ self.view_v.append(v.view(num_slots, max_len, kv_dim))+ self._free: list[int] = list(range(num_slots))+ heapq.heapify(self._free)++ @property+ def free_slots(self) -> int:+ return len(self._free)++ def alloc(self) -> int:+ return heapq.heappop(self._free)++ def free(self, slot: int) -> None:+ heapq.heappush(self._free, slot)++ def bytes_per_token(self) -> int:+ return 2 * self.cfg.num_layers * self.cfg.num_kv_heads * self.cfg.head_dim * 2+++def plan_capacity(cfg: ModelConfig, max_len: int, max_slots: int,+ reserve_gib: float, device: int = 0) -> int:+ """Pick the slot count that fits in free HBM after weights are resident."""+ free_b, _total = torch.npu.mem_get_info(device)+ budget = free_b - int(reserve_gib * (1 << 30))+ per_slot = 2 * cfg.num_layers * cfg.num_kv_heads * cfg.head_dim * 2 * max_len+ slots = int(budget // per_slot) if per_slot > 0 else 0+ return max(1, min(max_slots, slots))@@ -0,0 +1,218 @@+"""Qwen3 dense forward pass on Ascend NPU (bf16, greedy decode).++Two entry points share one weight set and one KV cache:++ ``prefill`` packed variable-length batch -> ATB flash attention, no padding.+ ``decode`` one token per active slot -> fused-infer-attention over the+ slot-contiguous cache, sliced to the active high-water mark.++Every op in the hot path is a torch_npu fused kernel; the per-step host work is+one small H2D copy of token/position/row metadata plus one D2H copy of the+sampled ids.+"""+from __future__ import annotations++import numpy as np+import torch+import torch_npu++from .config import ModelConfig+from .kvcache import KVCache+from .weights import TRANSPOSE_WEIGHTS, LayerWeights, ModelWeights+++_ARANGE = np.arange(1 << 16, dtype=np.int64)+++def _mm(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:+ if TRANSPOSE_WEIGHTS:+ return torch.matmul(x, w)+ return torch.nn.functional.linear(x, w)+++class Qwen3Runner:+ def __init__(self, cfg: ModelConfig, weights: ModelWeights, cache: KVCache,+ device: str = "npu:0", dtype: torch.dtype = torch.bfloat16):+ self.cfg = cfg+ self.w = weights+ self.cache = cache+ self.device = device+ self.dtype = dtype+ self.eps = cfg.rms_norm_eps+ self.scale = float(cfg.head_dim) ** -0.5+ self.max_len = cache.max_len++ inv = 1.0 / (cfg.rope_theta ** (+ torch.arange(0, cfg.head_dim, 2, dtype=torch.float32) / cfg.head_dim))+ pos = torch.arange(self.max_len, dtype=torch.float32)+ freqs = torch.outer(pos, inv)+ emb = torch.cat((freqs, freqs), dim=-1)+ # [max_len, 1, head_dim] so it broadcasts over the head axis of [T, H, D]+ self.cos = emb.cos().to(device=device, dtype=dtype).unsqueeze(1).contiguous()+ self.sin = emb.sin().to(device=device, dtype=dtype).unsqueeze(1).contiguous()++ self._masks: dict[int, torch.Tensor] = {}+ # host-side staging for per-step metadata: token ids, positions, cache rows+ self._h_meta = torch.empty((3, max(cache.num_slots, 8)), dtype=torch.int64)+ self._h_np = self._h_meta.numpy()+ self._d_meta = torch.empty_like(self._h_meta, device=device)+ self._rotary_ok = True+ self._add_rms_ok = True+ # slot -> first cache row, so decode row = base + position+ self._row_base = np.arange(cache.num_slots, dtype=np.int64) * cache.max_len+ # pinned landing buffer so sampled ids come back without a hard sync+ self._pin = torch.empty(max(cache.num_slots, 64), dtype=torch.int64).pin_memory()++ # ---------------------------------------------------------------- helpers+ def _mask(self, m: int) -> torch.Tensor:+ got = self._masks.get(m)+ if got is None:+ got = torch.triu(torch.ones((m, m), dtype=self.dtype,+ device=self.device), diagonal=1).contiguous()+ self._masks[m] = got+ return got++ def _rope(self, x: torch.Tensor, cos: torch.Tensor,+ sin: torch.Tensor) -> torch.Tensor:+ if self._rotary_ok:+ try:+ return torch_npu.npu_rotary_mul(x, cos, sin, rotary_mode="half")+ except Exception:+ self._rotary_ok = False+ half = x.shape[-1] // 2+ rot = torch.cat((-x[..., half:], x[..., :half]), dim=-1)+ return x * cos + rot * sin++ def _stage(self, n: int):+ if self._h_meta.shape[1] < n:+ self._h_meta = torch.empty((3, n), dtype=torch.int64)+ self._h_np = self._h_meta.numpy()+ self._d_meta = torch.empty((3, n), dtype=torch.int64, device=self.device)+ return self._h_np++ def _ship(self, n: int):+ dst = self._d_meta[:, :n]+ dst.copy_(self._h_meta[:, :n], non_blocking=True)+ return dst[0], dst[1], dst[2]++ def _add_norm(self, residual: torch.Tensor, x: torch.Tensor, gamma: torch.Tensor):+ if self._add_rms_ok:+ try:+ y, _, r = torch_npu.npu_add_rms_norm(residual, x, gamma, self.eps)+ return y, r+ except Exception:+ self._add_rms_ok = False+ r = residual + x+ return torch_npu.npu_rms_norm(r, gamma, self.eps)[0], r++ # ---------------------------------------------------------------- attention+ def _attn_prefill(self, seq_len_cpu: torch.Tensor, m: int):+ cfg = self.cfg+ mask = self._mask(m)++ def fn(q, k, v, layer):+ out = torch.empty_like(q)+ torch_npu._npu_flash_attention(+ query=q, key=k.contiguous(), value=v.contiguous(), mask=mask,+ seq_len=seq_len_cpu, scale_value=self.scale,+ num_heads=cfg.num_heads, num_kv_heads=cfg.num_kv_heads, out=out)+ return out.view(q.shape[0], cfg.q_size)++ return fn++ def _attn_decode(self, hi: int, kv_lens: list[int]):+ cfg = self.cfg++ def fn(q, k, v, layer):+ out = torch_npu.npu_fused_infer_attention_score(+ q.view(hi, 1, cfg.q_size),+ self.cache.view_k[layer][:hi], self.cache.view_v[layer][:hi],+ actual_seq_lengths_kv=kv_lens, num_heads=cfg.num_heads,+ num_key_value_heads=cfg.num_kv_heads, input_layout="BSH",+ scale=self.scale)[0]+ return out.view(hi, cfg.q_size)++ return fn++ # ------------------------------------------------------------------ forward+ def _forward(self, tok_d, pos_d, row_d, attn, gather_d=None) -> torch.Tensor:+ cfg = self.cfg+ qs, ks = cfg.q_size, cfg.q_size + cfg.kv_size+ x = self.w.embed.index_select(0, tok_d)+ t = x.shape[0]+ # gather rotary tables once for the whole step, not once per layer+ cos = self.cos.index_select(0, pos_d)+ sin = self.sin.index_select(0, pos_d)+ residual: torch.Tensor | None = None+ for i, lw in enumerate(self.w.layers):+ if residual is None:+ residual = x+ h = torch_npu.npu_rms_norm(x, lw.input_norm, self.eps)[0]+ else:+ h, residual = self._add_norm(residual, x, lw.input_norm)++ qkv = _mm(h, lw.qkv)+ q = qkv[:, :qs].view(t, cfg.num_heads, cfg.head_dim)+ k = qkv[:, qs:ks].view(t, cfg.num_kv_heads, cfg.head_dim)+ v = qkv[:, ks:].view(t, cfg.num_kv_heads, cfg.head_dim).contiguous()+ q = torch_npu.npu_rms_norm(q, lw.q_norm, self.eps)[0]+ k = torch_npu.npu_rms_norm(k, lw.k_norm, self.eps)[0]+ q = self._rope(q, cos, sin)+ k = self._rope(k, cos, sin).contiguous()++ self.cache.flat_k[i].index_copy_(0, row_d, k)+ self.cache.flat_v[i].index_copy_(0, row_d, v)++ x = _mm(attn(q, k, v, i), lw.o)+ h, residual = self._add_norm(residual, x, lw.post_norm)+ x = _mm(torch_npu.npu_swiglu(_mm(h, lw.gate_up), -1), lw.down)++ if gather_d is not None:+ residual = residual.index_select(0, gather_d)+ x = x.index_select(0, gather_d)+ h, _ = self._add_norm(residual, x, self.w.norm)+ return _mm(h, self.w.lm_head)++ def _sample(self, logits: torch.Tensor) -> list[int]:+ n = logits.shape[0]+ ids = torch.argmax(logits.float(), dim=-1)+ if self._pin.shape[0] < n:+ self._pin = torch.empty(n, dtype=torch.int64).pin_memory()+ dst = self._pin[:n]+ dst.copy_(ids, non_blocking=True)+ torch.npu.current_stream().synchronize()+ return dst.tolist()++ # -------------------------------------------------------------- public API+ @torch.inference_mode()+ def prefill(self, batch: list[tuple[int, list[int]]]) -> list[int]:+ """batch: [(slot, prompt_ids)]. Returns the first sampled id per entry."""+ lens = [len(ids) for _, ids in batch]+ total = sum(lens)+ buf = self._stage(total)+ gather = []+ off = 0+ for (slot, ids), n in zip(batch, lens):+ buf[0, off:off + n] = ids+ buf[1, off:off + n] = _ARANGE[:n]+ base = slot * self.max_len+ buf[2, off:off + n] = _ARANGE[:n] + base+ off += n+ gather.append(off - 1)+ tok_d, pos_d, row_d = self._ship(total)+ gather_d = torch.tensor(gather, dtype=torch.int64, device=self.device)+ seq_len = torch.tensor(lens, dtype=torch.int32)+ logits = self._forward(tok_d, pos_d, row_d,+ self._attn_prefill(seq_len, max(lens)), gather_d)+ return self._sample(logits)++ @torch.inference_mode()+ def decode(self, hi: int, tokens, cached, kv_lens: list[int]) -> list[int]:+ """One step for slots [0, hi). ``cached[i]`` = tokens already in slot i."""+ buf = self._stage(hi)+ buf[0, :hi] = tokens+ buf[1, :hi] = cached+ buf[2, :hi] = self._row_base[:hi] + buf[1, :hi]+ tok_d, pos_d, row_d = self._ship(hi)+ logits = self._forward(tok_d, pos_d, row_d, self._attn_decode(hi, kv_lens))+ return self._sample(logits)@@ -0,0 +1,254 @@+"""OpenAI-compatible HTTP surface (Starlette + uvicorn).++Endpoints: ``GET /v1/models``, ``POST /v1/chat/completions`` (streaming and+non-streaming), ``GET /health``.++The engine thread owns the NPU; each request handler is a coroutine that drains+a per-request asyncio queue of token ids and turns them into SSE deltas. Usage+counts come from the engine's own counters, never from a re-tokenization.+"""+from __future__ import annotations++import asyncio+import time+import uuid++import orjson+from starlette.applications import Starlette+from starlette.requests import Request as HTTPRequest+from starlette.responses import JSONResponse, Response, StreamingResponse+from starlette.routing import Route++from .config import ServeConfig+from .engine import Engine, Request+from .tokenizer import ChatTokenizer, Incremental++_CREATED = int(time.time())+++class _JSON(Response):+ media_type = "application/json"++ def render(self, content) -> bytes:+ return orjson.dumps(content)+++def _err(status: int, message: str, code: str = "invalid_request_error") -> Response:+ return _JSON({"error": {"message": message, "type": code, "code": None}},+ status_code=status)+++def _as_int(val, default: int | None = None) -> int | None:+ if val is None:+ return default+ try:+ out = int(val)+ except (TypeError, ValueError):+ return default+ return out+++def _normalize_messages(raw) -> list[dict] | None:+ if not isinstance(raw, list) or not raw:+ return None+ out: list[dict] = []+ for m in raw:+ if not isinstance(m, dict):+ return None+ role = m.get("role")+ content = m.get("content", "")+ if isinstance(content, list):+ parts = []+ for c in content:+ if isinstance(c, dict):+ if c.get("type") in (None, "text") and isinstance(c.get("text"), str):+ parts.append(c["text"])+ elif isinstance(c, str):+ parts.append(c)+ content = "".join(parts)+ if content is None:+ content = ""+ if not isinstance(role, str) or not isinstance(content, str):+ return None+ out.append({"role": role, "content": content})+ return out+++class App:+ def __init__(self, cfg: ServeConfig):+ self.cfg = cfg+ self.engine = Engine(cfg)+ self.tokenizer = ChatTokenizer(cfg.tokenizer_path)+ self.model = cfg.served_model++ # ----------------------------------------------------------------- routes+ async def models(self, _req: HTTPRequest) -> Response:+ return _JSON({+ "object": "list",+ "data": [{+ "id": self.model,+ "object": "model",+ "created": _CREATED,+ "owned_by": "openbuild",+ "root": self.model,+ "parent": None,+ "max_model_len": self.engine.max_len,+ "permission": [],+ }],+ })++ async def health(self, _req: HTTPRequest) -> Response:+ return _JSON({"status": "ok", **self.engine.stats})++ async def chat(self, http: HTTPRequest) -> Response:+ try:+ body = orjson.loads(await http.body())+ except Exception:+ return _err(400, "invalid JSON body")+ if not isinstance(body, dict):+ return _err(400, "request body must be a JSON object")++ messages = _normalize_messages(body.get("messages"))+ if messages is None:+ return _err(400, "'messages' must be a non-empty list of chat messages")++ want = body.get("model")+ if isinstance(want, str) and want and want != self.model:+ return _err(404, f"model '{want}' not found", "model_not_found")++ try:+ prompt = self.tokenizer.encode_chat(+ messages,+ chat_template_kwargs=body.get("chat_template_kwargs")+ if isinstance(body.get("chat_template_kwargs"), dict) else None)+ except Exception as exc: # noqa: BLE001+ return _err(400, f"could not apply chat template: {exc}")+ if not prompt:+ return _err(400, "empty prompt after templating")++ room = self.engine.max_len - len(prompt)+ if room <= 0:+ return _err(400, f"prompt is {len(prompt)} tokens, which exceeds the "+ f"{self.engine.max_len}-token context window")++ req_max = _as_int(body.get("max_completion_tokens"),+ _as_int(body.get("max_tokens")))+ if req_max is None:+ req_max = room+ if req_max <= 0:+ return _err(400, "max_tokens must be positive")+ max_tokens = min(req_max, room)++ stop_ids = set()+ raw_stop = body.get("stop_token_ids")+ if isinstance(raw_stop, list):+ stop_ids = {int(v) for v in raw_stop if isinstance(v, int)}++ stream = bool(body.get("stream"))+ opts = body.get("stream_options")+ include_usage = bool(isinstance(opts, dict) and opts.get("include_usage"))++ req = Request(prompt=prompt, max_tokens=max_tokens,+ ignore_eos=bool(body.get("ignore_eos")),+ stop_token_ids=stop_ids, queue=asyncio.Queue(),+ loop=asyncio.get_running_loop())+ cid = f"chatcmpl-{uuid.uuid4().hex}"+ self.engine.submit(req)++ if stream:+ return StreamingResponse(+ self._stream(req, cid, include_usage),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})+ return await self._complete(http, req, cid)++ # -------------------------------------------------------------- generation+ def _usage(self, req: Request) -> dict:+ prompt = req.prompt_len+ completion = req.produced+ return {"prompt_tokens": prompt, "completion_tokens": completion,+ "total_tokens": prompt + completion}++ async def _complete(self, http: HTTPRequest, req: Request, cid: str) -> Response:+ ids: list[int] = []+ finish = None+ try:+ while finish is None:+ toks, finish = await req.queue.get()+ ids.extend(toks)+ except asyncio.CancelledError:+ self.engine.abort(req)+ raise+ if finish == "error":+ return _err(500, "engine failure while generating", "internal_error")+ text = self.tokenizer.decode(ids)+ return _JSON({+ "id": cid, "object": "chat.completion", "created": int(time.time()),+ "model": self.model,+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": text},+ "logprobs": None,+ "finish_reason": finish,+ }],+ "usage": self._usage(req),+ })++ async def _stream(self, req: Request, cid: str, include_usage: bool):+ created = int(time.time())+ head = {"id": cid, "object": "chat.completion.chunk", "created": created,+ "model": self.model}+ detok = Incremental(self.tokenizer)+ first = True+ finish = None+ try:+ while finish is None:+ toks, finish = await req.queue.get()+ delta = detok.push(toks)+ if finish is not None and finish != "error":+ delta += detok.finalize()+ if delta:+ payload = {"content": delta}+ if first:+ payload = {"role": "assistant", "content": delta}+ first = False+ yield b"data: " + orjson.dumps({+ **head,+ "choices": [{"index": 0, "delta": payload,+ "logprobs": None, "finish_reason": None}],+ }) + b"\n\n"+ if finish == "error":+ yield b"data: " + orjson.dumps({+ **head, "choices": [],+ "error": {"message": "engine failure while generating",+ "type": "internal_error"},+ }) + b"\n\n"+ yield b"data: [DONE]\n\n"+ return+ yield b"data: " + orjson.dumps({+ **head,+ "choices": [{"index": 0, "delta": {}, "logprobs": None,+ "finish_reason": finish}],+ }) + b"\n\n"+ if include_usage:+ yield b"data: " + orjson.dumps({+ **head, "choices": [], "usage": self._usage(req),+ }) + b"\n\n"+ yield b"data: [DONE]\n\n"+ except asyncio.CancelledError:+ self.engine.abort(req)+ raise+ except GeneratorExit:+ self.engine.abort(req)+ raise+++def build(cfg: ServeConfig) -> tuple[Starlette, App]:+ app_impl = App(cfg)+ routes = [+ Route("/v1/models", app_impl.models, methods=["GET"]),+ Route("/v1/chat/completions", app_impl.chat, methods=["POST"]),+ Route("/health", app_impl.health, methods=["GET"]),+ ]+ star = Starlette(routes=routes)+ return star, app_impl@@ -0,0 +1,92 @@+"""Chat templating and incremental detokenization.++Streaming needs the concatenation of all emitted deltas to equal the one-shot+decode of the full token list. A per-token ``decode`` cannot guarantee that for+byte-level BPE, so we keep a sliding window: re-decode a short suffix each time+and emit only the part that grew. ``<think>``/``</think>`` are non-special added+tokens in this checkpoint, so they survive ``skip_special_tokens=True`` while+``<|im_end|>`` is dropped.+"""+from __future__ import annotations++from transformers import AutoTokenizer++_WINDOW = 8+++class ChatTokenizer:+ def __init__(self, path: str):+ self.tok = AutoTokenizer.from_pretrained(path, use_fast=True,+ trust_remote_code=False)++ # -------------------------------------------------------------- encoding+ def encode_chat(self, messages: list[dict], add_generation_prompt: bool = True,+ chat_template_kwargs: dict | None = None) -> list[int]:+ kwargs = dict(chat_template_kwargs or {})+ out = self.tok.apply_chat_template(+ messages, tokenize=True, add_generation_prompt=add_generation_prompt,+ **kwargs)+ # transformers >=5 returns a BatchEncoding (a UserDict, *not* a dict),+ # older versions return a flat list of ids.+ if not isinstance(out, (list, tuple)):+ out = out["input_ids"]+ if len(out) and isinstance(out[0], (list, tuple)):+ out = out[0]+ return [int(v) for v in out]++ def encode(self, text: str) -> list[int]:+ return self.tok.encode(text, add_special_tokens=False)++ def decode(self, ids: list[int]) -> str:+ return self.tok.decode(ids, skip_special_tokens=True)+++class Incremental:+ """Stateful incremental detokenizer for one sequence."""++ __slots__ = ("_tok", "_ids", "_read", "_text")++ def __init__(self, tokenizer: ChatTokenizer):+ self._tok = tokenizer.tok+ self._ids: list[int] = []+ self._read = 0+ self._text = ""++ def push(self, new_ids: list[int]) -> str:+ if not new_ids:+ return ""+ self._ids.extend(new_ids)+ start = max(0, self._read - _WINDOW)+ window = self._ids[start:]+ text = self._tok.decode(window, skip_special_tokens=True)+ prefix = self._tok.decode(self._ids[start:self._read],+ skip_special_tokens=True) if start < self._read else ""+ if not text.startswith(prefix):+ # Rare: window boundary changed the rendering. Fall back to a full+ # re-decode so the concatenated stream still matches one-shot decode.+ full = self._tok.decode(self._ids, skip_special_tokens=True)+ delta = full[len(self._text):]+ self._text = full+ self._read = len(self._ids)+ return delta+ delta = text[len(prefix):]+ if delta.endswith("�"):+ # incomplete UTF-8 sequence: hold it until the next token arrives+ return ""+ self._read = len(self._ids)+ self._text += delta+ return delta++ @property+ def text(self) -> str:+ return self._text++ def finalize(self) -> str:+ """Flush anything held back, returning the remaining delta."""+ if self._read == len(self._ids) and not self._text.endswith("�"):+ return ""+ full = self._tok.decode(self._ids, skip_special_tokens=True)+ delta = full[len(self._text):]+ self._text = full+ self._read = len(self._ids)+ return delta@@ -0,0 +1,119 @@+"""Offline safetensors -> NPU weight loader with QKV / gate-up fusion.++Weights are fused and (optionally) pre-transposed at load time so that the+decode hot loop issues the minimum number of device ops per layer:+ 1 fused QKV GEMM, 1 O GEMM, 1 fused gate/up GEMM, 1 down GEMM.+"""+from __future__ import annotations++import json+import os+from dataclasses import dataclass, field+from pathlib import Path++import torch+from safetensors import safe_open++from .config import ModelConfig++# torch.matmul(x, [in, out]) vs F.linear(x, [out, in]); selectable because the+# faster path differs between CANN releases.+TRANSPOSE_WEIGHTS = os.environ.get("OPENBUILD_TRANSPOSE_WEIGHTS", "1") == "1"+++@dataclass+class LayerWeights:+ input_norm: torch.Tensor+ post_norm: torch.Tensor+ q_norm: torch.Tensor+ k_norm: torch.Tensor+ qkv: torch.Tensor+ o: torch.Tensor+ gate_up: torch.Tensor+ down: torch.Tensor+++@dataclass+class ModelWeights:+ embed: torch.Tensor+ norm: torch.Tensor+ lm_head: torch.Tensor+ layers: list[LayerWeights] = field(default_factory=list)+++class _ShardReader:+ """Reads tensors from a sharded safetensors checkpoint, one handle per file."""++ def __init__(self, root: Path):+ self.root = root+ index = root / "model.safetensors.index.json"+ if index.is_file():+ meta = json.loads(index.read_text(encoding="utf-8"))+ self.map: dict[str, str] = dict(meta["weight_map"])+ else:+ single = "model.safetensors"+ if not (root / single).is_file():+ raise RuntimeError(f"no safetensors checkpoint under {root}")+ with safe_open(str(root / single), framework="pt") as fh:+ self.map = {k: single for k in fh.keys()}+ self._open: dict[str, object] = {}++ def get(self, name: str) -> torch.Tensor:+ shard = self.map.get(name)+ if shard is None:+ raise KeyError(f"missing tensor {name}")+ handle = self._open.get(shard)+ if handle is None:+ handle = safe_open(str(self.root / shard), framework="pt")+ self._open[shard] = handle+ return handle.get_tensor(name) # type: ignore[attr-defined]++ def close(self) -> None:+ self._open.clear()+++def _to_device(t: torch.Tensor, device: str, dtype: torch.dtype) -> torch.Tensor:+ return t.to(device=device, dtype=dtype, non_blocking=True)+++def _pack(mats: list[torch.Tensor]) -> torch.Tensor:+ """Concatenate [out_i, in] matrices on the output axis, optional transpose."""+ packed = mats[0] if len(mats) == 1 else torch.cat(mats, dim=0)+ if TRANSPOSE_WEIGHTS:+ packed = packed.t().contiguous()+ return packed+++def load_weights(model_path: str, cfg: ModelConfig, device: str = "npu:0",+ dtype: torch.dtype = torch.bfloat16) -> ModelWeights:+ reader = _ShardReader(Path(model_path))+ get = lambda n: _to_device(reader.get(n), device, dtype) # noqa: E731++ embed = get("model.embed_tokens.weight")+ norm = get("model.norm.weight")+ try:+ head = reader.get("lm_head.weight")+ except KeyError:+ head = reader.get("model.embed_tokens.weight")+ lm_head = _pack([_to_device(head, device, dtype)])+ del head++ out = ModelWeights(embed=embed, norm=norm, lm_head=lm_head)+ for i in range(cfg.num_layers):+ p = f"model.layers.{i}."+ qkv = _pack([get(p + "self_attn.q_proj.weight"),+ get(p + "self_attn.k_proj.weight"),+ get(p + "self_attn.v_proj.weight")])+ o = _pack([get(p + "self_attn.o_proj.weight")])+ gate_up = _pack([get(p + "mlp.gate_proj.weight"),+ get(p + "mlp.up_proj.weight")])+ down = _pack([get(p + "mlp.down_proj.weight")])+ out.layers.append(LayerWeights(+ input_norm=get(p + "input_layernorm.weight"),+ post_norm=get(p + "post_attention_layernorm.weight"),+ q_norm=get(p + "self_attn.q_norm.weight"),+ k_norm=get(p + "self_attn.k_norm.weight"),+ qkv=qkv, o=o, gate_up=gate_up, down=down))+ reader.close()+ torch.npu.synchronize()+ return out