Inspect · Source & workspace
Requested workspace inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <val> <n> > <path>ls -l -a <path>MiniMax M3 · Serving
OpenBuild Qwen3-8B serving 1dev · Open Build
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentMiniMax M3 · 293 visible calls
02 / EVENT SEQUENCE
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.
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>.
Requested workspace inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <val> <n> > <path>ls -l -a <path>Requested file and log inspection related to task requirements.
2 calls · #0002–#0003
Read <path>Requested workspace inspection and file and log inspection related to source & workspace.
3 calls · #0004–#0006
ls -l -a <path>echo <flag>ls -l -a <path> <n> > <path>echo <val>cat <path>Requested workspace inspection related to task requirements.
1 call · #0007–#0007
ls <path>echo <flag>Requested file and log inspection related to source & workspace.
1 call · #0008–#0008
cat <path>echo <flag>Requested file and log inspection related to benchmark & validation setup.
1 call · #0009–#0009
cat <path>Requested file and log inspection related to source & workspace.
2 calls · #0010–#0011
cat <path>Requested task coordination related to task requirements.
1 call · #0012–#0012
Create task <task>Requested task coordination related to source & workspace.
1 call · #0013–#0013
Create task <task>Requested task coordination related to task requirements.
1 call · #0014–#0014
Create task <task>Requested task coordination related to batching & scheduling.
1 call · #0015–#0015
Create task <task>Requested task coordination related to benchmark & validation setup.
1 call · #0016–#0016
Create task <task>Requested task coordination related to dependencies & build setup.
1 call · #0017–#0017
Create task <task>Requested task coordination related to source & workspace.
1 call · #0018–#0018
Update task <task>Requested file and log inspection, workspace inspection and script or workload execution related to source & workspace.
2 calls · #0019–#0020
Read <path>ls <path> <n> > <path>echo <flag>python3 -c <script> <n> >& <path>head -n <n>Requested environment setup or inspection, source searches and file and log inspection related to runtime processes.
1 call · #0021–#0021
echo <val>envgrep -i <val> <n> > <path>head -n <n>Requested script or workload execution related to source & workspace.
1 call · #0022–#0022
python3 -c <script> <n> >& <path>echo <flag>Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0023–#0024
find <path> -maxdepth <n> -type <val> -name <val> <n> > <path>echo <flag>find <path> -maxdepth <n> -name <val> <n> > <path>head -n <n>ls -l -a <path>cat <path> <n> > <path>Requested file and log inspection and script or workload execution related to task requirements.
2 calls · #0025–#0026
cat <path>python3 -c <script>head -n <n>Requested file and log inspection related to benchmark & validation setup.
2 calls · #0027–#0028
cat <path>echo <flag>head -n <n>Requested workspace inspection and file and log inspection related to task requirements.
1 call · #0029–#0029
ls <path>echo <flag>cat <path>head -n <n>Requested task coordination and script or workload execution related to source & workspace.
3 calls · #0030–#0032
Update task <task>python3 -c <script>Requested script or workload execution and file and log inspection related to device memory.
2 calls · #0033–#0034
python3 -c <script> <n> >& <path>tail -n <n>timeout <n> <val> -c <path> <n> >& <path>Requested script or workload execution, file and log inspection and workspace inspection related to source & workspace.
8 calls · #0035–#0042
python3 -c <script> <n> >& <path>tail -n <n>python3 -c <script>ls <path>wc -l <path>grep -n <val> <path>head -n <n>Read <path>Requested source searches, file and log inspection and workspace inspection related to attention kernels.
8 calls · #0043–#0050
grep -n <val> <path> <path> <n> > <path>head -n <n>grep -r -n <val> <path> <n> > <path>sed -n <val> <path>echo <flag>ls <path>grep -n <val> <path>cat <path>timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested script or workload execution and file and log inspection related to attention kernels.
1 call · #0051–#0051
timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested file and log inspection related to source & workspace.
1 call · #0052–#0052
Read task output <task>Requested file and log inspection and workspace inspection related to source & workspace.
2 calls · #0053–#0054
cat <path> <n> > <path>tail -n <n>ls -l -a <path> <n> > <path>Requested task coordination related to source & workspace.
3 calls · #0055–#0057
Stop task <task>Update task <task>Requested code edits related to task requirements.
1 call · #0058–#0058
Write <path>Requested code edits related to source & workspace.
1 call · #0059–#0059
Write <path>Requested workspace file updates related to source & workspace.
1 call · #0060–#0060
chmod <val> <path>Requested code edits related to runtime processes.
1 call · #0061–#0061
Write <path>Requested workspace file updates related to runtime processes.
1 call · #0062–#0062
chmod <val> <path>Requested task coordination related to source & workspace.
2 calls · #0063–#0064
Update task <task>Requested source searches, file and log inspection and workspace inspection related to source & workspace.
2 calls · #0065–#0066
grep -r -n <val> <path> <n> > <path>head -n <n>ls <path> <n> > <path>Requested file and log inspection related to attention kernels.
1 call · #0067–#0067
sed -n <val> <path>Requested file and log inspection related to source & workspace.
1 call · #0068–#0068
sed -n <val> <path>Requested code edits related to source & workspace.
1 call · #0069–#0069
Write <path>Requested script or workload execution related to source & workspace.
2 calls · #0070–#0071
python3 -c <script>cd <path>Requested code edits related to source & workspace.
1 call · #0072–#0072
Write <path>Requested script or workload execution related to source & workspace.
1 call · #0073–#0073
python3 -c <script>Requested code edits related to runtime processes.
1 call · #0074–#0074
Write <path>Requested script or workload execution related to runtime processes.
1 call · #0075–#0075
python3 -c <script>Requested script or workload execution, file and log inspection and source searches related to source & workspace.
2 calls · #0076–#0077
cd <path>bash <script> <n> >& <path>tail -n <n>grep -r -n <val> <path>head -n <n>Requested workspace inspection and file and log inspection related to benchmark & validation setup.
1 call · #0078–#0078
find <path> -type <val>headecho <flag>cat <path>find <path> -name <val> -type <val> <n> > <path>Requested workspace inspection, source searches and file and log inspection related to source & workspace.
8 calls · #0079–#0086
find <path> -name <val> -o -name <path> <n> > <path>grep -v <val>grep -v <path>head -n <n>ls <path>ls <path> <n> > <path>echo <flag>find <path> -type <val> <n> > <path>headcat <path> <n> > <path>cat <path>head -n <n> <path> <n> > <path>grep -n <val>find <path> -name <path> <n> > <path>find <path> -name <val> -type <val> <n> > <path>find <path> -type <val> -name <val> -o -name <val> <n> > <path>Requested workspace inspection and file and log inspection related to task requirements.
1 call · #0087–#0087
ls -l -a <path>echo <flag>cat <path>Requested environment setup or inspection and file and log inspection related to device memory.
2 calls · #0088–#0089
env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>cd <path>Requested source searches related to batching & scheduling.
1 call · #0090–#0090
grep -n <val> <path>Requested file and log inspection and source searches related to source & workspace.
3 calls · #0091–#0093
Read <path>wc -l <path>grep -c <val> <path>Requested code edits related to source & workspace.
1 call · #0094–#0094
Edit <path>Requested script or workload execution related to runtime processes.
1 call · #0095–#0095
python3 -c <script>Requested environment setup or inspection and file and log inspection related to device memory.
1 call · #0096–#0096
env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested environment setup or inspection and file and log inspection related to batching & scheduling.
1 call · #0097–#0097
env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested source searches, file and log inspection and script or workload execution related to attention kernels.
7 calls · #0098–#0104
grep -n <val> <path>head -n <n>sed -n <val> <path>python3 -c <script> <n> >& <path>tail -n <n>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0105–#0106
grep -n <val> <path>head -n <n>echo <flag>sed -n <val> <path>Requested script or workload execution and file and log inspection related to attention kernels.
1 call · #0107–#0107
python3 -c <script> <n> >& <path>tail -n <n>Requested script or workload execution and file and log inspection related to attention kernels.
1 call · #0108–#0108
python3 -c <script> <n> >& <path>tail -n <n>Requested code edits related to source & workspace.
1 call · #0109–#0109
Write <path>Requested script or workload execution related to runtime processes.
1 call · #0110–#0110
python3 -c <script>Requested environment setup or inspection and file and log inspection related to batching & scheduling.
1 call · #0111–#0111
env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested code edits related to source & workspace.
1 call · #0112–#0112
Edit <path>Requested environment setup or inspection and file and log inspection related to batching & scheduling.
1 call · #0113–#0113
env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested script or workload execution related to source & workspace.
1 call · #0114–#0114
python3 -c <script>Requested script or workload execution and file and log inspection related to attention kernels.
4 calls · #0115–#0118
python3 -c <script> <n> >& <path>tail -n <n>Requested environment setup or inspection and file and log inspection related to batching & scheduling.
2 calls · #0119–#0120
env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested source searches, file and log inspection and workspace inspection related to attention kernels.
40 calls · #0121–#0160
grep -r -n <val> <path> <n> > <path>echo <flag>grep -r -n <val> <path>headls <path> <n> > <path>env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>grep -n <val> <path>head -n <n>sed -n <val> <path>python3 -c <script> <n> >& <path>grep -n <val> <path> -r <n> > <path>grep -i <val>Requested source searches and file and log inspection related to source & workspace.
1 call · #0161–#0161
grep -n <val> <path>head -n <n>Requested source searches, file and log inspection and environment setup or inspection related to attention kernels.
14 calls · #0162–#0175
grep -n <val> <path>head -n <n>sed -n <val> <path>env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>python3 -c <script> <n> >& <path>Requested task coordination related to source & workspace.
1 call · #0176–#0176
Update task <task>Requested code edits related to source & workspace.
1 call · #0177–#0177
Write <path>Requested script or workload execution related to source & workspace.
1 call · #0178–#0178
python3 -c <script>Requested environment setup or inspection and file and log inspection related to batching & scheduling.
1 call · #0179–#0179
env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested script or workload execution, workspace file updates and environment setup or inspection related to runtime processes.
3 calls · #0180–#0182
python3 -c <script>cd <path>rm -f <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <path>sleep <n>echo <flag>tail -n <n> <path>curl -s -m <n> <url> <n> >& <path>Requested service requests and file and log inspection related to source & workspace.
4 calls · #0183–#0186
curl -s -m <n> <url> <n> >& <path>curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>head -n <n>tail -n <n>Requested task coordination related to source & workspace.
2 calls · #0187–#0188
Update task <task>Requested script or workload execution and execution waits related to source & workspace.
1 call · #0189–#0189
echo <val><command> <args>python3 -c <script>waitRequested process termination, execution waits and runtime inspection related to runtime processes.
1 call · #0190–#0190
kill <val> <path> <n> > <path>sleep <n>ps <flag>grep -i <path>grep -v <val>Requested workspace file updates, environment setup or inspection and file and log inspection related to runtime processes.
2 calls · #0191–#0192
cd <path>rm -rf <path>env <vars> bash <script> <n> >& <path>tail -n <n>echo <flag>Requested file and log inspection and workspace inspection related to source & workspace.
3 calls · #0193–#0195
cat <path> <n> > <path>head -n <n>echo <flag>headls <path>ls <path> <n> > <path>cat <path>Requested workspace file updates, environment setup or inspection and file and log inspection related to benchmark & validation setup.
3 calls · #0196–#0198
mkdir -p <path> <n> > <path>env <vars> bash <script> <n> >& <path>tail -n <n>Requested task coordination related to source & workspace.
2 calls · #0199–#0200
Update task <task>Requested environment setup or inspection and file and log inspection related to benchmark & validation setup.
1 call · #0201–#0201
env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0202–#0202
ls -l -a <path>tail -n <n>echo <flag>tail -n <n> <path> <n> > <path>head -n <n>cat <path> <n> > <path>Requested file and log inspection related to batching & scheduling.
2 calls · #0203–#0204
cat <path>echo <flag>head -n <n> <path>cat <path> <n> > <path>head -n <n>Requested tool activity related to source & workspace.
1 call · #0205–#0205
shell <script>Requested workspace file updates, environment setup or inspection and execution waits related to runtime processes.
1 call · #0206–#0206
rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <path>sleep <n>tail -n <n> <path>Requested execution waits and service requests related to source & workspace.
1 call · #0207–#0207
sleep <n>curl -s -m <n> <url>Requested file and log inspection related to benchmark & validation setup.
1 call · #0208–#0208
cat > <path> <script>Requested code edits related to source & workspace.
1 call · #0209–#0209
Write <path>Requested dependency and build commands, file and log inspection and script or workload execution related to dependencies & build setup.
1 call · #0210–#0210
pip install <val> <n> >& <path>tail -n <n>python3 <script>Requested script or workload execution and file and log inspection related to attention kernels.
5 calls · #0211–#0215
timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested code edits related to source & workspace.
1 call · #0216–#0216
Write <path>Requested script or workload execution related to source & workspace.
1 call · #0217–#0217
python3 -c <script>Requested process termination, execution waits and runtime inspection related to runtime processes.
1 call · #0218–#0218
kill <val> <path> <n> > <path>sleep <n>ps <flag>grep <path>grep -v <val>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <flag>tail -n <n> <path>curl -s -m <n> <url>Requested service requests related to source & workspace.
1 call · #0219–#0219
curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>Requested file and log inspection related to source & workspace.
1 call · #0220–#0220
tail -n <n> <path>Requested file and log inspection related to runtime processes.
1 call · #0221–#0221
Read <path>Requested code edits related to runtime processes.
1 call · #0222–#0222
Edit <path>Requested process termination, execution waits and workspace file updates related to runtime processes.
1 call · #0223–#0223
kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <flag>curl -s -m <n> <url>tail -n <n> <path>Requested service requests related to source & workspace.
1 call · #0224–#0224
curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>Requested file and log inspection and source searches related to source & workspace.
2 calls · #0225–#0226
tail -n <n> <path>grep -E <val>head -n <n>grep -B <n> -A <n> <val>Requested code edits related to runtime processes.
1 call · #0227–#0227
Edit <path>Requested process termination, execution waits and workspace file updates related to runtime processes.
1 call · #0228–#0228
kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>Requested service requests related to source & workspace.
1 call · #0229–#0229
curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>Requested source searches and file and log inspection related to runtime processes.
1 call · #0230–#0230
grep -n <val> <path>headRequested file and log inspection and script or workload execution related to benchmark & validation setup.
1 call · #0231–#0231
cat > <path> <script>python3 <script>Requested file and log inspection related to runtime processes.
2 calls · #0232–#0233
Read <path>Requested service requests and file and log inspection related to source & workspace.
1 call · #0234–#0234
curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>tail -n <n>Requested service requests, file and log inspection and source searches related to source & workspace.
2 calls · #0235–#0236
curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>wc -lgrep -c <val>Requested code edits related to source & workspace.
1 call · #0237–#0237
Edit <path>Requested process termination, execution waits and workspace file updates related to runtime processes.
1 call · #0238–#0238
kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>Requested process termination, execution waits and environment setup or inspection related to benchmark & validation setup.
1 call · #0239–#0239
kill <val> <path> <n> > <path>sleep <n>env <vars> bash <script> <n> >& <path>tail -n <n>Requested script or workload execution, file and log inspection and workspace file updates related to benchmark & validation setup.
2 calls · #0240–#0241
timeout <n> <val> <path> <n> >& <path>tail -n <n>rm -rf <path>ls <path>Requested file and log inspection related to batching & scheduling.
1 call · #0242–#0242
cat <path>tail -n <n>echo <flag>tail -n <n> <path>Requested workspace file updates, environment setup or inspection and execution waits related to runtime processes.
1 call · #0243–#0243
rm -rf <path>mkdir -p <path>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>sleep <n>curl -s -m <n> <url>Requested script or workload execution, file and log inspection and process termination related to benchmark & validation setup.
2 calls · #0244–#0245
timeout <n> <val> <path> <n> >& <path>tail -n <n>kill <val> <path> <n> > <path>sleep <n>ps <flag>grep <path>grep -v <val>echo <flag>rm -rf <path>env <vars> timeout <n> <val> <path> <n> >& <path>Requested file and log inspection related to batching & scheduling.
1 call · #0246–#0246
cat <path>tail -n <n>echo <flag>tail -n <n> <path>Requested source searches and file and log inspection related to source & workspace.
6 calls · #0247–#0252
grep -n <val> <path>headecho <flag>sed -n <val> <path>head -n <n>Requested source searches related to runtime processes.
1 call · #0253–#0253
grep -n <val> <path>Requested code edits related to runtime processes.
1 call · #0254–#0254
Edit <path>Requested process termination, execution waits and workspace file updates related to runtime processes.
1 call · #0255–#0255
kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>curl -s -m <n> <url>Requested process termination, execution waits and workspace file updates related to benchmark & validation setup.
3 calls · #0256–#0258
kill <val> <path> <n> > <path>sleep <n>rm -rf <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>echo <val>waitenv <vars> bash <script> <n> >& <path> > <path>echo <val> > <path>echo <path><command> <args>tail -n <n> <path>cat <path>Requested runtime inspection, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0259–#0259
ps <flag>grep -E <val>grep -v <val>headecho <flag>ls <path>head -n <n>wc -lRequested file and log inspection, workspace inspection and runtime inspection related to benchmark & validation setup.
2 calls · #0260–#0261
cat <path> <n> > <path>tail -n <n>echo <flag>ls -l -a <path> <n> > <path>ps <flag>grep -i <val>grep -v <val>head -n <n>grep <path>Requested workspace inspection and file and log inspection related to batching & scheduling.
2 calls · #0262–#0263
ls <path>echo <flag>cat <path>tail -n <n>tail -n <n> <path>Requested runtime inspection, source searches and workspace inspection related to benchmark & validation setup.
1 call · #0264–#0264
ps <flag>grep -E <path>grep -v <val>echo <flag>ls <path>wc -ltail -n <n>Requested file and log inspection, workspace inspection and runtime inspection related to benchmark & validation setup.
4 calls · #0265–#0268
cat <path> <n> > <path>tail -n <n>echo <flag>ls -l -a <path> <n> > <path>dateps <flag>grep <val>grep -v <val><command> <args>ps -p <val> <path> <n> > <path> <n> > <path>rm -rf <path>nohup <val> -c <path> > <path> <n> >& <path>echo <val> > <path>echo <path>sleep <n>tail -n <n> <path>ls <path>wc -lps -p <val> <path> <n> > <path>Requested execution waits, workspace inspection and file and log inspection related to source & workspace.
5 calls · #0269–#0273
sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>dategrep -v <val><command> <args>echo <val>tail -n <n> <val>Requested file and log inspection related to batching & scheduling.
1 call · #0274–#0274
cat <path>head -n <n>echo <flag>Requested execution waits, workspace inspection and file and log inspection related to source & workspace.
1 call · #0275–#0275
sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>dateRequested file and log inspection related to batching & scheduling.
1 call · #0276–#0276
cat <path>tail -n <n>Requested execution waits, workspace inspection and file and log inspection related to source & workspace.
2 calls · #0277–#0278
sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>dateRequested workspace inspection, source searches and file and log inspection related to batching & scheduling.
3 calls · #0279–#0281
ls <path>grep -E <val>headecho <flag>tail -n <n> <path>sleep <n>wc -ltail -n <n>ps -p <val> <path> <n> > <path>datecat <path>Requested execution waits, workspace inspection and file and log inspection related to source & workspace.
1 call · #0282–#0282
sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>dateRequested execution waits, workspace inspection and file and log inspection related to benchmark & validation setup.
1 call · #0283–#0283
sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>dateRequested workspace inspection, file and log inspection and runtime inspection related to source & workspace.
1 call · #0284–#0284
ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>dateRequested file and log inspection related to benchmark & validation setup.
1 call · #0285–#0285
cat <path> <n> > <path>Requested code edits related to source & workspace.
1 call · #0286–#0286
Write <path>Requested script or workload execution related to source & workspace.
1 call · #0287–#0287
python3 -c <script>Requested process termination, execution waits and workspace file updates related to benchmark & validation setup.
1 call · #0288–#0288
kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>python3 -c <script>Requested execution waits, service requests and file and log inspection related to runtime processes.
1 call · #0289–#0289
sleep <n>curl -s -m <n> <url>echo <flag>tail -n <n> <path>Requested code edits related to source & workspace.
1 call · #0290–#0290
Edit <path>Requested process termination, execution waits and workspace file updates related to runtime processes.
1 call · #0291–#0291
kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>python3 -c <script>Requested script or workload execution and file and log inspection related to source & workspace.
1 call · #0292–#0292
python3 <script> <n> >& <path>tail -n <n>Requested process termination, execution waits and workspace file updates related to benchmark & validation setup.
1 call · #0293–#0293
kill <val> <path> <n> > <path>sleep <n>rm -rf <path>nohup <val> -c <path> > <path> <n> >& <path>echo <val> > <path>echo <val>ls <path>wc -ltail -n <n>03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: 8f62ee8f410c38ae7cd90305300afd08f0fdb098
@@ -0,0 +1,63 @@+#!/usr/bin/env bash+# Bootstrap for the Qwen3-8B OpenBuild serving system.+#+# The base runtime already supplies Python, PyTorch, torch_npu, the+# transformers stack, and the read-only Ascend runtime components. This+# script performs only the offline-replayable preparation that the+# serving system needs: verify the runtime, materialize the runtime+# directory, and warm-load the model weights so the actual launch path+# can come up quickly.+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-${SCRIPT_DIR}}"+ENV_DIR="${OPENBUILD_ENV_DIR:-${TASK_HOME:-/tmp}/openbuild-runtime}"++mkdir -p "${ENV_DIR}"+mkdir -p "${ENV_DIR}/logs"++PYTHON_BIN="${PYTHON_BIN:-python3}"+if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then+ echo "[bootstrap] python3 is unavailable" >&2+ exit 1+fi++# Probe the runtime once so we fail fast on a misconfigured host.+"${PYTHON_BIN}" - <<'PY'+import sys, json+try:+ import torch+ import torch_npu+except ImportError as exc:+ print(f"[bootstrap] missing torch/torch_npu: {exc}", file=sys.stderr)+ sys.exit(1)+if not torch.npu.is_available():+ print("[bootstrap] torch.npu.is_available() returned False", file=sys.stderr)+ sys.exit(1)+if torch.npu.device_count() < 1:+ print("[bootstrap] no Ascend devices visible", file=sys.stderr)+ sys.exit(1)+import transformers # noqa: F401+PY++# Validate the model and tokenizer paths.+MODEL_PATH="${OPENBUILD_MODEL_PATH:-}"+TOKENIZER_PATH="${OPENBUILD_TOKENIZER_PATH:-${MODEL_PATH}}"+if [[ -z "${MODEL_PATH}" || ! -d "${MODEL_PATH}" ]]; then+ echo "[bootstrap] OPENBUILD_MODEL_PATH is missing or not a directory" >&2+ exit 1+fi+if [[ ! -f "${MODEL_PATH}/config.json" || ! -f "${MODEL_PATH}/tokenizer.json" ]]; then+ echo "[bootstrap] model projection is missing config.json or tokenizer.json" >&2+ exit 1+fi+if [[ ! -d "${TOKENIZER_PATH}" ]]; then+ echo "[bootstrap] tokenizer projection is not a directory" >&2+ exit 1+fi++echo "[bootstrap] solution_dir=${SOLUTION_DIR}"+echo "[bootstrap] env_dir=${ENV_DIR}"+echo "[bootstrap] model_path=${MODEL_PATH}"+echo "[bootstrap] tokenizer_path=${TOKENIZER_PATH}"+echo "[bootstrap] done"\ No newline at end of file@@ -0,0 +1,382 @@+"""Continuous-batched inference engine for Qwen3-8B on Ascend NPU.++The engine loads the reference transformers Qwen3 model once and then+manages a pool of per-group ``DynamicCache`` instances. Prefill and+decode are both batched across requests sharing identical cache+length, amortising per-token cost.+"""+from __future__ import annotations++import asyncio+import os+import threading+import time+from dataclasses import dataclass, field+from typing import Any, List, Optional++import torch++import torch_npu # noqa: F401+from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer+from transformers.cache_utils import DynamicCache+++class _Sink:+ """Async queue used to deliver decoded tokens to a request."""++ def __init__(self) -> None:+ self.queue: asyncio.Queue = asyncio.Queue(maxsize=8192)++ def push(self, item: Any) -> None:+ try:+ self.queue.put_nowait(item)+ except asyncio.QueueFull:+ pass++ def push_blocking(self, item: Any) -> None:+ try:+ self.queue.put_nowait(item)+ except asyncio.QueueFull:+ pass+++@dataclass+class _Group:+ cache: DynamicCache+ slots: list[Optional[str]]+ prompt_len: int+ length: int = 0++ def alloc(self, request_id: str) -> int:+ for idx, slot in enumerate(self.slots):+ if slot is None:+ self.slots[idx] = request_id+ return idx+ raise RuntimeError("group full")++ def free(self, slot: int) -> None:+ self.slots[slot] = None++ def active_slots(self) -> list[int]:+ return [idx for idx, slot in enumerate(self.slots) if slot is not None]+++@dataclass+class RequestState:+ request_id: str+ group_id: int+ slot: int = -1+ prompt_ids: list[int] = field(default_factory=list)+ prompt_len: int = 0+ last_token: int = 0+ emitted: list[int] = field(default_factory=list)+ max_new_tokens: int = 0+ ignore_eos: bool = False+ eos_token_id: int = 0+ sink: _Sink | None = None+ done: bool = False+ finish_reason: str | None = None+ arrival_time: float = 0.0+ first_token_time: float | None = None+ last_token_time: float | None = None+ error: str | None = None+++class Qwen3Engine:+ """Reference-model backed inference engine."""++ def __init__(self, model_path: str, device: torch.device,+ max_batch: int, max_seq_len: int) -> None:+ self.device = device+ self.max_batch = max_batch+ self.max_seq_len = max_seq_len++ torch.npu.set_device(device)++ self.config = AutoConfig.from_pretrained(model_path, local_files_only=True)+ self.tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)++ self.model = AutoModelForCausalLM.from_pretrained(+ model_path,+ dtype=torch.bfloat16,+ low_cpu_mem_usage=True,+ local_files_only=True,+ attn_implementation="flash_attention_2",+ ).to(device)+ self.model.eval()+ for p in self.model.parameters():+ p.requires_grad_(False)++ self.num_layers = len(self.model.model.layers)+ self.eos_token_id = self.config.eos_token_id if isinstance(+ self.config.eos_token_id, int+ ) else int(self.tokenizer.eos_token_id)++ def encode_messages(self, messages):+ encoded = self.tokenizer.apply_chat_template(+ messages, tokenize=True, add_generation_prompt=True,+ )+ if hasattr(encoded, "input_ids"):+ encoded = encoded["input_ids"]+ if isinstance(encoded, list) and encoded and isinstance(encoded[0], list):+ encoded = encoded[0]+ return list(encoded)+++class AsyncScheduler:+ """Continuous-batched scheduler using one DynamicCache per group."""++ def __init__(self, engine: Qwen3Engine) -> None:+ self.engine = engine+ self._lock = threading.Lock()+ self._active: dict[str, RequestState] = {}+ self._pending: list[RequestState] = []+ self._groups: dict[int, _Group] = {}+ self._next_group_id = 0+ self._wake = threading.Event()+ self._stop = False++ def submit(self, state: RequestState) -> None:+ with self._lock:+ self._pending.append(state)+ self._wake.set()++ def shutdown(self) -> None:+ self._stop = True+ self._wake.set()++ def run(self) -> None:+ torch.npu.set_device(self.engine.device)+ while not self._stop:+ progressed = self._admit_pending()+ progressed |= self._step()+ if not progressed:+ self._wake.wait(timeout=0.002)+ self._wake.clear()+ torch.npu.synchronize()++ # ------------------------------------------------------------------+ def _find_or_make_group(self, prompt_len: int) -> _Group:+ for gid, group in self._groups.items():+ if group.length == prompt_len and len(group.active_slots()) < self.engine.max_batch:+ return group+ gid = self._next_group_id+ self._next_group_id += 1+ cache = DynamicCache()+ slots: list[Optional[str]] = [None] * self.engine.max_batch+ group = _Group(cache=cache, slots=slots, prompt_len=prompt_len,+ length=prompt_len)+ self._groups[gid] = group+ return group++ def _admit_pending(self) -> bool:+ """Batch-admit pending requests with the same prompt length."""+ with self._lock:+ pending = list(self._pending)+ if not pending:+ return False+ # Group by prompt_len.+ by_len: dict[int, list[RequestState]] = {}+ for state in pending:+ by_len.setdefault(state.prompt_len, []).append(state)+ progressed = False+ for prompt_len, group_states in by_len.items():+ if not self._admit_group(prompt_len, group_states):+ continue+ progressed = True+ return progressed++ def _admit_group(self, prompt_len: int,+ states: list[RequestState]) -> bool:+ """Admit up to one batch of same-length requests."""+ # Find or create a group with room.+ group = None+ for gid, g in self._groups.items():+ if g.length == prompt_len and len(g.active_slots()) < self.engine.max_batch:+ group = g+ state_group_id = gid+ break+ if group is None:+ gid = self._next_group_id+ self._next_group_id += 1+ cache = DynamicCache()+ slots: list[Optional[str]] = [None] * self.engine.max_batch+ group = _Group(cache=cache, slots=slots,+ prompt_len=prompt_len, length=prompt_len)+ self._groups[gid] = group+ state_group_id = gid+ # Allocate slots for as many requests as fit.+ active = group.active_slots()+ free = self.engine.max_batch - len(active)+ if free <= 0:+ return False+ chosen = states[:free]+ # Prepare batched prefill input.+ device = self.engine.device+ prompt_lens = {len(s.prompt_ids) for s in chosen}+ if len(prompt_lens) != 1:+ # If for some reason prompts differ in length, fall back to+ # serial single-row prefill.+ for s in chosen:+ self._admit_single(s, group, state_group_id)+ return True+ # All chosen requests share the same prompt length.+ B = len(chosen)+ input_ids = torch.tensor(+ [s.prompt_ids for s in chosen], dtype=torch.long, device=device,+ )+ try:+ with torch.no_grad():+ out = self.engine.model(+ input_ids,+ past_key_values=group.cache,+ use_cache=True,+ num_logits_to_keep=1,+ )+ torch.npu.synchronize()+ next_tokens = out.logits[:, -1, :].argmax(dim=-1).tolist()+ except Exception as exc: # noqa: BLE001+ for s in chosen:+ s.error = str(exc)+ s.done = True+ s.finish_reason = "error"+ if s.sink is not None:+ s.sink.push_blocking({"error": str(exc)})+ s.sink.push_blocking({"done": True})+ with self._lock:+ for s in chosen:+ if s in self._pending:+ self._pending.remove(s)+ return True+ # Allocate slots and notify.+ now = time.monotonic()+ with self._lock:+ for s, token in zip(chosen, next_tokens):+ slot = group.alloc(s.request_id)+ s.slot = slot+ s.group_id = state_group_id+ s.last_token = token+ s.first_token_time = now+ self._active[s.request_id] = s+ if s in self._pending:+ self._pending.remove(s)+ # Push first token to each client outside the lock.+ for s, token in zip(chosen, next_tokens):+ self._push_token(s, token)+ return True++ def _admit_single(self, state: RequestState, group: _Group,+ gid: int) -> None:+ """Fallback path: serial single-row prefill for one request."""+ device = self.engine.device+ slot = group.alloc(state.request_id)+ state.slot = slot+ state.group_id = gid+ try:+ input_ids = torch.tensor(+ [state.prompt_ids], dtype=torch.long, device=device,+ )+ with torch.no_grad():+ out = self.engine.model(+ input_ids,+ past_key_values=group.cache,+ use_cache=True,+ num_logits_to_keep=1,+ )+ torch.npu.synchronize()+ state.last_token = int(out.logits[0, -1, :].argmax(dim=-1).item())+ state.first_token_time = time.monotonic()+ with self._lock:+ self._active[state.request_id] = state+ if state in self._pending:+ self._pending.remove(state)+ self._push_token(state, state.last_token)+ except Exception as exc: # noqa: BLE001+ state.error = str(exc)+ state.done = True+ state.finish_reason = "error"+ if state.sink is not None:+ state.sink.push_blocking({"error": str(exc)})+ state.sink.push_blocking({"done": True})+ with self._lock:+ if state in self._pending:+ self._pending.remove(state)++ # ------------------------------------------------------------------+ def _step(self) -> bool:+ with self._lock:+ active = dict(self._active)+ if not active:+ return False+ by_group: dict[int, list[RequestState]] = {}+ for state in active.values():+ if state.done:+ continue+ by_group.setdefault(state.group_id, []).append(state)+ progressed = False+ for gid, states in by_group.items():+ if self._step_group(self._groups[gid], states):+ progressed = True+ return progressed++ def _step_group(self, group: _Group, states: list[RequestState]) -> bool:+ if not states:+ return False+ cache = group.cache+ active_slots = group.active_slots()+ if not active_slots:+ return False+ slot_to_state = {s.slot: s for s in states}+ rows = [slot_to_state[slot] for slot in active_slots]+ device = self.engine.device+ input_ids = torch.tensor(+ [[s.last_token] for s in rows], dtype=torch.long, device=device,+ )+ try:+ with torch.no_grad():+ out = self.engine.model(+ input_ids,+ past_key_values=cache,+ use_cache=True,+ num_logits_to_keep=1,+ )+ torch.npu.synchronize()+ next_tokens = out.logits[:, -1, :].argmax(dim=-1).tolist()+ except Exception as exc: # noqa: BLE001+ for s in rows:+ s.error = str(exc)+ s.done = True+ s.finish_reason = "error"+ if s.sink is not None:+ s.sink.push_blocking({"error": str(exc)})+ s.sink.push_blocking({"done": True})+ return False+ group.length += 1+ completed: list[tuple[RequestState, int]] = []+ for state, token in zip(rows, next_tokens):+ state.last_token = token+ state.last_token_time = time.monotonic()+ reason = None+ if token == state.eos_token_id and not state.ignore_eos:+ reason = "stop"+ elif len(state.emitted) + 1 >= state.max_new_tokens:+ reason = "length"+ elif group.length >= self.engine.max_seq_len:+ reason = "length"+ self._push_token(state, token)+ if reason is not None:+ state.done = True+ state.finish_reason = reason+ if state.sink is not None:+ state.sink.push_blocking({"done": True})+ completed.append((state, state.slot))+ for state, slot in completed:+ group.free(slot)+ with self._lock:+ self._active.pop(state.request_id, None)+ return True++ def _push_token(self, state: RequestState, token: int) -> None:+ state.emitted.append(token)+ if state.sink is not None:+ state.sink.push({"token": token})\ No newline at end of file@@ -0,0 +1,64 @@+#!/usr/bin/env bash+# Launch the Qwen3-8B OpenBuild serving system in the foreground.+#+# The launch script owns every child process in its process group and+# binds a single HTTP service to ${OPENBUILD_HOST}:${OPENBUILD_PORT}.+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-${SCRIPT_DIR}}"+ENV_DIR="${OPENBUILD_ENV_DIR:-${TASK_HOME:-/tmp}/openbuild-runtime}"+mkdir -p "${ENV_DIR}/logs"++HOST="${OPENBUILD_HOST:-127.0.0.1}"+PORT="${OPENBUILD_PORT:-8080}"+DEVICE_ID="${ASCEND_RT_VISIBLE_DEVICES:-${OPENBUILD_DEVICE_IDS:-0}}"+MODEL_PATH="${OPENBUILD_MODEL_PATH:-}"+TOKENIZER_PATH="${OPENBUILD_TOKENIZER_PATH:-${MODEL_PATH}}"+SERVED_MODEL="${OPENBUILD_SERVED_MODEL:-Qwen/Qwen3-8B}"++if [[ -z "${MODEL_PATH}" ]]; then+ echo "[launch] OPENBUILD_MODEL_PATH is empty" >&2+ exit 1+fi+if [[ -z "${TOKENIZER_PATH}" ]]; then+ echo "[launch] OPENBUILD_TOKENIZER_PATH is empty" >&2+ exit 1+fi++export OPENBUILD_SOLUTION_DIR="${SOLUTION_DIR}"+export OPENBUILD_ENV_DIR="${ENV_DIR}"+export OPENBUILD_MODEL_PATH="${MODEL_PATH}"+export OPENBUILD_TOKENIZER_PATH="${TOKENIZER_PATH}"+export OPENBUILD_SERVED_MODEL="${SERVED_MODEL}"+export OPENBUILD_HOST="${HOST}"+export OPENBUILD_PORT="${PORT}"+export OPENBUILD_DEVICE_IDS="${DEVICE_ID}"+export ASCEND_RT_VISIBLE_DEVICES="${DEVICE_ID}"+export PYTHONPATH="${SOLUTION_DIR}:${PYTHONPATH:-}"+export PYTHONNOUSERSITE=1+export PYTHONSAFEPATH=1+export PYTHONDONTWRITEBYTECODE=1+export PYTHONUNBUFFERED=1+export HF_HUB_OFFLINE=1+export TRANSFORMERS_OFFLINE=1+export TOKENIZERS_PARALLELISM=false+export OMP_NUM_THREADS="${OMP_NUM_THREADS:-4}"+export TASK_MODE="${TASK_MODE:-normal}"++# Trap signals to ensure the child server is torn down cleanly.+SERVER_PID=""+cleanup() {+ local signal="$1"+ if [[ -n "${SERVER_PID}" ]] && kill -0 "${SERVER_PID}" 2>/dev/null; then+ kill -"${signal}" "${SERVER_PID}" 2>/dev/null || true+ fi+}+trap 'cleanup TERM; wait 2>/dev/null || true' TERM+trap 'cleanup INT; wait 2>/dev/null || true' INT+trap 'cleanup HUP; wait 2>/dev/null || true' HUP++PYTHON_BIN="${PYTHON_BIN:-python3}"+exec "${PYTHON_BIN}" -u "${SOLUTION_DIR}/server.py" &+SERVER_PID=$!+wait "${SERVER_PID}"\ No newline at end of file@@ -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-engine",+ "bootstrap": "bootstrap.sh",+ "launch": "launch.sh",+ "offline_replay": true+}\ No newline at end of file@@ -0,0 +1,373 @@+#!/usr/bin/env python3+"""HTTP entrypoint for the OpenBuild Qwen3-8B serving system.++The server wraps the continuous-batching ``AsyncScheduler`` behind an+OpenAI-compatible HTTP surface implemented with FastAPI + uvicorn. The+inference engine runs on a dedicated background thread that owns the+NPU; the FastAPI loop merely translates HTTP requests into scheduler+submissions and streams tokens back as Server-Sent Events.+"""+from __future__ import annotations++import argparse+import asyncio+import json+import logging+import os+import signal+import sys+import threading+import time+import uuid+from typing import Any, AsyncIterator++import torch+import torch_npu # noqa: F401 (registers NPU as a torch device)+import uvicorn+from fastapi import FastAPI, HTTPException, Request+from fastapi.responses import JSONResponse, StreamingResponse++from engine import AsyncScheduler, Qwen3Engine, RequestState, _Sink+++LOG = logging.getLogger("openbuild.serving")+logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+++SERVED_MODEL = os.environ.get("OPENBUILD_SERVED_MODEL", "Qwen/Qwen3-8B")+HOST = os.environ.get("OPENBUILD_HOST", "127.0.0.1")+PORT = int(os.environ.get("OPENBUILD_PORT", "8080"))+DEVICE_IDS = os.environ.get("OPENBUILD_DEVICE_IDS", "0")+MODEL_PATH = os.environ.get("OPENBUILD_MODEL_PATH", "")+TOKENIZER_PATH = os.environ.get("OPENBUILD_TOKENIZER_PATH", MODEL_PATH)+ENV_DIR = os.environ.get("OPENBUILD_ENV_DIR", "/tmp/openbuild-runtime")+MAX_BATCH = int(os.environ.get("OPENBUILD_MAX_BATCH", "64"))+MAX_SEQ_LEN = int(os.environ.get("OPENBUILD_MAX_SEQ_LEN", "4096"))+++# Engine + scheduler are populated at startup so the worker thread can+# pick them up after the model is loaded on the NPU.+ENGINE: Qwen3Engine | None = None+SCHEDULER: AsyncScheduler | None = None+SCHEDULER_THREAD: threading.Thread | None = None+++def _create_ids() -> str:+ return uuid.uuid4().hex+++# ---------------------------------------------------------------------------+# Token / message helpers+# ---------------------------------------------------------------------------+++def _coerce_message(message: Any) -> dict[str, str]:+ if not isinstance(message, dict):+ raise HTTPException(400, "messages entries must be objects")+ role = message.get("role")+ content = message.get("content")+ if role not in {"system", "user", "assistant"}:+ raise HTTPException(400, "unsupported message role")+ if not isinstance(content, str):+ raise HTTPException(400, "message content must be a string")+ return {"role": role, "content": content}+++def _validate_chat_body(body: dict[str, Any]) -> dict[str, Any]:+ if body.get("model") != SERVED_MODEL:+ raise HTTPException(400, f"unknown model '{body.get('model')}'")+ messages = body.get("messages")+ if not isinstance(messages, list) or not messages:+ raise HTTPException(400, "messages must be a non-empty list")+ coerced = [_coerce_message(m) for m in messages]+ temperature = body.get("temperature", 0.0)+ if temperature != 0:+ # Strictly greedy per the contract.+ temperature = 0.0+ max_tokens = body.get("max_tokens")+ if max_tokens is None:+ max_tokens = body.get("max_completion_tokens")+ if not isinstance(max_tokens, int) or not 1 <= max_tokens <= MAX_SEQ_LEN:+ raise HTTPException(400, "max_tokens out of range")+ stream = bool(body.get("stream", False))+ seed = body.get("seed", 0)+ ignore_eos = bool(body.get("ignore_eos", False))+ stream_options = body.get("stream_options") or {}+ include_usage = bool(stream_options.get("include_usage", False))+ return {+ "messages": coerced,+ "temperature": 0.0,+ "max_tokens": max_tokens,+ "stream": stream,+ "seed": seed,+ "ignore_eos": ignore_eos,+ "include_usage": include_usage,+ }+++# ---------------------------------------------------------------------------+# Streaming helpers+# ---------------------------------------------------------------------------+++async def _drain_sink(sink: _Sink) -> AsyncIterator[dict[str, Any]]:+ """Yield everything currently queued, then wait for the next item."""+ while True:+ item = await sink.queue.get()+ yield item+++async def _stream_response(state: RequestState,+ completion_id: str,+ created_ts: int,+ include_usage: bool) -> AsyncIterator[bytes]:+ first_token_emitted = False+ while True:+ item = await state.sink.queue.get()+ if "error" in item:+ err_payload = {+ "id": completion_id,+ "object": "chat.completion.chunk",+ "created": created_ts,+ "model": SERVED_MODEL,+ "choices": [+ {"index": 0, "delta": {}, "finish_reason": "error"}+ ],+ }+ yield _sse_line(err_payload)+ yield _sse_done()+ return+ if "done" in item:+ break+ token = item["token"]+ text = ENGINE.tokenizer.decode(+ [token], skip_special_tokens=True,+ )+ if not first_token_emitted:+ chunk = {+ "id": completion_id,+ "object": "chat.completion.chunk",+ "created": created_ts,+ "model": SERVED_MODEL,+ "choices": [+ {"index": 0, "delta": {"role": "assistant", "content": text},+ "finish_reason": None}+ ],+ }+ first_token_emitted = True+ else:+ chunk = {+ "id": completion_id,+ "object": "chat.completion.chunk",+ "created": created_ts,+ "model": SERVED_MODEL,+ "choices": [+ {"index": 0, "delta": {"content": text},+ "finish_reason": None}+ ],+ }+ yield _sse_line(chunk)++ # Final chunk with finish_reason; always include usage when requested.+ final_chunk: dict[str, Any] = {+ "id": completion_id,+ "object": "chat.completion.chunk",+ "created": created_ts,+ "model": SERVED_MODEL,+ "choices": [+ {"index": 0, "delta": {}, "finish_reason": state.finish_reason or "stop"}+ ],+ }+ if include_usage:+ final_chunk["usage"] = {+ "prompt_tokens": state.prompt_len,+ "completion_tokens": len(state.emitted),+ "total_tokens": state.prompt_len + len(state.emitted),+ }+ yield _sse_line(final_chunk)+ yield _sse_done()+++def _sse_line(payload: dict[str, Any]) -> bytes:+ return ("data: " + json.dumps(payload, ensure_ascii=False) + "\n\n").encode("utf-8")+++def _sse_done() -> bytes:+ return b"data: [DONE]\n\n"+++# ---------------------------------------------------------------------------+# FastAPI application+# ---------------------------------------------------------------------------+++app = FastAPI()+++@app.get("/v1/models")+async def list_models() -> JSONResponse:+ return JSONResponse({+ "object": "list",+ "data": [+ {+ "id": SERVED_MODEL,+ "object": "model",+ "created": int(time.time()),+ "owned_by": "openbuild",+ }+ ],+ })+++@app.get("/health")+async def health() -> JSONResponse:+ return JSONResponse({"status": "ok"})+++async def _handle_chat(request: Request) -> JSONResponse | StreamingResponse:+ raw = await request.json()+ if not isinstance(raw, dict):+ raise HTTPException(400, "body must be a JSON object")+ params = _validate_chat_body(raw)+ completion_id = "chatcmpl-" + _create_ids()+ created_ts = int(time.time())++ prompt_ids = ENGINE.encode_messages(params["messages"])+ if len(prompt_ids) >= MAX_SEQ_LEN - 1:+ raise HTTPException(400, "prompt exceeds maximum context length")++ sink = _Sink()+ state = RequestState(+ request_id=completion_id,+ group_id=-1,+ prompt_ids=prompt_ids,+ prompt_len=len(prompt_ids),+ last_token=0,+ max_new_tokens=params["max_tokens"],+ ignore_eos=params["ignore_eos"],+ eos_token_id=ENGINE.eos_token_id,+ sink=sink,+ arrival_time=time.monotonic(),+ )+ SCHEDULER.submit(state)++ if not params["stream"]:+ # Non-streaming: collect all emitted tokens before returning.+ emitted: list[int] = []+ finish_reason: str | None = None+ while True:+ item = await sink.queue.get()+ if "error" in item:+ raise HTTPException(500, item["error"])+ if "done" in item:+ finish_reason = state.finish_reason or "stop"+ break+ emitted.append(item["token"])+ text = ENGINE.tokenizer.decode(emitted, skip_special_tokens=True)+ response = {+ "id": completion_id,+ "object": "chat.completion",+ "created": created_ts,+ "model": SERVED_MODEL,+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": text},+ "finish_reason": finish_reason,+ }+ ],+ "usage": {+ "prompt_tokens": state.prompt_len,+ "completion_tokens": len(emitted),+ "total_tokens": state.prompt_len + len(emitted),+ },+ }+ return JSONResponse(response)++ # Streaming: hand control to a generator that pumps the sink.+ generator = _stream_response(+ state, completion_id, created_ts, params["include_usage"]+ )+ return StreamingResponse(generator, media_type="text/event-stream")+++@app.post("/v1/chat/completions")+async def chat_completions(request: Request):+ return await _handle_chat(request)+++# ---------------------------------------------------------------------------+# Startup+# ---------------------------------------------------------------------------+++def _initialise_engine() -> None:+ global ENGINE, SCHEDULER, SCHEDULER_THREAD+ if ENGINE is not None:+ return+ LOG.info("Initialising Qwen3 engine on %s", DEVICE_IDS)+ device = torch.device(f"npu:{DEVICE_IDS}")+ ENGINE = Qwen3Engine(+ model_path=MODEL_PATH,+ device=device,+ max_batch=MAX_BATCH,+ max_seq_len=MAX_SEQ_LEN,+ )+ LOG.info("Engine ready: %d layers, max_batch=%d, max_seq=%d",+ ENGINE.num_layers, MAX_BATCH, MAX_SEQ_LEN)+ SCHEDULER = AsyncScheduler(ENGINE)+ SCHEDULER_THREAD = threading.Thread(+ target=SCHEDULER.run, name="scheduler", daemon=True+ )+ SCHEDULER_THREAD.start()+ LOG.info("Scheduler started")+++@app.on_event("startup")+async def _on_startup() -> None:+ _initialise_engine()+++@app.on_event("shutdown")+async def _on_shutdown() -> None:+ if SCHEDULER is not None:+ SCHEDULER.shutdown()+++def _install_signal_handlers(loop: asyncio.AbstractEventLoop) -> None:+ def _stop(*_args: Any) -> None:+ LOG.info("Received termination signal")+ if SCHEDULER is not None:+ SCHEDULER.shutdown()+ for task in asyncio.all_tasks(loop):+ task.cancel()+ loop.stop()++ for sig in (signal.SIGTERM, signal.SIGINT):+ try:+ loop.add_signal_handler(sig, _stop)+ except (NotImplementedError, RuntimeError):+ pass+++def main() -> None:+ if not MODEL_PATH:+ print("OPENBUILD_MODEL_PATH is empty", file=sys.stderr)+ sys.exit(1)+ config = uvicorn.Config(+ app,+ host=HOST,+ port=PORT,+ log_level="warning",+ access_log=False,+ loop="asyncio",+ )+ server = uvicorn.Server(config)+ server.run()+++if __name__ == "__main__":+ main()\ No newline at end of file