GLM-5.3 · Serving

S13 · Serving build

Measurement failed

OpenBuild Qwen3-8B serving 1dev · Open Build

—PERFORMANCE RATIO
155TOOL 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 agentGLM-5.3 · 155 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
72Inspect
45Edit
4Validate
17Execute
10Profile
7Other

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 timeline105 groups · 155 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 · Task requirements

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

    1 call · #0001–#0001

    ls <path> <n> > <path>echo <flag>find <path> -maxdepth <n> -name <val> -o -maxdepth <n> -name <val> <n> <args>head -n <n>
  2. Inspect · Source & workspace

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

    3 calls · #0002–#0004

    ls -l -a <path> <n> > <path>head -n <n>ls -l -a <path> <path>echo <val>cat <path>env
    1 more command sketches
    grep -i -E <val>
  3. Inspect · Task requirements

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

    2 calls · #0005–#0006

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

    Requested file and log inspection related to source & workspace.

    3 calls · #0007–#0009

    cat <path>cd <path>wc -l <path>echo <val>
  5. Inspect · Benchmark & validation setup

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

    2 calls · #0010–#0011

    cd <path>echo <val>cat <path>ls -l -a <path>wc -l <path>
  6. Other · Task requirements

    1 tool error

    Requested file and log inspection related to task requirements.

    1 call · #0012–#0012

    cd <path>wc -c <val> <path> <n> > <path>
  7. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    3 calls · #0013–#0015

    cd <path>cat <val>echo <val>head -n <n>
  8. Inspect · Source & workspace

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

    7 calls · #0016–#0022

    Read <path>python3 -c <script> <n> >& <path>tail -n <n>
  9. Inspect · Attention kernels

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

    1 call · #0023–#0023

    python3 -c <script>echo <flag>echo <val>ls <path> <n> > <path>
  10. Inspect · Source & workspace

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

    2 calls · #0024–#0025

    ls -l -a <path>echo <val>cat <path>cd <path>
  11. Validate · Task requirements

    Requested task coordination related to task requirements.

    1 call · #0026–#0026

    Create task <task>
  12. Execute · Benchmark & validation setup

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

    1 call · #0027–#0027

    cd <path>wc -l <path> <path> <path>python3 -c <script>
  13. Inspect · Source & workspace

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

    1 call · #0028–#0028

    cd <path>grep -n <val> <path>head -n <n>
  14. Inspect · Benchmark & validation setup

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

    1 call · #0029–#0029

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

    Requested file and log inspection related to source & workspace.

    1 call · #0030–#0030

    sed -n <val> <path>
  16. Inspect · Benchmark & validation setup

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

    3 calls · #0031–#0033

    cat <path>cd <path>grep -n <val> <path> <path>head -n <n>echo <flag>sed -n <val> <path>
  17. Execute · Benchmark & validation setup

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

    1 call · #0034–#0034

    cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  18. Inspect · Source & workspace

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

    1 call · #0035–#0035

    python3 -c <script> <n> >& <path>grep -v <val>tail -n <n>
  19. Inspect · Attention kernels

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

    4 calls · #0036–#0039

    python3 - <script>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  20. Execute · Benchmark & validation setup

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

    1 call · #0040–#0040

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  21. Inspect · Attention kernels

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

    2 calls · #0041–#0042

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  22. Inspect · Source & workspace

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

    2 calls · #0043–#0044

    python3 -c <script>cat <path>mkdir -p <path>ls -l -a <path>
  23. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0045–#0047

    Write <path>
  24. Inspect · Attention kernels

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

    2 calls · #0048–#0049

    python3 - <script>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  25. Edit · Source & workspace

    Requested code edits related to source & workspace.

    4 calls · #0050–#0053

    Write <path>Edit <path>
  26. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0054–#0054

    Write <path>
  27. Edit · Task requirements

    Requested code edits related to task requirements.

    1 call · #0055–#0055

    Write <path>
  28. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0056–#0057

    Write <path>
  29. Edit · Runtime processes

    Requested code edits related to runtime processes.

    2 calls · #0058–#0059

    Write <path>
  30. Edit · Source & workspace

    Requested code edits related to source & workspace.

    4 calls · #0060–#0063

    Write <path>Edit <path>
  31. Edit · Runtime processes

    Requested code edits related to runtime processes.

    3 calls · #0064–#0066

    Edit <path>
  32. Profile · Attention kernels

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

    1 call · #0067–#0067

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  33. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0068–#0069

    Edit <path>
  34. Inspect · Source & workspace

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

    1 call · #0070–#0070

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  35. Profile · Attention kernels

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

    1 call · #0071–#0071

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  36. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0072–#0072

    Edit <path>
  37. Edit · Benchmark & validation setup

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

    1 call · #0073–#0073

    cd <path>sed -i <val> <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  38. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0074–#0074

    date -u <val>python3 -c <script>
  39. Profile · Attention kernels

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

    1 call · #0075–#0075

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  40. Execute · Runtime processes

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

    1 call · #0076–#0076

    cd <path>export <vars><command> <args>sleep <n>tail -n <n> <path>echo <val>
    2 more command sketches
    curl -s -m <n> <url>head -c <n>
  41. Inspect · Task requirements

    1 tool error

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

    1 call · #0077–#0077

    cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>tail -n <n>
  42. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0078–#0078

    tail -n <n> <path>
  43. Inspect · Attention kernels

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

    1 call · #0079–#0079

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  44. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0080–#0080

    Edit <path>
  45. Execute · Runtime processes

    1 tool error

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

    1 call · #0081–#0081

    pkill -f <path> <n> > <path>sleep <n>export <vars><command> <args>timeout <n> <val> <path> <n> >& <path>tail -n <n>
  46. Inspect · Source & workspace

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

    2 calls · #0082–#0083

    tail -n <n> <path>echo <val>timeout <n> <val> <path> <n> >& <path>tail -n <n>grep -n <val> <path>head -n <n>
    2 more command sketches
    echo <flag>sed -n <val> <path>
  47. Execute · Runtime processes

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

    1 call · #0084–#0084

    export <vars><command> <args>sleep <n>tail -n <n> <path>echo <val>timeout <n> <val> <path> <n> >& <path>
    1 more command sketches
    tail -n <n>
  48. Inspect · Source & workspace

    1 tool error

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

    1 call · #0085–#0085

    sleep <n>tail -n <n> <path>echo <val>timeout <n> <val> <path> <n> >& <path>tail -n <n>
  49. Inspect · Runtime processes

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

    2 calls · #0086–#0087

    grep -v <val> <path>sed -n <val>tr -s <val> <val> < <path>head -n <n>echo <val>ps <val>
    1 more command sketches
    grep -c <val>
  50. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0088–#0089

    Edit <path>
  51. Inspect · Runtime processes

    1 tool error

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

    1 call · #0090–#0090

    pkill -f <path>sleep <n>export <vars><command> <args>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>
    1 more command sketches
    tail -n <n>
  52. Inspect · Source & workspace

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

    1 call · #0091–#0091

    timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>echo <val>tr -s <val> <val> < <path>
  53. Execute · Runtime processes

    1 tool error

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

    1 call · #0092–#0092

    pkill -f <path>sleep <n>export <vars><command> <args>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>
    1 more command sketches
    tail -n <n>
  54. Inspect · Source & workspace

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

    1 call · #0093–#0093

    timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  55. Inspect · Runtime processes

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

    1 call · #0094–#0094

    ps <val>grep -v <val>grep <val>head -n <n>echo <flag>tr -s <val> <val> < <path>
  56. Other · Runtime processes

    1 tool error

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

    1 call · #0095–#0095

    pkill <flag> <args>sleep <n>ps <val>grep -v <val>grep -c <val><command> <args>
    2 more command sketches
    grep <n>echo <val>
  57. Execute · Runtime processes

    Requested file and log inspection, workspace file updates and execution waits related to runtime processes.

    1 call · #0096–#0096

    cat > <path> <script>chmod <val> <path><command> <args>sleep <n>tr -s <val> <val> < <path>tail -n <n>
    3 more command sketches
    echo <val>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>
  58. Inspect · Runtime processes

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

    1 call · #0097–#0097

    ps <val>grep -v <val>grep <val>headecho <flag>head -c <n> <path>
  59. Inspect · Source & workspace

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

    1 call · #0098–#0098

    sleep <n>tr -s <val> <val> < <path>tail -n <n>echo <val>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>
  60. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0099–#0099

    Edit <path>
  61. Execute · Runtime processes

    1 tool error

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

    1 call · #0100–#0100

    cat > <path> <script>chmod <val> <path>bash <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  62. Inspect · Source & workspace

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

    1 call · #0101–#0101

    env <vars> bash <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  63. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0102–#0102

    Edit <path>
  64. Inspect · Source & workspace

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

    2 calls · #0103–#0104

    sed -n <val> <path>grep -n <val> <path>bash <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  65. Profile · Attention kernels

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

    1 call · #0105–#0105

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  66. Inspect · Attention kernels

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

    2 calls · #0106–#0107

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>head -n <n>echo <val>tail -n <n>
    1 more command sketches
    env <vars> timeout <n> <val> <path> <n> >& <path>
  67. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0108–#0108

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

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

    1 call · #0109–#0109

    cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  69. Edit · Benchmark & validation setup

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

    1 call · #0110–#0110

    sed -i <val> <path>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  70. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0111–#0112

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

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

    1 call · #0113–#0113

    cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  72. Profile · Attention kernels

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

    1 call · #0114–#0114

    env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  73. Execute · Benchmark & validation setup

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

    1 call · #0115–#0115

    cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  74. Profile · Attention kernels

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

    1 call · #0116–#0116

    cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  75. Inspect · Source & workspace

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

    1 call · #0117–#0117

    cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  76. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0118–#0118

    Edit <path>
  77. Other · Batching & scheduling

    Requested script or workload execution and source searches related to batching & scheduling.

    1 call · #0119–#0119

    cd <path>python3 - <script>grep -n <val> <path>
  78. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0120–#0120

    sed -n <val> <path>
  79. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0121–#0122

    Edit <path>
  80. Profile · Benchmark & validation setup

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

    1 call · #0123–#0123

    cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>grep -E <val>tail -n <n>echo <val>
  81. Execute · Batching & scheduling

    1 tool error

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

    1 call · #0124–#0124

    cat > <path> <script>bash <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  82. Execute · Runtime processes

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

    1 call · #0125–#0125

    bash <script>echo <val>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  83. Inspect · Latency & request handling

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

    1 call · #0126–#0126

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  84. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0127–#0129

    Edit <path>
  85. Inspect · Latency & request handling

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

    1 call · #0130–#0130

    bash <script>echo <val>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  86. Profile · Batching & scheduling

    1 tool error

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

    1 call · #0131–#0131

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  87. Execute · Benchmark & validation setup

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

    2 calls · #0132–#0133

    cd <path>nohup <val> <n> <val> <path> > <path> <n> >& <path>sleep <n>cat <path>tr -s <val> <val>tail -n <n>
  88. Profile · Attention kernels

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

    1 call · #0134–#0134

    cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -E <val>tail -n <n>
  89. Inspect · Batching & scheduling

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

    1 call · #0135–#0135

    cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  90. Edit · Batching & scheduling

    1 tool error

    Requested process termination, execution waits and code edits related to batching & scheduling.

    2 calls · #0136–#0137

    pkill <flag> <args>sleep <n>cd <path>sed -i <path> <path>env <vars> timeout <n> <val> <path> <n> >& <path>grep -E <val>
    1 more command sketches
    tail -n <n>
  91. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0138–#0138

    Edit <path>
  92. Other · Source & workspace

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

    1 call · #0139–#0139

    cd <path>python3 - <script>grep -n <val> <path>
  93. Execute · Runtime processes

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

    1 call · #0140–#0140

    python3 - <script>grep -n <val> <path>
  94. Validate · Benchmark & validation setup

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

    1 call · #0141–#0141

    bash <script>echo <val>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  95. Execute · Benchmark & validation setup

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

    1 call · #0142–#0142

    cd <path>nohup <val> <n> <val> <path> > <path> <n> >& <path>sleep <n>chmod <val> <path> <path>ls -l -a <path>echo <val>
    1 more command sketches
    du <flag> <args>
  96. Inspect · Task requirements

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

    1 call · #0143–#0143

    find <path> -name <val> -type <val> -exec <val> -rf <val> <val> <n> <args>chmod <n> <path> <path> <path> <path>chmod <n> <path> <path>find <path> -type <val> <flag> <args>sortdu <flag> <args>
  97. Other · Source & workspace

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

    1 call · #0144–#0144

    cd <path>export <vars><command> <args>echo <val>echo <flag>bash <script>
  98. Execute · Benchmark & validation setup

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

    1 call · #0145–#0145

    sleep <n>cat <path>tr -s <val> <val>tail -n <n>
  99. Edit · Batching & scheduling

    Requested code edits, source searches and script or workload execution related to batching & scheduling.

    2 calls · #0146–#0147

    cd <path>sed -i <path> <path>grep -n <val> <path>bash <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>
    1 more command sketches
    tail -n <n>
  100. Profile · Batching & scheduling

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

    1 call · #0148–#0148

    cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  101. Inspect · Source & workspace

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

    2 calls · #0149–#0150

    cd <path>python3 - <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>tail -n <n> <path>
  102. Edit · Batching & scheduling

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

    1 call · #0151–#0151

    cd <path>sed -i <path> <path>bash <script>echo <val>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>
    1 more command sketches
    tail -n <n>
  103. Inspect · Task requirements

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

    1 call · #0152–#0152

    cat > <path> <script>timeout <n> <val> <path> <n> >& <path>tr -s <val> <val>tail -n <n>
  104. Inspect · Runtime processes

    1 tool error

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

    2 calls · #0153–#0154

    pkill <flag> <args>sleep <n>ps <val>grep -v <val>grep -c <val>rm -rf <path>
    11 more command sketches
    find <path> -name <val> -type <val> -exec <val> -rf <val> <val> <n> <args>cd <path>git status --shortecho <flag>find <val> -type <val>sortdu <flag> <args>git status --short <n> >& <path>headgrep <val>wc -l
  105. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0155–#0155

    Update task <task>

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 · 9 changed files

Base commit: 8f62ee8f410c38ae7cd90305300afd08f0fdb098

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