Kimi K3 · Serving

S13 · Serving build

Valid

OpenBuild Qwen3-8B serving 1dev · Open Build

1.03×PERFORMANCE RATIO
174TOOL 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 agentKimi K3 · 174 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
73Inspect
35Edit
2Build
6Validate
22Execute
11Profile
25Other

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 timeline116 groups · 174 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. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0001–#0001

    echo <val>ls -l -a <path>
  2. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0002–#0003

    Read <path>
  3. Inspect · Source & workspace

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

    6 calls · #0004–#0009

    find <path> -type <val>head -n <n>echo <flag>ls -l -a <path>Read <path>
  4. Inspect · Benchmark & validation setup

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

    3 calls · #0010–#0012

    Read <path>
  5. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    3 calls · #0013–#0015

    Read <path>
  6. Inspect · Benchmark & validation setup

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

    1 call · #0016–#0016

    Read <path>
  7. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0017–#0017

    Read <path>
  8. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0018–#0018

    Read <path>
  9. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0019–#0019

    which <val>python3 --versionpython3 -c <script> <n> >& <path>
  10. Inspect · Device memory

    Requested runtime inspection, file and log inspection and workspace inspection related to device memory.

    1 call · #0020–#0020

    npu-smi info <n> >& <path>head -n <n>echo <flag>ls <path> <n> > <path>envgrep -i -E <val>
  11. Inspect · Source & workspace

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

    1 call · #0021–#0021

    ls -l -a <path> <n> > <path>echo <flag>envgrep -E <val>ls <path>
  12. Build · Dependencies & build setup

    Requested dependency and build commands, source searches and file and log inspection related to dependencies & build setup.

    2 calls · #0022–#0023

    pip list <n> > <path>grep -v -i -E <val>head -n <n>tail -n <n>
  13. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0024–#0024

    cat <path> <n> > <path>echo <flag>cat <path>
  14. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0025–#0026

    Read <path>
  15. Inspect · Latency & request handling

    Requested source searches and file and log inspection related to latency & request handling.

    1 call · #0027–#0027

    grep -n <val> <path>head -n <n>
  16. Inspect · Source & workspace

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

    5 calls · #0028–#0032

    sed -n <val> <path>grep -n <val> <path>head -n <n>
  17. Inspect · Benchmark & validation setup

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

    1 call · #0033–#0033

    Read <path>
  18. Other · Attention kernels

    Requested script or workload execution and source searches related to attention kernels.

    2 calls · #0034–#0035

    python3 -c <script> <n> >& <path>grep -v <val>python3 - <script>
  19. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0036–#0036

    Update task list <tasks>
  20. Other · Precision & numerical checks

    Requested script or workload execution related to precision & numerical checks.

    1 call · #0037–#0037

    cd <path>python3 - <script>
  21. Inspect · Attention kernels

    Requested script or workload execution related to attention kernels.

    12 calls · #0038–#0049

    cd <path>python3 - <script>
  22. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0050–#0050

    cd <path><command> <args>df -h <path> <path> <n> > <path>head -n <n>
  23. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    2 calls · #0051–#0052

    cd <path>python3 - <script>
  24. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0053–#0053

    Update task list <tasks>
  25. Edit · Task requirements

    Requested code edits related to task requirements.

    1 call · #0054–#0054

    Write <path>
  26. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0055–#0055

    Write <path>
  27. Edit · Runtime processes

    Requested code edits related to runtime processes.

    9 calls · #0056–#0064

    Write <path>Edit <path>
  28. Execute · Runtime processes

    Requested workspace file updates and workspace inspection related to runtime processes.

    1 call · #0065–#0065

    cd <path>touch <path>chmod <val> <path> <path>ls -l -a <path> <path>
  29. Execute · Task requirements

    Requested workspace file updates and workspace inspection related to task requirements.

    1 call · #0066–#0066

    cd <path>chmod <n> <path> <path>chmod <n> <val> <path>ls -l -a
  30. Profile · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0067–#0067

    cd <path>python3 -B -u - <script>
  31. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0068–#0068

    Update task list <tasks>
  32. Validate · Benchmark & validation setup

    Requested environment setup or inspection, file and log inspection and script or workload execution related to benchmark & validation setup.

    2 calls · #0069–#0070

    cd <path>env <vars> bash <script> <n> >& <path>tail -n <n>bash <script> > <path> <n> >& <path>echo <val>
  33. Inspect · Source & workspace

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

    2 calls · #0071–#0072

    sleep <n>tail -c <n> <path> <n> > <path>echols <path> <n> > <path>tail -n <n> <path>echo <val>
    2 more command sketches
    cat <path>head -n <n>
  34. Other · Runtime processes

    Requested environment setup or inspection related to runtime processes.

    1 call · #0073–#0073

    cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val>
  35. Execute · Source & workspace

    Requested execution waits and service requests related to source & workspace.

    1 call · #0074–#0074

    <command> <args>sleep <n>curl -s <url> <val>
  36. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0075–#0075

    cd <path>python3 - <script>
  37. Inspect · Runtime processes

    Requested source searches related to runtime processes.

    1 call · #0076–#0076

    grep -n <val> <path>
  38. Edit · Runtime processes

    1 tool error

    Requested code edits related to runtime processes.

    1 call · #0077–#0077

    Edit <path>
  39. Execute · Runtime processes

    Requested file and log inspection, script or workload execution and source searches related to runtime processes.

    3 calls · #0078–#0080

    sed -n <val> <path><command> <args>head -n <n>cd <path>python3 - <script>grep -n <val> <path>
  40. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0081–#0081

    Read <path>
  41. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0082–#0082

    Edit <path>
  42. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0083–#0083

    Read <path>
  43. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0084–#0084

    Edit <path>
  44. Execute · Runtime processes

    Requested process termination, execution waits and environment setup or inspection related to runtime processes.

    1 call · #0085–#0085

    kill <n> <n> > <path>sleep <n>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val>curl -s <url>
    1 more command sketches
    echo
  45. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    2 calls · #0086–#0087

    cd <path>python3 - <script>
  46. Profile · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0088–#0088

    cd <path>python3 - <script>
  47. Inspect · Runtime processes

    Requested file and log inspection, runtime inspection and source searches related to runtime processes.

    1 call · #0089–#0089

    tail -n <n> <path>echo <val>ps <val>grep -E <val>grep -v <val>
  48. Execute · Device memory

    1 tool error

    Requested process termination, execution waits and runtime inspection related to device memory.

    1 call · #0090–#0090

    pkill -f <path>sleep <n>pkill <flag> <args>ps <val>grep <path>grep -v <val>
    2 more command sketches
    npu-smi infotail -n <n>
  49. Other · Device memory

    Requested execution waits, runtime inspection and source searches related to device memory.

    1 call · #0091–#0091

    sleep <n>ps <val>grep <path>grep -v <val>echo <flag>npu-smi info <n> > <path>
    1 more command sketches
    grep <flag> <args>
  50. Execute · Runtime processes

    Requested environment setup or inspection, execution waits and service requests related to runtime processes.

    1 call · #0092–#0092

    cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val>sleep <n>curl -s <url> <val>
  51. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0093–#0093

    cd <path>python3 - <script>
  52. Execute · Runtime processes

    Requested file and log inspection, process termination and execution waits related to runtime processes.

    1 call · #0094–#0094

    <command> <args>head <flag>echo <val>kill <flag> <args>sleep <n>ps <val>
    3 more command sketches
    grep <path>grep -v <val>python3 -c <script>
  53. Validate · Benchmark & validation setup

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

    1 call · #0095–#0095

    cd <path>bash <script> > <path> <n> >& <path>echo <val>
  54. Other · Source & workspace

    Requested script or workload execution, source searches and file and log inspection related to source & workspace.

    2 calls · #0096–#0097

    python3 -c <script> <n> >& <path>grep -v <val>Read task output <task>
  55. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0098–#0098

    tail -c <n> <path>
  56. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0099–#0099

    Edit <path>
  57. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0100–#0100

    cd <path>bash <script> > <path> <n> >& <path>echo <val>tail -c <n> <path>
  58. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0101–#0101

    Write <path>
  59. Other · Source & workspace

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

    2 calls · #0102–#0103

    Read task output <task>Wait for <task>
  60. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0104–#0104

    cd <path>bash <script> > <path> <n> >& <path>echo <val>tail -c <n> <path>
  61. Other · Source & workspace

    Requested execution waits related to source & workspace.

    1 call · #0105–#0105

    Wait for <task>
  62. Other · Runtime processes

    Requested environment setup or inspection related to runtime processes.

    1 call · #0106–#0106

    cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val>
  63. Execute · Source & workspace

    Requested execution waits, script or workload execution and file and log inspection related to source & workspace.

    1 call · #0107–#0107

    <command> <args>sleep <n>echo <val>cd <path>python3 <script> <n> <n> <n> <n> <n> >& <path>tail -n <n>
  64. Profile · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0108–#0108

    cd <path>python3 -B -u - <script>
  65. Execute · Device memory

    1 tool error

    Requested process termination, execution waits and runtime inspection related to device memory.

    1 call · #0109–#0109

    pkill -f <path>sleep <n>npu-smi info <n> > <path>grep -c <val>true
  66. Inspect · Device memory

    Requested runtime inspection, source searches and file and log inspection related to device memory.

    1 call · #0110–#0110

    ps <val>grep <path>grep -v <val>npu-smi info <n> > <path>grep -E <val>head -n <n>
  67. Profile · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0111–#0111

    cd <path>python3 -B -u - <script>
  68. Inspect · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0112–#0112

    cd <path>python3 -B -u - <script>
  69. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0113–#0113

    cd <path>python3 -B -u - <script>
  70. Inspect · Source & workspace

    Requested script or workload execution related to source & workspace.

    2 calls · #0114–#0115

    python3 - <script>
  71. Profile · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0116–#0116

    cd <path>python3 -B -u - <script>
  72. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0117–#0117

    cd <path>python3 -B -u - <script>
  73. Inspect · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0118–#0118

    cd <path>python3 -B -u - <script>
  74. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0119–#0119

    Read <path>
  75. Edit · Runtime processes

    Requested code edits related to runtime processes.

    2 calls · #0120–#0121

    Edit <path>
  76. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0122–#0122

    Read <path>
  77. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0123–#0123

    Edit <path>
  78. Execute · Data movement

    Requested file and log inspection related to data movement.

    1 call · #0124–#0124

    cat >> <path> <script>echo <val>
  79. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0125–#0125

    Read <path>
  80. Edit · Runtime processes

    1 tool error

    Requested code edits related to runtime processes.

    4 calls · #0126–#0129

    Edit <path>
  81. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0130–#0130

    Read <path>
  82. Edit · Runtime processes

    Requested code edits related to runtime processes.

    2 calls · #0131–#0132

    Edit <path>
  83. Profile · Runtime processes

    Requested script or workload execution related to runtime processes.

    2 calls · #0133–#0134

    cd <path>python3 -B -u - <script>
  84. Inspect · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0135–#0135

    cd <path>python3 - <script>
  85. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0136–#0136

    Read <path>
  86. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0137–#0137

    Edit <path>
  87. Profile · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0138–#0138

    cd <path>python3 -B -u - <script>
  88. Profile · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0139–#0139

    cd <path>python3 -B -u - <script>
  89. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0140–#0140

    Edit <path>
  90. Profile · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0141–#0141

    cd <path>python3 -B -u - <script>
  91. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0142–#0142

    cd <path>bash <script> > <path> <n> >& <path>echo <val>python3 -c <script> <n> > <path>tail -c <n> <path>
  92. Execute · Runtime processes

    Requested environment setup or inspection and execution waits related to runtime processes.

    1 call · #0143–#0143

    cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path><command> <args>sleep <n>echo <val>
  93. Inspect · Batching & scheduling

    Requested script or workload execution, source searches and file and log inspection related to batching & scheduling.

    1 call · #0144–#0144

    cd <path>echo <val>python3 <script> <n> <n> <n> <n> <n> >& <path>grep -v -E <val>tail -n <n>
  94. Other · Source & workspace

    Requested file and log inspection and script or workload execution related to source & workspace.

    1 call · #0145–#0145

    wc -l <path>python3 - <script>
  95. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0146–#0146

    Edit <path>
  96. Inspect · Source & workspace

    Requested script or workload execution, source searches and file and log inspection related to source & workspace.

    1 call · #0147–#0147

    cd <path>echo <val>python3 <script> <n> <n> <n> <n> <n> >& <path>grep -v -E <val>tail -n <n>
  97. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0148–#0148

    python3 - <script>
  98. Edit · Runtime processes

    1 tool error

    Requested code edits related to runtime processes.

    2 calls · #0149–#0150

    Edit <path>
  99. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0151–#0151

    Read <path>
  100. Edit · Runtime processes

    1 tool error

    Requested code edits related to runtime processes.

    1 call · #0152–#0152

    Edit <path>
  101. Execute · Runtime processes

    Requested script or workload execution related to runtime processes.

    2 calls · #0153–#0154

    cd <path>python3 - <script>python3 -c <script>
  102. Edit · Runtime processes

    1 tool error

    Requested code edits related to runtime processes.

    1 call · #0155–#0155

    Edit <path>
  103. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    2 calls · #0156–#0157

    Read <path>
  104. Edit · Runtime processes

    Requested code edits related to runtime processes.

    3 calls · #0158–#0160

    Edit <path>
  105. Profile · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0161–#0161

    cd <path>python3 -c <script>python3 - <script>
  106. Execute · Runtime processes

    1 tool error

    Requested process termination, execution waits and runtime inspection related to runtime processes.

    1 call · #0162–#0162

    pkill -f <path>sleep <n>ps <val>grep <path>grep -v <val>cd <path>
    3 more command sketches
    env <vars> nohup <val> <path> > <path> <n> >& <path><command> <args>echo <val>
  107. Execute · Source & workspace

    Requested execution waits, runtime inspection and source searches related to source & workspace.

    1 call · #0163–#0163

    sleep <n>ps <val>grep <path>grep -v <val>awk <val>curl -s -m <n> <url> > <path> <n> >& <path>
    1 more command sketches
    echo <val>
  108. Other · Runtime processes

    Requested environment setup or inspection related to runtime processes.

    1 call · #0164–#0164

    cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path><command> <args>echo <val>
  109. Execute · Source & workspace

    Requested execution waits, script or workload execution and source searches related to source & workspace.

    1 call · #0165–#0165

    <command> <args>sleep <n>echo <val>cd <path>python3 <script> <n> <n> <n> <n> <n> >& <path>grep -v -E <val>
    1 more command sketches
    tail -n <n>
  110. Inspect · Source & workspace

    Requested script or workload execution, source searches and file and log inspection related to source & workspace.

    1 call · #0166–#0166

    cd <path>python3 <script> <n> <n> <n> <n> <flag> <args>grep -v -E <val>tail -n <n>
  111. Execute · Runtime processes

    1 tool error

    Requested process termination, execution waits and runtime inspection related to runtime processes.

    1 call · #0167–#0167

    pkill -f <path>truesleep <n>ps <val>grep <path>grep -v <val>
    1 more command sketches
    wc -l
  112. Inspect · Source & workspace

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

    2 calls · #0168–#0169

    ps <val>grep <path>grep -v <val>wc -lUpdate task list <tasks>
  113. Execute · Benchmark & validation setup

    Requested script or workload execution, execution waits and workspace inspection related to benchmark & validation setup.

    2 calls · #0170–#0171

    cd <path>bash <script> > <path> <n> >& <path>echo <val>sleep <n>ls -l -a <path>grep -E <val>
    2 more command sketches
    tail -n <n>tail -n <n> <path> <n> > <path>
  114. Other · Batching & scheduling

    Requested script or workload execution related to batching & scheduling.

    1 call · #0172–#0172

    python3 - <script>
  115. Inspect · Source & workspace

    Requested execution waits, workspace inspection and source searches related to source & workspace.

    1 call · #0173–#0173

    sleep <n>ls <path>grep -E <val>tail -n <n> <path>
  116. Other · Batching & scheduling

    Requested script or workload execution related to batching & scheduling.

    1 call · #0174–#0174

    python3 - <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 · 8 changed files

Base commit: 8f62ee8f410c38ae7cd90305300afd08f0fdb098

diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..204a41223078f4bf59279c414ddf6fcab743127c--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,28 @@+#!/usr/bin/env bash+# Idempotent offline preparation for the custom torch_npu serving stack.+# Everything runs from the base runtime (Python, PyTorch, torch_npu,+# transformers, aiohttp, safetensors); no installation is performed, so the+# base Python environment surface stays untouched.+set -euo pipefail++export PYTHONDONTWRITEBYTECODE=1+export PIP_NO_INDEX=1+export HF_HUB_OFFLINE=1+export TRANSFORMERS_OFFLINE=1++python3 -B - <<'PY'+import importlib+import sys++required = ("torch", "torch_npu", "transformers", "safetensors", "aiohttp")+missing = []+for name in required:+    try:+        importlib.import_module(name)+    except Exception as exc:  # noqa: BLE001+        missing.append(f"{name}: {exc}")+if missing:+    sys.stderr.write("missing runtime dependencies:\n" + "\n".join(missing) + "\n")+    sys.exit(1)+print("bootstrap: all runtime dependencies available", flush=True)+PYdiff --git a/solution/launch.sh b/solution/launch.shnew file mode 100755index 0000000000000000000000000000000000000000..7a71f72f405ace9b72da2c8e4114e01fcaa90ba1--- /dev/null+++ b/solution/launch.sh@@ -0,0 +1,13 @@+#!/usr/bin/env bash+# Foreground launch of the Qwen3-8B OpenAI-compatible serving stack.+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++export PYTHONDONTWRITEBYTECODE=1+export TOKENIZERS_PARALLELISM=false+export HF_HUB_OFFLINE=1+export TRANSFORMERS_OFFLINE=1++# exec keeps the same PID/process group so SIGTERM reaches the server directly.+exec python3 -B -u "${HERE}/server/main.py"diff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..871e4289126af99fcfc58cb049b215bb40108276--- /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-custom-torch-npu",+  "bootstrap": "bootstrap.sh",+  "launch": "launch.sh",+  "offline_replay": true+}diff --git a/solution/server/__init__.py b/solution/server/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391diff --git a/solution/server/engine.py b/solution/server/engine.pynew file mode 100644index 0000000000000000000000000000000000000000..a5a86fb7fa443a98478dd5a6b31f31aa5916cef1--- /dev/null+++ b/solution/server/engine.py@@ -0,0 +1,353 @@+"""Continuous-batching inference engine thread for the Qwen3-8B NPU server."""++from __future__ import annotations++import queue+import threading+import time+from collections import deque++import torch+import torch_npu  # noqa: F401++from model import DecodeGraphCache, KVCachePool, Qwen3Forward, Qwen3Weights++EOS_IDS = frozenset((151645, 151643))++BLOCK_SIZE = 128+MAX_PROMPT = 2048+MAX_OUTPUT = 3072+MAX_TOTAL = 5120+MAX_BLOCKS_PER_SEQ = MAX_TOTAL // BLOCK_SIZE  # 40+PREFILL_TOKEN_BUDGET = 4096+MAX_SEQS = 80+RESERVE_MEM_BYTES = 6 * 1024**3+MAX_KV_BLOCKS = 1792+# (b_pad, l_pad) graph shapes captured eagerly at startup; others are lazy.+PRECAPTURE = (+    [(b, 640) for b in (1, 2, 4, 8, 12, 16, 24, 32, 48, 64)]+    + [(1, l) for l in (256, 384, 512)]+    + [(64, l) for l in (256, 384, 512)]+    + [(32, 768), (64, 768), (16, 2112), (32, 2112)]+)+++class Request:+    __slots__ = (+        "rid",+        "prompt_ids",+        "n_prompt",+        "max_tokens",+        "ignore_eos",+        "gen",+        "blocks",+        "kv_len",+        "created",+        "loop",+        "aqueue",+        "stream",+        "finish_reason",+        "aborted",+    )++    def __init__(self, rid, prompt_ids, max_tokens, ignore_eos, stream, loop, aqueue):+        self.rid = rid+        self.prompt_ids = prompt_ids+        self.n_prompt = len(prompt_ids)+        self.max_tokens = max_tokens+        self.ignore_eos = ignore_eos+        self.stream = stream+        self.gen: list[int] = []+        self.blocks: list[int] = []+        self.kv_len = 0+        self.created = time.monotonic()+        self.loop = loop+        self.aqueue = aqueue+        self.finish_reason = None+        self.aborted = False+++class Engine(threading.Thread):+    def __init__(self, model_path: str, served_model: str, log=print):+        super().__init__(daemon=True, name="engine")+        self.model_path = model_path+        self.served_model = served_model+        self.log = log+        self.inbound: queue.Queue = queue.Queue()+        self.waiting: deque[Request] = deque()+        self.running: list[Request] = []+        self.free_blocks: list[int] = []+        self.ready = threading.Event()+        self.start_error: BaseException | None = None++    # ------------------------------------------------------------ public API+    def submit(self, req: Request) -> None:+        self.inbound.put(("submit", req))++    def abort(self, rid: str) -> None:+        self.inbound.put(("abort", rid))++    # ------------------------------------------------------------- main loop+    def run(self) -> None:+        try:+            self._startup()+        except BaseException as exc:  # noqa: BLE001+            self.start_error = exc+            self.log(f"engine: startup failed: {exc!r}")+            self.ready.set()+            return+        self.ready.set()+        self._loop()++    def _startup(self) -> None:+        torch.npu.set_device(0)+        device = "npu:0"+        t0 = time.monotonic()+        self.weights = Qwen3Weights(self.model_path, device=device)+        self.log(f"engine: weights loaded in {time.monotonic()-t0:.1f}s")+        self.cos, self.sin = self.weights.build_rope(MAX_TOTAL + 256)+        free_b, _total_b = torch.npu.mem_get_info()+        block_bytes = BLOCK_SIZE * self.weights.kv_dim * 2 * 2 * self.weights.n_layers+        num_blocks = int((free_b - RESERVE_MEM_BYTES) // block_bytes)+        num_blocks = max(64, min(num_blocks, MAX_KV_BLOCKS))+        self.cache = KVCachePool(+            self.weights.n_layers, num_blocks, BLOCK_SIZE, self.weights.kv_dim, device+        )+        self.fwd = Qwen3Forward(self.weights, self.cache, MAX_PROMPT)+        self.fwd.attach_rope(self.cos, self.sin)+        dummy_block = num_blocks - 1+        self.free_blocks = list(range(num_blocks - 2, -1, -1))+        self.log(+            f"engine: kv cache {num_blocks} blocks x {BLOCK_SIZE} tokens "+            f"({num_blocks * BLOCK_SIZE} tokens), ready in {time.monotonic()-t0:.1f}s"+        )+        self.block_tables = torch.zeros(+            MAX_SEQS, MAX_BLOCKS_PER_SEQ, dtype=torch.int32, device=device+        )+        self._pin_in_ids = torch.empty(MAX_SEQS, dtype=torch.int64, pin_memory=True)+        self._pin_pos = torch.empty(MAX_SEQS, dtype=torch.int64, pin_memory=True)+        self._pin_slots = torch.empty(MAX_SEQS, dtype=torch.int64, pin_memory=True)+        self._pin_seql = torch.empty(MAX_SEQS, dtype=torch.int32, pin_memory=True)+        self._pin_out = torch.empty(MAX_SEQS, dtype=torch.int64, pin_memory=True)+        self._pin_pf_ids = torch.empty(PREFILL_TOKEN_BUDGET, dtype=torch.int64, pin_memory=True)+        self._pin_pf_pos = torch.empty(PREFILL_TOKEN_BUDGET, dtype=torch.int64, pin_memory=True)+        self._pin_pf_slots = torch.empty(PREFILL_TOKEN_BUDGET, dtype=torch.int64, pin_memory=True)+        self.graphs = DecodeGraphCache(self.fwd, MAX_BLOCKS_PER_SEQ, dummy_block)+        t1 = time.monotonic()+        self.graphs.precapture(PRECAPTURE)+        self.log(+            f"engine: {len(self.graphs.graphs)} decode graphs captured in "+            f"{time.monotonic()-t1:.1f}s (failed: {len(self.graphs.failed)})"+        )+        # Warm up the NPU context with a tiny decode-shaped step is skipped;+        # first real request pays the one-time op-compile cost.++    def _loop(self) -> None:+        pending = None  # (reqs, n, event)+        while True:+            if pending is not None:+                reqs, n, event = pending+                event.synchronize()+                toks = self._pin_out[:n].tolist()+                pending = None+                self._process_outputs(reqs, toks)+            try:+                while True:+                    self._handle_msg(*self.inbound.get_nowait())+            except queue.Empty:+                pass+            batch = self._schedule()+            if batch is None:+                msg = self.inbound.get()+                self._handle_msg(*msg)+                continue+            kind, reqs = batch+            if kind == "prefill":+                pending = (reqs, len(reqs), self._run_prefill(reqs))+            else:+                pending = (reqs, len(reqs), self._run_decode(reqs))++    # ------------------------------------------------------------- messaging+    def _handle_msg(self, kind: str, payload) -> None:+        if kind == "submit":+            self.waiting.append(payload)+            return+        rid = payload+        for item in list(self.waiting):+            if item.rid == rid:+                self.waiting.remove(item)+                break+        for idx, item in enumerate(self.running):+            if item.rid == rid:+                item.aborted = True+                self._remove_running(idx)+                break++    def _emit(self, req: Request, event: tuple) -> None:+        try:+            req.loop.call_soon_threadsafe(req.aqueue.put_nowait, event)+        except RuntimeError:+            req.aborted = True++    def _emit_batch(self, events: list) -> None:+        if not events:+            return+        loop = events[0][0].loop++        def distribute() -> None:+            for req, ev in events:+                try:+                    req.aqueue.put_nowait(ev)+                except Exception:  # noqa: BLE001+                    pass++        try:+            loop.call_soon_threadsafe(distribute)+        except RuntimeError:+            for req, _ev in events:+                req.aborted = True++    # ------------------------------------------------------------ scheduling+    def _schedule(self):+        if self.waiting and len(self.running) < MAX_SEQS:+            batch: list[Request] = []+            tokens = 0+            while self.waiting and len(self.running) + len(batch) < MAX_SEQS:+                req = self.waiting[0]+                need_blocks = -(-(req.n_prompt + req.max_tokens) // BLOCK_SIZE)+                if len(self.free_blocks) < need_blocks:+                    break+                if tokens and tokens + req.n_prompt > PREFILL_TOKEN_BUDGET:+                    break+                self.waiting.popleft()+                tokens += req.n_prompt+                batch.append(req)+            if batch:+                return ("prefill", batch)+        if self.running:+            return ("decode", list(self.running))+        return None++    # ----------------------------------------------------------------- steps+    def _run_prefill(self, reqs: list[Request]):+        ids_all: list[int] = []+        pos_all: list[int] = []+        slot_all: list[int] = []+        cu = [0]+        for req in reqs:+            need = -(-(req.n_prompt + req.max_tokens) // BLOCK_SIZE)+            for _ in range(need):+                req.blocks.append(self.free_blocks.pop())+            n = req.n_prompt+            ids_all.extend(req.prompt_ids)+            pos_all.extend(range(n))+            for j in range(n):+                slot_all.append(req.blocks[j // BLOCK_SIZE] * BLOCK_SIZE + j % BLOCK_SIZE)+            cu.append(cu[-1] + n)+            req.kv_len = n+            self.running.append(req)+            slot = len(self.running) - 1+            self.block_tables[slot, : len(req.blocks)] = torch.tensor(+                req.blocks, dtype=torch.int32+            )+        T = len(ids_all)+        self._pin_pf_ids[:T] = torch.tensor(ids_all, dtype=torch.int64)+        self._pin_pf_pos[:T] = torch.tensor(pos_all, dtype=torch.int64)+        self._pin_pf_slots[:T] = torch.tensor(slot_all, dtype=torch.int64)+        dev = self.cache.k[0].device+        ids = self._pin_pf_ids[:T].to(dev, non_blocking=True)+        pos = self._pin_pf_pos[:T].to(dev, non_blocking=True)+        slots = self._pin_pf_slots[:T].to(dev, non_blocking=True)+        with torch.inference_mode():+            logits = self.fwd.prefill(ids, pos, cu, slots, self.cos, self.sin)+            toks = torch.argmax(logits, dim=-1)+            self._pin_out[: len(reqs)].copy_(toks, non_blocking=True)+        ev = torch.npu.Event()+        ev.record()+        return ev++    def _run_decode(self, reqs: list[Request]):+        B = len(reqs)+        last_toks = [req.gen[-1] for req in reqs]+        positions: list[int] = []+        kv_lens: list[int] = []+        slots: list[int] = []+        for req in reqs:+            p = req.kv_len+            positions.append(p)+            kv_lens.append(p + 1)+            slots.append(req.blocks[p // BLOCK_SIZE] * BLOCK_SIZE + p % BLOCK_SIZE)+            req.kv_len = p + 1+        self._pin_in_ids[:B] = torch.tensor(last_toks, dtype=torch.int64)+        self._pin_pos[:B] = torch.tensor(positions, dtype=torch.int64)+        self._pin_slots[:B] = torch.tensor(slots, dtype=torch.int64)+        self._pin_seql[:B] = torch.tensor(kv_lens, dtype=torch.int32)+        max_kv = max(kv_lens)+        b_pad, l_pad = self.graphs.buckets(B, max_kv)+        entry = self.graphs.get(b_pad, l_pad)+        if entry is not None:+            with torch.inference_mode():+                toks = entry.run(+                    self._pin_in_ids[:B],+                    self._pin_pos[:B],+                    self._pin_slots[:B],+                    self.block_tables[:B],+                    self._pin_seql[:B],+                    B,+                )+                self._pin_out[:B].copy_(toks, non_blocking=True)+            ev = torch.npu.Event()+            ev.record()+            return ev+        dev = self.cache.k[0].device+        ids = self._pin_in_ids[:B].to(dev, non_blocking=True)+        pos = self._pin_pos[:B].to(dev, non_blocking=True)+        slot_t = self._pin_slots[:B].to(dev, non_blocking=True)+        block_tables = self.block_tables[:B]+        with torch.inference_mode():+            logits = self.fwd.decode(ids, pos, slot_t, block_tables, kv_lens, self.cos, self.sin)+            toks = torch.argmax(logits, dim=-1)+            self._pin_out[:B].copy_(toks, non_blocking=True)+        ev = torch.npu.Event()+        ev.record()+        return ev++    # ---------------------------------------------------------------- output+    def _process_outputs(self, reqs: list[Request], toks: list[int]) -> None:+        done: list[Request] = []+        events: list = []+        for req, tok in zip(reqs, toks):+            if req.aborted:+                done.append(req)+                continue+            req.gen.append(tok)+            finish = None+            if not req.ignore_eos and tok in EOS_IDS:+                finish = "stop"+            elif len(req.gen) >= req.max_tokens:+                finish = "length"+            if finish is not None:+                req.finish_reason = finish+                events.append((req, ("finish", finish, req.n_prompt, list(req.gen))))+                done.append(req)+            elif req.stream:+                events.append((req, ("token", tok)))+        if events:+            self._emit_batch(events)+        for req in done:+            try:+                idx = self.running.index(req)+            except ValueError:+                continue+            self._remove_running(idx)++    def _remove_running(self, idx: int) -> None:+        req = self.running[idx]+        self.free_blocks.extend(req.blocks)+        req.blocks = []+        last = len(self.running) - 1+        if idx != last:+            moved = self.running[last]+            self.running[idx] = moved+            self.block_tables[idx] = self.block_tables[last]+        self.running.pop()diff --git a/solution/server/http_api.py b/solution/server/http_api.pynew file mode 100644index 0000000000000000000000000000000000000000..060a7ac9f320ba4005876135cf84c5c7db704861--- /dev/null+++ b/solution/server/http_api.py@@ -0,0 +1,305 @@+"""OpenAI-compatible HTTP API layer (aiohttp) for the Qwen3-8B NPU server."""++from __future__ import annotations++import asyncio+import json+import time+import traceback+import uuid+from concurrent.futures import ThreadPoolExecutor++from aiohttp import web++from engine import MAX_OUTPUT, MAX_PROMPT, MAX_TOTAL, Request++CHUNK = "chat.completion.chunk"+COMPLETION = "chat.completion"+++def _build_byte_decoder() -> dict:+    # GPT-2/Qwen byte-level BPE byte<->unicode mapping.+    bs = (+        list(range(ord("!"), ord("~") + 1))+        + list(range(ord("¡"), ord("¬") + 1))+        + list(range(ord("®"), ord("ÿ") + 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(c): b for b, c in zip(bs, cs)}+++def build_token_byte_table(tokenizer) -> list[bytes]:+    """token id -> raw bytes (empty for special tokens), matching+    tokenizer.decode(ids, skip_special_tokens=True) when concatenated."""+    decoder_map = _build_byte_decoder()+    n = len(tokenizer)+    special = set(getattr(tokenizer, "all_special_ids", []) or [])+    table: list[bytes] = [b""] * n+    for tid in range(n):+        if tid in special:+            continue+        try:+            s = tokenizer.convert_ids_to_tokens(tid)+        except Exception:  # noqa: BLE001+            continue+        if not s:+            continue+        try:+            table[tid] = bytes(decoder_map[ch] for ch in s)+        except KeyError:+            table[tid] = s.encode("utf-8")+    return table+++def _err(message: str, status: int = 400, err_type: str = "invalid_request_error"):+    return web.json_response(+        {"error": {"message": message, "type": err_type, "code": None}}, status=status+    )+++class Detokenizer:+    """Incremental decode: O(1) per token via a precomputed id->bytes table+    and an incremental UTF-8 decoder (holds incomplete code points)."""++    def __init__(self, tokenizer, byte_table=None):+        import codecs++        self.tokenizer = tokenizer+        self.byte_table = byte_table+        self.ids: list[int] = []+        self._dec = codecs.getincrementaldecoder("utf-8")("replace")++    def push(self, token_id: int) -> str:+        self.ids.append(token_id)+        if self.byte_table is None or token_id >= len(self.byte_table):+            return self.tokenizer.decode(self.ids, skip_special_tokens=True)+        piece = self.byte_table[token_id]+        if not piece:+            return ""+        return self._dec.decode(piece)++    def flush(self) -> str:+        return self._dec.decode(b"", final=True)++    def decode_all(self) -> str:+        return self.tokenizer.decode(self.ids, skip_special_tokens=True)+++def _dump(obj) -> bytes:+    return json.dumps(obj, ensure_ascii=False, separators=(",", ":")).encode("utf-8")+++def _normalize_messages(raw):+    if not isinstance(raw, list) or not raw:+        raise ValueError("messages must be a non-empty list")+    messages = []+    for item in raw:+        if not isinstance(item, dict):+            raise ValueError("each message must be an object")+        role = item.get("role")+        if role not in ("system", "user", "assistant", "tool"):+            raise ValueError(f"unsupported role: {role!r}")+        content = item.get("content")+        if isinstance(content, list):+            parts = []+            for part in content:+                if isinstance(part, dict) and part.get("type") in ("text", "input_text"):+                    parts.append(str(part.get("text", "")))+                elif isinstance(part, str):+                    parts.append(part)+            content = "".join(parts)+        if not isinstance(content, str):+            raise ValueError("message content must be a string")+        messages.append({"role": role, "content": content})+    return messages+++def create_app(engine, tokenizer, served_model: str) -> web.Application:+    executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="tokenize")+    byte_table = build_token_byte_table(tokenizer)++    async def models(_request: web.Request) -> web.Response:+        return web.json_response(+            {+                "object": "list",+                "data": [+                    {+                        "id": served_model,+                        "object": "model",+                        "created": int(time.time()),+                        "owned_by": "openbuild",+                    }+                ],+            }+        )++    def tokenize(messages):+        ids = tokenizer.apply_chat_template(+            messages, tokenize=True, add_generation_prompt=True+        )+        if hasattr(ids, "keys"):+            ids = ids["input_ids"]+        ids = list(ids)+        if ids and isinstance(ids[0], (list, tuple)):+            ids = list(ids[0])+        return [int(x) for x in ids]++    async def chat(request: web.Request) -> web.StreamResponse:+        try:+            body = await request.json()+        except Exception:  # noqa: BLE001+            return _err("request body must be valid JSON")+        if not isinstance(body, dict):+            return _err("request body must be a JSON object")+        try:+            messages = _normalize_messages(body.get("messages"))+        except ValueError as exc:+            return _err(str(exc))++        max_tokens = body.get("max_tokens")+        if max_tokens is None:+            max_tokens = body.get("max_completion_tokens")+        if max_tokens is None:+            max_tokens = MAX_OUTPUT+        try:+            max_tokens = int(max_tokens)+        except (TypeError, ValueError):+            return _err("max_tokens must be an integer")+        if max_tokens < 1:+            return _err("max_tokens must be positive")++        stream = bool(body.get("stream", False))+        ignore_eos = bool(body.get("ignore_eos", False))++        loop = asyncio.get_running_loop()+        try:+            prompt_ids = await loop.run_in_executor(executor, tokenize, messages)+        except Exception as exc:  # noqa: BLE001+            return _err(f"failed to apply chat template: {exc}")+        n_prompt = len(prompt_ids)+        if n_prompt == 0:+            return _err("prompt is empty")+        if n_prompt > MAX_PROMPT:+            return _err(f"prompt too long: {n_prompt} tokens (max {MAX_PROMPT})")+        max_tokens = min(max_tokens, MAX_OUTPUT, MAX_TOTAL - n_prompt)+        if max_tokens < 1:+            return _err("no room left for generation")++        aqueue: asyncio.Queue = asyncio.Queue()+        rid = "chatcmpl-" + uuid.uuid4().hex[:24]+        created = int(time.time())+        req = Request(rid, prompt_ids, max_tokens, ignore_eos, stream, loop, aqueue)+        engine.submit(req)++        def usage(n_completion: int) -> dict:+            return {+                "prompt_tokens": n_prompt,+                "completion_tokens": n_completion,+                "total_tokens": n_prompt + n_completion,+            }++        if not stream:+            detok = Detokenizer(tokenizer, byte_table)+            try:+                while True:+                    ev = await aqueue.get()+                    if ev[0] == "finish":+                        _reason, n_completion, gen_ids = ev[1], len(ev[3]), ev[3]+                        detok.ids = gen_ids+                        content = detok.decode_all()+                        return web.json_response(+                            {+                                "id": rid,+                                "object": COMPLETION,+                                "created": created,+                                "model": served_model,+                                "choices": [+                                    {+                                        "index": 0,+                                        "message": {"role": "assistant", "content": content},+                                        "finish_reason": ev[1],+                                    }+                                ],+                                "usage": usage(n_completion),+                            }+                        )+                    # token events are not emitted for non-stream requests+            except (asyncio.CancelledError, ConnectionResetError, BrokenPipeError):+                engine.abort(rid)+                raise++        resp = web.StreamResponse(+            status=200,+            headers={+                "Content-Type": "text/event-stream; charset=utf-8",+                "Cache-Control": "no-cache",+                "Connection": "keep-alive",+            },+        )+        await resp.prepare(request)+        detok = Detokenizer(tokenizer, byte_table)++        def chunk(choices, usage_obj=None) -> bytes:+            payload = {+                "id": rid,+                "object": CHUNK,+                "created": created,+                "model": served_model,+                "choices": choices,+            }+            if usage_obj is not None:+                payload["usage"] = usage_obj+            return b"data: " + _dump(payload) + b"\n\n"++        try:+            first = True+            while True:+                ev = await aqueue.get()+                if ev[0] == "token":+                    piece = detok.push(ev[1])+                    if not piece and not first:+                        continue+                    delta = {"content": piece}+                    if first:+                        delta["role"] = "assistant"+                        first = False+                    await resp.write(+                        chunk([{"index": 0, "delta": delta, "finish_reason": None}])+                    )+                elif ev[0] == "finish":+                    reason = ev[1]+                    gen_ids = ev[3]+                    n_completion = len(gen_ids)+                    final_piece = detok.push(gen_ids[-1]) if gen_ids else ""+                    final_piece += detok.flush()+                    delta: dict = {}+                    if first:+                        delta["role"] = "assistant"+                        first = False+                    if final_piece:+                        delta["content"] = final_piece+                    await resp.write(+                        chunk([{"index": 0, "delta": delta, "finish_reason": reason}])+                    )+                    await resp.write(chunk([], usage(n_completion)))+                    await resp.write(b"data: [DONE]\n\n")+                    break+        except (ConnectionResetError, asyncio.CancelledError, BrokenPipeError):+            engine.abort(rid)+            raise+        except Exception:  # noqa: BLE001+            engine.abort(rid)+            traceback.print_exc()+            raise+        return resp++    app = web.Application()+    app.router.add_get("/v1/models", models)+    app.router.add_post("/v1/chat/completions", chat)+    return appdiff --git a/solution/server/main.py b/solution/server/main.pynew file mode 100644index 0000000000000000000000000000000000000000..c134ea802e9f86d2595b7814f9cc934d0e5b233a--- /dev/null+++ b/solution/server/main.py@@ -0,0 +1,68 @@+"""Service entrypoint: loads model + tokenizer, starts engine thread and HTTP."""++from __future__ import annotations++import asyncio+import os+import sys+import time++_HERE = os.path.dirname(os.path.abspath(__file__))+if _HERE not in sys.path:+    sys.path.insert(0, _HERE)+++def log(msg: str) -> None:+    print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)+++def main() -> int:+    host = os.environ.get("OPENBUILD_HOST", "127.0.0.1")+    port = int(os.environ.get("OPENBUILD_PORT", "8000"))+    model_path = os.environ["OPENBUILD_MODEL_PATH"]+    tokenizer_path = os.environ.get("OPENBUILD_TOKENIZER_PATH") or model_path+    served_model = os.environ.get("OPENBUILD_SERVED_MODEL", "Qwen/Qwen3-8B")++    t0 = time.monotonic()+    log(f"loading tokenizer from {tokenizer_path}")+    from transformers import AutoTokenizer++    tokenizer = AutoTokenizer.from_pretrained(+        tokenizer_path, trust_remote_code=False, local_files_only=True+    )++    import torch  # noqa: F401+    import torch_npu  # noqa: F401++    torch.npu.set_device(0)++    from engine import Engine+    from http_api import create_app++    engine = Engine(model_path, served_model, log=log)+    engine.start()+    engine.ready.wait()+    if engine.start_error is not None:+        log(f"engine startup failed: {engine.start_error!r}")+        return 1+    log(f"engine ready in {time.monotonic()-t0:.1f}s")++    from aiohttp import web++    app = create_app(engine, tokenizer, served_model)+    loop = asyncio.new_event_loop()+    asyncio.set_event_loop(loop)+    runner = web.AppRunner(app, access_log=None)+    loop.run_until_complete(runner.setup())+    site = web.TCPSite(runner, host, port, backlog=512, reuse_address=True)+    loop.run_until_complete(site.start())+    log(f"serving http://{host}:{port} model={served_model}")+    try:+        loop.run_forever()+    finally:+        loop.run_until_complete(runner.cleanup())+    return 0+++if __name__ == "__main__":+    sys.exit(main())diff --git a/solution/server/model.py b/solution/server/model.pynew file mode 100644index 0000000000000000000000000000000000000000..4eccd54534501ef16b9446c0c9229a8ec05c3d68--- /dev/null+++ b/solution/server/model.py@@ -0,0 +1,444 @@+"""Qwen3-8B model weights and NPU forward passes (prefill / paged decode).++Uses fused torch_npu operators:+  - npu_rms_norm                (fp32-accumulated RMSNorm)+  - npu_rotary_mul              (half-rotation RoPE)+  - npu_prompt_flash_attention  (varlen causal prefill attention, TND layout)+  - npu_incre_flash_attention   (paged-KV decode attention, BSH layout)+  - npu_swiglu                  (fused MLP activation)+"""++from __future__ import annotations++import json+import math+import os++import torch+import torch.nn.functional as F+import torch_npu  # noqa: F401  (registers the npu backend)++from safetensors import safe_open++EPS = 1e-6+++class Qwen3Weights:+    def __init__(self, model_path: str, device: str = "npu:0"):+        with open(os.path.join(model_path, "config.json"), encoding="utf-8") as fh:+            cfg = json.load(fh)+        self.cfg = cfg+        self.n_layers = int(cfg["num_hidden_layers"])+        self.hidden = int(cfg["hidden_size"])+        self.n_heads = int(cfg["num_attention_heads"])+        self.n_kv_heads = int(cfg["num_key_value_heads"])+        self.head_dim = int(cfg["head_dim"])+        self.intermediate = int(cfg["intermediate_size"])+        self.vocab = int(cfg["vocab_size"])+        self.rope_theta = float(cfg.get("rope_theta", 1000000.0))+        self.eps = float(cfg.get("rms_norm_eps", EPS))+        self.device = device++        index_path = os.path.join(model_path, "model.safetensors.index.json")+        with open(index_path, encoding="utf-8") as fh:+            index = json.load(fh)+        weight_map = index["weight_map"]++        readers: dict[str, safe_open] = {}++        def get(name: str) -> torch.Tensor:+            shard = weight_map[name]+            if shard not in readers:+                readers[shard] = safe_open(+                    os.path.join(model_path, shard), framework="pt", device="cpu"+                )+            return readers[shard].get_tensor(name)++        def to_dev(t: torch.Tensor) -> torch.Tensor:+            return t.to(device, non_blocking=True)++        qkv_dim = (self.n_heads + 2 * self.n_kv_heads) * self.head_dim+        gateup_dim = 2 * self.intermediate++        self.embed = to_dev(get("model.embed_tokens.weight"))+        self.final_norm = to_dev(get("model.norm.weight"))+        self.lm_head = to_dev(get("lm_head.weight"))++        self.wqkv: list[torch.Tensor] = []+        self.wo: list[torch.Tensor] = []+        self.q_norm: list[torch.Tensor] = []+        self.k_norm: list[torch.Tensor] = []+        self.wgateup: list[torch.Tensor] = []+        self.wdown: list[torch.Tensor] = []+        self.ln1: list[torch.Tensor] = []+        self.ln2: list[torch.Tensor] = []+        for i in range(self.n_layers):+            p = f"model.layers.{i}."+            wq = get(p + "self_attn.q_proj.weight")+            wk = get(p + "self_attn.k_proj.weight")+            wv = get(p + "self_attn.v_proj.weight")+            wqkv = torch.cat([wq, wk, wv], dim=0)+            assert wqkv.shape == (qkv_dim, self.hidden)+            self.wqkv.append(to_dev(wqkv.contiguous()))+            del wq, wk, wv, wqkv+            self.wo.append(to_dev(get(p + "self_attn.o_proj.weight")))+            self.q_norm.append(to_dev(get(p + "self_attn.q_norm.weight")))+            self.k_norm.append(to_dev(get(p + "self_attn.k_norm.weight")))+            wg = get(p + "mlp.gate_proj.weight")+            wu = get(p + "mlp.up_proj.weight")+            wgu = torch.cat([wg, wu], dim=0)+            assert wgu.shape == (gateup_dim, self.hidden)+            self.wgateup.append(to_dev(wgu.contiguous()))+            del wg, wu, wgu+            self.wdown.append(to_dev(get(p + "mlp.down_proj.weight")))+            self.ln1.append(to_dev(get(p + "input_layernorm.weight")))+            self.ln2.append(to_dev(get(p + "post_attention_layernorm.weight")))+        torch.npu.synchronize()++        self.scale = 1.0 / math.sqrt(self.head_dim)+        self.q_dim = self.n_heads * self.head_dim+        self.kv_dim = self.n_kv_heads * self.head_dim++    def build_rope(self, max_pos: int) -> tuple[torch.Tensor, torch.Tensor]:+        inv_freq = 1.0 / (+            self.rope_theta+            ** (torch.arange(0, self.head_dim, 2, dtype=torch.float32) / self.head_dim)+        )+        pos = torch.arange(max_pos, dtype=torch.float32)+        freqs = torch.outer(pos, inv_freq)  # [max_pos, head_dim/2]+        emb = torch.cat([freqs, freqs], dim=-1)  # [max_pos, head_dim]+        cos = emb.cos().to(torch.bfloat16).to(self.device)+        sin = emb.sin().to(torch.bfloat16).to(self.device)+        return cos, sin+++class KVCachePool:+    """Paged KV cache: per layer K/V tensors of [num_blocks, block_size, kv_dim]."""++    def __init__(+        self,+        n_layers: int,+        num_blocks: int,+        block_size: int,+        kv_dim: int,+        device: str,+    ):+        self.n_layers = n_layers+        self.num_blocks = num_blocks+        self.block_size = block_size+        self.kv_dim = kv_dim+        self.k: list[torch.Tensor] = []+        self.v: list[torch.Tensor] = []+        for _ in range(n_layers):+            self.k.append(+                torch.empty(num_blocks, block_size, kv_dim, dtype=torch.bfloat16, device=device)+            )+            self.v.append(+                torch.empty(num_blocks, block_size, kv_dim, dtype=torch.bfloat16, device=device)+            )+++class Qwen3Forward:+    def __init__(self, weights: Qwen3Weights, cache: KVCachePool, max_prompt: int):+        self.w = weights+        self.cache = cache+        self.device = weights.device+        self.n_layers = weights.n_layers+        self.n_heads = weights.n_heads+        self.n_kv = weights.n_kv_heads+        self.head_dim = weights.head_dim+        self.q_dim = weights.q_dim+        self.kv_dim = weights.kv_dim+        self.eps = weights.eps+        self.scale = weights.scale+        # causal mask for prefill (True = masked out), fixed shape required by PFA+        self.causal_mask = torch.triu(+            torch.ones(max_prompt, max_prompt, dtype=torch.bool, device=self.device), 1+        )+        self._cos: torch.Tensor | None = None+        self._sin: torch.Tensor | None = None++    def attach_rope(self, cos: torch.Tensor, sin: torch.Tensor) -> None:+        self._cos = cos+        self._sin = sin++    # ---------------------------------------------------------------- prefill+    def prefill(+        self,+        input_ids: torch.Tensor,      # [T] int64 on device+        positions: torch.Tensor,      # [T] int64 on device+        cu_seqlens: list[int],        # cumulative sequence lengths, len B+1+        slot_mapping: torch.Tensor,   # [T] int64 on device+        cos: torch.Tensor,            # [max_pos, D]+        sin: torch.Tensor,+    ) -> torch.Tensor:+        """Returns hidden states of the last position of each sequence: [B, hidden]."""+        w = self.w+        T = input_ids.shape[0]+        cos_t = cos.index_select(0, positions).unsqueeze(1)  # [T,1,D]+        sin_t = sin.index_select(0, positions).unsqueeze(1)+        h = F.embedding(input_ids, w.embed)+        for i in range(self.n_layers):+            norm, _ = torch_npu.npu_rms_norm(h, w.ln1[i], epsilon=self.eps)+            qkv = F.linear(norm, w.wqkv[i])  # [T, qkv_dim]+            q = qkv[:, : self.q_dim].view(T, self.n_heads, self.head_dim)+            k = qkv[:, self.q_dim : self.q_dim + self.kv_dim].view(T, self.n_kv, self.head_dim)+            v = qkv[:, self.q_dim + self.kv_dim :].view(T, self.n_kv, self.head_dim)+            q, _ = torch_npu.npu_rms_norm(q, w.q_norm[i], epsilon=self.eps)+            k, _ = torch_npu.npu_rms_norm(k, w.k_norm[i], epsilon=self.eps)+            q = torch_npu.npu_rotary_mul(q, cos_t, sin_t, rotary_mode="half")+            k = torch_npu.npu_rotary_mul(k, cos_t, sin_t, rotary_mode="half")+            self.cache.k[i].view(-1, self.kv_dim).index_copy_(0, slot_mapping, k.view(T, self.kv_dim))+            self.cache.v[i].view(-1, self.kv_dim).index_copy_(0, slot_mapping, v.view(T, self.kv_dim))+            a = torch_npu.npu_prompt_flash_attention(+                q,+                k,+                v,+                atten_mask=self.causal_mask,+                num_heads=self.n_heads,+                scale_value=self.scale,+                input_layout="TND",+                num_key_value_heads=self.n_kv,+                actual_seq_lengths=cu_seqlens,+                actual_seq_lengths_kv=cu_seqlens,+                sparse_mode=3,+            )  # [T, n_heads, head_dim]+            h = h + F.linear(a.view(T, self.q_dim), w.wo[i])+            norm2, _ = torch_npu.npu_rms_norm(h, w.ln2[i], epsilon=self.eps)+            gu = F.linear(norm2, w.wgateup[i])+            act = torch_npu.npu_swiglu(gu, dim=-1)+            h = h + F.linear(act, w.wdown[i])+        last_rows = [c - 1 for c in cu_seqlens[1:]]+        h_last = h[last_rows]+        hn, _ = torch_npu.npu_rms_norm(h_last, w.final_norm, epsilon=self.eps)+        return F.linear(hn, w.lm_head)  # [B, vocab]++    # ----------------------------------------------------------------- decode+    def decode(+        self,+        input_ids: torch.Tensor,      # [B] int64 on device+        positions: torch.Tensor,      # [B] int64 on device+        slot_mapping: torch.Tensor,   # [B] int64 on device+        block_tables: torch.Tensor,   # [B, max_blocks] int32 on device+        kv_lens: list[int],           # new kv length per sequence (incl. current token)+        cos: torch.Tensor,+        sin: torch.Tensor,+    ) -> torch.Tensor:+        """Returns logits [B, vocab]."""+        w = self.w+        B = input_ids.shape[0]+        cos_t = cos.index_select(0, positions).unsqueeze(1)  # [B,1,D]+        sin_t = sin.index_select(0, positions).unsqueeze(1)+        h = F.embedding(input_ids, w.embed)  # [B, hidden]+        for i in range(self.n_layers):+            norm, _ = torch_npu.npu_rms_norm(h, w.ln1[i], epsilon=self.eps)+            qkv = F.linear(norm, w.wqkv[i])  # [B, qkv_dim]+            q = qkv[:, : self.q_dim].view(B, self.n_heads, self.head_dim)+            k = qkv[:, self.q_dim : self.q_dim + self.kv_dim].view(B, self.n_kv, self.head_dim)+            v = qkv[:, self.q_dim + self.kv_dim :].view(B, self.n_kv, self.head_dim)+            q, _ = torch_npu.npu_rms_norm(q, w.q_norm[i], epsilon=self.eps)+            k, _ = torch_npu.npu_rms_norm(k, w.k_norm[i], epsilon=self.eps)+            q = torch_npu.npu_rotary_mul(q, cos_t, sin_t, rotary_mode="half")+            k = torch_npu.npu_rotary_mul(k, cos_t, sin_t, rotary_mode="half")+            self.cache.k[i].view(-1, self.kv_dim).index_copy_(0, slot_mapping, k.view(B, self.kv_dim))+            self.cache.v[i].view(-1, self.kv_dim).index_copy_(0, slot_mapping, v.view(B, self.kv_dim))+            a = torch_npu.npu_incre_flash_attention(+                q.view(B, 1, self.q_dim),+                self.cache.k[i],+                self.cache.v[i],+                actual_seq_lengths=kv_lens,+                block_table=block_tables,+                num_heads=self.n_heads,+                scale_value=self.scale,+                input_layout="BSH",+                num_key_value_heads=self.n_kv,+                block_size=self.cache.block_size,+            )  # [B, 1, q_dim]+            h = h + F.linear(a.view(B, self.q_dim), w.wo[i])+            norm2, _ = torch_npu.npu_rms_norm(h, w.ln2[i], epsilon=self.eps)+            gu = F.linear(norm2, w.wgateup[i])+            act = torch_npu.npu_swiglu(gu, dim=-1)+            h = h + F.linear(act, w.wdown[i])+        hn, _ = torch_npu.npu_rms_norm(h, w.final_norm, epsilon=self.eps)+        return F.linear(hn, w.lm_head)  # [B, vocab]++    # ------------------------------------------------ decode (graph-capturable)+    def decode_graphable(+        self,+        input_ids: torch.Tensor,      # [B] int64 static buffer+        positions: torch.Tensor,      # [B] int64 static buffer+        slot_mapping: torch.Tensor,   # [B] int64 static buffer+        block_tables: torch.Tensor,   # [B, MB] int32 static buffer+        seq_lens: torch.Tensor,       # [B] int32 static buffer (new kv len incl. current)+        l_pad: int,                   # padded kv length (multiple of block_size)+    ) -> torch.Tensor:+        """Full decode step with padded IFA paged attention; returns tokens [B].++        Every input is a device tensor, so the whole step can be captured in an+        NPUGraph and replayed with new buffer contents. The sequence length seen+        by the kernel is baked to l_pad; a device-side mask hides the padding,+        which keeps numerics identical to the exact-length eager path.+        """+        w = self.w+        B = input_ids.shape[0]+        dev = input_ids.device+        s_max = block_tables.shape[1] * self.cache.block_size+        offs_len = torch.arange(s_max, device=dev)+        cos_t = self._cos.index_select(0, positions).unsqueeze(1)  # [B,1,D]+        sin_t = self._sin.index_select(0, positions).unsqueeze(1)+        attn_mask = (offs_len.view(1, -1) >= seq_lens.view(-1, 1)).view(B, 1, 1, s_max)+        kv_lens = [l_pad] * B+        h = F.embedding(input_ids, w.embed)  # [B, hidden]+        kv_flat = self.kv_dim+        for i in range(self.n_layers):+            norm, _ = torch_npu.npu_rms_norm(h, w.ln1[i], epsilon=self.eps)+            qkv = F.linear(norm, w.wqkv[i])  # [B, qkv_dim]+            q = qkv[:, : self.q_dim].view(B, self.n_heads, self.head_dim)+            k = qkv[:, self.q_dim : self.q_dim + self.kv_dim].view(B, self.n_kv, self.head_dim)+            v = qkv[:, self.q_dim + self.kv_dim :].view(B, self.n_kv, self.head_dim)+            q, _ = torch_npu.npu_rms_norm(q, w.q_norm[i], epsilon=self.eps)+            k, _ = torch_npu.npu_rms_norm(k, w.k_norm[i], epsilon=self.eps)+            q = torch_npu.npu_rotary_mul(q, cos_t, sin_t, rotary_mode="half")+            k = torch_npu.npu_rotary_mul(k, cos_t, sin_t, rotary_mode="half")+            self.cache.k[i].view(-1, kv_flat).index_copy_(0, slot_mapping, k.view(B, kv_flat))+            self.cache.v[i].view(-1, kv_flat).index_copy_(0, slot_mapping, v.view(B, kv_flat))+            a = torch_npu.npu_incre_flash_attention(+                q.view(B, 1, self.q_dim),+                self.cache.k[i],+                self.cache.v[i],+                atten_mask=attn_mask,+                actual_seq_lengths=kv_lens,+                block_table=block_tables,+                num_heads=self.n_heads,+                scale_value=self.scale,+                input_layout="BSH",+                num_key_value_heads=self.n_kv,+                block_size=self.cache.block_size,+            )  # [B, 1, q_dim]+            h = h + F.linear(a.view(B, self.q_dim), w.wo[i])+            norm2, _ = torch_npu.npu_rms_norm(h, w.ln2[i], epsilon=self.eps)+            gu = F.linear(norm2, w.wgateup[i])+            act = torch_npu.npu_swiglu(gu, dim=-1)+            h = h + F.linear(act, w.wdown[i])+        hn, _ = torch_npu.npu_rms_norm(h, w.final_norm, epsilon=self.eps)+        logits = F.linear(hn, w.lm_head)  # [B, vocab]+        return torch.argmax(logits, dim=-1)+++B_BUCKETS = (1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 80)+++class GraphedDecode:+    """One captured NPUGraph decode step for a fixed (b_pad, l_pad) shape."""++    def __init__(self, fwd: Qwen3Forward, b_pad: int, l_pad: int, dummy_block: int):+        self.fwd = fwd+        self.b_pad = b_pad+        self.l_pad = l_pad+        dev = fwd.device+        mb = fwd.cache.k[0].shape[0]  # not used; keep signature simple+        self.block_size = fwd.cache.block_size+        max_blocks = 0+        self.s_ids = torch.zeros(b_pad, dtype=torch.int64, device=dev)+        self.s_pos = torch.zeros(b_pad, dtype=torch.int64, device=dev)+        self.s_slots = torch.zeros(b_pad, dtype=torch.int64, device=dev)+        self.s_seql = torch.ones(b_pad, dtype=torch.int32, device=dev)+        # dummy rows: all point at the reserved dummy block, distinct slots+        dummy_slots = dummy_block * self.block_size + (+            torch.arange(b_pad, dtype=torch.int64) % self.block_size+        )+        # static block table width is set on first run+        self.s_bt = None+        self._dummy_slots = dummy_slots.to(dev)+        self._dummy_block = dummy_block+        self.graph = None+        self.s_out = None+        self._max_blocks = None++    def capture(self, max_blocks: int) -> None:+        fwd = self.fwd+        dev = fwd.device+        self._max_blocks = max_blocks+        bt = torch.full(+            (self.b_pad, max_blocks), self._dummy_block, dtype=torch.int32, device=dev+        )+        self.s_bt = bt+        # warmups run with pure-dummy contents so no live cache slot is touched+        self.s_ids.zero_()+        self.s_pos.zero_()+        self.s_slots.copy_(self._dummy_slots)+        self.s_seql.fill_(1)+        torch.npu.synchronize()+        with torch.inference_mode():+            stream = torch.npu.Stream()+            with torch.npu.stream(stream):+                for _ in range(2):+                    fwd.decode_graphable(+                        self.s_ids, self.s_pos, self.s_slots, self.s_bt, self.s_seql, self.l_pad+                    )+            torch.npu.synchronize()+            graph = torch.npu.NPUGraph()+            with torch.npu.graph(graph):+                self.s_out = fwd.decode_graphable(+                    self.s_ids, self.s_pos, self.s_slots, self.s_bt, self.s_seql, self.l_pad+                )+        self.graph = graph++    def run(self, ids, pos, slots, bt_dev, seql, n: int) -> torch.Tensor:+        """Fill static buffers and replay. bt_dev: device int32 [n, max_blocks]."""+        self.s_ids[:n].copy_(ids, non_blocking=True)+        self.s_pos[:n].copy_(pos, non_blocking=True)+        self.s_slots[:n].copy_(slots, non_blocking=True)+        self.s_seql[:n].copy_(seql, non_blocking=True)+        self.s_bt[:n].copy_(bt_dev, non_blocking=True)+        self.graph.replay()+        return self.s_out[:n]+++class DecodeGraphCache:+    def __init__(self, fwd: Qwen3Forward, max_blocks: int, dummy_block: int, max_graphs: int = 28):+        self.fwd = fwd+        self.max_blocks = max_blocks+        self.dummy_block = dummy_block+        self.max_graphs = max_graphs+        self.graphs: dict[tuple[int, int], GraphedDecode] = {}+        self.failed: set[tuple[int, int]] = set()+        self.lru: list[tuple[int, int]] = []+        self.block_size = fwd.cache.block_size++    def buckets(self, b: int, max_kv: int) -> tuple[int, int]:+        b_pad = B_BUCKETS[-1]+        for cand in B_BUCKETS:+            if cand >= b:+                b_pad = cand+                break+        l_pad = -(-max_kv // self.block_size) * self.block_size+        return b_pad, l_pad++    def get(self, b_pad: int, l_pad: int) -> GraphedDecode | None:+        key = (b_pad, l_pad)+        entry = self.graphs.get(key)+        if entry is not None:+            if key in self.lru:+                self.lru.remove(key)+            self.lru.append(key)+            return entry+        if key in self.failed or len(self.graphs) >= self.max_graphs:+            return None+        free_b, _ = torch.npu.mem_get_info()+        if free_b < 2 * 1024**3:+            return None+        entry = GraphedDecode(self.fwd, b_pad, l_pad, self.dummy_block)+        try:+            entry.capture(self.max_blocks)+        except Exception:+            self.failed.add(key)+            torch.npu.empty_cache()+            return None+        self.graphs[key] = entry+        self.lru.append(key)+        return entry++    def precapture(self, keys) -> None:+        for b_pad, l_pad in keys:+            self.get(b_pad, l_pad)