Claude Fable 5.1 · Serving

S13 · Serving build

Valid

OpenBuild Qwen3-8B serving 1dev · Open Build

1.00×PERFORMANCE RATIO
94TOOL 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 agentClaude Fable 5.1 · 94 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
32Inspect
2Build
12Validate
21Execute
7Profile
20Other

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 timeline81 groups · 94 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> <n> > <path>echo <flag>ls -l -a <path>
  2. Inspect · Task requirements

    Requested environment setup or inspection, workspace inspection and file and log inspection related to task requirements.

    1 call · #0002–#0002

    env <vars>ls -l -a <val>echo <val>cat <path>
  3. Inspect · Source & workspace

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

    2 calls · #0003–#0004

    cd <path>echo <val>cat <val>echoecho <path>ls -l -a <path>
    4 more command sketches
    find <path> -path <path> <flag> <args>head -n <n>env <vars>cat <path>
  4. Validate · Benchmark & validation setup

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

    2 calls · #0005–#0006

    env <vars><command> <args>cat <path>echo
  5. Execute · Benchmark & validation setup

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

    1 call · #0007–#0007

    env <vars><command> <args>cat <path>echo
  6. Execute · Task requirements

    Requested environment setup or inspection, file and log inspection and workspace inspection related to task requirements.

    1 call · #0008–#0008

    env <vars>echo <val>cat <path>echols -l -a <path> <path> <path> <path>
  7. Inspect · Device memory

    Requested script or workload execution, runtime inspection and file and log inspection related to device memory.

    1 call · #0009–#0009

    echo <val>uname -awhich -a <val> <val>python3 -Vecho <path><command> <args>
    10 more command sketches
    free -ghead -n <n>df -h <path> <path> <path> <n> > <path>headpython3 -c <script> <n> >& <path>tail -n <n>envgrep -i -E <val>sorthead <flag>
  8. Inspect · Dependencies & build setup

    Requested workspace inspection, file and log inspection and script or workload execution related to dependencies & build setup.

    1 call · #0010–#0010

    echo <val>find <path> -maxdepth <n> -iname <val> <flag> <args>head -n <n>python3 -m <module> <val> <n> > <path>echo <path>ls <path> <n> > <path>
    1 more command sketches
    head
  9. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    4 calls · #0011–#0014

    cd <path>wc -l <path>sed -n <val> <path>
  10. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0015–#0015

    cd <path>echo <val>cat <val>echoecho <path>cat <path>
  11. Inspect · Source & workspace

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

    2 calls · #0016–#0017

    cd <path>cat <path>env <vars>ls -l -a <val>echo <val>cat <path> <n> > <path>
    6 more command sketches
    head -c <n> <path>echohead -c <n> <path> <n> > <path><command> <args>grep -E <path>head
  12. Inspect · Dependencies & build setup

    Requested script or workload execution and file and log inspection related to dependencies & build setup.

    1 call · #0018–#0018

    python3 -m <module> <val> <n> > <path>sed -n <val>echo <val>python3 - <script>
  13. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0019–#0019

    python3 - <script>
  14. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0020–#0020

    cd <path>python3 - <script>
  15. Validate · Device memory

    Requested script or workload execution related to device memory.

    1 call · #0021–#0021

    cd <path>timeout <n> <val> <val> <script>
  16. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0022–#0022

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

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

    4 calls · #0023–#0026

    <command> <args>tail <flag>echo <val>ls <val>head -n <n>grep -i -E <val>
    8 more command sketches
    find <val> -maxdepth <n> -iname <val>headpython3 -c <script> <n> >& <path>grep -v <val>env <vars>wc -l <path>grep -n <val> <path>sed -n <path> <path>
  18. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0027–#0027

    cd <path>python3 - <script>
  19. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0028–#0028

    cd <path>timeout <n> <val> <val> <script>
  20. Execute · Benchmark & validation setup

    Requested environment setup or inspection, file and log inspection and source searches related to benchmark & validation setup.

    1 call · #0029–#0029

    env <vars>echo <val>cat <path>echo <path>grep -n <path> <path>head -n <n>
  21. Inspect · Source & workspace

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

    1 call · #0030–#0030

    date -uecho <val>tail -n <n> <path> <n> > <path>grep -v <val>
  22. Execute · Benchmark & validation setup

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

    1 call · #0031–#0031

    env <vars>sed -n <val> <path>
  23. Execute · Task requirements

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

    1 call · #0032–#0032

    cd <path>mkdir -p <val>cat > <path> <script>chmod <val> <path> <path>touch <path>ls -l -a
    1 more command sketches
    echo <val>
  24. Validate · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0033–#0033

    cd <path>timeout <n> <val> <val> <script>
  25. Inspect · Source & workspace

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

    1 call · #0034–#0034

    env <vars>echo <val><command> <args>tail -n <n>cd <path>timeout <n> <val> <val> <script>
  26. Inspect · Attention kernels

    Requested file and log inspection, environment setup or inspection and source searches related to attention kernels.

    1 call · #0035–#0035

    <command> <args>tail <flag>env <vars>echo <val>sed -n <val> <val>echo <path>
    2 more command sketches
    grep -n <val> <path> <path> <n> > <path>head -n <n>
  27. Inspect · Source & workspace

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

    1 call · #0036–#0036

    env <vars>echo <val>sed -n <val> <path>grep -n <val> <path>head -n <n>sed -n <path> <path>
  28. Other · Source & workspace

    Requested environment setup or inspection, workspace file updates and execution waits related to source & workspace.

    1 call · #0037–#0037

    <command> <args>env <vars>mkdir -p <val>echo <val>waitcut <flag>
    3 more command sketches
    echo <path>cd <path>python3 - <script>
  29. Execute · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0038–#0038

    cd <path>timeout <n> <val> <val> <script>
  30. Inspect · Checkpoints & weight state

    Requested file and log inspection and script or workload execution related to checkpoints & weight state.

    1 call · #0039–#0039

    cat > <path> <script>python3 -c <script>
  31. Inspect · Attention kernels

    Requested file and log inspection and script or workload execution related to attention kernels.

    1 call · #0040–#0040

    cat > <path> <script>python3 -c <script>
  32. Execute · Runtime processes

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

    1 call · #0041–#0041

    cat > <path> <script>python3 -c <script>
  33. Execute · Benchmark & validation setup

    Requested environment setup or inspection, source searches and file and log inspection related to benchmark & validation setup.

    1 call · #0042–#0042

    env <vars>echo <path>grep -v <val> <path> <n> > <path>tail -n <n>echoecho <val>
  34. Build · Data movement

    Requested script or workload execution and source searches related to data movement.

    1 call · #0043–#0043

    cd <path>python3 - <script>python3 -c <script>grep -n <val> <path> <path>
  35. Inspect · Device memory

    Requested script or workload execution, runtime inspection and file and log inspection related to device memory.

    1 call · #0044–#0044

    date -upython3 - <script>echo <val>npu-smi infosed -n <val>pgrep <flag> <args>
  36. Profile · Latency & request handling

    Requested workspace file updates and file and log inspection related to latency & request handling.

    1 call · #0045–#0045

    mkdir -p <path>cat > <path> <script>echo <val>
  37. Execute · Runtime processes

    Requested workspace file updates, environment setup or inspection and script or workload execution related to runtime processes.

    1 call · #0046–#0046

    mkdir -p <path> <path>cd <path>export <vars>echo <val><script> <args>grep -v <val>
    4 more command sketches
    tail -n <n><command> <args>sleep <n>grep -v <val> <path>
  38. Execute · Device memory

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

    1 call · #0047–#0047

    <command> <args>sleep <n>echo <val>grep -v <val> <path>tail -n <n>echo <path>
    4 more command sketches
    curl -s -m <n> <url>echonpu-smi infosed -n <val>
  39. Other · Source & workspace

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

    1 call · #0048–#0048

    python3 - <script>du <flag> <args>awk <path>
  40. Execute · Runtime processes

    1 tool error

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

    3 calls · #0049–#0051

    echo <val>grep -a <val> <path>grep <flag> <args>head -n <n>python3 -c <script>cd <path>
    12 more command sketches
    python3 - <script>pkill -f <val> <n> > <path>sleep <n>rm -f <path>export <vars><command> <args>tail -n <n>curl -s -m <n> <url> <val>cat > <path> <script>chmod <val> <path>date -ubash <script> <val>
  41. Validate · Benchmark & validation setup

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

    1 call · #0052–#0052

    cd <path>timeout <n> <val> <path> <n> <n> >& <path>grep -v <val>echo <val>
  42. Execute · Device memory

    Requested script or workload execution, runtime inspection and file and log inspection related to device memory.

    1 call · #0053–#0053

    python3 - <script>echo <val>npu-smi infosed -n <val>
  43. Execute · Runtime processes

    Requested service requests related to runtime processes.

    1 call · #0054–#0054

    echo <val>curl -s -m <n> -X <val> <url> -H <path> -d <path>echo
  44. Inspect · Runtime processes

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

    1 call · #0055–#0055

    grep <flag> <args>tail -n <n>
  45. Profile · Runtime processes

    Requested script or workload execution related to runtime processes.

    2 calls · #0056–#0057

    cd <path>python3 - <script>python3 -c <script>
  46. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0058–#0058

    python3 - <script>
  47. Validate · Benchmark & validation setup

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

    1 call · #0059–#0059

    bash <script> <val><command> <args>echo <val>cd <path>timeout <n> <val> <path> <n> <n> >& <path>grep -v <val>
  48. Profile · Batching & scheduling

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

    1 call · #0060–#0060

    cat > <path> <script>cd <path>timeout <n> <val> <path> <n> <val> <n> >& <path>grep -v <val>
  49. Validate · Benchmark & validation setup

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

    1 call · #0061–#0061

    echo <val>envgrep -E <val>sortechols -l -a <path> <n> > <path>
    6 more command sketches
    head -n <n>mkdir -p <path>cat > <path> <script>cat <path>chmod <val> <path>python3 -c <script>
  50. Inspect · Source & workspace

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

    1 call · #0062–#0062

    env <vars>echo <val>ls -l -a <val> <n> >& <path>cat <val> <n> >& <path>echols -l -a <path> <n> >& <path>
    1 more command sketches
    head
  51. Inspect · Attention kernels

    Requested script or workload execution and execution waits related to attention kernels.

    1 call · #0063–#0063

    bash <script> <val> > <path> <n> >& <path>sleep <n>cd <path>timeout <n> <val> <val> <script>
  52. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0064–#0064

    cd <path>timeout <n> <val> <val> <script>
  53. Inspect · Source & workspace

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

    1 call · #0065–#0065

    python3 -c <script>echo <val>find <path> -type <val> <flag> <args>sortdu <flag> <args>awk <path>
  54. Execute · Attention kernels

    Requested script or workload execution, source searches and file and log inspection related to attention kernels.

    1 call · #0066–#0066

    cd <path>python3 - <script>python3 -c <script>grep -n <val> <path>head
  55. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0067–#0067

    python3 -c <script>
  56. Validate · Benchmark & validation setup

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

    1 call · #0068–#0068

    bash <script> <val><command> <args>echo <val>cd <path>timeout <n> <val> <path> <n> <n> >& <path>grep -v <val>
    2 more command sketches
    tail -n <n>timeout <n> <val> <path> <n> <val> <n> >& <path>
  57. Execute · Runtime processes

    Requested service requests, script or workload execution and source searches related to runtime processes.

    1 call · #0069–#0069

    echo <val>curl -s -m <n> <url> > <path>cd <path>python3 - <script>grep <flag> <args>tail -n <n>
  58. Other · Latency & request handling

    Requested script or workload execution related to latency & request handling.

    1 call · #0070–#0070

    cd <path>python3 - <script>python3 -c <script>
  59. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0071–#0071

    python3 -c <script>
  60. Validate · Device memory

    Requested script or workload execution, source searches and file and log inspection related to device memory.

    1 call · #0072–#0072

    cd <path>python3 - <script>python3 -c <script>bash <script> <val><command> <args>grep <flag> <args>
    5 more command sketches
    tail -n <n>echo <val>timeout <n> <val> <path> <n> <n> >& <path>grep -v <val>timeout <n> <val> <path> <n> <val> <n> >& <path>
  61. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0073–#0073

    python3 -c <script>
  62. Profile · Latency & request handling

    Requested file and log inspection and script or workload execution related to latency & request handling.

    1 call · #0074–#0074

    cat > <path> <script>python3 -c <script>
  63. Validate · Benchmark & validation setup

    Requested script or workload execution, execution waits and source searches related to benchmark & validation setup.

    1 call · #0075–#0075

    cd <path>python3 - <script>bash <script> <val>sleep <n>echo <val>timeout <n> <val> <path> <val> <n> >& <path>
    2 more command sketches
    grep -v <val>tail -n <n>
  64. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0076–#0076

    python3 -c <script>
  65. Execute · Latency & request handling

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

    1 call · #0077–#0077

    bash <script> <val><command> <args>echo <val>cd <path>timeout <n> <val> <path> <n> <n> <n> <n> >& <path>grep -v <val>
    1 more command sketches
    tail -n <n>
  66. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0078–#0078

    python3 -c <script>
  67. Validate · Attention kernels

    Requested script or workload execution, source searches and file and log inspection related to attention kernels.

    1 call · #0079–#0079

    cd <path>python3 - <script>python3 -c <script>bash <script> <val><command> <args>grep <flag> <args>
    5 more command sketches
    tail -n <n>echo <val>timeout <n> <val> <path> <n> <n> >& <path>grep -v <val>timeout <n> <val> <path> <n> <val> <n> >& <path>
  68. Execute · Benchmark & validation setup

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

    1 call · #0080–#0080

    bash <script> <val>sleep <n>rm -rf <path>mkdir -p <path>cd <path>echo <val>
    1 more command sketches
    env <vars> timeout <n> <val> <path> <val> > <path> <n> >& <path>
  69. Inspect · Task requirements

    Requested workspace inspection, file and log inspection and repository inspection related to task requirements.

    1 call · #0081–#0081

    cd <path>echo <path>find <path> -mindepth <n>sortechofind <path> -name <val> -o -name <val> -o -name <path>
    9 more command sketches
    trueecho <val>find <path> -type <val> -exec <val> <flag> <args>tail -n <n>awk <path>ls -l <path> <path> <val>cat <path>git status --shorthead -n <n>
  70. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0082–#0082

    python3 -c <script>
  71. Profile · Benchmark & validation setup

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

    1 call · #0083–#0083

    env <vars><command> <args>echo <val>sleep <n>echo <flag>ls <flag> <args>
    7 more command sketches
    grep -E <val>sed <path>grep -v <val>sorttail -n <n>wc -lgrep <flag> <args>
  72. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    2 calls · #0084–#0085

    python3 -c <script>
  73. Inspect · Task requirements

    Requested workspace file updates, workspace inspection and script or workload execution related to task requirements.

    1 call · #0086–#0086

    cd <path>chmod <n> <val>chmod <n> <path> <path>chmod <n> <val> <path>echo <val>ls -l <path> <path> <val>
    3 more command sketches
    ls <flag> <args>ls -l <path>python3 -c <script>
  74. Profile · Benchmark & validation setup

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

    1 call · #0087–#0087

    env <vars><command> <args>sleep <n>echo <flag>ls <flag> <args>grep -E <val>
    6 more command sketches
    grep -v -E <val>sortpython3 -c <script>echo <val>grep <flag> <args>tail -n <n>
  75. Execute · Latency & request handling

    Requested environment setup or inspection and script or workload execution related to latency & request handling.

    1 call · #0088–#0088

    env <vars>python3 - <script>
  76. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0089–#0089

    python3 -c <script>
  77. Execute · Task requirements

    Requested workspace inspection, script or workload execution and file and log inspection related to task requirements.

    1 call · #0090–#0090

    cd <path>echo <val>find <path> -type <val> <flag> <args>sortechopython3 - <script>
    3 more command sketches
    sha256sum <path> <path> <val> <path>sed <path>python3 -c <script>
  78. Validate · Device memory

    Requested script or workload execution, execution waits and environment setup or inspection related to device memory.

    1 call · #0091–#0091

    bash <script> <val> > <path> <n> >& <path>sleep <n>cd <path>echo <val>env <vars> timeout <n> <val> <path> <val> <n> >& <path>grep -v <val>
    8 more command sketches
    tail -n <n>echoecho <flag><command> <args>grep -E <val>ps <flag> <args>npu-smi infosed -n <val>
  79. Inspect · Source & workspace

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

    1 call · #0092–#0092

    python3 -c <script>echo <val>du <flag> <args>rm -rf <path>ls -d <path>df -h <path>
    1 more command sketches
    tail -n <n>
  80. Build · Task requirements

    Requested workspace inspection, file and log inspection and repository inspection related to task requirements.

    1 call · #0093–#0093

    cd <path>echo <val>find <path> -mindepth <n>sortechofind <path> -name <val> -o -name <val> -o -name <path>
    8 more command sketches
    sha256sum <path> <path> <val> <path>sed <path>awk <val>cat <script>find <path> -type <val> -exec <val> <flag> <args>tail -n <n>awk <path>git -C <path> <val> --stat <flag> <args>
  81. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0094–#0094

    python3 -c <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..b5c0bde2848e879c5d1af0b2c921f08f9d3d0a10--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,34 @@+#!/usr/bin/env bash+# Offline, idempotent preparation. Installs nothing into the base environment:+# the delivery is pure Python on top of the runtime-supplied torch/torch_npu.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"+ENV_DIR="${OPENBUILD_ENV_DIR:?OPENBUILD_ENV_DIR is required}"++mkdir -p "${ENV_DIR}"+# Run-owned scratch for compile caches so nothing lands in user caches.+mkdir -p "${ENV_DIR}/pycache" "${ENV_DIR}/state"++PY="$(command -v python3 || command -v python)"++# Verify the required runtime surface is importable and the delivery parses.+PYTHONPYCACHEPREFIX="${ENV_DIR}/pycache" \+"${PY}" - "${SOLUTION_DIR}" <<'PYEOF'+import compileall, pathlib, sys+root = pathlib.Path(sys.argv[1])+import torch  # noqa: F401+import torch_npu  # noqa: F401+import transformers  # noqa: F401+import uvicorn  # noqa: F401+ok = compileall.compile_dir(str(root / "qwensrv"), quiet=2, force=False)+if not ok:+    raise SystemExit("delivery source failed to compile")+model = pathlib.Path(__import__("os").environ.get("OPENBUILD_MODEL_PATH", ""))+if model.name and not (model / "config.json").is_file():+    raise SystemExit("model projection is not readable")+print("qwensrv bootstrap ok")+PYEOF++printf 'ready\n' > "${ENV_DIR}/state/bootstrap.done"+exit 0diff --git a/solution/launch.sh b/solution/launch.shnew file mode 100755index 0000000000000000000000000000000000000000..94f176dbf4323a4ee5f539c7aaa8068d73791ecc--- /dev/null+++ b/solution/launch.sh@@ -0,0 +1,20 @@+#!/usr/bin/env bash+# One foreground HTTP service. exec keeps this shell's pid as the service pid so+# the task's process-group SIGTERM reaches the real server directly.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"+ENV_DIR="${OPENBUILD_ENV_DIR:-${SOLUTION_DIR}/.runtime}"+mkdir -p "${ENV_DIR}/pycache"++export PYTHONPYCACHEPREFIX="${ENV_DIR}/pycache"+export PYTHONUNBUFFERED=1+export PYTHONPATH="${SOLUTION_DIR}${PYTHONPATH:+:${PYTHONPATH}}"+# Keep host threads from oversubscribing the 21 available cores.+export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}"+export TOKENIZERS_PARALLELISM=false+export HF_HUB_OFFLINE=1+export TRANSFORMERS_OFFLINE=1++PY="$(command -v python3 || command -v python)"+exec "${PY}" -u -m qwensrv.serverdiff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..f46bf15750b0c5404ef8bd6cc5f2b7555afad797--- /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": "qwensrv-npu-paged-continuous-batching",+  "bootstrap": "bootstrap.sh",+  "launch": "launch.sh",+  "offline_replay": true+}diff --git a/solution/qwensrv/__init__.py b/solution/qwensrv/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391diff --git a/solution/qwensrv/detok.py b/solution/qwensrv/detok.pynew file mode 100644index 0000000000000000000000000000000000000000..82c5c8899a10d880a8e7d6f365e32a68629a829b--- /dev/null+++ b/solution/qwensrv/detok.py@@ -0,0 +1,86 @@+"""Exact incremental detokenisation for byte-level BPE vocabularies.++Decoding a growing prefix with the HF tokenizer each step is O(n^2) and shows up+in TPOT at 64-way concurrency. Instead every token id is mapped once to its+exact byte string; streaming is then byte concatenation plus a UTF-8 boundary+check, which never splits a multi-byte character across SSE chunks.+"""+from __future__ import annotations+++def _byte_decoder() -> dict[str, int]:+    printable = (+        list(range(ord("!"), ord("~") + 1))+        + list(range(ord("¡"), ord("¬") + 1))+        + list(range(ord("®"), ord("ÿ") + 1))+    )+    mapped = printable[:]+    extra = 0+    for byte in range(256):+        if byte not in printable:+            printable.append(byte)+            mapped.append(256 + extra)+            extra += 1+    return {chr(code): byte for byte, code in zip(printable, mapped)}+++def build_token_bytes(tokenizer) -> list[bytes]:+    """id -> exact bytes, so concatenation reproduces tokenizer.decode()."""+    decoder = _byte_decoder()+    size = len(tokenizer)+    table: list[bytes] = [b""] * size+    vocab = tokenizer.get_vocab()+    added = set()+    for token_id in getattr(tokenizer, "all_special_ids", []) or []:+        added.add(int(token_id))+    for token_id in (getattr(tokenizer, "added_tokens_decoder", {}) or {}):+        added.add(int(token_id))+    for token, token_id in vocab.items():+        if token_id >= size:+            continue+        if token_id in added:+            table[token_id] = token.encode("utf-8")+            continue+        try:+            table[token_id] = bytes(decoder[ch] for ch in token)+        except KeyError:+            table[token_id] = token.encode("utf-8")+    return table+++class IncrementalDetokenizer:+    """Emits the longest valid UTF-8 prefix available after each token."""++    __slots__ = ("_table", "_pending")++    def __init__(self, table: list[bytes]):+        self._table = table+        self._pending = b""++    def push(self, token_id: int) -> str:+        self._pending += self._table[token_id] if token_id < len(self._table) else b""+        if not self._pending:+            return ""+        try:+            text = self._pending.decode("utf-8")+        except UnicodeDecodeError as exc:+            if exc.start == 0:+                # Leading bytes are undecodable on their own; keep waiting unless+                # the buffer has grown past any legal multi-byte sequence.+                if len(self._pending) < 4:+                    return ""+                text = self._pending.decode("utf-8", errors="replace")+                self._pending = b""+                return text+            text = self._pending[: exc.start].decode("utf-8")+            self._pending = self._pending[exc.start :]+            return text+        self._pending = b""+        return text++    def flush(self) -> str:+        if not self._pending:+            return ""+        text = self._pending.decode("utf-8", errors="replace")+        self._pending = b""+        return textdiff --git a/solution/qwensrv/engine.py b/solution/qwensrv/engine.pynew file mode 100644index 0000000000000000000000000000000000000000..e97966fd3940e027a0118969470db9c354badbfc--- /dev/null+++ b/solution/qwensrv/engine.py@@ -0,0 +1,264 @@+"""Continuous-batching scheduler on top of Qwen3Runner.++One dedicated OS thread drives the NPU so the asyncio event loop stays free for+HTTP and SSE work. Requests move waiting -> running; each iteration either+admits a prefill batch or advances every running sequence by one token.+"""+from __future__ import annotations++import os+import threading+import time+from collections import deque+from dataclasses import dataclass, field+from typing import Any, Callable++import numpy as np+import torch++from .model import BLOCK_SIZE, Qwen3Runner+++class BlockAllocator:+    def __init__(self, num_blocks: int):+        # Block 0 is never handed out: a zero entry in a block table is the+        # natural "unused" padding value.+        self.free = deque(range(1, num_blocks))++    def available(self) -> int:+        return len(self.free)++    def allocate(self, count: int) -> list[int] | None:+        if count > len(self.free):+            return None+        return [self.free.popleft() for _ in range(count)]++    def release(self, blocks: list[int]) -> None:+        self.free.extend(blocks)+++@dataclass+class Request:+    rid: str+    prompt_ids: list[int]+    max_new_tokens: int+    ignore_eos: bool+    eos_ids: set[int]+    stop_token_ids: set[int]+    on_event: Callable[[dict[str, Any]], None]+    blocks: list[int] = field(default_factory=list)+    block_array: Any = None+    output_ids: list[int] = field(default_factory=list)+    kv_len: int = 0+    next_token: int = 0+    aborted: bool = False+    finish_reason: str | None = None++    @property+    def prompt_len(self) -> int:+        return len(self.prompt_ids)++    def total_needed(self) -> int:+        return self.prompt_len + self.max_new_tokens+++class Engine:+    def __init__(self, model_path: str, **runner_kwargs):+        self.runner = Qwen3Runner(model_path, **runner_kwargs)+        self.cfg = self.runner.cfg+        self.graphs_captured = 0+        self.allocator = BlockAllocator(self.runner.num_blocks)+        self.max_batch = self.runner.max_batch+        # A prefill batch blocks every running decode for its duration, so the+        # budget trades prefill efficiency against decode-side jitter (TTFT p95).+        self.prefill_budget = int(os.environ.get("QWENSRV_PREFILL_TOKENS", "4096"))++        # Share the runner's numpy view of the pinned block-table buffer.+        self._bt_host = self.runner._bt_host++        self._lock = threading.Lock()+        self._waiting: deque[Request] = deque()+        self._running: list[Request] = []+        self._wake = threading.Event()+        self._stop = threading.Event()+        self._thread: threading.Thread | None = None+        self.errors = 0++    # ------------------------------------------------------------- lifecycle+    def start(self) -> None:+        self.graphs_captured = self.runner.capture_decode_graphs()+        self._thread = threading.Thread(target=self._loop, name="qwensrv-engine", daemon=True)+        self._thread.start()++    def stop(self) -> None:+        self._stop.set()+        self._wake.set()+        thread = self._thread+        if thread is not None:+            thread.join(timeout=10)++    def submit(self, request: Request) -> None:+        with self._lock:+            self._waiting.append(request)+        self._wake.set()++    def max_context(self) -> int:+        return min(self.cfg.max_position, self.runner.cache_capacity_tokens())++    # -------------------------------------------------------------- internals+    def _emit(self, request: Request, event: dict[str, Any]) -> None:+        try:+            request.on_event(event)+        except Exception:  # a dead client must not take the engine down+            request.aborted = True++    def _finish(self, request: Request, reason: str) -> None:+        request.finish_reason = reason+        self.allocator.release(request.blocks)+        request.blocks = []+        self._emit(request, {"type": "done", "reason": reason})++    def _admit(self) -> list[Request]:+        """Pull waiting requests into a prefill batch under the token budget."""+        admitted: list[Request] = []+        budget = self.prefill_budget+        with self._lock:+            while self._waiting and len(self._running) + len(admitted) < self.max_batch:+                request = self._waiting[0]+                if request.aborted:+                    self._waiting.popleft()+                    continue+                if admitted and request.prompt_len > budget:+                    break+                need = (request.total_needed() + BLOCK_SIZE - 1) // BLOCK_SIZE+                blocks = self.allocator.allocate(need)+                if blocks is None:+                    break+                self._waiting.popleft()+                request.blocks = blocks+                request.block_array = np.asarray(blocks, dtype=np.int32)+                admitted.append(request)+                budget -= request.prompt_len+                if budget <= 0:+                    break+        return admitted++    def _slots_for(self, request: Request, start: int, count: int) -> np.ndarray:+        positions = np.arange(start, start + count, dtype=np.int64)+        blocks = np.asarray(request.blocks, dtype=np.int64)+        return blocks[positions // BLOCK_SIZE] * BLOCK_SIZE + (positions % BLOCK_SIZE)++    def _run_prefill(self, batch: list[Request]) -> None:+        device = self.runner.device+        token_list: list[np.ndarray] = []+        pos_list: list[np.ndarray] = []+        slot_list: list[np.ndarray] = []+        cu: list[int] = []+        last: list[int] = []+        offset = 0+        for request in batch:+            n = request.prompt_len+            token_list.append(np.asarray(request.prompt_ids, dtype=np.int64))+            pos_list.append(np.arange(n, dtype=np.int64))+            slot_list.append(self._slots_for(request, 0, n))+            offset += n+            cu.append(offset)+            last.append(offset - 1)++        tokens = torch.from_numpy(np.concatenate(token_list)).to(device, non_blocking=True)+        positions = torch.from_numpy(np.concatenate(pos_list)).to(device, non_blocking=True)+        slots = torch.from_numpy(np.concatenate(slot_list)).to(device, non_blocking=True)+        last_idx = torch.tensor(last, dtype=torch.int64, device=device)++        logits = self.runner.prefill(tokens, positions, slots, cu, last_idx)+        chosen = torch.argmax(logits, dim=-1).to("cpu").tolist()++        for request, token in zip(batch, chosen):+            request.kv_len = request.prompt_len+            request.next_token = int(token)+            self._running.append(request)+            self._accept_token(request, int(token))++    def _accept_token(self, request: Request, token: int) -> None:+        request.output_ids.append(token)+        stop = (not request.ignore_eos) and (+            token in request.eos_ids or token in request.stop_token_ids+        )+        if stop:+            self._emit(request, {"type": "token", "token": token, "visible": False})+            self._finish(request, "stop")+            return+        self._emit(request, {"type": "token", "token": token, "visible": True})+        if len(request.output_ids) >= request.max_new_tokens:+            self._finish(request, "length")++    def _run_decode(self) -> None:+        active = [r for r in self._running if r.finish_reason is None and not r.aborted]+        for request in self._running:+            if request.aborted and request.finish_reason is None:+                self._finish(request, "abort")+        self._running = active+        if not active:+            return++        batch = len(active)+        runner = self.runner+        max_blocks = 0+        kv_lens: list[int] = []+        for i, request in enumerate(active):+            runner.h_tokens[i] = request.next_token+            runner.h_pos[i] = request.kv_len+            blocks = request.blocks+            pos = request.kv_len+            runner.h_slots[i] = blocks[pos // BLOCK_SIZE] * BLOCK_SIZE + (pos % BLOCK_SIZE)+            used = pos // BLOCK_SIZE + 1+            max_blocks = max(max_blocks, used)+            self._bt_host[i, :used] = request.block_array[:used]+            kv_lens.append(pos + 1)++        chosen = runner.decode_step(batch, max_blocks, kv_lens)++        for request, token in zip(active, chosen):+            request.kv_len += 1+            request.next_token = int(token)+            if request.finish_reason is None:+                self._accept_token(request, int(token))++        self._running = [r for r in self._running if r.finish_reason is None and not r.aborted]++    def _loop(self) -> None:+        torch.npu.set_device(self.runner.device)+        while not self._stop.is_set():+            with self._lock:+                pending = bool(self._waiting)+            if not pending and not self._running:+                self._wake.wait(timeout=0.05)+                self._wake.clear()+                continue+            try:+                # Prefill first: a queued request's TTFT clock is already running,+                # while decode latency is amortised over the whole response.+                if pending and len(self._running) < self.max_batch:+                    batch = self._admit()+                    if batch:+                        self._run_prefill(batch)+                if self._running:+                    self._run_decode()+            except Exception as exc:  # noqa: BLE001+                self.errors += 1+                self._fail_all(exc)++    def _fail_all(self, exc: Exception) -> None:+        message = f"{type(exc).__name__}: {exc}"[:500]+        for request in list(self._running):+            self.allocator.release(request.blocks)+            request.blocks = []+            request.finish_reason = "error"+            self._emit(request, {"type": "error", "message": message})+        self._running = []+        with self._lock:+            waiting = list(self._waiting)+            self._waiting.clear()+        for request in waiting:+            request.finish_reason = "error"+            self._emit(request, {"type": "error", "message": message})diff --git a/solution/qwensrv/model.py b/solution/qwensrv/model.pynew file mode 100644index 0000000000000000000000000000000000000000..99b647b3c6cb5e9ba44ca0abf76328b5abd464f4--- /dev/null+++ b/solution/qwensrv/model.py@@ -0,0 +1,499 @@+"""Qwen3-8B inference runner for Ascend NPU.++Layout choices that matter for speed:+  * qkv and gate/up projections are pre-fused into single weight matrices so a+    decode step issues 4 GEMMs per layer instead of 7.+  * KV cache is paged, one [num_blocks, block_size, kv_heads*head_dim] pair per+    layer, which is the layout npu_fused_infer_attention_score consumes directly+    with a block_table (verified on-device).+  * residual chaining uses npu_add_rms_norm so the residual add and the norm are+    one kernel.+"""+from __future__ import annotations++import json+import math+import os+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from typing import Any++import torch+import torch_npu  # noqa: F401  (registers npu ops / device backend)+from safetensors import safe_open++FIA = torch.ops.npu.npu_fused_infer_attention_score+RMS = torch.ops.npu.npu_rms_norm+ADD_RMS = torch.ops.npu.npu_add_rms_norm+SWIGLU = torch.ops.npu.npu_swiglu+ROTARY = torch.ops.npu.npu_rotary_mul++BLOCK_SIZE = 128++# Decode is launch-bound: ~360 kernel launches per step against a ~11 ms+# weight-bandwidth roofline. Capturing a step as one NPU graph removes the+# per-op dispatch cost. The graph bakes host-side ints, so actual_seq_lengths_kv+# is baked at a bucket ceiling and true lengths are applied through an attention+# mask computed inside the graph (verified to be bit-exact against exact-length+# eager attention).+BATCH_BUCKETS = (1, 2, 4, 8, 16, 24, 32, 48, 64)+# The baked bucket ceiling is what attention actually reads, so a coarse step+# wastes KV bandwidth: at batch 64 a 1024-slot ceiling over ~384 real tokens+# reads ~9.7 GB/step instead of ~3.6 GB. Keep the step tight.+KV_BUCKET_STEP = 256+++class Qwen3Config:+    def __init__(self, path: Path):+        raw = json.loads((path / "config.json").read_text(encoding="utf-8"))+        self.hidden_size = int(raw["hidden_size"])+        self.num_layers = int(raw["num_hidden_layers"])+        self.num_heads = int(raw["num_attention_heads"])+        self.num_kv_heads = int(raw["num_key_value_heads"])+        self.head_dim = int(raw.get("head_dim") or self.hidden_size // self.num_heads)+        self.intermediate_size = int(raw["intermediate_size"])+        self.vocab_size = int(raw["vocab_size"])+        self.rms_eps = float(raw["rms_norm_eps"])+        self.rope_theta = float(raw["rope_theta"])+        self.max_position = int(raw["max_position_embeddings"])+        self.tie_word_embeddings = bool(raw.get("tie_word_embeddings", False))+        self.q_size = self.num_heads * self.head_dim+        self.kv_size = self.num_kv_heads * self.head_dim+        self.scale = 1.0 / math.sqrt(self.head_dim)++        gen = path / "generation_config.json"+        eos: list[int] = []+        if gen.is_file():+            value = json.loads(gen.read_text(encoding="utf-8")).get("eos_token_id")+            if isinstance(value, int):+                eos = [value]+            elif isinstance(value, list):+                eos = [int(v) for v in value]+        if not eos:+            eos = [int(raw.get("eos_token_id", 151645))]+        self.eos_token_ids = sorted(set(eos))+++class LayerWeights:+    __slots__ = ("wqkv", "wo", "wgu", "wd", "n_in", "n_post", "q_norm", "k_norm")+++class Qwen3Runner:+    """Owns the weights, the paged KV cache, and the two forward paths."""++    def __init__(+        self,+        model_path: str,+        *,+        dtype: torch.dtype = torch.bfloat16,+        kv_cache_blocks: int | None = None,+        load_workers: int = 16,+    ):+        self.path = Path(model_path)+        self.cfg = Qwen3Config(self.path)+        self.dtype = dtype+        self.device = torch.device("npu:0")+        torch.npu.set_device(self.device)++        cfg = self.cfg+        self.layers: list[LayerWeights] = [LayerWeights() for _ in range(cfg.num_layers)]+        self._allocate_weights()+        self._load_weights(load_workers)+        self._build_rope()++        # sparse_mode=3 consumes a fixed 2048x2048 compressed causal mask for any+        # sequence length, so one small mask covers every prefill shape.+        self.prefill_mask = torch.triu(+            torch.ones(2048, 2048, device=self.device, dtype=torch.bool), diagonal=1+        )++        self.num_blocks = kv_cache_blocks or self._auto_cache_blocks()+        self._allocate_cache()++        self.max_batch = int(os.environ.get("QWENSRV_MAX_BATCH", "64"))+        self.max_batch = max(1, min(self.max_batch, 128))+        self.enable_graphs = os.environ.get("QWENSRV_GRAPHS", "1") != "0"+        # Covers every scored shape (longest is 2048 prompt + 64 output); longer+        # requests fall back to the eager path automatically.+        self.max_graph_kv = int(os.environ.get("QWENSRV_GRAPH_KV", "2560"))+        self._graphs: dict[tuple[int, int], Any] = {}+        self._graph_pool = torch.npu.graph_pool_handle() if self.enable_graphs else None+        self._decode_buffers()++    # ---------------------------------------------------------------- weights+    def _allocate_weights(self) -> None:+        cfg, dt, dev = self.cfg, self.dtype, self.device+        self.embed = torch.empty(cfg.vocab_size, cfg.hidden_size, dtype=dt, device=dev)+        self.norm_f = torch.empty(cfg.hidden_size, dtype=dt, device=dev)+        self.lm_head = torch.empty(cfg.vocab_size, cfg.hidden_size, dtype=dt, device=dev)+        fused_qkv = cfg.q_size + 2 * cfg.kv_size+        for ly in self.layers:+            ly.wqkv = torch.empty(fused_qkv, cfg.hidden_size, dtype=dt, device=dev)+            ly.wo = torch.empty(cfg.hidden_size, cfg.q_size, dtype=dt, device=dev)+            ly.wgu = torch.empty(2 * cfg.intermediate_size, cfg.hidden_size, dtype=dt, device=dev)+            ly.wd = torch.empty(cfg.hidden_size, cfg.intermediate_size, dtype=dt, device=dev)+            ly.n_in = torch.empty(cfg.hidden_size, dtype=dt, device=dev)+            ly.n_post = torch.empty(cfg.hidden_size, dtype=dt, device=dev)+            ly.q_norm = torch.empty(cfg.head_dim, dtype=dt, device=dev)+            ly.k_norm = torch.empty(cfg.head_dim, dtype=dt, device=dev)++    def _destination(self, name: str):+        """Map a checkpoint tensor name onto a slice of a pre-allocated buffer."""+        cfg = self.cfg+        if name == "model.embed_tokens.weight":+            return self.embed+        if name == "model.norm.weight":+            return self.norm_f+        if name == "lm_head.weight":+            return self.lm_head+        if not name.startswith("model.layers."):+            return None+        parts = name.split(".")+        idx = int(parts[2])+        ly = self.layers[idx]+        leaf = ".".join(parts[3:])+        q, kv = cfg.q_size, cfg.kv_size+        table = {+            "self_attn.q_proj.weight": lambda: ly.wqkv[:q],+            "self_attn.k_proj.weight": lambda: ly.wqkv[q : q + kv],+            "self_attn.v_proj.weight": lambda: ly.wqkv[q + kv : q + 2 * kv],+            "self_attn.o_proj.weight": lambda: ly.wo,+            "self_attn.q_norm.weight": lambda: ly.q_norm,+            "self_attn.k_norm.weight": lambda: ly.k_norm,+            "mlp.gate_proj.weight": lambda: ly.wgu[: cfg.intermediate_size],+            "mlp.up_proj.weight": lambda: ly.wgu[cfg.intermediate_size :],+            "mlp.down_proj.weight": lambda: ly.wd,+            "input_layernorm.weight": lambda: ly.n_in,+            "post_attention_layernorm.weight": lambda: ly.n_post,+        }+        fn = table.get(leaf)+        return fn() if fn is not None else None++    def _load_weights(self, workers: int) -> None:+        index_path = self.path / "model.safetensors.index.json"+        if index_path.is_file():+            weight_map = json.loads(index_path.read_text(encoding="utf-8"))["weight_map"]+            shards: dict[str, list[str]] = {}+            for tensor_name, shard in weight_map.items():+                shards.setdefault(shard, []).append(tensor_name)+        else:+            shards = {"model.safetensors": None}  # type: ignore[dict-item]++        def load_shard(item) -> None:+            shard, names = item+            # Each thread gets its own NPU stream so host reads of one shard can+            # overlap the device copies of another.+            stream = torch.npu.Stream(device=self.device)+            with torch.npu.stream(stream):+                with safe_open(str(self.path / shard), framework="pt", device="cpu") as f:+                    keys = names if names is not None else list(f.keys())+                    for name in keys:+                        dst = self._destination(name)+                        if dst is None:+                            continue+                        src = f.get_tensor(name)+                        dst.copy_(src.to(self.dtype), non_blocking=False)+            stream.synchronize()++        with ThreadPoolExecutor(max_workers=max(1, min(workers, len(shards)))) as pool:+            list(pool.map(load_shard, shards.items()))+        torch.npu.synchronize()++        if self.cfg.tie_word_embeddings:+            self.lm_head = self.embed++    def _build_rope(self) -> None:+        cfg = self.cfg+        inv = 1.0 / (+            cfg.rope_theta+            ** (torch.arange(0, cfg.head_dim, 2, dtype=torch.float64) / cfg.head_dim)+        )+        pos = torch.arange(cfg.max_position, dtype=torch.float64)+        freqs = torch.outer(pos, inv)+        emb = torch.cat((freqs, freqs), dim=-1)+        self.cos = emb.cos().to(self.dtype).to(self.device)+        self.sin = emb.sin().to(self.dtype).to(self.device)++    # ------------------------------------------------------------------ cache+    def _bytes_per_token(self) -> int:+        return 2 * self.cfg.num_layers * self.cfg.kv_size * self.dtype.itemsize++    def _auto_cache_blocks(self) -> int:+        free, total = torch.npu.mem_get_info()+        # Hold back headroom for activations, workspaces and fragmentation.+        reserve = 6 * (1 << 30)+        budget = max(free - reserve, 2 << 30)+        env = os.environ.get("QWENSRV_KV_GIB")+        if env:+            budget = int(float(env) * (1 << 30))+        blocks = int(budget // (self._bytes_per_token() * BLOCK_SIZE))+        return max(64, min(blocks, 20000))++    def _allocate_cache(self) -> None:+        cfg = self.cfg+        shape = (self.num_blocks, BLOCK_SIZE, cfg.kv_size)+        self.k_cache = [+            torch.zeros(shape, dtype=self.dtype, device=self.device)+            for _ in range(cfg.num_layers)+        ]+        self.v_cache = [+            torch.zeros(shape, dtype=self.dtype, device=self.device)+            for _ in range(cfg.num_layers)+        ]+        self.k_flat = [t.view(-1, cfg.kv_size) for t in self.k_cache]+        self.v_flat = [t.view(-1, cfg.kv_size) for t in self.v_cache]++    def _decode_buffers(self) -> None:+        dev = self.device+        self.d_tokens = torch.zeros(self.max_batch, dtype=torch.int64, device=dev)+        self.d_slots = torch.zeros(self.max_batch, dtype=torch.int64, device=dev)+        self.d_pos = torch.zeros(self.max_batch, dtype=torch.int64, device=dev)+        self.h_tokens = torch.zeros(self.max_batch, dtype=torch.int64).pin_memory()+        self.h_slots = torch.zeros(self.max_batch, dtype=torch.int64).pin_memory()+        self.h_pos = torch.zeros(self.max_batch, dtype=torch.int64).pin_memory()+        columns = max(512, self.max_graph_kv // BLOCK_SIZE)+        self.h_bt = torch.zeros(self.max_batch, columns, dtype=torch.int32).pin_memory()+        self.d_bt = torch.zeros(self.max_batch, columns, dtype=torch.int32, device=dev)+        self.h_kvlen = torch.zeros(self.max_batch, dtype=torch.int32).pin_memory()+        self.d_kvlen = torch.zeros(self.max_batch, dtype=torch.int32, device=dev)+        self.d_next = torch.zeros(self.max_batch, dtype=torch.int64, device=dev)+        self.arange_kv = torch.arange(self.max_graph_kv, dtype=torch.int32, device=dev)++        # numpy views over the pinned staging buffers: writing per-lane scalars+        # through numpy avoids allocating a torch tensor inside the decode step.+        self._bt_host = self.h_bt.numpy()+        self._kvlen_host = self.h_kvlen.numpy()+        self._tokens_host = self.h_tokens.numpy()+        self._pos_host = self.h_pos.numpy()+        self._slots_host = self.h_slots.numpy()++    def cache_capacity_tokens(self) -> int:+        return self.num_blocks * BLOCK_SIZE++    # --------------------------------------------------------------- forwards+    @torch.inference_mode()+    def prefill(+        self,+        token_ids: torch.Tensor,   # int64 [T] on device+        positions: torch.Tensor,   # int64 [T] on device+        slots: torch.Tensor,       # int64 [T] on device+        cu_seqlens: list[int],     # cumulative lengths, len == nseq+        last_indices: torch.Tensor,  # int64 [nseq] on device+    ) -> torch.Tensor:+        cfg = self.cfg+        total = token_ids.shape[0]+        x = self.embed.index_select(0, token_ids)+        cos = self.cos.index_select(0, positions).view(1, total, 1, cfg.head_dim)+        sin = self.sin.index_select(0, positions).view(1, total, 1, cfg.head_dim)++        res = x+        pending = None+        for i, ly in enumerate(self.layers):+            if pending is None:+                h = RMS(res, ly.n_in, cfg.rms_eps)[0]+            else:+                h, _, res = ADD_RMS(res, pending, ly.n_in, cfg.rms_eps)++            qkv = torch.nn.functional.linear(h, ly.wqkv)+            q, k, v = qkv.split([cfg.q_size, cfg.kv_size, cfg.kv_size], dim=-1)+            q = RMS(q.view(total, cfg.num_heads, cfg.head_dim).contiguous(), ly.q_norm, cfg.rms_eps)[0]+            k = RMS(k.view(total, cfg.num_kv_heads, cfg.head_dim).contiguous(), ly.k_norm, cfg.rms_eps)[0]+            q = ROTARY(q.view(1, total, cfg.num_heads, cfg.head_dim), cos, sin, "half", None)+            k = ROTARY(k.view(1, total, cfg.num_kv_heads, cfg.head_dim), cos, sin, "half", None)+            q = q.view(total, cfg.num_heads, cfg.head_dim)+            k = k.view(total, cfg.num_kv_heads, cfg.head_dim)++            self.k_flat[i].index_copy_(0, slots, k.reshape(total, cfg.kv_size))+            self.v_flat[i].index_copy_(0, slots, v.reshape(total, cfg.kv_size))++            attn = FIA(+                q,+                k,+                v.view(total, cfg.num_kv_heads, cfg.head_dim),+                num_heads=cfg.num_heads,+                num_key_value_heads=cfg.num_kv_heads,+                input_layout="TND",+                scale=cfg.scale,+                actual_seq_lengths=cu_seqlens,+                actual_seq_lengths_kv=cu_seqlens,+                atten_mask=self.prefill_mask,+                sparse_mode=3,+            )[0]+            attn_out = torch.nn.functional.linear(attn.reshape(total, cfg.q_size), ly.wo)++            h2, _, res = ADD_RMS(res, attn_out, ly.n_post, cfg.rms_eps)+            gu = torch.nn.functional.linear(h2, ly.wgu)+            pending = torch.nn.functional.linear(SWIGLU(gu, -1), ly.wd)++        hidden = ADD_RMS(res, pending, self.norm_f, cfg.rms_eps)[0]+        # Only the final position of each sequence needs a vocab projection.+        return torch.nn.functional.linear(hidden.index_select(0, last_indices), self.lm_head)++    @torch.inference_mode()+    def _decode_body(+        self,+        batch: int,+        block_table: torch.Tensor,+        kv_lens: list[int],+        mask: torch.Tensor | None,+    ) -> torch.Tensor:+        """One decode step for `batch` lanes. Returns logits [batch, vocab].++        When `mask` is supplied, `kv_lens` is the baked bucket ceiling and the+        mask carries the true per-sequence lengths.+        """+        cfg = self.cfg+        tokens = self.d_tokens[:batch]+        positions = self.d_pos[:batch]+        slots = self.d_slots[:batch]++        x = self.embed.index_select(0, tokens)+        cos = self.cos.index_select(0, positions).view(batch, 1, 1, cfg.head_dim)+        sin = self.sin.index_select(0, positions).view(batch, 1, 1, cfg.head_dim)++        res = x+        pending = None+        for i, ly in enumerate(self.layers):+            if pending is None:+                h = RMS(res, ly.n_in, cfg.rms_eps)[0]+            else:+                h, _, res = ADD_RMS(res, pending, ly.n_in, cfg.rms_eps)++            qkv = torch.nn.functional.linear(h, ly.wqkv)+            q, k, v = qkv.split([cfg.q_size, cfg.kv_size, cfg.kv_size], dim=-1)+            q = RMS(q.view(batch, cfg.num_heads, cfg.head_dim).contiguous(), ly.q_norm, cfg.rms_eps)[0]+            k = RMS(k.view(batch, cfg.num_kv_heads, cfg.head_dim).contiguous(), ly.k_norm, cfg.rms_eps)[0]+            q = ROTARY(q.view(batch, 1, cfg.num_heads, cfg.head_dim), cos, sin, "half", None)+            k = ROTARY(k.view(batch, 1, cfg.num_kv_heads, cfg.head_dim), cos, sin, "half", None)++            self.k_flat[i].index_copy_(0, slots, k.reshape(batch, cfg.kv_size))+            self.v_flat[i].index_copy_(0, slots, v.reshape(batch, cfg.kv_size))++            attn = FIA(+                q.view(batch, 1, cfg.q_size),+                self.k_cache[i],+                self.v_cache[i],+                num_heads=cfg.num_heads,+                num_key_value_heads=cfg.num_kv_heads,+                input_layout="BSH",+                scale=cfg.scale,+                block_table=block_table,+                block_size=BLOCK_SIZE,+                actual_seq_lengths_kv=kv_lens,+                atten_mask=mask,+            )[0]+            attn_out = torch.nn.functional.linear(attn.view(batch, cfg.q_size), ly.wo)++            h2, _, res = ADD_RMS(res, attn_out, ly.n_post, cfg.rms_eps)+            gu = torch.nn.functional.linear(h2, ly.wgu)+            pending = torch.nn.functional.linear(SWIGLU(gu, -1), ly.wd)++        hidden = ADD_RMS(res, pending, self.norm_f, cfg.rms_eps)[0]+        return torch.nn.functional.linear(hidden, self.lm_head)++    def _graph_mask(self, batch: int, kv_bucket: int) -> torch.Tensor:+        """True where a position is past that lane's real KV length."""+        lengths = self.d_kvlen[:batch].view(batch, 1, 1, 1)+        return self.arange_kv[:kv_bucket].view(1, 1, 1, kv_bucket) >= lengths++    def kv_bucket_for(self, max_kv: int) -> int | None:+        bucket = ((max_kv + KV_BUCKET_STEP - 1) // KV_BUCKET_STEP) * KV_BUCKET_STEP+        return bucket if bucket <= self.max_graph_kv else None++    def batch_bucket_for(self, batch: int) -> int | None:+        for candidate in BATCH_BUCKETS:+            if candidate >= batch:+                return candidate+        return None++    def capture_decode_graphs(self) -> int:+        """Pre-capture one graph per (batch bucket, KV bucket) shape."""+        if not self.enable_graphs:+            return 0+        kv_buckets = [+            b for b in range(KV_BUCKET_STEP, self.max_graph_kv + 1, KV_BUCKET_STEP)+        ]+        # Warm the allocator and kernel caches on a side stream before capture.+        side = torch.npu.Stream(device=self.device)+        side.wait_stream(torch.npu.current_stream())+        with torch.npu.stream(side):+            for _ in range(3):+                self.d_kvlen[: BATCH_BUCKETS[-1]].fill_(1)+                bt = self.d_bt[: BATCH_BUCKETS[-1], : kv_buckets[0] // BLOCK_SIZE]+                self._decode_body(+                    BATCH_BUCKETS[-1],+                    bt,+                    [kv_buckets[0]] * BATCH_BUCKETS[-1],+                    self._graph_mask(BATCH_BUCKETS[-1], kv_buckets[0]),+                )+        torch.npu.current_stream().wait_stream(side)+        torch.npu.synchronize()++        captured = 0+        for kv_bucket in kv_buckets:+            blocks = kv_bucket // BLOCK_SIZE+            for batch in BATCH_BUCKETS:+                if batch > self.max_batch:+                    continue+                self.d_kvlen[:batch].fill_(1)+                block_table = self.d_bt[:batch, :blocks]+                graph = torch.npu.NPUGraph()+                try:+                    with torch.npu.graph(graph, pool=self._graph_pool):+                        logits = self._decode_body(+                            batch,+                            block_table,+                            [kv_bucket] * batch,+                            self._graph_mask(batch, kv_bucket),+                        )+                        out = torch.argmax(logits, dim=-1)+                        self.d_next[:batch].copy_(out)+                except Exception:+                    # Any unsupported shape simply stays on the eager path.+                    continue+                self._graphs[(batch, kv_bucket)] = graph+                captured += 1+        torch.npu.synchronize()+        return captured++    @torch.inference_mode()+    def decode_step(self, batch: int, max_blocks: int, kv_lens: list[int]) -> list[int]:+        """Advance `batch` sequences by one token; returns the chosen token ids."""+        max_kv = max(kv_lens)+        kv_bucket = self.kv_bucket_for(max_kv)+        batch_bucket = self.batch_bucket_for(batch)+        graph = None+        if kv_bucket is not None and batch_bucket is not None:+            graph = self._graphs.get((batch_bucket, kv_bucket))++        if graph is not None:+            # Pad the tail lanes onto the reserved block 0 with length 1 so the+            # softmax of an unused lane is well defined and touches no live KV.+            if batch_bucket > batch:+                # Idle lanes point at reserved block 0 with length 1, so their+                # softmax is well defined and reads no live sequence's KV.+                self._kvlen_host[batch:batch_bucket] = 1+                self._tokens_host[batch:batch_bucket] = 0+                self._pos_host[batch:batch_bucket] = 0+                self._slots_host[batch:batch_bucket] = 0+                self._bt_host[batch:batch_bucket, : kv_bucket // BLOCK_SIZE] = 0+            self._kvlen_host[:batch] = kv_lens+            n = batch_bucket+            blocks = kv_bucket // BLOCK_SIZE+            self.d_tokens[:n].copy_(self.h_tokens[:n], non_blocking=True)+            self.d_pos[:n].copy_(self.h_pos[:n], non_blocking=True)+            self.d_slots[:n].copy_(self.h_slots[:n], non_blocking=True)+            self.d_kvlen[:n].copy_(self.h_kvlen[:n], non_blocking=True)+            self.d_bt[:n, :blocks].copy_(self.h_bt[:n, :blocks], non_blocking=True)+            graph.replay()+            return self.d_next[:batch].to("cpu", non_blocking=False).tolist()++        # Eager fallback: exact lengths, no mask needed.+        self.d_tokens[:batch].copy_(self.h_tokens[:batch], non_blocking=True)+        self.d_pos[:batch].copy_(self.h_pos[:batch], non_blocking=True)+        self.d_slots[:batch].copy_(self.h_slots[:batch], non_blocking=True)+        self.d_bt[:batch, :max_blocks].copy_(self.h_bt[:batch, :max_blocks], non_blocking=True)+        logits = self._decode_body(+            batch, self.d_bt[:batch, :max_blocks], kv_lens, None+        )+        return torch.argmax(logits, dim=-1).to("cpu").tolist()diff --git a/solution/qwensrv/server.py b/solution/qwensrv/server.pynew file mode 100644index 0000000000000000000000000000000000000000..9843e7409552575adf56a13329e308d58d1d1efe--- /dev/null+++ b/solution/qwensrv/server.py@@ -0,0 +1,398 @@+"""OpenAI-compatible HTTP front end for the Qwen3-8B NPU engine."""+from __future__ import annotations++import asyncio+import json+import os+import signal+import sys+import time+import uuid+from collections.abc import Mapping, Sequence+from typing import Any++import orjson+import uvicorn+from starlette.applications import Starlette+from starlette.requests import Request as HTTPRequest+from starlette.responses import JSONResponse, Response, StreamingResponse+from starlette.routing import Route++from .detok import IncrementalDetokenizer, build_token_bytes+from .engine import Engine, Request as EngineRequest++SERVED_MODEL = os.environ.get("OPENBUILD_SERVED_MODEL", "Qwen/Qwen3-8B")+MODEL_PATH = os.environ.get("OPENBUILD_MODEL_PATH") or ""+TOKENIZER_PATH = os.environ.get("OPENBUILD_TOKENIZER_PATH") or MODEL_PATH+HOST = os.environ.get("OPENBUILD_HOST", "127.0.0.1")+PORT = int(os.environ.get("OPENBUILD_PORT", "8000"))++STATE: dict[str, Any] = {}+++class ORJSONResponse(JSONResponse):+    media_type = "application/json"++    def render(self, content: Any) -> bytes:+        return orjson.dumps(content)+++def _error(message: str, status: int = 400, kind: str = "invalid_request_error") -> Response:+    return ORJSONResponse({"error": {"message": message, "type": kind}}, status_code=status)+++def _as_text(content: Any) -> str:+    """Accept both the plain string and the typed-parts content forms."""+    if isinstance(content, str):+        return content+    if isinstance(content, list):+        parts = []+        for item in content:+            if isinstance(item, str):+                parts.append(item)+            elif isinstance(item, dict):+                if isinstance(item.get("text"), str):+                    parts.append(item["text"])+        return "".join(parts)+    if content is None:+        return ""+    return str(content)+++def _normalise_messages(raw: Any) -> list[dict[str, str]] | None:+    if not isinstance(raw, list) or not raw:+        return None+    messages: list[dict[str, str]] = []+    for item in raw:+        if not isinstance(item, dict):+            return None+        role = item.get("role")+        if not isinstance(role, str):+            return None+        message: dict[str, str] = {"role": role, "content": _as_text(item.get("content"))}+        if isinstance(item.get("reasoning_content"), str):+            message["reasoning_content"] = item["reasoning_content"]+        messages.append(message)+    return messages+++def _encode_prompt(messages: list[dict[str, str]]) -> list[int]:+    """Encode via the model's own chat template.++    BatchEncoding is a Mapping but not a dict subclass, so the unwrap has to test+    against collections.abc.Mapping; the batch dimension is likewise unwrapped by+    Sequence test. This mirrors the reference tokenisation exactly, which is what+    prompt_tokens accounting is compared against.+    """+    tokenizer = STATE["tokenizer"]+    encoded = tokenizer.apply_chat_template(+        messages, tokenize=True, add_generation_prompt=True+    )+    if isinstance(encoded, Mapping):+        encoded = encoded.get("input_ids")+    if isinstance(encoded, (str, bytes)) or not isinstance(encoded, Sequence):+        raise ValueError("chat template did not return token ids")+    if encoded and isinstance(encoded[0], Sequence):+        if len(encoded) != 1:+            raise ValueError("chat template returned more than one prompt")+        encoded = encoded[0]+    return [int(t) for t in encoded]+++def _int_field(body: dict[str, Any], *names: str) -> int | None:+    for name in names:+        value = body.get(name)+        if value is None or isinstance(value, bool):+            continue+        if isinstance(value, int):+            return value+        if isinstance(value, float) and value.is_integer():+            return int(value)+    return None+++async def list_models(_: HTTPRequest) -> Response:+    return ORJSONResponse(+        {+            "object": "list",+            "data": [+                {+                    "id": SERVED_MODEL,+                    "object": "model",+                    "created": STATE["created"],+                    "owned_by": "openbuild",+                    "root": SERVED_MODEL,+                    "permission": [],+                }+            ],+        }+    )+++async def health(_: HTTPRequest) -> Response:+    return ORJSONResponse({"status": "ok", "model": SERVED_MODEL})+++def _stop_token_ids(body: dict[str, Any]) -> set[int]:+    out: set[int] = set()+    raw = body.get("stop_token_ids")+    if isinstance(raw, list):+        for item in raw:+            if isinstance(item, int) and not isinstance(item, bool):+                out.add(int(item))+    return out+++async def chat_completions(http_request: HTTPRequest) -> Response:+    try:+        body = orjson.loads(await http_request.body())+    except Exception:+        return _error("request body is not valid JSON")+    if not isinstance(body, dict):+        return _error("request body must be a JSON object")++    messages = _normalise_messages(body.get("messages"))+    if messages is None:+        return _error("messages must be a non-empty array of message objects")++    engine: Engine = STATE["engine"]+    model = body.get("model")+    if model is not None and not isinstance(model, str):+        return _error("model must be a string")++    try:+        prompt_ids = _encode_prompt(messages)+    except Exception as exc:  # noqa: BLE001+        return _error(f"could not apply the chat template: {type(exc).__name__}")++    max_context = engine.max_context()+    if len(prompt_ids) >= max_context:+        return _error(+            f"prompt is {len(prompt_ids)} tokens, which exceeds the {max_context}-token context",+            status=400,+            kind="context_length_exceeded",+        )++    requested = _int_field(body, "max_completion_tokens", "max_tokens")+    room = max_context - len(prompt_ids)+    # An unspecified limit still needs a bounded KV reservation.+    default_new = min(room, 2048)+    max_new = default_new if requested is None else max(1, min(int(requested), room))++    ignore_eos = bool(body.get("ignore_eos", False))+    stream = bool(body.get("stream", False))+    stream_options = body.get("stream_options") or {}+    include_usage = bool(+        stream_options.get("include_usage", False) if isinstance(stream_options, dict) else False+    )++    loop = asyncio.get_running_loop()+    queue: asyncio.Queue = asyncio.Queue()++    def on_event(event: dict[str, Any]) -> None:+        loop.call_soon_threadsafe(queue.put_nowait, event)++    request = EngineRequest(+        rid=f"chatcmpl-{uuid.uuid4().hex}",+        prompt_ids=prompt_ids,+        max_new_tokens=max_new,+        ignore_eos=ignore_eos,+        eos_ids=set(engine.cfg.eos_token_ids),+        stop_token_ids=_stop_token_ids(body),+        on_event=on_event,+    )+    engine.submit(request)++    created = int(time.time())+    detok = IncrementalDetokenizer(STATE["token_bytes"])+    prompt_tokens = len(prompt_ids)++    if not stream:+        pieces: list[str] = []+        completion_tokens = 0+        reason = "stop"+        while True:+            event = await queue.get()+            kind = event["type"]+            if kind == "token":+                completion_tokens += 1+                if event["visible"]:+                    pieces.append(detok.push(event["token"]))+            elif kind == "error":+                return _error(event["message"], status=500, kind="internal_error")+            else:+                reason = event["reason"]+                break+        pieces.append(detok.flush())+        if reason == "abort":+            return _error("request was aborted", status=500, kind="internal_error")+        return ORJSONResponse(+            {+                "id": request.rid,+                "object": "chat.completion",+                "created": created,+                "model": SERVED_MODEL,+                "choices": [+                    {+                        "index": 0,+                        "message": {"role": "assistant", "content": "".join(pieces)},+                        "logprobs": None,+                        "finish_reason": reason,+                    }+                ],+                "usage": {+                    "prompt_tokens": prompt_tokens,+                    "completion_tokens": completion_tokens,+                    "total_tokens": prompt_tokens + completion_tokens,+                },+            }+        )++    async def sse():+        completion_tokens = 0+        reason = "stop"+        head = {+            "id": request.rid,+            "object": "chat.completion.chunk",+            "created": created,+            "model": SERVED_MODEL,+            "choices": [+                {"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}+            ],+        }+        yield b"data: " + orjson.dumps(head) + b"\n\n"+        try:+            while True:+                event = await queue.get()+                kind = event["type"]+                if kind == "token":+                    completion_tokens += 1+                    if event["visible"]:+                        text = detok.push(event["token"])+                        if text:+                            chunk = {+                                "id": request.rid,+                                "object": "chat.completion.chunk",+                                "created": created,+                                "model": SERVED_MODEL,+                                "choices": [+                                    {"index": 0, "delta": {"content": text}, "finish_reason": None}+                                ],+                            }+                            yield b"data: " + orjson.dumps(chunk) + b"\n\n"+                elif kind == "error":+                    payload = {"error": {"message": event["message"], "type": "internal_error"}}+                    yield b"data: " + orjson.dumps(payload) + b"\n\n"+                    yield b"data: [DONE]\n\n"+                    return+                else:+                    reason = event["reason"]+                    break+            tail = detok.flush()+            if tail:+                chunk = {+                    "id": request.rid,+                    "object": "chat.completion.chunk",+                    "created": created,+                    "model": SERVED_MODEL,+                    "choices": [+                        {"index": 0, "delta": {"content": tail}, "finish_reason": None}+                    ],+                }+                yield b"data: " + orjson.dumps(chunk) + b"\n\n"+            final = {+                "id": request.rid,+                "object": "chat.completion.chunk",+                "created": created,+                "model": SERVED_MODEL,+                "choices": [{"index": 0, "delta": {}, "finish_reason": reason}],+            }+            yield b"data: " + orjson.dumps(final) + b"\n\n"+            if include_usage:+                usage = {+                    "id": request.rid,+                    "object": "chat.completion.chunk",+                    "created": created,+                    "model": SERVED_MODEL,+                    "choices": [],+                    "usage": {+                        "prompt_tokens": prompt_tokens,+                        "completion_tokens": completion_tokens,+                        "total_tokens": prompt_tokens + completion_tokens,+                    },+                }+                yield b"data: " + orjson.dumps(usage) + b"\n\n"+            yield b"data: [DONE]\n\n"+        finally:+            request.aborted = True++    return StreamingResponse(+        sse(),+        media_type="text/event-stream",+        headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},+    )+++def build_app() -> Starlette:+    return Starlette(+        routes=[+            Route("/v1/models", list_models, methods=["GET"]),+            Route("/health", health, methods=["GET"]),+            Route("/v1/chat/completions", chat_completions, methods=["POST"]),+        ]+    )+++def main() -> int:+    if not MODEL_PATH:+        print("OPENBUILD_MODEL_PATH is required", file=sys.stderr)+        return 2+    started = time.time()+    from transformers import AutoTokenizer++    tokenizer = AutoTokenizer.from_pretrained(+        TOKENIZER_PATH, local_files_only=True, trust_remote_code=False+    )+    STATE["tokenizer"] = tokenizer+    STATE["token_bytes"] = build_token_bytes(tokenizer)+    STATE["created"] = int(time.time())++    engine = Engine(MODEL_PATH)+    STATE["engine"] = engine+    engine.start()+    print(+        f"qwensrv ready model={SERVED_MODEL} kv_blocks={engine.runner.num_blocks} "+        f"max_batch={engine.max_batch} graphs={engine.graphs_captured} "+        f"load_s={time.time() - started:.1f}",+        flush=True,+    )++    # httptools is the faster parser but is not guaranteed present in the base+    # runtime; fall back to the pure-Python h11 parser when it is missing.+    try:+        import httptools  # noqa: F401++        http_impl = "httptools"+    except ImportError:+        http_impl = "h11"++    config = uvicorn.Config(+        build_app(),+        host=HOST,+        port=PORT,+        log_level="warning",+        access_log=False,+        loop="uvloop",+        http=http_impl,+        timeout_keep_alive=600,+    )+    server = uvicorn.Server(config)+    try:+        server.run()+    finally:+        engine.stop()+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())