Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
openbuild_solution · 9 changed files
Base commit: 8f62ee8f410c38ae7cd90305300afd08f0fdb098
diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..143585afc18d5eab2bd81f1a816de000ed819e15--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,46 @@+#!/usr/bin/env bash+# Idempotent offline preparation of the OpenBuild Qwen3-8B delivery.+#+# The delivery carries pure-Python serving code with no third-party runtime+# dependency beyond the base runtime (torch, torch_npu, transformers,+# safetensors, aiohttp), so preparation only validates the read-only inputs+# and stamps a run-owned marker under OPENBUILD_ENV_DIR. It never installs,+# patches or mutates the base Python environment.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)}"+ENV_DIR="${OPENBUILD_ENV_DIR:-${TMPDIR:-/tmp}/openbuild-runtime}"+MODEL_PATH="${OPENBUILD_MODEL_PATH:-}"+TOKENIZER_PATH="${OPENBUILD_TOKENIZER_PATH:-$MODEL_PATH}"++log() { printf '[openbuild bootstrap] %s\n' "$1" >&2; }++[[ -f "$SOLUTION_DIR/manifest.json" ]] || { log "manifest.json is missing"; exit 1; }+[[ -x "$SOLUTION_DIR/launch.sh" ]] || { log "launch.sh is missing"; exit 1; }+[[ -d "$SOLUTION_DIR/openbuild" ]] || { log "openbuild package is missing"; exit 1; }++mkdir -p "$ENV_DIR"++PYTHON_BIN="$(command -v python3 || command -v python)"+[[ -n "$PYTHON_BIN" ]] || { log "python interpreter not found"; exit 1; }++if [[ -n "$MODEL_PATH" ]]; then+ [[ -f "$MODEL_PATH/config.json" ]] || { log "model config.json not found at $MODEL_PATH"; exit 1; }+ [[ -f "$MODEL_PATH/model.safetensors.index.json" ]] || { log "model index not found"; exit 1; }+fi+if [[ -n "$TOKENIZER_PATH" && ! -f "$TOKENIZER_PATH/tokenizer.json" ]]; then+ log "tokenizer.json not found at $TOKENIZER_PATH"+ exit 1+fi++# Import probe: the serving package must load against the base runtime only.+(+ cd "$SOLUTION_DIR"+ PYTHONPATH="$SOLUTION_DIR" PYTHONDONTWRITEBYTECODE=1 \+ "$PYTHON_BIN" -c 'import openbuild, openbuild.qwen3, openbuild.engine, openbuild.server' \+ >/dev/null+) || { log "serving package failed to import"; exit 1; }++printf 'prepared\n' > "$ENV_DIR/.openbuild-prepared"+log "bootstrap complete (solution=$SOLUTION_DIR env=$ENV_DIR)"+exit 0diff --git a/solution/launch.sh b/solution/launch.shnew file mode 100755index 0000000000000000000000000000000000000000..ca2da0951468d91fbea22395fb0f858daeca0284--- /dev/null+++ b/solution/launch.sh@@ -0,0 +1,28 @@+#!/usr/bin/env bash+# Foreground launch of the OpenBuild Qwen3-8B serving process.+#+# One process, no detached services: launch.sh becomes the HTTP server via+# exec so SIGTERM to the process group reaches the serving loop, which+# releases the port and exits cleanly.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)}"+MODEL_PATH="${OPENBUILD_MODEL_PATH:-}"+TOKENIZER_PATH="${OPENBUILD_TOKENIZER_PATH:-$MODEL_PATH}"+HOST="${OPENBUILD_HOST:-127.0.0.1}"+PORT="${OPENBUILD_PORT:-8000}"+export OPENBUILD_SOLUTION_DIR="$SOLUTION_DIR"+export OPENBUILD_MODEL_PATH="$MODEL_PATH"+export OPENBUILD_TOKENIZER_PATH="$TOKENIZER_PATH"+export OPENBUILD_HOST="$HOST"+export OPENBUILD_PORT="$PORT"++# Single logical Ascend device is already pinned by ASCEND_RT_VISIBLE_DEVICES.+export TASK_QUEUE_ENABLE="${TASK_QUEUE_ENABLE:-2}"+export PYTHONDONTWRITEBYTECODE=1+export PYTHONUNBUFFERED=1+export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}"+export PYTHONPATH="$SOLUTION_DIR${PYTHONPATH:+:$PYTHONPATH}"++PYTHON_BIN="$(command -v python3 || command -v python)"+exec "$PYTHON_BIN" -u "$SOLUTION_DIR/openbuild_serve.py"diff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..a496c6680c354707399283046ce7ce1202669c48--- /dev/null+++ b/solution/manifest.json@@ -0,0 +1,10 @@+{+ "schema_version": 1,+ "kind": "openbuild_solution",+ "task_id": "openbuild_serving_qwen3_8b_1dev_v1",+ "model": "Qwen/Qwen3-8B",+ "framework": "openbuild-npu-serve/1.0 (torch 2.10 + torch_npu 2.10, custom continuous batching)",+ "bootstrap": "bootstrap.sh",+ "launch": "launch.sh",+ "offline_replay": true+}diff --git a/solution/openbuild/__init__.py b/solution/openbuild/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..e1bed3ad0b57483ccc375a4842e183ec9e99a6bd--- /dev/null+++ b/solution/openbuild/__init__.py@@ -0,0 +1,3 @@+"""OpenBuild Qwen3-8B serving package (single Ascend 910B device)."""++__all__ = ["engine", "qwen3", "server", "text"]diff --git a/solution/openbuild/engine.py b/solution/openbuild/engine.pynew file mode 100644index 0000000000000000000000000000000000000000..c50ac026e770fa0753f7efc3c76379f390e8ba4a--- /dev/null+++ b/solution/openbuild/engine.py@@ -0,0 +1,338 @@+"""Continuous-batching inference engine for one Ascend 910B device.++Batch layout invariant: decoding sequences occupy cache slots ``0..n-1`` and+prefilling sequences the slots above them, so the incremental flash-attention+kernel can read the whole decode cohort as a single strided view.+"""++from __future__ import annotations++import asyncio+import os+import threading+import time+from collections import deque+from typing import Any++import torch++from .qwen3 import AttentionPlan, Qwen3Model, log++PREFILL = 0+DECODE = 1+++class Sequence:+ __slots__ = (+ "seq_id", "prompt_ids", "prompt_len", "max_tokens", "ignore_eos",+ "temperature", "seed", "stream", "state", "cached", "generated",+ "loop", "events", "future", "finish_reason", "first_token_time",+ "cancelled", "detokenizer", "arrival", "text_parts", "prompt_tensor",+ )++ def __init__(self, seq_id: int, prompt_ids: list[int], max_tokens: int, *,+ ignore_eos: bool, temperature: float, seed: int | None,+ stream: bool, loop: asyncio.AbstractEventLoop | None,+ detokenizer: Any = None, device: str = "npu:0"):+ self.seq_id = seq_id+ self.prompt_ids = prompt_ids+ self.prompt_len = len(prompt_ids)+ self.max_tokens = max_tokens+ self.ignore_eos = ignore_eos+ self.temperature = temperature+ self.seed = seed+ self.stream = stream+ self.state = PREFILL+ self.cached = 0+ self.generated: list[int] = []+ self.loop = loop+ self.events: asyncio.Queue | None = None+ self.future: Any = None+ self.finish_reason: str | None = None+ self.first_token_time: float | None = None+ self.cancelled = False+ self.detokenizer = detokenizer+ self.arrival = time.monotonic()+ self.text_parts: list[str] = []+ self.prompt_tensor = torch.tensor(prompt_ids, dtype=torch.int64, device=device)++ @property+ def needed(self) -> int:+ return self.prompt_len + self.max_tokens++ def emit(self, kind: str, payload: Any = None) -> None:+ if self.loop is None:+ return+ if self.events is not None:+ self.loop.call_soon_threadsafe(self.events.put_nowait, (kind, payload))+ if kind not in ("finish", "error"):+ return+ future = self.future+ if future is None or future.done():+ return+ error = RuntimeError(str(payload)) if kind == "error" else None++ def deliver(future: asyncio.Future = future, error: BaseException | None = error) -> None:+ if future.done():+ return+ if error is not None:+ future.set_exception(error)+ else:+ future.set_result(None)++ self.loop.call_soon_threadsafe(deliver)+++class Engine:+ def __init__(self, model_path: str, tokenizer: Any, *, device: str = "npu:0",+ max_prefill_tokens: int = 4096):+ self.tokenizer = tokenizer+ self.device = device+ self.dtype = torch.bfloat16+ self.eos_ids = (151645, 151643)+ self.max_prefill_tokens = int(+ os.environ.get("OPENBUILD_MAX_PREFILL_TOKENS", max_prefill_tokens)+ )+ self.kv_budget_gb = float(os.environ.get("OPENBUILD_KV_BUDGET_GB", "24"))++ self.model = Qwen3Model(model_path, device=device, dtype=self.dtype)+ cfg = self.model.cfg+ self.kv_per_token = cfg.num_layers * 2 * cfg.num_kv_heads * cfg.head_dim * 2+ self.slot_tokens = int(os.environ.get("OPENBUILD_SLOT_TOKENS", "2176"))+ self.num_slots = self._slots_for(self.slot_tokens)+ self._allocate_cache()++ self._lock = threading.Lock()+ self._incoming: deque[Sequence] = deque()+ self._wakeup = threading.Event()+ self.batch: list[Sequence] = []+ self.running = False+ self._thread: threading.Thread | None = None+ self._steps = 0+ self._seq_counter = 0++ # -- cache -----------------------------------------------------------+ def _slots_for(self, slot_tokens: int) -> int:+ per_slot = self.kv_per_token * slot_tokens+ count = int(self.kv_budget_gb * (1024 ** 3) // per_slot)+ return max(1, min(count, 96))++ def _allocate_cache(self) -> None:+ shape = (self.model.L, self.num_slots, self.slot_tokens,+ self.model.KVH, self.model.D)+ self.k_cache = torch.zeros(shape, dtype=self.dtype, device=self.device)+ self.v_cache = torch.zeros(shape, dtype=self.dtype, device=self.device)+ log(f"kv cache: {self.num_slots} slots x {self.slot_tokens} tokens "+ f"({self.k_cache.numel() * 4 / (1024 ** 3):.1f} GiB)")++ def _resize_cache(self, slot_tokens: int) -> None:+ wanted = max(slot_tokens, self.slot_tokens)+ slots = max(1, self._slots_for(wanted))+ if slots == self.num_slots and wanted == self.slot_tokens:+ return+ self.k_cache = None+ self.v_cache = None+ self.slot_tokens = wanted+ self.num_slots = slots+ self._allocate_cache()+ log(f"kv cache resized: {slots} slots x {wanted} tokens")++ def _swap_slots(self, left: int, right: int) -> None:+ if left == right:+ return+ a = self.batch[left].cached+ b = self.batch[right].cached+ tmp_k = self.k_cache[:, left, :a].clone()+ tmp_v = self.v_cache[:, left, :a].clone()+ self.k_cache[:, left, :b] = self.k_cache[:, right, :b]+ self.v_cache[:, left, :b] = self.v_cache[:, right, :b]+ self.k_cache[:, right, :a] = tmp_k+ self.v_cache[:, right, :a] = tmp_v++ # -- lifecycle -------------------------------------------------------+ def start(self) -> None:+ self.running = True+ self._thread = threading.Thread(target=self._run, name="openbuild-engine", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ self.running = False+ self._wakeup.set()+ if self._thread is not None:+ self._thread.join(timeout=10)++ def next_id(self) -> int:+ self._seq_counter += 1+ return self._seq_counter++ def submit(self, sequence: Sequence) -> None:+ with self._lock:+ self._incoming.append(sequence)+ self._wakeup.set()++ # -- scheduling ------------------------------------------------------+ def _drain_incoming(self) -> None:+ while True:+ with self._lock:+ if not self._incoming:+ return+ sequence = self._incoming.popleft()+ if sequence.cancelled:+ continue+ if sequence.needed > self.slot_tokens and not self.batch:+ self._resize_cache(sequence.needed)+ if len(self.batch) < self.num_slots and sequence.needed <= self.slot_tokens:+ self.batch.append(sequence)++ def _drop_finished(self) -> None:+ index = 0+ while index < len(self.batch):+ sequence = self.batch[index]+ if sequence.finish_reason is None and not sequence.cancelled:+ index += 1+ continue+ last = len(self.batch) - 1+ if index != last:+ self._swap_slots(index, last)+ self.batch[index], self.batch[last] = self.batch[last], self.batch[index]+ self.batch.pop()++ def _maintain_order(self) -> None:+ boundary = 0+ size = len(self.batch)+ while boundary < size and self.batch[boundary].state == DECODE:+ boundary += 1+ for index in range(boundary, size):+ if self.batch[index].state == DECODE:+ if index != boundary:+ self._swap_slots(boundary, index)+ self.batch[boundary], self.batch[index] = (+ self.batch[index], self.batch[boundary])+ boundary += 1++ def _build_plan(self):+ plan = AttentionPlan(self.model)+ token_parts: list[torch.Tensor] = []+ position_parts: list[torch.Tensor] = []+ slot_parts: list[torch.Tensor] = []+ targets: list[int] = []+ device = self.device+ arange = torch.arange+ full = torch.full++ budget = self.max_prefill_tokens+ for slot, sequence in enumerate(self.batch):+ if sequence.state != PREFILL:+ continue+ remaining = sequence.prompt_len - sequence.cached+ if remaining <= 0 or budget <= 0:+ continue+ take = remaining if remaining < budget else budget+ start = sequence.cached+ plan.add_prefill(slot, start, take)+ prompt = sequence.prompt_tensor+ token_parts.append(prompt[start : start + take])+ position_parts.append(arange(start, start + take, device=device))+ slot_parts.append(full((take,), slot, dtype=torch.int64, device=device))+ sequence.cached = start + take+ budget -= take+ if sequence.cached >= sequence.prompt_len:+ targets.append(plan.prefill_rows - 1)++ decode_slots: list[int] = []+ decode_positions: list[int] = []+ decode_tokens: list[int] = []+ for slot, sequence in enumerate(self.batch):+ if sequence.state != DECODE or sequence.finish_reason is not None:+ continue+ plan.add_decode(slot, sequence.cached + 1)+ decode_tokens.append(sequence.generated[-1])+ decode_positions.append(sequence.cached)+ decode_slots.append(slot)+ sequence.cached += 1+ targets.append(plan.prefill_rows + len(plan.decode_slots) - 1)++ if decode_tokens:+ token_parts.append(torch.tensor(decode_tokens, dtype=torch.int64, device=device))+ position_parts.append(torch.tensor(decode_positions, dtype=torch.int64, device=device))+ slot_parts.append(torch.tensor(decode_slots, dtype=torch.int64, device=device))++ plan.finish()+ if len(token_parts) == 1:+ tokens = token_parts[0]+ positions = position_parts[0]+ slots = slot_parts[0]+ elif token_parts:+ tokens = torch.cat(token_parts)+ positions = torch.cat(position_parts)+ slots = torch.cat(slot_parts)+ else:+ tokens = position_parts = slots = torch.empty(0, dtype=torch.int64, device=device)+ return plan, tokens, positions, slots, targets++ def _run(self) -> None:+ while self.running:+ self._drain_incoming()+ self._drop_finished()+ self._maintain_order()+ if not self.batch:+ self._wakeup.wait(0.05)+ self._wakeup.clear()+ continue+ plan, tokens, positions, slots, targets = self._build_plan()+ if tokens.numel() == 0:+ self._wakeup.wait(0.02)+ self._wakeup.clear()+ continue+ try:+ hidden = self.model.forward(plan, tokens, positions, slots,+ self.k_cache, self.v_cache)+ if targets:+ rows = hidden[torch.tensor(targets, dtype=torch.int64, device=self.device)]+ logits = self.model.logits(rows)+ next_tokens = torch.argmax(logits, dim=-1).tolist()+ else:+ next_tokens = []+ except Exception as exc: # pragma: no cover+ import traceback+ traceback.print_exc()+ for sequence in self.batch:+ sequence.finish_reason = "error"+ sequence.emit("error", repr(exc))+ self.batch.clear()+ continue+ self._step_complete(targets, next_tokens)+ self._steps += 1+ log(f"engine stopped after {self._steps} steps")++ def _step_complete(self, targets: list[int], next_tokens: list[int]) -> None:+ cursor = 0+ for sequence in self.batch:+ if sequence.state == PREFILL and sequence.cached >= sequence.prompt_len:+ self._accept(sequence, next_tokens[cursor])+ cursor += 1+ sequence.state = DECODE+ for sequence in self.batch:+ if sequence.state == DECODE and sequence.finish_reason is None \+ and sequence.cached == sequence.prompt_len + len(sequence.generated):+ self._accept(sequence, next_tokens[cursor])+ cursor += 1++ def _accept(self, sequence: Sequence, token: int) -> None:+ if sequence.first_token_time is None:+ sequence.first_token_time = time.monotonic()+ sequence.generated.append(token)+ if sequence.detokenizer is not None:+ text = sequence.detokenizer.push(token)+ if text:+ sequence.text_parts.append(text)+ sequence.emit("token", text)+ if not sequence.ignore_eos and token in self.eos_ids:+ sequence.finish_reason = "stop"+ sequence.emit("finish", "stop")+ elif len(sequence.generated) >= sequence.max_tokens:+ sequence.finish_reason = "length"+ sequence.emit("finish", "length")++ def stats(self) -> dict[str, Any]:+ return {"steps": self._steps, "active": len(self.batch), "slots": self.num_slots}diff --git a/solution/openbuild/qwen3.py b/solution/openbuild/qwen3.pynew file mode 100644index 0000000000000000000000000000000000000000..d157295a682b8a8c839b9d3c9f8d7f1c6437b03e--- /dev/null+++ b/solution/openbuild/qwen3.py@@ -0,0 +1,306 @@+"""Qwen3-8B forward pass tuned for a single Ascend 910B device.++Dependency free: reads the supplied read-only safetensors projection, keeps+bf16 weights resident on the NPU and exposes one packed-token forward used by+the continuous-batching engine.+"""++from __future__ import annotations++import json+import math+import time+from pathlib import Path++import torch++import torch_npu # noqa: F401 (registers the npu backend)+++def log(message: str) -> None:+ print(f"[openbuild {time.strftime('%H:%M:%S')}] {message}", flush=True)+++class Qwen3Config:+ def __init__(self, model_path: str | Path):+ self.path = Path(model_path)+ raw = json.loads((self.path / "config.json").read_text(encoding="utf-8"))+ self.hidden_size = int(raw["hidden_size"])+ self.num_heads = int(raw["num_attention_heads"])+ self.num_kv_heads = int(raw["num_key_value_heads"])+ self.head_dim = int(raw["head_dim"])+ self.num_layers = int(raw["num_hidden_layers"])+ self.intermediate_size = int(raw["intermediate_size"])+ self.vocab_size = int(raw["vocab_size"])+ self.rope_theta = float(raw.get("rope_theta", 1000000.0))+ self.rms_eps = float(raw.get("rms_norm_eps", 1e-6))+ self.max_position_embeddings = int(raw.get("max_position_embeddings", 40960))+ self.eos_token_ids = (151645, 151643)+++class Qwen3Model:+ """Packed-token forward with an external, engine-owned KV cache."""++ def __init__(self, model_path: str | Path, device: str = "npu:0",+ dtype: torch.dtype = torch.bfloat16):+ try:+ torch.npu.config.allow_internal_format = False+ except Exception: # pragma: no cover+ pass+ self.cfg = Qwen3Config(model_path)+ self.device = device+ self.dtype = dtype+ cfg = self.cfg+ self.H = cfg.num_heads+ self.KVH = cfg.num_kv_heads+ self.D = cfg.head_dim+ self.L = cfg.num_layers+ self.hidden = cfg.hidden_size+ self.scale = 1.0 / math.sqrt(self.D)+ self.q_size = self.H * self.D+ self.kv_size = self.KVH * self.D+ self._load(model_path)+ self._build_rope()++ # -- setup -----------------------------------------------------------+ def _load(self, model_path: str | Path) -> None:+ from safetensors.torch import safe_open++ path = Path(model_path)+ index = path / "model.safetensors.index.json"+ if index.is_file():+ mapping = json.loads(index.read_text(encoding="utf-8"))["weight_map"]+ shards = sorted(set(mapping.values()))+ else:+ shards = sorted(p.name for p in path.glob("*.safetensors"))+ started = time.monotonic()+ raw: dict[str, torch.Tensor] = {}+ for shard in shards:+ with safe_open(path / shard, framework="pt", device="cpu") as handle:+ for key in handle.keys():+ raw[key] = handle.get_tensor(key)+ log(f"read {len(raw)} tensors from {len(shards)} shards in "+ f"{time.monotonic() - started:.1f}s")++ device, dtype = self.device, self.dtype+ self.layers: list[dict[str, torch.Tensor]] = []+ self_q_size = self.q_size+ self_kv_size = self.kv_size+ upload_started = time.monotonic()+ for index in range(self.L):+ prefix = f"model.layers.{index}."+ layer = {+ "ln1": raw[prefix + "input_layernorm.weight"].to(device=device, dtype=dtype),+ "ln2": raw[prefix + "post_attention_layernorm.weight"].to(device=device, dtype=dtype),+ "q_norm": raw[prefix + "self_attn.q_norm.weight"].to(device=device, dtype=dtype),+ "k_norm": raw[prefix + "self_attn.k_norm.weight"].to(device=device, dtype=dtype),+ "wq": raw[prefix + "self_attn.q_proj.weight"].to(device=device, dtype=dtype),+ "wk": raw[prefix + "self_attn.k_proj.weight"].to(device=device, dtype=dtype),+ "wv": raw[prefix + "self_attn.v_proj.weight"].to(device=device, dtype=dtype),+ "wo": raw[prefix + "self_attn.o_proj.weight"].to(device=device, dtype=dtype),+ "w_gate": raw[prefix + "mlp.gate_proj.weight"].to(device=device, dtype=dtype),+ "w_up": raw[prefix + "mlp.up_proj.weight"].to(device=device, dtype=dtype),+ "w_down": raw[prefix + "mlp.down_proj.weight"].to(device=device, dtype=dtype),+ }+ layer["wqkv"] = torch.cat((layer.pop("wq"), layer.pop("wk"),+ layer.pop("wv")), dim=0).contiguous()+ layer["w_gate_up"] = torch.cat((layer.pop("w_gate"),+ layer.pop("w_up")), dim=0).contiguous()+ layer["wq_t"] = layer["wqkv"].narrow(0, 0, self_q_size).t()+ layer["wk_t"] = layer["wqkv"].narrow(0, self_q_size, self_kv_size).t()+ layer["wv_t"] = layer["wqkv"].narrow(+ 0, self_q_size + self_kv_size, self_kv_size).t()+ layer["wo_t"] = layer["wo"].t()+ layer["w_gate_up_t"] = layer["w_gate_up"].t()+ layer["w_down_t"] = layer["w_down"].t()+ self.layers.append(layer)+ self.embed = raw["model.embed_tokens.weight"].to(device=device, dtype=dtype)+ self.final_norm = raw["model.norm.weight"].to(device=device, dtype=dtype)+ self.lm_head = raw["lm_head.weight"].to(device=device, dtype=dtype)+ raw.clear()+ torch.npu.synchronize()+ log(f"weights resident on {device} in {time.monotonic() - upload_started:.1f}s")++ def _build_rope(self) -> None:+ device = self.device+ dim = self.D+ inv_freq = 1.0 / (+ self.cfg.rope_theta+ ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim)+ )+ table = min(self.cfg.max_position_embeddings, 32768)+ position = torch.arange(table, device=device, dtype=torch.float32)+ freqs = torch.outer(position, inv_freq)+ emb = torch.cat((freqs, freqs), dim=-1)+ self.cos = emb.cos().contiguous()+ self.sin = emb.sin().contiguous()++ # -- primitives ------------------------------------------------------+ @staticmethod+ def rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:+ if x.dim() == 2:+ return torch_npu.npu_rms_norm(x, weight, eps)[0]+ return torch_npu.npu_rms_norm(x, weight, eps)[0]++ def head_norm(self, x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:+ """RMSNorm over the trailing head dimension of [N, heads, head_dim]."""+ return torch_npu.npu_rms_norm(x, weight, eps)[0]++ def rope(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:+ """x: [N, heads, D]; cos/sin: [N, D]. One fused NPU op per call."""+ shape = x.shape+ return torch_npu.npu_rotary_mul(+ x.view(shape[0], 1, shape[1], shape[2]),+ cos.view(shape[0], 1, 1, self.D),+ sin.view(shape[0], 1, 1, self.D),+ ).view(shape)++ # -- forward ---------------------------------------------------------+ def forward(+ self,+ plan: "AttentionPlan",+ token_ids: torch.Tensor,+ positions: torch.Tensor,+ slot_ids: torch.Tensor,+ k_cache: torch.Tensor,+ v_cache: torch.Tensor,+ ) -> torch.Tensor:+ hidden = self.embed.index_select(0, token_ids)+ cos = self.cos.index_select(0, positions)+ sin = self.sin.index_select(0, positions)+ eps = self.cfg.rms_eps+ rope = self.rope+ norm = self.rms_norm+ head_norm = self.head_norm+ rows = -1+ rotary_mul = torch_npu.npu_rotary_mul+ rms_norm = torch_npu.npu_rms_norm+ swiglu = torch_npu.npu_swiglu+ mm = torch.mm+ addmm = torch.addmm++ for index in range(self.L):+ layer = self.layers[index]+ normed = rms_norm(hidden, layer["ln1"], eps)[0]+ q = mm(normed, layer["wq_t"]).view(rows, self.H, self.D)+ k_new = mm(normed, layer["wk_t"]).view(rows, self.KVH, self.D)+ v_new = mm(normed, layer["wv_t"]).view(rows, self.KVH, self.D)+ q = rms_norm(q, layer["q_norm"], eps)[0]+ k_new = rms_norm(k_new, layer["k_norm"], eps)[0]+ q = rotary_mul(q.view(rows, 1, self.H, self.D),+ cos.view(rows, 1, 1, self.D),+ sin.view(rows, 1, 1, self.D)).view(rows, self.H, self.D)+ k_new = rotary_mul(k_new.view(rows, 1, self.KVH, self.D),+ cos.view(rows, 1, 1, self.D),+ sin.view(rows, 1, 1, self.D)).view(rows, self.KVH, self.D)++ k_cache[index][slot_ids, positions] = k_new+ v_cache[index][slot_ids, positions] = v_new++ attended = plan.attend(index, q, k_cache, v_cache)+ hidden = addmm(hidden, attended.view(rows, self.hidden), layer["wo_t"])++ normed = rms_norm(hidden, layer["ln2"], eps)[0]+ gate_up = mm(normed, layer["w_gate_up_t"])+ hidden = addmm(hidden, swiglu(gate_up), layer["w_down_t"])++ return rms_norm(hidden, self.final_norm, eps)[0]++ def logits(self, hidden: torch.Tensor) -> torch.Tensor:+ return torch.mm(hidden, self.lm_head.t())+++class AttentionPlan:+ """How a packed token batch splits into attention groups.++ Layout of the packed batch:+ rows [0, prefill_rows) -> prefill chunks, one contiguous run per request+ rows [prefill_rows, N) -> exactly one decode token per decoding request++ Decode requests must occupy cache slots ``0..len(decode_slots)-1`` so the+ incremental flash-attention kernel can read the cache as a strided view.+ """++ def __init__(self, model: Qwen3Model):+ self.model = model+ self.prefill: list[dict] = []+ self.prefill_rows = 0+ self.decode_slots: list[int] = []+ self.decode_lens: list[int] = []++ def add_prefill(self, slot: int, start: int, length: int) -> None:+ self.prefill.append(+ {"slot": slot, "start": start, "length": length,+ "offset": self.prefill_rows, "mask": None}+ )+ self.prefill_rows += length++ def add_decode(self, slot: int, length: int) -> None:+ self.decode_slots.append(slot)+ self.decode_lens.append(length)++ def finish(self) -> None:+ self.total_rows = self.prefill_rows + len(self.decode_slots)+ self.decode_width = max(self.decode_lens) if self.decode_lens else 0++ def attend(+ self, layer: int, q: torch.Tensor, k_cache: torch.Tensor, v_cache: torch.Tensor+ ) -> torch.Tensor:+ model = self.model+ count = len(self.decode_slots)++ if not self.prefill:+ if not count:+ return q+ width = self.decode_width+ k = k_cache[layer, :count, :width].reshape(count, width, model.kv_size)+ v = v_cache[layer, :count, :width].reshape(count, width, model.kv_size)+ attended = torch_npu.npu_incre_flash_attention(+ q[:count].reshape(count, 1, model.q_size),+ k,+ v,+ num_heads=model.H,+ num_key_value_heads=model.KVH,+ input_layout="BSH",+ scale_value=model.scale,+ actual_seq_lengths=self.decode_lens,+ )+ return attended.reshape(count, model.H, model.D)++ out = torch.empty(q.shape, dtype=q.dtype, device=q.device)+ for group in self.prefill:+ offset = group["offset"]+ length = group["length"]+ total = group["start"] + length+ slot = group["slot"]+ q_slice = q[offset : offset + length]+ k = k_cache[layer, slot, :total].view(1, total, model.KVH, model.D)+ v = v_cache[layer, slot, :total].view(1, total, model.KVH, model.D)+ attended = torch.nn.functional.scaled_dot_product_attention(+ q_slice.transpose(0, 1).unsqueeze(0),+ k.permute(0, 2, 1, 3),+ v.permute(0, 2, 1, 3),+ scale=model.scale,+ enable_gqa=True,+ is_causal=group["start"] == 0,+ attn_mask=group["mask"],+ )+ out[offset : offset + length] = attended.squeeze(0).transpose(0, 1)++ if count:+ rows = self.prefill_rows+ width = self.decode_width+ k = k_cache[layer, :count, :width].reshape(count, width, model.kv_size)+ v = v_cache[layer, :count, :width].reshape(count, width, model.kv_size)+ attended = torch_npu.npu_incre_flash_attention(+ q[rows : rows + count].reshape(count, 1, model.q_size),+ k,+ v,+ num_heads=model.H,+ num_key_value_heads=model.KVH,+ input_layout="BSH",+ scale_value=model.scale,+ actual_seq_lengths=self.decode_lens,+ )+ out[rows : rows + count] = attended.reshape(count, model.H, model.D)+ return outdiff --git a/solution/openbuild/server.py b/solution/openbuild/server.pynew file mode 100644index 0000000000000000000000000000000000000000..12a14a7173f071566bb92b665dd5a73b6e7be623--- /dev/null+++ b/solution/openbuild/server.py@@ -0,0 +1,281 @@+"""OpenAI-compatible HTTP front end for the OpenBuild serving engine."""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import signal+import sys+import time+import uuid+from pathlib import Path++from aiohttp import web++from .engine import Engine, Sequence+from .qwen3 import log+from .text import PromptRenderer, StreamDetokenizer++MODEL_ID = os.environ.get("OPENBUILD_SERVED_MODEL", "Qwen/Qwen3-8B")+++class AppState:+ def __init__(self, engine: Engine, renderer: PromptRenderer, tokenizer):+ self.engine = engine+ self.renderer = renderer+ self.tokenizer = tokenizer+ self.started = time.time()+++def _models_response() -> dict:+ return {+ "object": "list",+ "data": [+ {+ "id": MODEL_ID,+ "object": "model",+ "created": int(time.time()),+ "owned_by": "openbuild",+ "root": MODEL_ID,+ "parent": None,+ "permission": [],+ }+ ],+ }+++async def handle_models(request: web.Request) -> web.Response:+ return web.json_response(_models_response())+++async def handle_health(request: web.Request) -> web.Response:+ state = request.app["state"]+ return web.json_response({"status": "ok", **state.engine.stats()})+++def _max_tokens(body: dict) -> int:+ for key in ("max_completion_tokens", "max_tokens", "max_new_tokens"):+ if key in body and isinstance(body[key], int) and body[key] > 0:+ return body[key]+ return 32+++def _served_model_ok(body: dict) -> bool:+ model = body.get("model")+ return model is None or model == MODEL_ID or "Qwen3-8B" in str(model) or "/" in str(model)+++async def handle_chat(request: web.Request) -> web.StreamResponse:+ state: AppState = request.app["state"]+ try:+ body = await request.json()+ except Exception:+ return web.json_response({"error": {"message": "invalid JSON body"}}, status=400)+ messages = body.get("messages")+ if not isinstance(messages, list) or not messages:+ return web.json_response(+ {"error": {"message": "messages must be a non-empty list", "type": "invalid_request_error"}},+ status=400,+ )+ normalised = []+ for message in messages:+ if not isinstance(message, dict):+ return web.json_response(+ {"error": {"message": "invalid message", "type": "invalid_request_error"}}, status=400)+ role = message.get("role", "user")+ content = message.get("content", "")+ if isinstance(content, list):+ content = "".join(+ part.get("text", "") for part in content if isinstance(part, dict)+ )+ normalised.append({"role": role, "content": str(content)})++ stream = bool(body.get("stream", False))+ prompt_ids = await asyncio.get_running_loop().run_in_executor(+ None, state.renderer.render, normalised+ )+ max_tokens = _max_tokens(body)+ ignore_eos = bool(body.get("ignore_eos", False))+ temperature = body.get("temperature", 0.0)+ if not isinstance(temperature, (int, float)):+ temperature = 0.0+ seed = body.get("seed")+ request_id = "chatcmpl-" + uuid.uuid4().hex[:24]+ created = int(time.time())++ loop = asyncio.get_running_loop()+ sequence = Sequence(+ state.engine.next_id(),+ prompt_ids,+ max_tokens,+ ignore_eos=ignore_eos,+ temperature=float(temperature),+ seed=int(seed) if isinstance(seed, int) else None,+ stream=stream,+ loop=loop,+ detokenizer=StreamDetokenizer(state.tokenizer),+ device=state.engine.device,+ )++ if not stream:+ future: asyncio.Future = loop.create_future()+ sequence.future = future+ state.engine.submit(sequence)+ try:+ await future+ except Exception as exc:+ return web.json_response({"error": {"message": str(exc)}}, status=500)+ text = "".join(sequence.text_parts) + sequence.detokenizer.flush()+ usage = {+ "prompt_tokens": sequence.prompt_len,+ "completion_tokens": len(sequence.generated),+ "total_tokens": sequence.prompt_len + len(sequence.generated),+ }+ return web.json_response(+ {+ "id": request_id,+ "object": "chat.completion",+ "created": created,+ "model": MODEL_ID,+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": text},+ "logprobs": None,+ "finish_reason": sequence.finish_reason or "stop",+ }+ ],+ "usage": usage,+ "system_fingerprint": "openbuild-qwen3-8b",+ }+ )++ sequence.events = asyncio.Queue()+ state.engine.submit(sequence)+ response = web.StreamResponse(+ status=200,+ reason="OK",+ headers={+ "Content-Type": "text/event-stream; charset=utf-8",+ "Cache-Control": "no-cache",+ "Connection": "keep-alive",+ "X-Accel-Buffering": "no",+ },+ )+ await response.prepare(request)++ async def write_chunk(payload: dict) -> None:+ await response.write(+ b"data: " + json.dumps(payload, ensure_ascii=False).encode("utf-8") + b"\n\n"+ )++ base = {+ "id": request_id,+ "object": "chat.completion.chunk",+ "created": created,+ "model": MODEL_ID,+ "system_fingerprint": "openbuild-qwen3-8b",+ }+ await write_chunk({**base, "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}]})++ pieces: list[str] = []+ finish_reason = "stop"+ error: str | None = None+ while True:+ kind, payload = await sequence.events.get()+ if kind == "token":+ pieces.append(payload)+ await write_chunk({**base, "choices": [{"index": 0, "delta": {"content": payload}, "finish_reason": None}]})+ elif kind == "finish":+ finish_reason = payload+ break+ elif kind == "error":+ error = payload+ break++ tail = sequence.detokenizer.flush()+ if tail:+ await write_chunk({**base, "choices": [{"index": 0, "delta": {"content": tail}, "finish_reason": None}]})+ completion_tokens = len(sequence.generated)+ await write_chunk({**base, "choices": [{"index": 0, "delta": {}, "finish_reason": finish_reason}]})+ usage = {+ "prompt_tokens": sequence.prompt_len,+ "completion_tokens": completion_tokens,+ "total_tokens": sequence.prompt_len + completion_tokens,+ }+ await write_chunk({**base, "choices": [], "usage": usage})+ await response.write(b"data: [DONE]\n\n")+ await response.write_eof()+ return response+++def sequence_text(sequence: Sequence): # pragma: no cover - retained for diagnostics+ return "".join(sequence.text_parts)+++async def make_app(state: AppState) -> web.Application:+ app = web.Application(client_max_size=64 * 1024 * 1024)+ app["state"] = state+ app.router.add_get("/v1/models", handle_models)+ app.router.add_post("/v1/chat/completions", handle_chat)+ app.router.add_get("/healthz", handle_health)+ app.router.add_get("/v1/healthz", handle_health)+ return app+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--host", default=os.environ.get("OPENBUILD_HOST", "127.0.0.1"))+ parser.add_argument("--port", type=int, default=int(os.environ.get("OPENBUILD_PORT", "8000")))+ parser.add_argument("--model-path", default=os.environ.get("OPENBUILD_MODEL_PATH", ""))+ parser.add_argument("--tokenizer-path", default=os.environ.get("OPENBUILD_TOKENIZER_PATH", ""))+ args = parser.parse_args()++ from transformers import AutoTokenizer++ tokenizer = AutoTokenizer.from_pretrained(+ args.tokenizer_path or args.model_path, trust_remote_code=False, local_files_only=True+ )+ started = time.monotonic()+ engine = Engine(args.model_path, tokenizer)+ engine.start()+ renderer = PromptRenderer(tokenizer)+ log(f"startup complete in {time.monotonic() - started:.1f}s")++ state = AppState(engine, renderer, tokenizer)+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ app = loop.run_until_complete(make_app(state))++ runner = web.AppRunner(app, access_log=None, keepalive_timeout=120)+ loop.run_until_complete(runner.setup())+ site = web.TCPSite(runner, args.host, args.port, backlog=1024, reuse_address=True)+ loop.run_until_complete(site.start())+ log(f"serving {MODEL_ID} on http://{args.host}:{args.port}")++ stop = loop.create_future()++ def _stop(*_args) -> None:+ if not stop.done():+ loop.call_soon_threadsafe(stop.set_result, True)++ for sig in (signal.SIGTERM, signal.SIGINT):+ try:+ loop.add_signal_handler(sig, _stop)+ except NotImplementedError: # pragma: no cover+ signal.signal(sig, _stop)++ try:+ loop.run_until_complete(stop)+ finally:+ log("shutting down")+ engine.stop()+ loop.run_until_complete(runner.cleanup())+ loop.close()+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/solution/openbuild/text.py b/solution/openbuild/text.pynew file mode 100644index 0000000000000000000000000000000000000000..e5709a9e96ac0a6da5d97be99e97c3220a234844--- /dev/null+++ b/solution/openbuild/text.py@@ -0,0 +1,124 @@+"""Prompt rendering and incremental detokenization for the Qwen3 tokenizer."""++from __future__ import annotations++from typing import Iterable+++def _bytes_to_unicode() -> dict[int, str]:+ bs = (+ list(range(ord("!"), ord("~") + 1))+ + list(range(ord("\xa1"), ord("\xac") + 1))+ + list(range(ord("\xae"), ord("\xff") + 1))+ )+ cs = bs[:]+ n = 0+ for b in range(256):+ if b not in bs:+ bs.append(b)+ cs.append(256 + n)+ n += 1+ return {chr(codepoint): byte for byte, codepoint in zip(bs, cs)}+++class TokenBytes:+ """Shared, immutable per-token byte strings for a byte-level BPE vocab."""++ def __init__(self, tokenizer):+ decoder = _bytes_to_unicode()+ pieces = tokenizer.convert_ids_to_tokens(list(range(len(tokenizer))))+ table: list[bytes] = []+ for piece in pieces:+ if piece is None:+ table.append(b"")+ continue+ try:+ table.append(bytes(decoder[ch] for ch in piece))+ except KeyError:+ table.append(piece.encode("utf-8", errors="replace"))+ self.table = table+++class StreamDetokenizer:+ """Emits complete UTF-8 text as tokens arrive (byte-level BPE)."""++ _shared: TokenBytes | None = None+ _shared_vocab: int | None = None++ def __init__(self, tokenizer, token_bytes: TokenBytes | None = None):+ if token_bytes is None:+ if StreamDetokenizer._shared is None or StreamDetokenizer._shared_vocab != id(tokenizer):+ StreamDetokenizer._shared = TokenBytes(tokenizer)+ StreamDetokenizer._shared_vocab = id(tokenizer)+ token_bytes = StreamDetokenizer._shared+ self.byte_cache = token_bytes.table+ self.buffer = bytearray()++ def push(self, token_id: int) -> str:+ self.buffer += self.byte_cache[token_id]+ try:+ text = bytes(self.buffer).decode("utf-8")+ except UnicodeDecodeError:+ return ""+ self.buffer.clear()+ return text++ def flush(self) -> str:+ if not self.buffer:+ return ""+ text = bytes(self.buffer).decode("utf-8", errors="replace")+ self.buffer.clear()+ return text+++class PromptRenderer:+ """Applies the model chat template.++ Single-message user turns dominate the benchmark traffic and render through+ a fixed prefix/suffix, so they are tokenized directly. Anything else falls+ back to the tokenizer's own template so behaviour stays identical.+ """++ def __init__(self, tokenizer):+ self.tokenizer = tokenizer+ probe = tokenizer.apply_chat_template(+ [{"role": "user", "content": "openbuild probe"}],+ tokenize=True, add_generation_prompt=True,+ )+ from collections.abc import Mapping, Sequence++ if isinstance(probe, Mapping):+ probe = probe.get("input_ids")+ if probe and isinstance(probe[0], Sequence):+ probe = probe[0]+ text = tokenizer.apply_chat_template(+ [{"role": "user", "content": "openbuild probe"}],+ tokenize=False, add_generation_prompt=True,+ )+ head, _, tail = text.partition("openbuild probe")+ self._head_ids = tokenizer.encode(head, add_special_tokens=False) if head else []+ self._tail_ids = tokenizer.encode(tail, add_special_tokens=False) if tail else []+ self._head, self._tail = head, tail+ self._exact = (+ self._head_ids + tokenizer.encode("openbuild probe", add_special_tokens=False)+ + self._tail_ids+ ) == list(probe)+ self._probe_len = len(probe)++ def render(self, messages: list[dict]) -> list[int]:+ from collections.abc import Mapping, Sequence++ if self._exact and len(messages) == 1 and messages[0].get("role") == "user" \+ and isinstance(messages[0].get("content"), str):+ body = self.tokenizer.encode(messages[0]["content"], add_special_tokens=False)+ return self._head_ids + body + self._tail_ids+ encoded = self.tokenizer.apply_chat_template(+ messages, tokenize=True, add_generation_prompt=True+ )+ if isinstance(encoded, Mapping):+ encoded = encoded.get("input_ids")+ if isinstance(encoded, (str, bytes)) or not isinstance(encoded, Sequence):+ raise ValueError("chat template did not return token ids")+ if encoded and isinstance(encoded[0], Sequence):+ encoded = encoded[0]+ return [int(token) for token in encoded]diff --git a/solution/openbuild_serve.py b/solution/openbuild_serve.pynew file mode 100755index 0000000000000000000000000000000000000000..6099c25b74eee20528a5e686c66793a90bedcbd5--- /dev/null+++ b/solution/openbuild_serve.py@@ -0,0 +1,9 @@+#!/usr/bin/env python3+"""Foreground entrypoint: load the model, then serve OpenAI-compatible HTTP."""++import sys++from openbuild.server import main++if __name__ == "__main__":+ sys.exit(main())