Gemini 3.7 Flash · Serving

S13 · Serving build

Correctness rejected

OpenBuild Qwen3-8B serving 1dev · Open Build

—PERFORMANCE RATIO
119TOOL EVENTS
1TEXT PATCHES
0BINARY NAMES

01 / PROCESS MAP

Tool activity

Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.

Main agentGemini 3.7 Flash · 119 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
40Inspect
1Edit
3Validate
1Execute
11Profile
63Other

02 / EVENT SEQUENCE

Event timeline

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.

Show event timelineHide event timeline70 groups · 119 calls

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>.

Main agent

  1. Other · Source & workspace

    Requested environment setup or inspection and source searches related to source & workspace.

    1 call · #0001–#0001

    envgrep <val>echo <val>
  2. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0002–#0003

    Read <path>
  3. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0004–#0005

    Read <path>
  4. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0006–#0006

    python3 -Vpython3 -c <script>
  5. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0007–#0008

    Read <path>
  6. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0009–#0009

    Manage task <task>
  7. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0010–#0011

    Read <path>
  8. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0012–#0012

    Manage task <task>
  9. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0013–#0013

    ls -l -a <path>
  10. Other · Dependencies & build setup

    Requested dependency and build commands related to dependencies & build setup.

    1 call · #0014–#0014

    pip list
  11. Inspect · Source & workspace

    Requested workspace inspection, file and log inspection and source searches related to source & workspace.

    8 calls · #0015–#0022

    find <path> -name <val> <n> > <path>head -n <n>ls -l -a <path>Read <path>find <path> -iname <val> -o -iname <val> <n> > <path>grep -v <path>
    2 more command sketches
    find <path> -name <val> -o -name <val> -o -name <val> -o -name <val> <args>ls -l -a <path> <path>
  12. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0023–#0024

    Read <path>
  13. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0025–#0025

    Read <path>
  14. Validate · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    1 call · #0026–#0026

    bash <script>
  15. Inspect · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0027–#0027

    Read <path>
  16. Validate · Benchmark & validation setup

    Requested environment setup or inspection related to benchmark & validation setup.

    1 call · #0028–#0028

    env <vars> bash <script>
  17. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0029–#0029

    Read <path>
  18. Other · Source & workspace

    Requested task coordination related to source & workspace.

    4 calls · #0030–#0033

    Manage task <task>
  19. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0034–#0034

    python3 -c <script>
  20. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0035–#0035

    Read <path>
  21. Other · Source & workspace

    Requested tool activity related to source & workspace.

    2 calls · #0036–#0037

    shell <script>
  22. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    4 calls · #0038–#0041

    shell <script>python3 -c <script>
  23. Other · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0042–#0042

    shell <script>
  24. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    2 calls · #0043–#0044

    python3 -c <script>shell <script>
  25. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    5 calls · #0045–#0049

    shell <script>python3 -c <script>
  26. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    3 calls · #0050–#0052

    python3 -c <script>shell <script>
  27. Other · Source & workspace

    Requested tool activity related to source & workspace.

    6 calls · #0053–#0058

    shell <script>
  28. Other · Attention kernels

    Requested tool activity related to attention kernels.

    2 calls · #0059–#0060

    shell <script>
  29. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0061–#0061

    python3 -c <script>
  30. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0062–#0062

    python3 -c <script>
  31. Other · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0063–#0063

    shell <script>
  32. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0064–#0064

    python3 -c <script>
  33. Other · Source & workspace

    Requested tool activity related to source & workspace.

    3 calls · #0065–#0067

    shell <script>
  34. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0068–#0069

    Read <path>
  35. Other · Source & workspace

    Requested workspace file updates related to source & workspace.

    3 calls · #0070–#0072

    shell <script>mkdir -p <path>
  36. Other · KV-cache management

    Requested script or workload execution related to kv-cache management.

    2 calls · #0073–#0074

    python3 -c <script>
  37. Other · Source & workspace

    Requested tool activity related to source & workspace.

    4 calls · #0075–#0078

    shell <script>
  38. Edit · Source & workspace

    1 tool error

    Requested code edits related to source & workspace.

    1 call · #0079–#0079

    Write <path>
  39. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0080–#0080

    cat <script>
  40. Profile · Batching & scheduling

    Requested tool activity related to batching & scheduling.

    1 call · #0081–#0081

    shell <script>
  41. Profile · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0082–#0082

    shell <script>
  42. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0083–#0083

    cat <script>
  43. Profile · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0084–#0084

    shell <script>
  44. Inspect · Batching & scheduling

    Requested file and log inspection related to batching & scheduling.

    3 calls · #0085–#0087

    cat <script>
  45. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0088–#0088

    cat <script>
  46. Other · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    1 call · #0089–#0089

    bash <script>
  47. Validate · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    1 call · #0090–#0090

    bash <script>
  48. Other · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    1 call · #0091–#0091

    bash <script>
  49. Inspect · Source & workspace

    Requested workspace inspection and file and log inspection related to source & workspace.

    1 call · #0092–#0092

    ls -l -a <val>tail -n <n> <path>
  50. Other · Attention kernels

    Requested tool activity related to attention kernels.

    1 call · #0093–#0093

    shell <script>
  51. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0094–#0094

    cat <script>
  52. Inspect · Batching & scheduling

    Requested file and log inspection related to batching & scheduling.

    2 calls · #0095–#0096

    cat <script>
  53. Other · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    2 calls · #0097–#0098

    bash <script>
  54. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0099–#0099

    bash <script>
  55. Profile · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0100–#0100

    rm -f <path> <path> <path> <path> <path>
  56. Other · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    1 call · #0101–#0101

    bash <script>
  57. Execute · Batching & scheduling

    Requested tool activity related to batching & scheduling.

    1 call · #0102–#0102

    shell <script>
  58. Profile · Source & workspace

    Requested tool activity related to source & workspace.

    2 calls · #0103–#0104

    shell <script>
  59. Inspect · Attention kernels

    Requested tool activity related to attention kernels.

    1 call · #0105–#0105

    shell <script>
  60. Inspect · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0106–#0106

    shell <script>
  61. Inspect · Batching & scheduling

    Requested file and log inspection related to batching & scheduling.

    1 call · #0107–#0107

    cat <script>
  62. Other · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0108–#0108

    shell <script>
  63. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0109–#0109

    cat <script>
  64. Profile · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0110–#0110

    rm -f <path> <path> <path> <path> <path>
  65. Other · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    1 call · #0111–#0111

    bash <script>
  66. Profile · Benchmark & validation setup

    Requested workspace file updates and script or workload execution related to benchmark & validation setup.

    1 call · #0112–#0112

    rm -f <path> <path> <path> <path> <path>bash <script>
  67. Other · Source & workspace

    Requested tool activity related to source & workspace.

    3 calls · #0113–#0115

    shell <script>
  68. Profile · Source & workspace

    Requested tool activity related to source & workspace.

    2 calls · #0116–#0117

    shell <script>
  69. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0118–#0118

    cat <script>
  70. Profile · Benchmark & validation setup

    1 missing return

    Requested workspace file updates and script or workload execution related to benchmark & validation setup.

    1 call · #0119–#0119

    rm -f <path> <path> <path> <path> <path>bash <script>

03 / CANDIDATE ARTIFACT

Text patches & binary names

Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.

openbuild_solution · 7 changed files

Base commit: 8f62ee8f410c38ae7cd90305300afd08f0fdb098

diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..5cb9ebc75dd14c8cda5a6319245b196966f0307b--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+set -euo pipefail++# Offline bootstrap script+# No installation needed as our pure PyTorch/torch_npu engine runs directly with the base runtime.+exit 0diff --git a/solution/engine/api_server.py b/solution/engine/api_server.pynew file mode 100644index 0000000000000000000000000000000000000000..4a02542dbd152c7d899fb69a8228b6330f4303cb--- /dev/null+++ b/solution/engine/api_server.py@@ -0,0 +1,176 @@+import json+import time+import uuid+from typing import Optional, List, Dict, Any+from fastapi import FastAPI, Request, HTTPException+from fastapi.responses import JSONResponse, StreamingResponse+from pydantic import BaseModel, Field++from engine.scheduler import AsyncEngine, TokenDelta++app = FastAPI(title="Qwen3 OpenBuild Serving Engine")+engine: Optional[AsyncEngine] = None+served_model_name: str = "Qwen/Qwen3-8B"++class StreamOptions(BaseModel):+    include_usage: Optional[bool] = False++class ChatCompletionRequest(BaseModel):+    model: str = "Qwen/Qwen3-8B"+    messages: List[Dict[str, Any]]+    max_tokens: Optional[int] = 16+    max_completion_tokens: Optional[int] = None+    temperature: Optional[float] = 0.0+    seed: Optional[int] = None+    ignore_eos: Optional[bool] = False+    stream: Optional[bool] = False+    stream_options: Optional[StreamOptions] = None++@app.on_event("startup")+async def startup_event():+    global engine+    if engine is not None:+        engine.start()++@app.on_event("shutdown")+async def shutdown_event():+    global engine+    if engine is not None:+        await engine.stop()++@app.get("/v1/models")+async def list_models():+    return {+        "object": "list",+        "data": [+            {+                "id": served_model_name,+                "object": "model",+                "created": int(time.time()),+                "owned_by": "openbuild"+            }+        ]+    }++@app.post("/v1/chat/completions")+async def chat_completions(req: ChatCompletionRequest, raw_req: Request):+    global engine+    if engine is None:+        raise HTTPException(status_code=500, detail="Inference engine not initialized")+    +    max_tokens = req.max_completion_tokens if req.max_completion_tokens is not None else (req.max_tokens or 16)+    if max_tokens <= 0:+        max_tokens = 16+        +    stream = bool(req.stream)+    include_usage = False+    if req.stream_options and req.stream_options.include_usage:+        include_usage = True+        +    output_queue = await engine.add_request(+        messages=req.messages,+        max_tokens=max_tokens,+        temperature=req.temperature or 0.0,+        seed=req.seed,+        ignore_eos=bool(req.ignore_eos),+        stream=stream+    )+    +    created_time = int(time.time())+    completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"+    +    if not stream:+        last_delta: Optional[TokenDelta] = None+        while True:+            item = await output_queue.get()+            if item is None:+                break+            last_delta = item+                +        if last_delta is None:+            raise HTTPException(status_code=500, detail="No generation produced")+            +        return {+            "id": completion_id,+            "object": "chat.completion",+            "created": created_time,+            "model": served_model_name,+            "choices": [+                {+                    "index": 0,+                    "message": {+                        "role": "assistant",+                        "content": last_delta.full_text+                    },+                    "finish_reason": last_delta.finish_reason or "length"+                }+            ],+            "usage": {+                "prompt_tokens": last_delta.prompt_tokens,+                "completion_tokens": last_delta.completion_tokens,+                "total_tokens": last_delta.total_tokens+            }+        }+    else:+        async def event_generator():+            first_chunk = True+            last_delta: Optional[TokenDelta] = None+            +            while True:+                item = await output_queue.get()+                if item is None:+                    break+                    +                last_delta = item+                +                if item.finish_reason is not None:+                    delta_content = {"content": item.text_delta} if item.text_delta else {}+                    chunk = {+                        "id": completion_id,+                        "object": "chat.completion.chunk",+                        "created": created_time,+                        "model": served_model_name,+                        "choices": [+                            {+                                "index": 0,+                                "delta": delta_content,+                                "finish_reason": item.finish_reason+                            }+                        ]+                    }+                else:+                    delta_content = {"role": "assistant", "content": item.text_delta} if first_chunk else {"content": item.text_delta}+                    chunk = {+                        "id": completion_id,+                        "object": "chat.completion.chunk",+                        "created": created_time,+                        "model": served_model_name,+                        "choices": [+                            {+                                "index": 0,+                                "delta": delta_content,+                                "finish_reason": None+                            }+                        ]+                    }+                first_chunk = False+                yield f"data: {json.dumps(chunk, separators=(',', ':'))}\n\n"+                +            if include_usage and last_delta is not None:+                usage_chunk = {+                    "id": completion_id,+                    "object": "chat.completion.chunk",+                    "created": created_time,+                    "model": served_model_name,+                    "choices": [],+                    "usage": {+                        "prompt_tokens": last_delta.prompt_tokens,+                        "completion_tokens": last_delta.completion_tokens,+                        "total_tokens": last_delta.total_tokens+                    }+                }+                yield f"data: {json.dumps(usage_chunk, separators=(',', ':'))}\n\n"+                +            yield "data: [DONE]\n\n"+            +        return StreamingResponse(event_generator(), media_type="text/event-stream")diff --git a/solution/engine/main.py b/solution/engine/main.pynew file mode 100644index 0000000000000000000000000000000000000000..54d15bd5a7a5328e8e0ee1fc932b477f8e46e3a1--- /dev/null+++ b/solution/engine/main.py@@ -0,0 +1,45 @@+import os+import sys+import uvicorn+import torch+import torch_npu++from engine.model_runner import Qwen3ModelRunner+from engine.scheduler import AsyncEngine+import engine.api_server as api_module++def main():+    host = os.environ.get("OPENBUILD_HOST", "127.0.0.1")+    port = int(os.environ.get("OPENBUILD_PORT", "39301"))+    model_path = os.environ.get("OPENBUILD_MODEL_PATH", "/mnt/shared/models/Qwen3-8B-b968826")+    tokenizer_path = os.environ.get("OPENBUILD_TOKENIZER_PATH", model_path)+    served_model = os.environ.get("OPENBUILD_SERVED_MODEL", "Qwen/Qwen3-8B")+    +    device_id = os.environ.get("OPENBUILD_DEVICE_IDS", os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "0")).split(",")[0]+    device_str = f"npu:{device_id}" if device_id.isdigit() else "npu:0"+    +    api_module.served_model_name = served_model+    +    print(f"[Main] Initializing Qwen3 on {device_str} for model '{served_model}'...")+    runner = Qwen3ModelRunner(+        model_path=model_path,+        tokenizer_path=tokenizer_path,+        device=device_str,+        num_blocks=1200,+        block_size=128+    )+    +    engine = AsyncEngine(runner)+    api_module.engine = engine+    +    print(f"[Main] Starting HTTP server on http://{host}:{port}...")+    uvicorn.run(+        api_module.app,+        host=host,+        port=port,+        log_level="warning",+        access_log=False+    )++if __name__ == "__main__":+    main()diff --git a/solution/engine/model_runner.py b/solution/engine/model_runner.pynew file mode 100644index 0000000000000000000000000000000000000000..ed29fbc98ecca1248fdc71b6baa6c60074e89ee4--- /dev/null+++ b/solution/engine/model_runner.py@@ -0,0 +1,244 @@+import math+import os+import json+import torch+import torch_npu+from safetensors.torch import load_file+from transformers import AutoTokenizer++class Qwen3ModelRunner:+    def __init__(self, model_path: str, tokenizer_path: str, device: str = "npu:0", num_blocks: int = 1200, block_size: int = 128):+        self.device = torch.device(device)+        self.dtype = torch.bfloat16+        self.num_blocks = num_blocks+        self.block_size = block_size+        +        self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, trust_remote_code=False, local_files_only=True)+        self.eos_token_id = self.tokenizer.eos_token_id or 151645+        +        self.hidden_size = 4096+        self.num_layers = 36+        self.num_heads = 32+        self.num_kv_heads = 8+        self.head_dim = 128+        self.intermediate_size = 12288+        self.vocab_size = 151936+        self.scale = 1.0 / math.sqrt(self.head_dim)+        +        print(f"[Engine] Loading weights from {model_path} onto {device}...")+        index_file = os.path.join(model_path, "model.safetensors.index.json")+        with open(index_file, "r") as f:+            index = json.load(f)+        +        weight_map = index["weight_map"]+        files = set(weight_map.values())+        tensors = {}+        for file_name in sorted(files):+            full_path = os.path.join(model_path, file_name)+            loaded = load_file(full_path, device="cpu")+            for k, v in loaded.items():+                tensors[k] = v.to(device=self.device, dtype=self.dtype)+        +        self.embed_weight = tensors["model.embed_tokens.weight"]+        self.final_norm_weight = tensors["model.norm.weight"]+        self.lm_head_weight_t = tensors["lm_head.weight"].t().contiguous()+        +        self.layers = []+        for l in range(self.num_layers):+            p = f"model.layers.{l}"+            q_proj = tensors[f"{p}.self_attn.q_proj.weight"]+            k_proj = tensors[f"{p}.self_attn.k_proj.weight"]+            v_proj = tensors[f"{p}.self_attn.v_proj.weight"]+            q_norm = tensors[f"{p}.self_attn.q_norm.weight"]+            k_norm = tensors[f"{p}.self_attn.k_norm.weight"]+            o_proj = tensors[f"{p}.self_attn.o_proj.weight"]+            +            gate_proj = tensors[f"{p}.mlp.gate_proj.weight"]+            up_proj = tensors[f"{p}.mlp.up_proj.weight"]+            down_proj = tensors[f"{p}.mlp.down_proj.weight"]+            +            input_norm = tensors[f"{p}.input_layernorm.weight"]+            post_norm = tensors[f"{p}.post_attention_layernorm.weight"]+            +            qkv_w = torch.cat([q_proj, k_proj, v_proj], dim=0).t().contiguous()+            o_w = o_proj.t().contiguous()+            gate_up_w = torch.cat([gate_proj, up_proj], dim=0).t().contiguous()+            down_w = down_proj.t().contiguous()+            +            self.layers.append({+                "qkv_w": qkv_w,+                "o_w": o_w,+                "gate_up_w": gate_up_w,+                "down_w": down_w,+                "q_norm": q_norm,+                "k_norm": k_norm,+                "input_norm": input_norm,+                "post_norm": post_norm+            })+        +        max_positions = 32768+        inv_freq = 1.0 / (1000000.0 ** (torch.arange(0, self.head_dim, 2, device=self.device, dtype=torch.float32) / self.head_dim))+        t = torch.arange(max_positions, device=self.device, dtype=torch.float32)+        freqs = torch.outer(t, inv_freq)+        emb = torch.cat((freqs, freqs), dim=-1)+        self.cos_table = emb.cos().to(dtype=self.dtype)+        self.sin_table = emb.sin().to(dtype=self.dtype)+        +        self.causal_mask_2048 = torch.triu(torch.ones(2048, 2048, dtype=torch.bool, device=self.device), diagonal=1)+        +        print(f"[Engine] Allocating KV Cache pool: {self.num_blocks} blocks of size {self.block_size}...")+        self.kv_cache_k = [torch.zeros(self.num_blocks, self.num_kv_heads, self.block_size, self.head_dim, dtype=self.dtype, device=self.device) for _ in range(self.num_layers)]+        self.kv_cache_v = [torch.zeros(self.num_blocks, self.num_kv_heads, self.block_size, self.head_dim, dtype=self.dtype, device=self.device) for _ in range(self.num_layers)]+        +        self.kc_flat = [k.view(-1, self.head_dim) for k in self.kv_cache_k]+        self.vc_flat = [v.view(-1, self.head_dim) for v in self.kv_cache_v]+        +        self.free_blocks = list(range(self.num_blocks))+        self.head_indices = torch.arange(self.num_kv_heads, device=self.device, dtype=torch.long)[None, :]+        +        torch.npu.synchronize()+        print("[Engine] Qwen3ModelRunner initialized successfully!")++    def allocate_blocks(self, count: int) -> list[int]:+        if len(self.free_blocks) < count:+            raise RuntimeError(f"Out of KV cache memory: requested {count} blocks, but only {len(self.free_blocks)} available")+        allocated = self.free_blocks[-count:]+        del self.free_blocks[-count:]+        return allocated++    def free_blocks_by_id(self, block_ids: list[int]):+        self.free_blocks.extend(block_ids)++    @staticmethod+    def _rotate_half(x: torch.Tensor) -> torch.Tensor:+        x1 = x[..., : x.shape[-1] // 2]+        x2 = x[..., x.shape[-1] // 2 :]+        return torch.cat((-x2, x1), dim=-1)++    def _apply_rope(self, q: torch.Tensor, k: torch.Tensor, pos_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+        cos = self.cos_table[pos_ids].unsqueeze(1)+        sin = self.sin_table[pos_ids].unsqueeze(1)+        q_rot = (q * cos) + (self._rotate_half(q) * sin)+        k_rot = (k * cos) + (self._rotate_half(k) * sin)+        return q_rot, k_rot++    def prefill(self, input_ids: torch.Tensor, block_ids: list[int]) -> tuple[int, int]:+        S = input_ids.shape[1]+        pos_ids = torch.arange(S, device=self.device).unsqueeze(0)+        h = torch.nn.functional.embedding(input_ids, self.embed_weight)+        +        mask = self.causal_mask_2048 if S <= 2048 else torch.triu(torch.ones(S, S, dtype=torch.bool, device=self.device), diagonal=1)+        +        num_full_blocks = S // self.block_size+        remainder = S % self.block_size+        +        for l in range(self.num_layers):+            layer = self.layers[l]+            norm_h, _ = torch_npu.npu_rms_norm(h, layer["input_norm"], epsilon=1e-6)+            qkv = torch.matmul(norm_h, layer["qkv_w"])+            +            q = qkv[:, :, :self.num_heads*self.head_dim].reshape(1, S, self.num_heads, self.head_dim).transpose(1, 2)+            k = qkv[:, :, self.num_heads*self.head_dim:(self.num_heads+self.num_kv_heads)*self.head_dim].reshape(1, S, self.num_kv_heads, self.head_dim).transpose(1, 2)+            v = qkv[:, :, (self.num_heads+self.num_kv_heads)*self.head_dim:].reshape(1, S, self.num_kv_heads, self.head_dim).transpose(1, 2)+            +            q, _ = torch_npu.npu_rms_norm(q, layer["q_norm"], epsilon=1e-6)+            k, _ = torch_npu.npu_rms_norm(k, layer["k_norm"], epsilon=1e-6)+            +            q, k = self._apply_rope(q, k, pos_ids)+            +            for b_idx in range(num_full_blocks):+                blk = block_ids[b_idx]+                start = b_idx * self.block_size+                end = start + self.block_size+                self.kv_cache_k[l][blk] = k[0, :, start:end, :]+                self.kv_cache_v[l][blk] = v[0, :, start:end, :]+            +            if remainder > 0:+                blk = block_ids[num_full_blocks]+                start = num_full_blocks * self.block_size+                self.kv_cache_k[l][blk, :, :remainder, :] = k[0, :, start:, :]+                self.kv_cache_v[l][blk, :, :remainder, :] = v[0, :, start:, :]+            +            attn_out = torch_npu.npu_fusion_attention(+                q, k, v, self.num_heads, input_layout="BNSD",+                scale=self.scale, sparse_mode=2, atten_mask=mask+            )[0].transpose(1, 2).reshape(1, S, -1)+            h = h + torch.matmul(attn_out, layer["o_w"])+            +            norm_h2, _ = torch_npu.npu_rms_norm(h, layer["post_norm"], epsilon=1e-6)+            gate_up = torch.matmul(norm_h2, layer["gate_up_w"])+            mlp_out = torch_npu.npu_swiglu(gate_up, dim=-1)+            h = h + torch.matmul(mlp_out, layer["down_w"])+        +        last_h = h[:, -1:, :]+        out_norm, _ = torch_npu.npu_rms_norm(last_h, self.final_norm_weight, epsilon=1e-6)+        logits = torch.matmul(out_norm.squeeze(1), self.lm_head_weight_t)+        next_token = torch.argmax(logits, dim=-1).item()+        return next_token, S++    def decode_batch(+        self,+        batch_token_ids: torch.Tensor,+        batch_pos_ids: torch.Tensor,+        block_tables: torch.Tensor,+        actual_seq_lengths: list[int],+        current_block_ids: torch.Tensor,+        offsets_in_block: torch.Tensor+    ) -> list[int]:+        B = batch_token_ids.shape[0]+        h = torch.nn.functional.embedding(batch_token_ids, self.embed_weight)+        +        cos = self.cos_table[batch_pos_ids].unsqueeze(1).unsqueeze(2)+        sin = self.sin_table[batch_pos_ids].unsqueeze(1).unsqueeze(2)+        flat_indices = (current_block_ids[:, None] * (self.num_kv_heads * self.block_size) + self.head_indices * self.block_size + offsets_in_block[:, None]).reshape(-1)+        +        norm_h, _ = torch_npu.npu_rms_norm(h, self.layers[0]["input_norm"], epsilon=1e-6)+        +        for l in range(self.num_layers):+            layer = self.layers[l]+            qkv = torch.matmul(norm_h, layer["qkv_w"])+            +            q = qkv[:, :self.num_heads*self.head_dim].reshape(B * self.num_heads, self.head_dim)+            k = qkv[:, self.num_heads*self.head_dim:(self.num_heads+self.num_kv_heads)*self.head_dim].reshape(B * self.num_kv_heads, self.head_dim)+            v = qkv[:, (self.num_heads+self.num_kv_heads)*self.head_dim:].reshape(B, self.num_kv_heads, 1, self.head_dim)+            +            q, _ = torch_npu.npu_rms_norm(q, layer["q_norm"], epsilon=1e-6)+            k, _ = torch_npu.npu_rms_norm(k, layer["k_norm"], epsilon=1e-6)+            +            q = q.reshape(B, self.num_heads, 1, self.head_dim)+            k = k.reshape(B, self.num_kv_heads, 1, self.head_dim)+            +            qk = torch.cat([q, k], dim=1)+            qk_rot = (qk * cos) + (self._rotate_half(qk) * sin)+            q = qk_rot[:, :self.num_heads]+            k = qk_rot[:, self.num_heads:]+            +            k_flat = k.reshape(B * self.num_kv_heads, self.head_dim)+            v_flat = v.reshape(B * self.num_kv_heads, self.head_dim)+            self.kc_flat[l].index_copy_(0, flat_indices, k_flat)+            self.vc_flat[l].index_copy_(0, flat_indices, v_flat)+            +            attn_out = torch_npu.npu_incre_flash_attention(+                q, self.kv_cache_k[l], self.kv_cache_v[l],+                num_heads=self.num_heads, num_key_value_heads=self.num_kv_heads,+                input_layout="BNSD", scale_value=self.scale,+                block_size=self.block_size, block_table=block_tables,+                actual_seq_lengths=actual_seq_lengths+            ).view(B, self.hidden_size)+            attn_proj = torch.matmul(attn_out, layer["o_w"])+            +            norm_h2, _, h = torch_npu.npu_add_rms_norm(h, attn_proj, layer["post_norm"], epsilon=1e-6)+            +            gate_up = torch.matmul(norm_h2, layer["gate_up_w"])+            mlp_out = torch_npu.npu_swiglu(gate_up, dim=-1)+            mlp_proj = torch.matmul(mlp_out, layer["down_w"])+            +            if l < self.num_layers - 1:+                norm_h, _, h = torch_npu.npu_add_rms_norm(h, mlp_proj, self.layers[l+1]["input_norm"], epsilon=1e-6)+            else:+                h = h + mlp_proj+                +        out_norm, _ = torch_npu.npu_rms_norm(h, self.final_norm_weight, epsilon=1e-6)+        logits = torch.matmul(out_norm, self.lm_head_weight_t)+        next_tokens = torch.argmax(logits, dim=-1).tolist()+        return next_tokensdiff --git a/solution/engine/scheduler.py b/solution/engine/scheduler.pynew file mode 100644index 0000000000000000000000000000000000000000..cfc282218bdfdaaba6940182009f91fc7dd54494--- /dev/null+++ b/solution/engine/scheduler.py@@ -0,0 +1,255 @@+import asyncio+import time+import uuid+import torch+from dataclasses import dataclass, field+from typing import Optional, List, Dict+from engine.model_runner import Qwen3ModelRunner++@dataclass+class GenerationRequest:+    request_id: str+    messages: list+    input_ids: torch.Tensor+    prompt_len: int+    max_tokens: int+    temperature: float+    seed: Optional[int]+    ignore_eos: bool+    stream: bool+    output_queue: asyncio.Queue+    created_at: float = field(default_factory=time.monotonic)+    block_ids: List[int] = field(default_factory=list)+    generated_tokens: List[int] = field(default_factory=list)+    cur_pos: int = 0+    finish_reason: Optional[str] = None+    cancelled: bool = False+    decoded_text: str = ""++@dataclass+class TokenDelta:+    token_id: int+    text_delta: str+    finish_reason: Optional[str]+    prompt_tokens: int+    completion_tokens: int+    total_tokens: int+    full_text: str++class AsyncEngine:+    def __init__(self, runner: Qwen3ModelRunner):+        self.runner = runner+        self.tokenizer = runner.tokenizer+        self.device = runner.device+        self.waiting_queue: asyncio.Queue[GenerationRequest] = asyncio.Queue()+        self.running_requests: Dict[str, GenerationRequest] = {}+        self.running_task: Optional[asyncio.Task] = None+        self._shutdown_event = asyncio.Event()++    def start(self):+        self.running_task = asyncio.create_task(self._scheduler_loop())++    async def stop(self):+        self._shutdown_event.set()+        if self.running_task:+            self.running_task.cancel()+            try:+                await self.running_task+            except asyncio.CancelledError:+                pass++    async def add_request(+        self,+        messages: list,+        max_tokens: int = 16,+        temperature: float = 0.0,+        seed: Optional[int] = None,+        ignore_eos: bool = False,+        stream: bool = False+    ) -> asyncio.Queue[Optional[TokenDelta]]:+        last_is_assistant = len(messages) > 0 and messages[-1].get("role") == "assistant"+        if last_is_assistant:+            enc = self.tokenizer.apply_chat_template(messages, tokenize=True, continue_final_message=True)+        else:+            enc = self.tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True)+            +        if hasattr(enc, "input_ids"):+            token_list = enc.input_ids+        elif isinstance(enc, dict):+            token_list = enc["input_ids"]+        elif hasattr(enc, "ids"):+            token_list = enc.ids+        else:+            token_list = list(enc)+            +        input_ids = torch.tensor(token_list, device=self.device, dtype=torch.long).unsqueeze(0)+        prompt_len = input_ids.shape[1]+        +        output_queue = asyncio.Queue()+        req = GenerationRequest(+            request_id=str(uuid.uuid4()),+            messages=messages,+            input_ids=input_ids,+            prompt_len=prompt_len,+            max_tokens=max_tokens,+            temperature=temperature,+            seed=seed,+            ignore_eos=ignore_eos,+            stream=stream,+            output_queue=output_queue+        )+        await self.waiting_queue.put(req)+        return output_queue++    async def _scheduler_loop(self):+        while not self._shutdown_event.is_set():+            has_work = False+            +            # 1. Process waiting requests (up to 2 if decoding is active, or all if idle)+            max_prefills = 2 if self.running_requests else 64+            prefilled_count = 0+            +            while not self.waiting_queue.empty() and prefilled_count < max_prefills and len(self.runner.free_blocks) >= 4:+                req = self.waiting_queue.get_nowait()+                if req.cancelled:+                    continue+                needed_blocks = (req.prompt_len + self.runner.block_size - 1) // self.runner.block_size+                if len(self.runner.free_blocks) >= needed_blocks:+                    req.block_ids = self.runner.allocate_blocks(needed_blocks)+                    first_tok, _ = self.runner.prefill(req.input_ids, req.block_ids)+                    req.generated_tokens.append(first_tok)+                    req.cur_pos = req.prompt_len+                    +                    if req.stream:+                        full_text = self.tokenizer.decode(req.generated_tokens)+                        text_delta = full_text+                        req.decoded_text = full_text+                    else:+                        full_text = ""+                        text_delta = ""+                    +                    if len(req.generated_tokens) >= req.max_tokens:+                        req.finish_reason = "length"+                    elif first_tok == self.runner.eos_token_id and not req.ignore_eos:+                        req.finish_reason = "stop"+                    +                    if req.finish_reason is not None and not req.stream:+                        full_text = self.tokenizer.decode(req.generated_tokens)+                        req.decoded_text = full_text+                        +                    delta = TokenDelta(+                        token_id=first_tok,+                        text_delta=text_delta,+                        finish_reason=req.finish_reason,+                        prompt_tokens=req.prompt_len,+                        completion_tokens=len(req.generated_tokens),+                        total_tokens=req.prompt_len + len(req.generated_tokens),+                        full_text=full_text+                    )+                    await req.output_queue.put(delta)+                    +                    if req.finish_reason is not None:+                        self.runner.free_blocks_by_id(req.block_ids)+                        await req.output_queue.put(None)+                    else:+                        self.running_requests[req.request_id] = req+                    prefilled_count += 1+                    has_work = True+                else:+                    await self.waiting_queue.put(req)+                    break+            +            # 2. Decode step on all active running requests+            if self.running_requests:+                active_list: List[GenerationRequest] = []+                for req_id, req in list(self.running_requests.items()):+                    if req.cancelled:+                        self.runner.free_blocks_by_id(req.block_ids)+                        del self.running_requests[req_id]+                        continue+                    cur_block_idx = req.cur_pos // self.runner.block_size+                    if cur_block_idx >= len(req.block_ids):+                        if len(self.runner.free_blocks) >= 1:+                            new_b = self.runner.allocate_blocks(1)+                            req.block_ids.extend(new_b)+                        else:+                            req.finish_reason = "length"+                            self.runner.free_blocks_by_id(req.block_ids)+                            del self.running_requests[req_id]+                            if not req.stream:+                                req.decoded_text = self.tokenizer.decode(req.generated_tokens)+                            delta = TokenDelta(+                                token_id=req.generated_tokens[-1],+                                text_delta="",+                                finish_reason="length",+                                prompt_tokens=req.prompt_len,+                                completion_tokens=len(req.generated_tokens),+                                total_tokens=req.prompt_len + len(req.generated_tokens),+                                full_text=req.decoded_text+                            )+                            await req.output_queue.put(delta)+                            await req.output_queue.put(None)+                            continue+                    active_list.append(req)+                +                if active_list:+                    B = len(active_list)+                    batch_tokens = torch.tensor([r.generated_tokens[-1] for r in active_list], device=self.device, dtype=torch.long)+                    batch_pos = torch.tensor([r.cur_pos for r in active_list], device=self.device, dtype=torch.long)+                    +                    max_b = max(len(r.block_ids) for r in active_list)+                    b_tables = torch.zeros(B, max_b, dtype=torch.int32, device=self.device)+                    for b_idx, r in enumerate(active_list):+                        for j, blk in enumerate(r.block_ids):+                            b_tables[b_idx, j] = blk+                            +                    cur_blk_ids = torch.tensor([r.block_ids[r.cur_pos // self.runner.block_size] for r in active_list], device=self.device, dtype=torch.long)+                    offsets = torch.tensor([r.cur_pos % self.runner.block_size for r in active_list], device=self.device, dtype=torch.long)+                    seq_lens = [r.cur_pos + 1 for r in active_list]+                    +                    nxt_tokens = self.runner.decode_batch(batch_tokens, batch_pos, b_tables, seq_lens, cur_blk_ids, offsets)+                    +                    for b_idx, req in enumerate(active_list):+                        nxt_tok = nxt_tokens[b_idx]+                        req.generated_tokens.append(nxt_tok)+                        req.cur_pos += 1+                        +                        if req.stream:+                            full_text = self.tokenizer.decode(req.generated_tokens)+                            text_delta = full_text[len(req.decoded_text):]+                            req.decoded_text = full_text+                        else:+                            full_text = ""+                            text_delta = ""+                        +                        if len(req.generated_tokens) >= req.max_tokens:+                            req.finish_reason = "length"+                        elif nxt_tok == self.runner.eos_token_id and not req.ignore_eos:+                            req.finish_reason = "stop"+                        +                        if req.finish_reason is not None and not req.stream:+                            full_text = self.tokenizer.decode(req.generated_tokens)+                            req.decoded_text = full_text+                            +                        delta = TokenDelta(+                            token_id=nxt_tok,+                            text_delta=text_delta,+                            finish_reason=req.finish_reason,+                            prompt_tokens=req.prompt_len,+                            completion_tokens=len(req.generated_tokens),+                            total_tokens=req.prompt_len + len(req.generated_tokens),+                            full_text=full_text+                        )+                        await req.output_queue.put(delta)+                        +                        if req.finish_reason is not None:+                            self.runner.free_blocks_by_id(req.block_ids)+                            del self.running_requests[req.request_id]+                            await req.output_queue.put(None)+                    +                    has_work = True+            +            if not has_work:+                await asyncio.sleep(0.0005)+            else:+                await asyncio.sleep(0)diff --git a/solution/launch.sh b/solution/launch.shnew file mode 100755index 0000000000000000000000000000000000000000..aa57945cbd2dff08d8cdc563d6c80a3aac34cde0--- /dev/null+++ b/solution/launch.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail++export PYTHONPATH="${OPENBUILD_SOLUTION_DIR}:${PYTHONPATH:-}"+export PYTHONUNBUFFERED=1++# Execute the serving engine+exec python3 -m engine.maindiff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..fe3945cbb4238c98b57f1e302c9712f06b3cb206--- /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": "custom-npu-engine",+  "bootstrap": "bootstrap.sh",+  "launch": "launch.sh",+  "offline_replay": true+}