a8nova commited on
Commit
f506411
·
verified ·
1 Parent(s): a554557

nnopt port: moonshine-streaming-LiteRT

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +17 -32
  2. LICENSE +16 -0
  3. NOTICE +4 -0
  4. README.md +76 -0
  5. config.json +33 -0
  6. sm8850-npu-fp16/README.md +125 -0
  7. sm8850-npu-fp16/REPRO.md +141 -0
  8. sm8850-npu-fp16/build.sh +79 -0
  9. sm8850-npu-fp16/build/moonshine_stream +0 -0
  10. sm8850-npu-fp16/build/stage/libLiteRt.so +3 -0
  11. sm8850-npu-fp16/build/stage/libLiteRtDispatch_Qualcomm.so +3 -0
  12. sm8850-npu-fp16/build/stage/moonshine_stream +0 -0
  13. sm8850-npu-fp16/build/stage/port.json +15 -0
  14. sm8850-npu-fp16/build/stage/run.sh +6 -0
  15. sm8850-npu-fp16/demo/demo.json +32 -0
  16. sm8850-npu-fp16/demo/input.wav +3 -0
  17. sm8850-npu-fp16/demo/metrics.json +1 -0
  18. sm8850-npu-fp16/demo/output.json +1 -0
  19. sm8850-npu-fp16/deploy.sh +21 -0
  20. sm8850-npu-fp16/fetch.sh +39 -0
  21. sm8850-npu-fp16/models/dec1536h_Qualcomm_SM8850_apply_plugin.tflite +3 -0
  22. sm8850-npu-fp16/models/dec4096h_Qualcomm_SM8850_apply_plugin.tflite +3 -0
  23. sm8850-npu-fp16/models/dec512h_Qualcomm_SM8850_apply_plugin.tflite +3 -0
  24. sm8850-npu-fp16/models/enc16_Qualcomm_SM8850_apply_plugin.tflite +3 -0
  25. sm8850-npu-fp16/models/vocab.bin +3 -0
  26. sm8850-npu-fp16/report.html +431 -0
  27. sm8850-npu-fp16/report/reproduce.sh +11 -0
  28. sm8850-npu-fp16/report/results.csv +80 -0
  29. sm8850-npu-fp16/report/results.json +0 -0
  30. sm8850-npu-fp16/repro/Dockerfile +8 -0
  31. sm8850-npu-fp16/repro/bench.py +729 -0
  32. sm8850-npu-fp16/repro/inputs/input.wav +3 -0
  33. sm8850-npu-fp16/repro/plan.json +136 -0
  34. sm8850-npu-fp16/src/aot_compile.py +35 -0
  35. sm8850-npu-fp16/src/convert_ckpt.py +51 -0
  36. sm8850-npu-fp16/src/export_requirements.txt +10 -0
  37. sm8850-npu-fp16/src/export_tflite.py +101 -0
  38. sm8850-npu-fp16/src/host_stream.py +133 -0
  39. sm8850-npu-fp16/src/make_cases.py +39 -0
  40. sm8850-npu-fp16/src/make_vocab.py +34 -0
  41. sm8850-npu-fp16/src/moonshine_npu.py +268 -0
  42. sm8850-npu-fp16/src/paths.sh +12 -0
  43. sm8850-npu-fp16/src/port.json +15 -0
  44. sm8850-npu-fp16/src/run.sh +6 -0
  45. sm8850-npu-fp16/src/runner.c +680 -0
  46. sm8850-npu-fp16/src/vm_pipeline.sh +36 -0
  47. sm8850-npu-fp16/vendor/litert/2.3.1/LICENSE +201 -0
  48. sm8850-npu-fp16/vendor/litert/2.3.1/SHA256SUMS +69 -0
  49. sm8850-npu-fp16/vendor/litert/2.3.1/include/LICENSE +201 -0
  50. sm8850-npu-fp16/vendor/litert/2.3.1/include/litert/build_common/build_config.h +18 -0
.gitattributes CHANGED
@@ -1,35 +1,20 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
1
  *.bin filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  *.tflite filter=lfs diff=lfs merge=lfs -text
3
+ *.gguf filter=lfs diff=lfs merge=lfs -text
4
+ *.onnx filter=lfs diff=lfs merge=lfs -text
5
+ *.npz filter=lfs diff=lfs merge=lfs -text
6
+ *.wav filter=lfs diff=lfs merge=lfs -text
7
+ *.so filter=lfs diff=lfs merge=lfs -text
8
+ *.bf16 filter=lfs diff=lfs merge=lfs -text
9
+ *.f16 filter=lfs diff=lfs merge=lfs -text
10
+ *.f32 filter=lfs diff=lfs merge=lfs -text
11
+ *.npy filter=lfs diff=lfs merge=lfs -text
12
+ *.tkb filter=lfs diff=lfs merge=lfs -text
13
+ *.png filter=lfs diff=lfs merge=lfs -text
14
+ *.jpg filter=lfs diff=lfs merge=lfs -text
15
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
16
+ *.pdf filter=lfs diff=lfs merge=lfs -text
17
  *.zip filter=lfs diff=lfs merge=lfs -text
18
+ *.gz filter=lfs diff=lfs merge=lfs -text
19
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) the authors of moonshine-ai/moonshine-streaming (Moonshine AI)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
NOTICE ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ This repository is a modified version of moonshine-ai/moonshine-streaming by Moonshine AI, revision da30bae714913eb0057e733bccb4700104afb1b0.
2
+
3
+ Changes, made by nnopt (https://nnopt.dev):
4
+ - `sm8850-npu-fp16/` (nnopt job NN-466F3D): included: models/*.tflite (4 graphs AOT-compiled for SM8850 by nnopt, Moonshine v2 Streaming Medium) and models/vocab.bin; Qualcomm's QNN runtime is fetched. The runtime code (src/, build.sh, deploy.sh, run.sh) is new, written by nnopt's agents for this device.
README.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ base_model: moonshine-ai/moonshine-streaming
4
+ pipeline_tag: automatic-speech-recognition
5
+ tags:
6
+ - on-device
7
+ - nnopt
8
+ - litert
9
+ - tflite
10
+ - android
11
+ - npu
12
+ - hexagon
13
+ - qualcomm
14
+ - asr
15
+ - streaming
16
+ - galaxy-s26-plus
17
+ ---
18
+
19
+ # moonshine-streaming on Samsung Galaxy S26+ (LiteRT)
20
+
21
+ Ported and verified on a real Samsung Galaxy S26+ by [nnopt.dev](https://nnopt.dev) — AI agents that port and optimize models for the hardware you ship.
22
+
23
+ The model is [moonshine-ai/moonshine-streaming](https://huggingface.co/moonshine-ai/moonshine-streaming) by Moonshine AI, and it is theirs. The LiteRT port in this repository is nnopt's work: nnopt job NN-466F3D.
24
+
25
+ | | |
26
+ |---|---|
27
+ | Device | Samsung Galaxy S26+, Android 16 |
28
+ | Chip | Snapdragon 8 Elite Gen 5 (SM8850) |
29
+ | Processor | NPU (Hexagon HTP v81) for every model graph; CPU for WAV I/O, chunking, argmax, detokenizing |
30
+ | Runtime | LiteRT 2.3.1 (Qualcomm dispatch), QNN 2.50.0 |
31
+ | Precision | FP16 on the HTP (fp32-exported graphs, AOT-compiled; fp16 cross/self KV cache I/O) |
32
+ | Modality | speech -> text (streaming ASR) |
33
+ | Weights | included: models/*.tflite (4 graphs AOT-compiled for SM8850 by nnopt, Moonshine v2 Streaming Medium) and models/vocab.bin; Qualcomm's QNN runtime is fetched |
34
+ | nnopt job | NN-466F3D (port) |
35
+ | Folder | [`sm8850-npu-fp16/`](https://huggingface.co/nnopt-dev/moonshine-streaming-LiteRT/tree/main/sm8850-npu-fp16) |
36
+
37
+ ## Verified results
38
+
39
+ nnopt built the folder from a clean copy, deployed it to the device and checked it against the model's reference code on hidden inputs. The full report is `report.html` in the folder.
40
+
41
+ - Passed. Word error rate vs reference 0.0% (bar at most 2.0%, original precision)
42
+ - full check passed
43
+ - no speculative decoding
44
+ - Real-time factor 0.076 (faster than real time)
45
+ - Latency 436 ms
46
+ - Decode 40.3 tokens/s
47
+ - Load time 286 ms
48
+ - Peak memory 623 MB
49
+ - 4 graphs, NPU 100%
50
+
51
+ ## Use it
52
+
53
+ ```
54
+ mkdir moonshine-streaming-LiteRT && cd moonshine-streaming-LiteRT
55
+ curl -fsSL https://huggingface.co/nnopt-dev/moonshine-streaming-LiteRT/resolve/main/config.json -o config.json
56
+ hf download nnopt-dev/moonshine-streaming-LiteRT --include "sm8850-npu-fp16/*" --local-dir .
57
+ cd sm8850-npu-fp16
58
+ bash fetch.sh
59
+ bash deploy.sh /data/local/tmp/moonshine # adb: runner, LiteRT, QNN libs, 4 NPU graphs
60
+ adb push demo/input.wav /data/local/tmp/moonshine/in.wav
61
+ adb shell 'cd /data/local/tmp/moonshine && sh ./run.sh --audio in.wav --out out.json --metrics m.json'
62
+ ```
63
+
64
+ Needs: A Snapdragon SM8850 phone (Galaxy S26+), adb, ~1.3 GB free storage; curl and unzip on the host. Rebuilding the runner (`bash build.sh`) fetches the NDK itself.
65
+
66
+ `README.md` in the folder has every flag, the requirements and the known limits; `REPRO.md` (where present) reproduces the measurements.
67
+
68
+ ## License
69
+
70
+ MIT, like moonshine-ai/moonshine-streaming: see LICENSE and NOTICE. LiteRT in `vendor/litert/` is Apache 2.0. Qualcomm's QNN runtime is not here: `fetch.sh` gets it from Maven Central, under Qualcomm's license.
71
+
72
+ ## Made with nnopt
73
+
74
+ [nnopt](https://nnopt.dev) is a platform where AI agents port, optimize and benchmark a model for a specific device. They write the runtime code on the real device, and a locked verification kit then checks the result against the model's own reference code before anything ships. Every number on this page comes from that check.
75
+
76
+ Want your model on your device? Start a job at [nnopt.dev](https://nnopt.dev).
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nnopt_manifest": 1,
3
+ "repo": "nnopt-dev/moonshine-streaming-LiteRT",
4
+ "model": {
5
+ "name": "moonshine-streaming",
6
+ "source_repo": "moonshine-ai/moonshine-streaming",
7
+ "source_revision": "da30bae714913eb0057e733bccb4700104afb1b0",
8
+ "authors": "Moonshine AI",
9
+ "license": "mit"
10
+ },
11
+ "variants": [
12
+ {
13
+ "id": "sm8850-npu-fp16",
14
+ "device": "Samsung Galaxy S26+",
15
+ "chip": "Snapdragon 8 Elite Gen 5 (SM8850)",
16
+ "os": "Android 16",
17
+ "processor": "NPU (Hexagon HTP v81) for every model graph; CPU for WAV I/O, chunking, argmax, detokenizing",
18
+ "runtime": "LiteRT 2.3.1 (Qualcomm dispatch), QNN 2.50.0",
19
+ "runtime_version": "LiteRT 2.3.1 + QNN 2.50.0",
20
+ "precision": "FP16 on the HTP (fp32-exported graphs, AOT-compiled; fp16 cross/self KV cache I/O)",
21
+ "weights": "included: models/*.tflite (4 graphs AOT-compiled for SM8850 by nnopt, Moonshine v2 Streaming Medium) and models/vocab.bin; Qualcomm's QNN runtime is fetched",
22
+ "nnopt_job": "NN-466F3D",
23
+ "job_kind": "port",
24
+ "verified": {
25
+ "verdict": "Passed. Word error rate vs reference 0.0% (bar at most 2.0%, original precision); full check passed; no speculative decoding",
26
+ "speed": "Real-time factor 0.076 (faster than real time); Latency 436 ms; Decode 40.3 tokens/s; Load time 286 ms; Peak memory 623 MB; 4 graphs, NPU 100%"
27
+ },
28
+ "fetch": "sm8850-npu-fp16/fetch.sh"
29
+ }
30
+ ],
31
+ "license": "mit",
32
+ "made_by": "nnopt (https://nnopt.dev)"
33
+ }
sm8850-npu-fp16/README.md ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Moonshine v2 Streaming Medium on the Galaxy S26+ NPU (LiteRT)
2
+
3
+ Streaming speech to text with Moonshine v2 Streaming Medium (moonshine-ai/moonshine-streaming @ da30bae, the
4
+ `tensilier` checkpoint, 245 M parameters). Audio is consumed in 320 ms chunks; the program prints partial transcripts
5
+ while audio arrives and the final transcript at the end.
6
+
7
+ - Device: Samsung Galaxy S26+ (Snapdragon 8 Elite Gen 5, SM8850), Android 16
8
+ - Runtime: LiteRT 2.3.1 C API with the Qualcomm dispatch, QNN (QAIRT) 2.50.0
9
+ - Processor: Hexagon NPU (HTP v81), every model graph: 4 graphs, 100% DISPATCH_OP, no CPU or GPU fallback.
10
+ The CPU only does glue: WAV reading, chunking, state copies, greedy argmax, detokenizing.
11
+ - Precision: fp16 (fp32 graphs compiled for the HTP, fp16 K/V caches, fp32 logits)
12
+
13
+ ## Layout
14
+ ```
15
+ src/runner.c the phone program (moonshine_stream), LiteRT C API
16
+ src/run.sh entry point on the phone (sets LD_LIBRARY_PATH / ADSP_LIBRARY_PATH)
17
+ src/port.json runtime description copied to DEST
18
+ src/moonshine_npu.py the graphs as static-shape PyTorch modules (EncoderChunk, DecoderStep), fp16-safe rewrites
19
+ src/export_tflite.py export to .tflite with litert-torch + CPU check; src/vm_pipeline.sh export + src/aot_compile.py AOT compile
20
+ src/convert_ckpt.py customer checkpoint -> transformers-style state dict (weight norm folded)
21
+ src/make_vocab.py tokenizer.json -> models/vocab.bin (token bytes for the runner's detokenizer)
22
+ src/host_stream.py host (CPU, torch) model of the same streaming loop, with --check-hf against transformers
23
+ src/make_cases.py captures real graph inputs for export checks
24
+ models/ the compiled NPU models (SM8850 only) and vocab.bin
25
+ vendor/litert/2.3.1/ libLiteRt.so, libLiteRtDispatch_Qualcomm.so, headers, LICENSE (Apache 2.0), SHA256SUMS
26
+ ```
27
+
28
+ ## Requirements
29
+ - Build host: Linux x86-64 or macOS, with bash, curl, unzip, python3 and internet access. build.sh fetches the
30
+ Android NDK r27d and Qualcomm's qnn-runtime 2.50.0 AAR (Maven Central, sha256-pinned) into `.deps/`.
31
+ - adb with the phone connected (ANDROID_SERIAL selects it). No root.
32
+
33
+ ## Build, deploy, run
34
+ ```
35
+ bash build.sh # -> build/moonshine_stream, build/stage/
36
+ bash deploy.sh /data/local/tmp/nnopt/port # pushes runner, libs, models; leaves run.sh and port.json
37
+ adb shell "cd /data/local/tmp/nnopt/port && sh ./run.sh --audio /data/local/tmp/in.wav --out /data/local/tmp/out.json --metrics /data/local/tmp/m.json"
38
+ ```
39
+ run.sh flags:
40
+ - `--audio IN.wav` 16 kHz mono 16-bit PCM; `--out OUT.json` writes `{"text": ..., "partials": [{"audio_s", "text"}]}`
41
+ - `--metrics M.json` load_ms, and per run total_ms, ttft_ms (= time to first partial), first_partial_audio_s,
42
+ chunk_ms (per 320 ms chunk), chunk_latency_ms, final_decode_ms, decode_ms_per_token, rtf, end_latency_ms
43
+ - `--repeat R` repeat the request R times in one process (warm timings)
44
+ - `--partial-every SEC` partial transcript interval (default 1.0; 0 = final transcript only)
45
+ - `--realtime` feed chunks at live-microphone pace (a chunk is processed when it would have arrived), to measure
46
+ latency per chunk and time to first partial as a live user sees them
47
+ - `--quiet` no PARTIAL/FINAL lines on stderr
48
+
49
+ ## Check
50
+ ```
51
+ nnopt-verify check --split public --bundle <reference bundle> --port /data/local/tmp/nnopt/port
52
+ ```
53
+
54
+ ## Measured (Galaxy S26+, burst mode)
55
+ | | |
56
+ |---|---|
57
+ | WER vs the PyTorch reference, 13 public LibriSpeech cases | 0.0 (bar 0.02) |
58
+ | Encoder per 320 ms chunk | 4.3 ms |
59
+ | Decoder per token (graph for <=10 s / <=30 s / <=82 s audio) | 5.5 / 6.6 / 8.6 ms |
60
+ | p002, 5.9 s, as fast as possible (with 5 partials) | 639 ms, RTF 0.11 |
61
+ | p010, 13.3 s, as fast as possible (with 13 partials) | 2.67 s, RTF 0.20 |
62
+ | --realtime p002: first partial | at 1.28 s of audio, 41 ms after its chunk arrived |
63
+ | --realtime p002: final transcript after the end of speech | 144 ms |
64
+ | Load (4 context binaries) | 0.32-0.34 s |
65
+ | 48 s (two cases joined), largest decoder graph | 11.8 s, RTF 0.245, transcript identical to host fp32 |
66
+ | nnopt-verify bench (p000, 5.7 s): request latency / RTF | 439 ms / 0.077 (median of 10) |
67
+ | nnopt-verify bench: sustained 10 min | RTF 0.077-0.085, 96 runs, 0 failures; peak memory 621 MB |
68
+
69
+ ## Known limits
70
+ - At most 81.9 s of audio per request (the model's 4096-position table); longer input fails with an error.
71
+ - A partial is a full greedy re-decode of the audio so far. To keep long inputs fast, the next partial waits at least
72
+ max(--partial-every, 0.04 s x the tokens the last partial decoded) of audio: short utterances get one per second,
73
+ long ones fewer (48 s test: 20 partials, RTF 0.25 instead of 0.84). The final transcript is unaffected.
74
+ - The model itself drops words on very long single utterances (a 48 s test stopped mid-sentence); the port matches the
75
+ PyTorch reference exactly there too.
76
+ - The models are compiled for SM8850 (HTP v81) only.
77
+
78
+ ## How the models were made
79
+ On an x86-64 Linux machine with Python 3.12 and >= 64 GB RAM (they were made on 16 vCPU / 128 GB):
80
+ ```
81
+ bash src/vm_pipeline.sh ~/moonshine-export enc16 dec512h dec1536h dec4096h
82
+ ```
83
+ It creates its own venv from src/export_requirements.txt (torch 2.14.1 CPU, litert-torch 0.10.0, ai-edge-litert 2.3.0,
84
+ ai-edge-quantizer 0.10.0, ai-edge-litert-sdk-qualcomm 2.3.0 = the QAIRT 2.50 AOT compiler; top-level pins, the full
85
+ transitive freeze of the original machine was not recorded), downloads tensilier @ da30bae (sha256-checked), exports
86
+ each graph with src/export_tflite.py (checked on the CPU against the torch module) and compiles it for SM8850 with
87
+ src/aot_compile.py, which fails unless every op went to the NPU. About a minute per graph.
88
+
89
+ sha256 of the shipped files in models/:
90
+ ```
91
+ a8010fb0397243d2d67c4c84f8f76ff85d6f94cf35467c3b8157f556e2563d3b enc16_Qualcomm_SM8850_apply_plugin.tflite
92
+ 7b1b4993c19de245475f04f8f404a5de7e0b564eae9342c9f8ef0e0e75c48222 dec512h_Qualcomm_SM8850_apply_plugin.tflite
93
+ a28fad21faf2097c7141316fb1417260338c4de8737e7f79890e4f32e5d5cc8b dec1536h_Qualcomm_SM8850_apply_plugin.tflite
94
+ c6f23a91a62d214af113ee469001b6cc82741e34ca7dadec8af6fb61a38e0e7c dec4096h_Qualcomm_SM8850_apply_plugin.tflite
95
+ 5b3e9c217d081a41c249dd4bf991da435d339ecc139360f2b149dbdaef2a3359 vocab.bin
96
+ ```
97
+ Details, fp16 fixes, the NPU proof: NOTES.md.
98
+
99
+ ## Verified by nnopt
100
+
101
+ **Passed** moonshine-ai/moonshine-streaming on Samsung Galaxy S26+ (2026-11-03). nnopt built this folder from a clean copy, deployed it to the device and ran it on hidden inputs; the full report is report.html.
102
+
103
+ | Check | Measured | Bar | Result |
104
+ |---|---|---|---|
105
+ | Outputs match your reference code | Word error rate vs reference 0.0% | at most 2.0% (original precision) | pass |
106
+ | Runs on LiteRT and QNN and the Hexagon NPU | src/runner.c:95: if (LiteRtCreateModelFromFile(env, path, &g->model) != kLiteRtStatusOk) DIE("cannot load model %s", path); | the runtime you asked for | pass |
107
+ | Decodes one token per pass | one token per pass through the model: no speculative decoding in the port's code | no speculative decoding | pass |
108
+
109
+ | Speed | This port |
110
+ |---|---|
111
+ | Real-time factor | 0.076 |
112
+ | Latency | 436 ms |
113
+ | Decode, tokens/s | 40.3 |
114
+ | Load time | 286 ms |
115
+ | Peak memory | 623 MB |
116
+
117
+ | Measurement | Median |
118
+ |---|---|
119
+ | Real-time factor | 0.0761763 |
120
+ | Latency | 435.695 ms |
121
+ | Decode | 40.3124 tokens/s (23% of roofline) |
122
+ | Load time | 285.8 ms |
123
+ | Peak memory | 622.8 MB |
124
+
125
+ To get these results on your own device, follow REPRO.md.
sm8850-npu-fp16/REPRO.md ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reproduce: moonshine-ai/moonshine-streaming on Samsung Galaxy S26+
2
+
3
+ nnopt ported this (NN-466F3D, 2026-11-03). Runtime: LiteRT 2.3.1, Qualcomm dispatch, QNN 2.50.0. Follow the steps on the same device model and OS build; the results should land within the tolerances in the last table.
4
+
5
+ ## 1. Device
6
+
7
+ | Property | nnopt ran on |
8
+ |---|---|
9
+ | Chip | Snapdragon 8 Elite Gen 5 |
10
+ | GPU | Adreno 840 |
11
+ | Memory | 12 GB |
12
+ | OS | Android 16 |
13
+
14
+ Keep the phone plugged in, screen on and awake (Developer options > Stay awake), no other apps open, and let it rest about 10 minutes before measuring (a warm phone throttles).
15
+
16
+ ## 2. Tools
17
+
18
+ **Tested:** nnopt built this folder from scratch on 2026-11-03 in the public image `ubuntu:24.04@sha256:68ee22004a9109b44973313b02ff7b1de250f1de0f5ecb628d73f579aaff33ac` with only these packages installed: git, curl, python3, python3-venv, build-essential, unzip, xz-utils. build.sh fetched everything else itself (its downloads are listed under step 3), and that build is the one nnopt deployed and measured.
19
+
20
+ Any Linux x86-64 machine with those packages builds it. build.sh is written to build on macOS arm64 as well (Xcode command line tools, git, curl, python3); nnopt did not test that for this deliverable.
21
+
22
+ | Tool | Version | Get it |
23
+ |---|---|---|
24
+ | gcc | 13.3.0 | – |
25
+ | Python | 3.12.3 | https://www.python.org/downloads/ |
26
+ | git | 2.43.0 | – |
27
+ | curl | 8.5.0 | – |
28
+
29
+ To deploy and measure you also need adb (Android platform-tools) and python3 (3.8 or newer, no packages).
30
+
31
+ build.sh and deploy.sh read these environment variables:
32
+
33
+ - `ANDROID_NDK`: the Android NDK folder (same as ANDROID_NDK_HOME)
34
+ - `BUILD`: set it before building
35
+ - `DEPS`: set it before building
36
+ - `WORK_ROOT`: set it before building
37
+
38
+ The same machine in Docker (`repro/Dockerfile`: the public image and packages above, nothing else):
39
+
40
+ ```
41
+ docker build --platform linux/amd64 -t build-env repro
42
+ docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD:/src" -w /src build-env bash build.sh
43
+ ```
44
+
45
+ ## 3. Model and inputs
46
+
47
+ **reference_code**: Hugging Face `moonshine-ai/moonshine-streaming` at revision `da30bae714913eb0057e733bccb4700104afb1b0`.
48
+
49
+ ```
50
+ huggingface-cli download moonshine-ai/moonshine-streaming --revision da30bae714913eb0057e733bccb4700104afb1b0 .gitattributes README.md slinkier/model.safetensors spindlier/model.safetensors tensilier/model.safetensors --local-dir inputs/reference_code
51
+ ```
52
+
53
+ | File | Size | sha256 |
54
+ |---|---|---|
55
+ | .gitattributes | 2.5 KB | `9cc1f73aa682dd96559d3671e8e09bea75ddf6be105f043e3841211c7b37ce87` |
56
+ | README.md | 24 B | `d8d7a46d41a1a37fe4f0a5f637bf55c649310185329127d8a2204632e480be17` |
57
+ | slinkier/model.safetensors | 128.1 MB | `da9fb3e3aa7d5596427c4173dfc738d8dbb2035dcfff29edff51f752e9730246` |
58
+ | spindlier/model.safetensors | 470.6 MB | `c6d88232d9258262a01aa7e6e7c77f5dda87618dca93ed30080552b52b2a8159` |
59
+ | tensilier/model.safetensors | 934.4 MB | `6a454dd0a064151946c7076d7b89c79d42a02eb41fc261083392a0349a34d86f` |
60
+
61
+ **weights**: Hugging Face `moonshine-ai/moonshine-streaming` at revision `da30bae714913eb0057e733bccb4700104afb1b0`.
62
+
63
+ ```
64
+ huggingface-cli download moonshine-ai/moonshine-streaming --revision da30bae714913eb0057e733bccb4700104afb1b0 .gitattributes README.md slinkier/model.safetensors spindlier/model.safetensors tensilier/model.safetensors --local-dir inputs/weights
65
+ ```
66
+
67
+ | File | Size | sha256 |
68
+ |---|---|---|
69
+ | .gitattributes | 2.5 KB | `9cc1f73aa682dd96559d3671e8e09bea75ddf6be105f043e3841211c7b37ce87` |
70
+ | README.md | 24 B | `d8d7a46d41a1a37fe4f0a5f637bf55c649310185329127d8a2204632e480be17` |
71
+ | slinkier/model.safetensors | 128.1 MB | `da9fb3e3aa7d5596427c4173dfc738d8dbb2035dcfff29edff51f752e9730246` |
72
+ | spindlier/model.safetensors | 470.6 MB | `c6d88232d9258262a01aa7e6e7c77f5dda87618dca93ed30080552b52b2a8159` |
73
+ | tensilier/model.safetensors | 934.4 MB | `6a454dd0a064151946c7076d7b89c79d42a02eb41fc261083392a0349a34d86f` |
74
+
75
+ build.sh also downloads:
76
+
77
+ | Download | Pinned |
78
+ |---|---|
79
+ | `curl -fL --retry 3 -o "$DEPS/$NDK_ZIP" "https://dl.google.com/android/repository/$NDK_ZIP"` | yes: a checksum or a versioned link |
80
+
81
+ ## 4. Build
82
+
83
+ ```
84
+ bash build.sh
85
+ ```
86
+
87
+ ## 5. Connect the device
88
+
89
+ ```
90
+ adb devices
91
+ ```
92
+
93
+ One device should be listed as `device`. With several, set `export ANDROID_SERIAL=<serial>` first.
94
+
95
+ ## 6. Deploy
96
+
97
+ ```
98
+ bash deploy.sh /data/local/tmp/nnopt/port
99
+ ```
100
+
101
+ ## 7. Run one input by hand
102
+
103
+ ```
104
+ adb shell 'mkdir -p /data/local/tmp/nnopt/port-repro-io'
105
+ adb push repro/inputs/input.wav /data/local/tmp/nnopt/port-repro-io/
106
+ adb shell 'cd /data/local/tmp/nnopt/port && sh ./run.sh --audio /data/local/tmp/nnopt/port-repro-io/input.wav --out /data/local/tmp/nnopt/port-repro-io/out.json --metrics /data/local/tmp/nnopt/port-repro-io/metrics.json'
107
+ adb pull /data/local/tmp/nnopt/port-repro-io/out.json .
108
+ adb pull /data/local/tmp/nnopt/port-repro-io/metrics.json .
109
+ ```
110
+
111
+ `out.json` is the output; `metrics.json` holds the program's own timings: `load_ms`, and per request `total_ms`.
112
+
113
+ ## 8. Measure
114
+
115
+ ```
116
+ python3 repro/bench.py
117
+ ```
118
+
119
+ bench.py runs nnopt's settings: 2 warm-up runs, then 5 timed runs of 3 requests each. Each run is timed on the device's own clock, and a paired shorter run checks the program's own timings, as nnopt does. `--sustained 600` adds nnopt's 10-minute sustained run.
120
+
121
+ ## 9. Check the outputs
122
+
123
+ ```
124
+ python3 repro/bench.py --check
125
+ ```
126
+
127
+ Runs the 13 public cases in `repro/expected/` and compares with the reference outputs of your reference code: word error rate against the expected transcripts at most 2%.
128
+
129
+ nnopt's full check also used hidden inputs and teacher-forced comparisons; report.html has every number.
130
+
131
+ ## Expected results
132
+
133
+ | Metric | nnopt (median) | Spread (p10 to p90) | Reproduced if within |
134
+ |---|---|---|---|
135
+ | Real-time factor (x) | 0.0762 | 0.0759 to 0.0767 | ±10% |
136
+ | Time per request (ms) | 435.7 | 434.3 to 438.6 | ±10% |
137
+ | Peak memory (MB) | 622.8 | – | ±10% (shown only) |
138
+
139
+ Each tolerance is half of nnopt's own spread between requests, at least ±10%. Numbers land outside it when the device is warm or throttling, runs another OS build or driver, has apps or battery saver running, or is not plugged in. bench.py prints the same table for your device and writes it to `repro/results/`.
140
+
141
+ `report/reproduce.sh` runs steps 8 and 9 in one go.
sm8850-npu-fp16/build.sh ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Builds the phone runner (src/runner.c -> moonshine_stream, arm64 Android) against the LiteRT 2.3.1 C API shipped in
3
+ # vendor/litert/2.3.1, and fetches the Qualcomm QNN 2.50.0 runtime libraries (not redistributable: fetched by version
4
+ # and sha256 from Google's Maven Central mirror). The compiled NPU models ship in models/ (made by src/export_tflite.py
5
+ # and litert-aot on an x86-64 Linux machine, see README.md); this script never exports or compiles models.
6
+ #
7
+ # Needs: bash, curl, unzip, shasum or sha256sum, python3 (only for the path hash). Fetches the Android NDK r27d into
8
+ # .deps/ (or uses $ANDROID_NDK when it is that exact release). Works on Linux x86-64 and macOS.
9
+ set -euo pipefail
10
+ cd "$(dirname "$0")"
11
+ ROOT=$PWD
12
+ NAME=moonshine-streaming-npu
13
+
14
+ # .deps/ and build/ next to this script, or under $HOME/.cache when the folder is read-only (deploy.sh does the same)
15
+ . "$ROOT/src/paths.sh"
16
+ mkdir -p "$DEPS" "$BUILD"
17
+ [ "$DEPS" = "$ROOT/.deps" ] || echo "build.sh: folder is read-only; using $WORK_ROOT for .deps and build"
18
+
19
+ sha_check() { # sha_check FILE SHA
20
+ local got
21
+ if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum "$1" | cut -d' ' -f1); else got=$(shasum -a 256 "$1" | cut -d' ' -f1); fi
22
+ if [ "$got" != "$2" ]; then echo "build.sh: sha256 mismatch for $1: $got (want $2)" >&2; return 1; fi
23
+ }
24
+
25
+ # ---- Android NDK r27d
26
+ NDK_REL=r27d; NDK_REV=27.3.13750724
27
+ case "$(uname -s)" in
28
+ Linux) NDK_ZIP=android-ndk-$NDK_REL-linux.zip; NDK_SHA=601246087a682d1944e1e16dd85bc6e49560fe8b6d61255be2829178c8ed15d9; HOST_TAG=linux-x86_64 ;;
29
+ Darwin) NDK_ZIP=android-ndk-$NDK_REL-darwin.zip; NDK_SHA=e69092f9d2bfa5d1199039980a14eb91c03cc971ab5c6968fc08a8e6b84e7bb7; HOST_TAG=darwin-x86_64 ;;
30
+ *) echo "build.sh: unsupported host $(uname -s)" >&2; exit 1 ;;
31
+ esac
32
+ if [ -n "${ANDROID_NDK:-}" ] && grep -q "Pkg.Revision = $NDK_REV" "$ANDROID_NDK/source.properties" 2>/dev/null; then
33
+ NDK=$ANDROID_NDK
34
+ else
35
+ NDK=$DEPS/android-ndk-$NDK_REL
36
+ if ! grep -q "Pkg.Revision = $NDK_REV" "$NDK/source.properties" 2>/dev/null; then
37
+ echo "build.sh: fetching Android NDK $NDK_REL"
38
+ rm -rf "$NDK"
39
+ curl -fL --retry 3 -o "$DEPS/$NDK_ZIP" "https://dl.google.com/android/repository/$NDK_ZIP"
40
+ sha_check "$DEPS/$NDK_ZIP" "$NDK_SHA"
41
+ (cd "$DEPS" && unzip -q "$NDK_ZIP" && rm "$NDK_ZIP")
42
+ chmod -R u+w "$NDK"
43
+ fi
44
+ fi
45
+ CC=$NDK/toolchains/llvm/prebuilt/$HOST_TAG/bin/clang
46
+ [ -x "$CC" ] || { echo "build.sh: no clang at $CC" >&2; exit 1; }
47
+
48
+ # ---- QNN runtime 2.50.0 (QAIRT 2.50.0.260828), the release the models were compiled with
49
+ QNN_VER=2.50.0
50
+ QNN_AAR=qnn-runtime-$QNN_VER.aar
51
+ QNN_SHA=b507656e4031d8aa6a7ab0fecf725b941096737ad7440ad7ea288f7c9cc9d743
52
+ QNN_DIR=$DEPS/qnn-runtime-$QNN_VER
53
+ if [ ! -f "$QNN_DIR/.ok" ]; then
54
+ echo "build.sh: fetching qnn-runtime $QNN_VER"
55
+ rm -rf "$QNN_DIR"; mkdir -p "$QNN_DIR"
56
+ curl -fL --retry 3 -o "$DEPS/$QNN_AAR" \
57
+ "https://storage.googleapis.com/maven-central/maven2/com/qualcomm/qti/qnn-runtime/$QNN_VER/$QNN_AAR"
58
+ sha_check "$DEPS/$QNN_AAR" "$QNN_SHA"
59
+ (cd "$QNN_DIR" && unzip -q -o "$DEPS/$QNN_AAR" jni/arm64-v8a/libQnnHtp.so jni/arm64-v8a/libQnnSystem.so \
60
+ jni/arm64-v8a/libQnnHtpV81Stub.so jni/arm64-v8a/libQnnHtpV81Skel.so LICENSE.pdf && chmod -R u+w .)
61
+ rm "$DEPS/$QNN_AAR"
62
+ touch "$QNN_DIR/.ok"
63
+ fi
64
+
65
+ # ---- the runner
66
+ LRT=$ROOT/vendor/litert/2.3.1
67
+ (cd "$LRT" && if command -v sha256sum >/dev/null 2>&1; then sha256sum -c --quiet SHA256SUMS; else shasum -a 256 -c --quiet SHA256SUMS; fi)
68
+ "$CC" --target=aarch64-linux-android31 -O2 -std=c11 -Wall -Wno-unused-function \
69
+ -I"$LRT/include" "$ROOT/src/runner.c" -L"$LRT" -lLiteRt -lm -o "$BUILD/moonshine_stream"
70
+
71
+ # ---- the phone folder, flat (deploy.sh pushes it as is, with models/)
72
+ STAGE=$BUILD/stage
73
+ rm -rf "$STAGE"; mkdir -p "$STAGE/dsp"
74
+ cp "$BUILD/moonshine_stream" "$LRT/libLiteRt.so" "$LRT/libLiteRtDispatch_Qualcomm.so" "$STAGE/"
75
+ cp "$QNN_DIR/jni/arm64-v8a/libQnnHtp.so" "$QNN_DIR/jni/arm64-v8a/libQnnSystem.so" \
76
+ "$QNN_DIR/jni/arm64-v8a/libQnnHtpV81Stub.so" "$STAGE/"
77
+ cp "$QNN_DIR/jni/arm64-v8a/libQnnHtpV81Skel.so" "$STAGE/dsp/"
78
+ cp "$ROOT/src/run.sh" "$ROOT/src/port.json" "$STAGE/"
79
+ echo "build.sh: built $BUILD/moonshine_stream; phone folder staged in $STAGE (models from $ROOT/models)"
sm8850-npu-fp16/build/moonshine_stream ADDED
Binary file (30.2 kB). View file
 
sm8850-npu-fp16/build/stage/libLiteRt.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ad1a5072b09087bddeb3d7be22854350191b21239136b78ebee2120443c7305
3
+ size 5475936
sm8850-npu-fp16/build/stage/libLiteRtDispatch_Qualcomm.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab6a581ef26d83f60d03ff4ce2436d9a75b7d0c0b276357787a865e5e9dd4b7d
3
+ size 445712
sm8850-npu-fp16/build/stage/moonshine_stream ADDED
Binary file (30.2 kB). View file
 
sm8850-npu-fp16/build/stage/port.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "contract": 1,
3
+ "model_type": "speech_to_text",
4
+ "model": "Moonshine v2 Streaming Medium (moonshine-ai/moonshine-streaming, tensilier checkpoint)",
5
+ "runtime": "LiteRT 2.3.1, Qualcomm dispatch, QNN 2.50.0",
6
+ "litert_version": "2.3.1",
7
+ "backend": "litert-qnn",
8
+ "soc": "SM8850",
9
+ "htp_arch": "v81",
10
+ "qairt_version": "2.50.0",
11
+ "precision": "fp16",
12
+ "cpu_fallback": false,
13
+ "graphs": ["enc16_Qualcomm_SM8850_apply_plugin.tflite", "dec512h_Qualcomm_SM8850_apply_plugin.tflite",
14
+ "dec1536h_Qualcomm_SM8850_apply_plugin.tflite", "dec4096h_Qualcomm_SM8850_apply_plugin.tflite"]
15
+ }
sm8850-npu-fp16/build/stage/run.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Moonshine v2 Streaming Medium on the Hexagon NPU (LiteRT 2.3.1, QNN 2.50, SM8850).
2
+ # sh ./run.sh --audio IN.wav --out OUT.json [--metrics M.json] [--repeat R] [--partial-every SEC] [--realtime]
3
+ cd "$(dirname "$0")" || exit 1
4
+ export LD_LIBRARY_PATH="$PWD:/system/lib64:/vendor/lib64"
5
+ export ADSP_LIBRARY_PATH="$PWD/dsp;$PWD;/vendor/lib/rfsa/adsp;/vendor/dsp/cdsp;/system/lib/rfsa/adsp;/vendor/dsp"
6
+ exec ./moonshine_stream "$@"
sm8850-npu-fp16/demo/demo.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "input": {
3
+ "text": "5.9 s LibriSpeech utterance (public case p002), streamed in 320 ms chunks at real-time pace",
4
+ "files": [
5
+ "demo/input.wav"
6
+ ]
7
+ },
8
+ "source": "chosen by the agent: the model card has no example input; a public LibriSpeech test utterance is typical English read speech",
9
+ "output": {
10
+ "text": "Mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.",
11
+ "files": [
12
+ "demo/output.json",
13
+ "demo/metrics.json"
14
+ ]
15
+ },
16
+ "seconds": 6.44,
17
+ "device": "Samsung Galaxy S26+ (SM8850, Hexagon v81 NPU)",
18
+ "command": "sh ./run.sh --audio /data/local/tmp/nnopt/demo_in.wav --out /data/local/tmp/nnopt/demo_out.json --metrics /data/local/tmp/nnopt/demo_metrics.json --realtime",
19
+ "notes": "--realtime waits for each chunk's live arrival time; partials: 1.28s: Mister Quilp.; 2.24s: Mr. Quilter is the apostle.; 3.2s: Mister Quilter is the apostle of the middle class.; 4.16s: Mister Quilter is the apostle of the middle classes, and we are glad.; 5.12s: Mister Quilter is the apostle of the middle classes, and we are glad to welcome his. First partial at 1.28 s of audio, final transcript 155 ms after the audio ended, encoder 5.86 ms per 320 ms chunk.",
20
+ "runs": [
21
+ {
22
+ "mode": "transcribe",
23
+ "inputs": {
24
+ "audio": "demo/input.wav"
25
+ },
26
+ "outputs": {
27
+ "text": "Mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel."
28
+ },
29
+ "metrics": "demo/metrics.json"
30
+ }
31
+ ]
32
+ }
sm8850-npu-fp16/demo/input.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:799f78ed4beb4de7ceae3a809262d4ce242394342ccd1d58cef7d49dbc2def46
3
+ size 187404
sm8850-npu-fp16/demo/metrics.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"load_ms": 431.5, "runs": [{"total_ms": 6010.33, "ttft_ms": 1332.01, "first_partial_ms": 1332.01, "first_partial_audio_s": 1.28, "new_tokens": 25, "audio_s": 5.855, "rtf": 1.0265, "chunks": 20, "chunk_ms_median": 5.864, "final_decode_ms": 144.29, "decode_ms_per_token": 5.772, "partials": 5, "partial_decode_ms": 451.00, "end_latency_ms": 155.33, "realtime": true, "chunk_ms": [12.290, 5.841, 6.303, 5.632, 6.344, 5.573, 5.888, 5.838, 6.334, 5.522, 6.307, 5.799, 6.020, 6.220, 5.995, 5.636, 6.306, 5.662, 5.633, 4.503], "chunk_latency_ms": [12.290, 5.841, 6.303, 51.363, 6.345, 5.573, 71.101, 5.838, 6.334, 94.590, 6.308, 5.799, 124.134, 6.221, 5.996, 139.344, 6.307, 5.662, 5.633, 4.504]}], "peak_mem_mb": 619.7}
sm8850-npu-fp16/demo/output.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"text": "Mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.", "partials": [{"audio_s": 1.28, "text": "Mister Quilp."}, {"audio_s": 2.24, "text": "Mr. Quilter is the apostle."}, {"audio_s": 3.20, "text": "Mister Quilter is the apostle of the middle class."}, {"audio_s": 4.16, "text": "Mister Quilter is the apostle of the middle classes, and we are glad."}, {"audio_s": 5.12, "text": "Mister Quilter is the apostle of the middle classes, and we are glad to welcome his."}]}
sm8850-npu-fp16/deploy.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # bash deploy.sh DEST: pushes the built phone folder (build.sh's stage) and the compiled models to DEST on the phone
3
+ # over adb (ANDROID_SERIAL selects the phone) and leaves DEST/run.sh and DEST/port.json.
4
+ set -euo pipefail
5
+ cd "$(dirname "$0")"
6
+ ROOT=$PWD
7
+ NAME=moonshine-streaming-npu
8
+ DEST=${1:?usage: bash deploy.sh DEST}
9
+ . "$ROOT/src/paths.sh"
10
+ STAGE=$BUILD/stage
11
+ [ -x "$STAGE/moonshine_stream" ] || { echo "deploy.sh: run build.sh first ($STAGE is missing)" >&2; exit 1; }
12
+ soc=$(adb shell getprop ro.soc.model | tr -d '\r')
13
+ [ "$soc" = "SM8850" ] || echo "deploy.sh: warning: the models are compiled for SM8850, this phone is '$soc'" >&2
14
+ adb shell "mkdir -p '$DEST/dsp'"
15
+ adb push --sync "$STAGE/." "$DEST/" >/dev/null
16
+ for f in "$ROOT"/models/*.tflite "$ROOT"/models/vocab.bin; do
17
+ adb push --sync "$f" "$DEST/" >/dev/null
18
+ done
19
+ adb shell "chmod 755 '$DEST/moonshine_stream'"
20
+ echo "deploy.sh: installed into $DEST:"
21
+ adb shell "ls -l '$DEST' '$DEST/dsp'"
sm8850-npu-fp16/fetch.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run once after downloading this folder: bash fetch.sh
3
+ # Gets Qualcomm's QNN runtime (not redistributable) into build/stage/, where deploy.sh expects it.
4
+ set -euo pipefail
5
+ cd "$(dirname "$0")"
6
+ REPO=nnopt-dev/moonshine-streaming-LiteRT
7
+
8
+ # The repository's manifest first (Hugging Face counts a download when config.json is requested).
9
+ curl -fsSL "https://huggingface.co/$REPO/resolve/main/config.json" -o ../config.json
10
+
11
+ sha256_of() { if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d" " -f1; else shasum -a 256 "$1" | cut -d" " -f1; fi; }
12
+ get() { # get URL FILE SHA256: download once, check the sha256
13
+ if [ -f "$2" ] && [ "$(sha256_of "$2")" = "$3" ]; then return 0; fi
14
+ mkdir -p "$(dirname "$2")"
15
+ curl -fL --retry 3 -o "$2.part" "$1"
16
+ [ "$(sha256_of "$2.part")" = "$3" ] || { echo "fetch.sh: sha256 mismatch for $1" >&2; rm -f "$2.part"; exit 1; }
17
+ mv "$2.part" "$2"
18
+ }
19
+ git_at() { # git_at URL COMMIT DIR: the exact commit, shallow
20
+ if [ "$(git -C "$3" rev-parse HEAD 2>/dev/null || true)" = "$2" ]; then return 0; fi
21
+ rm -rf "$3"; mkdir -p "$3"
22
+ git -C "$3" init -q && git -C "$3" remote add origin "$1"
23
+ git -C "$3" fetch -q --depth 1 origin "$2" && git -C "$3" -c advice.detachedHead=false checkout -q FETCH_HEAD
24
+ }
25
+
26
+ # Qualcomm's QNN runtime: its license forbids redistribution, so it is not in this repository. It comes from
27
+ # Maven Central (Google's mirror), pinned by version and sha256, the same file build.sh uses.
28
+ QNN_VER=2.50.0
29
+ QNN_SHA=b507656e4031d8aa6a7ab0fecf725b941096737ad7440ad7ea288f7c9cc9d743
30
+ get "https://storage.googleapis.com/maven-central/maven2/com/qualcomm/qti/qnn-runtime/$QNN_VER/qnn-runtime-$QNN_VER.aar" \
31
+ ".deps/qnn-runtime-$QNN_VER.aar" "$QNN_SHA"
32
+
33
+ rm -rf ".deps/qnn-runtime-$QNN_VER" && mkdir -p ".deps/qnn-runtime-$QNN_VER" build/stage/dsp
34
+ (cd ".deps/qnn-runtime-$QNN_VER" && unzip -q -o "../qnn-runtime-$QNN_VER.aar" jni/arm64-v8a/libQnnHtp.so jni/arm64-v8a/libQnnSystem.so \
35
+ jni/arm64-v8a/libQnnHtpV81Stub.so jni/arm64-v8a/libQnnHtpV81Skel.so LICENSE.pdf && chmod -R u+w .) && touch ".deps/qnn-runtime-$QNN_VER/.ok"
36
+ Q=".deps/qnn-runtime-$QNN_VER/jni/arm64-v8a"
37
+ cp "$Q/libQnnHtp.so" "$Q/libQnnSystem.so" "$Q/libQnnHtpV81Stub.so" build/stage/ && cp "$Q/libQnnHtpV81Skel.so" build/stage/dsp/
38
+ chmod +x build/stage/moonshine_stream build/moonshine_stream
39
+ echo "fetch.sh: done. Next: bash deploy.sh /data/local/tmp/moonshine"
sm8850-npu-fp16/models/dec1536h_Qualcomm_SM8850_apply_plugin.tflite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a28fad21faf2097c7141316fb1417260338c4de8737e7f79890e4f32e5d5cc8b
3
+ size 336700512
sm8850-npu-fp16/models/dec4096h_Qualcomm_SM8850_apply_plugin.tflite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6f23a91a62d214af113ee469001b6cc82741e34ca7dadec8af6fb61a38e0e7c
3
+ size 337212512
sm8850-npu-fp16/models/dec512h_Qualcomm_SM8850_apply_plugin.tflite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b1b4993c19de245475f04f8f404a5de7e0b564eae9342c9f8ef0e0e75c48222
3
+ size 336467040
sm8850-npu-fp16/models/enc16_Qualcomm_SM8850_apply_plugin.tflite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8010fb0397243d2d67c4c84f8f76ff85d6f94cf35467c3b8157f556e2563d3b
3
+ size 256416888
sm8850-npu-fp16/models/vocab.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b3e9c217d081a41c249dd4bf991da435d339ecc139360f2b149dbdaef2a3359
3
+ size 282467
sm8850-npu-fp16/report.html ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
3
+ <title>nnopt report · moonshine-ai/moonshine-streaming</title>
4
+ <link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
5
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans+Condensed:wght@600;700&family=IBM+Plex+Sans:wght@400;500;600&display=swap">
6
+ <style>
7
+ :root {
8
+ --bg: #f3f5f2; --panel: #ffffff; --ink: #17201d; --ink-2: #33403b; --muted: #5a6762; --line: #cfd8d3;
9
+ --accent: #0b6e79; --accent-soft: #dcefee; --keep: #1d7a3e; --keep-soft: #dcf1e2; --stop: #b3261e;
10
+ --stop-soft: #f9dedb; --warn: #9a5b00; --warn-soft: #fbecd2; --grid: #e3e9e5;
11
+ --display: "IBM Plex Sans Condensed", "Arial Narrow", system-ui, sans-serif;
12
+ --body: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
13
+ --mono: "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, monospace;
14
+ color-scheme: light;
15
+ }
16
+ @media (prefers-color-scheme: dark) {
17
+ :root:not([data-theme="light"]) {
18
+ --bg: #111715; --panel: #18201d; --ink: #e4ebe7; --ink-2: #c3cec9; --muted: #9aa8a2; --line: #2c3833;
19
+ --accent: #4fc1cc; --accent-soft: #123236; --keep: #6fd394; --keep-soft: #143222; --stop: #ff8a80;
20
+ --stop-soft: #3d1715; --warn: #f0b45a; --warn-soft: #3a2a10; --grid: #222c28; color-scheme: dark;
21
+ }
22
+ }
23
+ :root[data-theme="dark"] {
24
+ --bg: #111715; --panel: #18201d; --ink: #e4ebe7; --ink-2: #c3cec9; --muted: #9aa8a2; --line: #2c3833;
25
+ --accent: #4fc1cc; --accent-soft: #123236; --keep: #6fd394; --keep-soft: #143222; --stop: #ff8a80;
26
+ --stop-soft: #3d1715; --warn: #f0b45a; --warn-soft: #3a2a10; --grid: #222c28; color-scheme: dark;
27
+ }
28
+ * { box-sizing: border-box; }
29
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.55 var(--body); }
30
+ .wrap { max-width: 1040px; margin: 0 auto; padding: 28px 20px 80px; display: grid; gap: 36px; }
31
+ h1, h2, h3 { font-family: var(--display); margin: 0; line-height: 1.15; text-wrap: balance; }
32
+ h1 { font-size: clamp(28px, 4.5vw, 40px); font-weight: 700; letter-spacing: -0.01em; }
33
+ h2 { font-size: 22px; font-weight: 600; }
34
+ h3 { font-size: 16px; font-weight: 600; }
35
+ p { margin: 0; max-width: 72ch; }
36
+ code, .mono { font-family: var(--mono); font-size: 0.88em; }
37
+ .eyebrow { font: 500 12px var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--muted); }
38
+ .sub { color: var(--muted); font-size: 13px; }
39
+ section { display: grid; gap: 14px; min-width: 0; }
40
+ header { display: grid; gap: 10px; }
41
+ .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
42
+ .tile { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; display: grid; gap: 4px; min-width: 0; }
43
+ .tile .v { font: 700 26px/1.1 var(--display); font-variant-numeric: tabular-nums; }
44
+ .tile .k { font: 500 12px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
45
+ .tile.pass { border-color: var(--keep); background: var(--keep-soft); }
46
+ .tile.fail { border-color: var(--stop); background: var(--stop-soft); }
47
+ .tile.na { border-style: dashed; }
48
+ .badge { display: inline-flex; align-items: center; gap: 6px; font: 600 12px/1 var(--mono); padding: 4px 8px; border-radius: 99px; border: 1px solid currentColor; white-space: nowrap; }
49
+ .badge.pass { color: var(--keep); } .badge.fail { color: var(--stop); } .badge.skip { color: var(--muted); } .badge.warn { color: var(--warn); }
50
+ .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 4px 0; overflow-x: auto; }
51
+ table { border-collapse: collapse; width: 100%; font-size: 14px; }
52
+ th, td { text-align: left; padding: 8px 14px; border-bottom: 1px solid var(--line); vertical-align: top; }
53
+ tr:last-child td { border-bottom: 0; }
54
+ th { font: 500 12px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .05em; }
55
+ td.num { font-family: var(--mono); font-variant-numeric: tabular-nums; white-space: nowrap; }
56
+ .flags { display: grid; gap: 6px; }
57
+ .flag { border-left: 3px solid var(--warn); background: var(--warn-soft); padding: 8px 12px; border-radius: 4px; font-size: 14px; }
58
+ .flag.bad { border-color: var(--stop); background: var(--stop-soft); }
59
+ .charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 12px; }
60
+ .chart { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px 8px; display: grid; gap: 6px; min-width: 0; }
61
+ .chart svg { width: 100%; height: auto; display: block; overflow: visible; }
62
+ .chart .ln { fill: none; stroke: var(--accent); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
63
+ .chart .pt { fill: var(--accent); stroke: var(--panel); stroke-width: 2; }
64
+ .chart .hit { fill: transparent; }
65
+ .chart .hit:hover + .pt, .chart .pt:hover { r: 5; }
66
+ .chart .gl { stroke: var(--grid); stroke-width: 1; }
67
+ .chart text { fill: var(--muted); font: 11px var(--mono); }
68
+ details { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 14px; }
69
+ summary { cursor: pointer; font-weight: 500; }
70
+ pre { font: 12px/1.5 var(--mono); white-space: pre-wrap; word-break: break-word; margin: 10px 0 0; color: var(--ink-2); }
71
+ .kv { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; font-size: 14px; }
72
+ .kv dt { color: var(--muted); font: 500 12px/1.9 var(--mono); text-transform: uppercase; letter-spacing: .05em; }
73
+ .kv dd { margin: 0; font-family: var(--mono); font-size: 13px; word-break: break-all; }
74
+ footer { color: var(--muted); font-size: 12px; }
75
+ .figs { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }
76
+ figure { margin: 0; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px; display: grid; gap: 8px; min-width: 0; }
77
+ figure svg { width: 100%; height: auto; display: block; border-radius: 4px; }
78
+ figure .frame { fill: var(--grid); }
79
+ figcaption { font-size: 13px; color: var(--ink-2); display: grid; gap: 2px; }
80
+ .box { fill: none; stroke-width: 2; vector-effect: non-scaling-stroke; }
81
+ .box.ref { stroke: var(--ink); stroke-dasharray: 6 4; }
82
+ .box.ref.missed { stroke: var(--stop); stroke-width: 3; }
83
+ .box.port { stroke: var(--accent); }
84
+ .box.port.extra { stroke: var(--warn); stroke-width: 3; }
85
+ .box.borderline { stroke: var(--muted); stroke-width: 1; opacity: .7; }
86
+ .legend { display: flex; flex-wrap: wrap; gap: 6px 18px; font: 12px var(--mono); color: var(--muted); }
87
+ .legend i { display: inline-block; width: 18px; height: 0; vertical-align: middle; margin-right: 6px; border-top: 2px solid; }
88
+ .vlm { display: grid; grid-template-columns: minmax(120px, 200px) 1fr; gap: 12px; align-items: start; }
89
+ .vlm img { width: 100%; border-radius: 4px; display: block; }
90
+ .said { display: grid; gap: 6px; font-size: 14px; }
91
+ .said .who { font: 500 11px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
92
+ .said p { white-space: pre-wrap; word-break: break-word; }
93
+ mark { background: var(--stop-soft); color: var(--ink); border-bottom: 2px solid var(--stop); padding: 0 1px; }
94
+ h4 { font: 600 14px/1.2 var(--display); margin: 0; }
95
+ .phone { border-top: 2px solid var(--line); padding-top: 24px; gap: 22px; }
96
+ .phone > .ph { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
97
+ @media (max-width: 560px) { .vlm { grid-template-columns: 1fr; } }
98
+ @media print { body { background: #fff; } .wrap { padding: 0; } }
99
+ </style></head><body><main class="wrap"><header><span class="eyebrow">nnopt verification report · Speech to text</span>
100
+ <h1>moonshine-ai/moonshine-streaming on galaxy-s26-plus</h1>
101
+ <p class="sub">Job NN-466F3D · 2026-11-03 21:51 UTC ·
102
+ nnopt-verify 0.1.0 · reference bundle <span class="mono">c7d954ce39edc45e</span></p>
103
+ </header><div class="tiles"><div class="tile pass"><span class="k">Correctness</span><span class="v">PASS</span><span class=sub>original precision policy</span></div><div class="tile na"><span class="k">Speed target</span><span class="v">no target</span></div><div class="tile pass"><span class="k">Runtime</span><span class="v">PASS</span><span class=sub>LiteRT and QNN and the Hexagon NPU, as asked</span></div><div class="tile pass"><span class="k">Decoding</span><span class="v">PASS</span><span class=sub>one token per pass, no speculative decoding</span></div><div class="tile "><span class="k">Real-time factor</span><span class="v">0.076 x</span><span class=sub>warm, median</span></div><div class="tile "><span class="k">Peak memory</span><span class="v">622.8 MB</span><span class=sub>process tree</span></div><div class="tile "><span class="k">Load time</span><span class="v">285.8 ms</span></div></div><section><h2>Correctness</h2>
104
+ <p>The port ran on 19 inputs (6 hidden, generated fresh for this job and never shown to the
105
+ porting agent) and was compared with the reference outputs captured from your code. Thresholds are for the
106
+ <b>original</b> precision policy.</p>
107
+ <div class="panel"><table><thead><tr><th>Check</th><th>Value</th><th>Threshold</th><th>Result</th></tr></thead><tbody><tr><td>All cases ran<div class=sub>19/19 cases produced valid output</div></td><td class=num>1.00</td><td class=num>&gt;= 1.00</td><td><span class="badge pass">&#10003; PASS</span></td></tr><tr><td>WER vs reference transcripts<div class=sub>port transcripts vs reference transcripts</div></td><td class=num>0.000</td><td class=num>&lt;= 0.020</td><td><span class="badge pass">&#10003; PASS</span></td></tr><tr><td>WER change vs true transcripts<div class=sub>WER vs truth: port 0.082, reference 0.082</div></td><td class=num>0.000</td><td class=num>&lt;= 0.010</td><td><span class="badge pass">&#10003; PASS</span></td></tr></tbody></table></div><details><summary>Per-case results (19 cases)</summary><div class="panel" style="margin-top:10px"><table><thead><tr><th>Case</th><th>Split</th><th>WER vs ref</th><th>Port transcript</th></tr></thead><tbody><tr><td class=num>p000</td><td>public · builtin</td><td class=num>0.000</td><td>The quick brown fox jumps over the lazy dog near the river bank.</td></tr><tr><td class=num>p001</td><td>public · builtin</td><td class=num>0.000</td><td>Please call me back when you get home this evening.</td></tr><tr><td class=num>p002</td><td>public · customer</td><td class=num>0.000</td><td>Mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.</td></tr><tr><td class=num>p003</td><td>public · customer</td><td class=num>0.000</td><td>Nor is Mister Quilter&#x27;s manner less interesting than his matter.</td></tr><tr><td class=num>p004</td><td>public · customer</td><td class=num>0.000</td><td>He tells us that at this festive season of the year, with Christmas and roast beef looming before us, similes drawn from eating and its results occur most readi</td></tr><tr><td class=num>p005</td><td>public · customer</td><td class=num>0.000</td><td>Linnell&#x27;s pictures are a sort of up guards and atom paintings and Mason&#x27;s exquisite idylls are as national as a jingo poem. Mr. Burkitt fosters landscapes smile</td></tr><tr><td class=num>p006</td><td>public · customer</td><td class=num>0.000</td><td>He laments most bitterly the divorce that has been made between decorative art and what we usually call pictures. Makes the customary appeal to the last judgmen</td></tr><tr><td class=num>p007</td><td>public · customer</td><td class=num>0.000</td><td>By Harry Quilter, M. A.</td></tr><tr><td class=num>p008</td><td>public · customer</td><td class=num>0.000</td><td>He doesn&#x27;t work at all.</td></tr><tr><td class=num>p009</td><td>public · customer</td><td class=num>0.000</td><td>Having returned to the royal cavern, Calico first pounded the gong, and then sat in the throne, wearing Ruggedo&#x27;s discarded ruby crown, and holding in his hand </td></tr><tr><td class=num>p010</td><td>public · customer</td><td class=num>0.000</td><td>The cardona&#x27;s chest still dripping blood, the ache of his overstrained eyes, even the soaring arena around him with thousands of spectators, were trivialities n</td></tr><tr><td class=num>p011</td><td>public · customer</td><td class=num>0.000</td><td>A red-haired mountain of a man with an apparently inexhaustible store of energy.</td></tr><tr><td class=num>p012</td><td>public · customer</td><td class=num>0.000</td><td>Breathing deeply, Breon softly spoke the auto-hypnotic phrases that triggered the process.</td></tr><tr><td class=num>h000</td><td>hidden · generated</td><td class=num>0.000</td><td>My brother cleaned the lantern and gave it to Dalai.</td></tr><tr><td class=num>h001</td><td>hidden · generated</td><td class=num>0.000</td><td>The hidden market in Accra opens at 5:00 in the morning.</td></tr><tr><td class=num>h002</td><td>hidden · generated</td><td class=num>0.000</td><td>When said, the weather in Dauphereza was busy all week.</td></tr><tr><td class=num>h003</td><td>hidden · generated</td><td class=num>0.000</td><td>Nobody expected the ancient camera to sell for so much money.</td></tr><tr><td class=num>h004</td><td>hidden · generated</td><td class=num>0.000</td><td>There are 16 boats waiting in the harbor tonight.</td></tr><tr><td class=num>h005</td><td>hidden · generated</td><td class=num>0.000</td><td>Anna and Bruno met for coffee near the Musum in Marrakech.</td></tr></tbody></table></div></details></section><section><h2>Runtime</h2>
108
+ <p>Asked for <b>LiteRT; every model graph on the Hexagon NPU, no GPU or CPU fallback (tokenizer and glue code on CPU are fine)</b>. Clean build, the port's own code and build log: uses LiteRT and QNN; runs on the Hexagon NPU: the kit&#x27;s own run on the phone loaded the HTP, every shipped NPU graph is all DISPATCH_OP, CPU fallback disabled.</p>
109
+ <ul><li class="mono">src/runner.c:95: if (LiteRtCreateModelFromFile(env, path, &amp;g-&gt;model) != kLiteRtStatusOk) DIE(&quot;cannot load model %s&quot;, path);</li><li class="mono">src/export_tflite.py:47: from ai_edge_litert.interpreter import Interpreter</li><li class="mono">src/aot_compile.py:8: from ai_edge_litert.aot import aot_compile as aot_lib</li><li class="mono">build log: build.sh: fetching qnn-runtime 2.50.0</li><li class="mono">the kit&#x27;s run on the phone: Successfully opened file /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so</li><li class="mono">the kit&#x27;s run on the phone: fully accelerated 3/4 · Skel V81 loaded · user PD ✓</li><li class="mono">npu-graphs: 4 of 4 NPU graphs all-DISPATCH · 0 CPU ops · SM8850 · QAIRT 2.50.0</li><li class="mono">NOTES.md: Successfully opened file /data/local/tmp/nnopt/port/dsp/./libQnnHtpV81Skel.so</li></ul></section><section><h2>NPU</h2><h3>NPU graphs</h3><p>4 of 4 NPU graphs all-DISPATCH · 0 CPU ops · SM8850 · QAIRT 2.50.0</p><table><tr><th>graph</th><th>runs on</th><th>DISPATCH_OP</th><th>CPU ops</th><th>SoC</th><th>QAIRT</th><th>precision</th><th>size</th></tr><tr><td>dec1536h</td><td>npu</td><td>1</td><td>0</td><td>SM8850</td><td>2.50.0</td><td>fp16</td><td>321 MB</td></tr><tr><td>dec4096h</td><td>npu</td><td>1</td><td>0</td><td>SM8850</td><td>2.50.0</td><td>fp16</td><td>322 MB</td></tr><tr><td>dec512h</td><td>npu</td><td>1</td><td>0</td><td>SM8850</td><td>2.50.0</td><td>fp16</td><td>321 MB</td></tr><tr><td>enc16</td><td>npu</td><td>1</td><td>0</td><td>SM8850</td><td>2.50.0</td><td>fp16</td><td>245 MB</td></tr></table><details><summary>output</summary><pre class="mono">$ nnopt-verify npu-graphs port/models --soc SM8850
110
+ graph ops SoC prec size ok
111
+ dec1536h 1 sig · 1 DISP SM8850 fp16 321M ✓
112
+ dec4096h 1 sig · 1 DISP SM8850 fp16 322M ✓
113
+ dec512h 1 sig · 1 DISP SM8850 fp16 321M ✓
114
+ enc16 1 sig · 1 DISP SM8850 fp16 245M ✓
115
+ 4 of 4 NPU graphs all-DISPATCH · 0 CPU ops · SM8850 · QAIRT 2.50.0</pre></details><h3>NPU on the device</h3><p>fully accelerated 3/4 · Skel V81 loaded · user PD ✓</p><details><summary>output</summary><pre class="mono">$ adb logcat -c; &lt;the kit&#x27;s runs&gt;; logcat -d -v time | grep -E &#x27;Skel\.so|user PD|fully accelerated|IsNonCpuFullyAccelerated|Replacing [0-9]+ out of|Partitioned subgraph|per graph ms|QnnDsp|LiteRt|litert|DISPATCH&#x27; | tail -n 400
116
+ ode(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
117
+ 11-03 13:42:44.739 I/moonshine_stream(28412): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3240: libQnnHtpV81Skel.so, handle 0x2cea10
118
+ 11-03 13:42:44.751 I/moonshine_stream(28412): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3610: remote_handle64_close: closed handle 0xb4000073a9e43960 remote handle 0x2cea10 name libQnnHtpV81Skel.so, refs 0, domain 100000, open_refs 0, non-domain handle list is empty
119
+ 11-03 13:42:46.038 I/moonshine_stream(28512): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3365: WARNING: get_handle_priority_from_uri: libQnnHtpV81Skel.so lib opened handle without priority token
120
+ 11-03 13:42:46.066 I/moonshine_stream(28512): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:6284: Created user PD on domain 100000, dbg_trace 0x0, enabled attr=&gt; RPC timeout:10000, Dbg Mode:Y, CRC:N, Unsigned:Y, Signed:N, Adapt QOS:N, PD dump: (Config:N, Dbg:N), Perf: (Kernel:N, DSP:N), Iregion:N, QTF:N, UAF:N userPD initmem len:0x500000, Log pkt: N
121
+ 11-03 13:42:46.070 E/moonshine_stream(28512): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:377: Error 0x2: apps_std_fopen_fd failed for /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/cdsp/./libQnnHtpV81Skel.so (No such file or directory)
122
+ 11-03 13:42:46.077 D/moonshine_stream(28512): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:369: apps_std_fopen_fd done for /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so with fsize:19708192 fopen:16us, fstat:2us, read:6158us, rpc_alloc:187us, mmap:411us fd 0x12 error_code 0x0
123
+ 11-03 13:42:46.077 I/moonshine_stream(28512): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:1236: Successfully opened file /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so
124
+ 11-03 13:42:46.118 I/moonshine_stream(28512): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3471: remote_handle64_open: opened handle 0xb400007100e49870 (remote 0x2cea10) for file:///libQnnHtpV81Skel.so?qnn_2_50_0_skel_handle_invoke&amp;_modver=1.0&amp;_dom=cdsp on domain 100000 (spawn time 29625 us, load time 50132 us), refs 1
125
+ 11-03 13:42:46.134 I/tflite (28512): Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
126
+ 11-03 13:42:46.227 I/tflite (28512): Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
127
+ 11-03 13:42:46.813 I/moonshine_stream(28512): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3240: libQnnHtpV81Skel.so, handle 0x2cea10
128
+ 11-03 13:42:46.824 I/moonshine_stream(28512): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3610: remote_handle64_close: closed handle 0xb400007100e49870 remote handle 0x2cea10 name libQnnHtpV81Skel.so, refs 0, domain 100000, open_refs 0, non-domain handle list is empty
129
+ 11-03 13:42:48.146 I/moonshine_stream(28613): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3365: WARNING: get_handle_priority_from_uri: libQnnHtpV81Skel.so lib opened handle without priority token
130
+ 11-03 13:42:48.176 I/moonshine_stream(28613): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:6284: Created user PD on domain 100000, dbg_trace 0x0, enabled attr=&gt; RPC timeout:10000, Dbg Mode:Y, CRC:N, Unsigned:Y, Signed:N, Adapt QOS:N, PD dump: (Config:N, Dbg:N), Perf: (Kernel:N, DSP:N), Iregion:N, QTF:N, UAF:N userPD initmem len:0x500000, Log pkt: N
131
+ 11-03 13:42:48.180 E/moonshine_stream(28613): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:377: Error 0x2: apps_std_fopen_fd failed for /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/cdsp/./libQnnHtpV81Skel.so (No such file or directory)
132
+ 11-03 13:42:48.186 D/moonshine_stream(28613): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:369: apps_std_fopen_fd done for /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so with fsize:19708192 fopen:14us, fstat:2us, read:5335us, rpc_alloc:161us, mmap:384us fd 0x12 error_code 0x0
133
+ 11-03 13:42:48.186 I/moonshine_stream(28613): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:1236: Successfully opened file /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so
134
+ 11-03 13:42:48.230 I/moonshine_stream(28613): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3471: remote_handle64_open: opened handle 0xb400007103849af0 (remote 0x2cea10) for file:///libQnnHtpV81Skel.so?qnn_2_50_0_skel_handle_invoke&amp;_modver=1.0&amp;_dom=cdsp on domain 100000 (spawn time 31685 us, load time 52442 us), refs 1
135
+ 11-03 13:42:48.246 I/tflite (28613): Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
136
+ 11-03 13:42:48.339 I/tflite (28613): Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
137
+ 11-03 13:42:48.889 I/moonshine_stream(28613): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3240: libQnnHtpV81Skel.so, handle 0x2cea10
138
+ 11-03 13:42:48.901 I/moonshine_stream(28613): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3610: remote_handle64_close: closed handle 0xb400007103849af0 remote handle 0x2cea10 name libQnnHtpV81Skel.so, refs 0, domain 100000, open_refs 0, non-domain handle list is empty
139
+ 11-03 13:42:50.178 I/moonshine_stream(28698): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3365: WARNING: get_handle_priority_from_uri: libQnnHtpV81Skel.so lib opened handle without priority token
140
+ 11-03 13:42:50.207 I/moonshine_stream(28698): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:6284: Created user PD on domain 100000, dbg_trace 0x0, enabled attr=&gt; RPC timeout:10000, Dbg Mode:Y, CRC:N, Unsigned:Y, Signed:N, Adapt QOS:N, PD dump: (Config:N, Dbg:N), Perf: (Kernel:N, DSP:N), Iregion:N, QTF:N, UAF:N userPD initmem len:0x500000, Log pkt: N
141
+ 11-03 13:42:50.211 E/moonshine_stream(28698): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:377: Error 0x2: apps_std_fopen_fd failed for /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/cdsp/./libQnnHtpV81Skel.so (No such file or directory)
142
+ 11-03 13:42:50.218 D/moonshine_stream(28698): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:369: apps_std_fopen_fd done for /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so with fsize:19708192 fopen:42us, fstat:1us, read:5476us, rpc_alloc:236us, mmap:408us fd 0x12 error_code 0x0
143
+ 11-03 13:42:50.218 I/moonshine_stream(28698): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:1236: Successfully opened file /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so
144
+ 11-03 13:42:50.261 I/moonshine_stream(28698): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3471: remote_handle64_open: opened handle 0xb4000077bc044140 (remote 0x2cea10) for file:///libQnnHtpV81Skel.so?qnn_2_50_0_skel_handle_invoke&amp;_modver=1.0&amp;_dom=cdsp on domain 100000 (spawn time 30966 us, load time 51711 us), refs 1
145
+ 11-03 13:42:50.278 I/tflite (28698): Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
146
+ 11-03 13:42:50.373 I/tflite (28698): Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
147
+ 11-03 13:42:50.888 I/moonshine_stream(28698): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3240: libQnnHtpV81Skel.so, handle 0x2cea10
148
+ 11-03 13:42:50.900 I/moonshine_stream(28698): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3610: remote_handle64_close: closed handle 0xb4000077bc044140 remote handle 0x2cea10 name libQnnHtpV81Skel.so, refs 0, domain 100000, open_refs 0, non-domain handle list is empty
149
+ 11-03 13:42:52.098 I/moonshine_stream(28786): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3365: WARNING: get_handle_priority_from_uri: libQnnHtpV81Skel.so lib opened handle without priority token
150
+ 11-03 13:42:52.123 I/moonshine_stream(28786): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:6284: Created user PD on domain 100000, dbg_trace 0x0, enabled attr=&gt; RPC timeout:10000, Dbg Mode:Y, CRC:N, Unsigned:Y, Signed:N, Adapt QOS:N, PD dump: (Config:N, Dbg:N), Perf: (Kernel:N, DSP:N), Iregion:N, QTF:N, UAF:N userPD initmem len:0x500000, Log pkt: N
151
+ 11-03 13:42:52.128 E/moonshine_stream(28786): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:377: Error 0x2: apps_std_fopen_fd failed for /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/cdsp/./libQnnHtpV81Skel.so (No such file or directory)
152
+ 11-03 13:42:52.138 D/moonshine_stream(28786): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:369: apps_std_fopen_fd done for /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so with fsize:19708192 fopen:27us, fstat:3us, read:8845us, rpc_alloc:321us, mmap:402us fd 0x12 error_code 0x0
153
+ 11-03 13:42:52.138 I/moonshine_stream(28786): vendor/qcom/proprietary/adsprpc/src/apps_std_imp.c:1236: Successfully opened file /data/local/tmp/nnopt-verify/check-27033ada/port/dsp/./libQnnHtpV81Skel.so
154
+ 11-03 13:42:52.181 I/moonshine_stream(28786): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3471: remote_handle64_open: opened handle 0xb4000074e62415a0 (remote 0x2ce7a0) for file:///libQnnHtpV81Skel.so?qnn_2_50_0_skel_handle_invoke&amp;_modver=1.0&amp;_dom=cdsp on domain 100000 (spawn time 27399 us, load time 56153 us), refs 1
155
+ 11-03 13:42:52.200 I/tflite (28786): Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
156
+ 11-03 13:42:52.287 I/tflite (28786): Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
157
+ 11-03 13:42:52.816 I/moonshine_stream(28786): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3240: libQnnHtpV81Skel.so, handle 0x2ce7a0
158
+ 11-03 13:42:52.827 I/moonshine_stream(28786): vendor/qcom/proprietary/adsprpc/src/fastrpc_apps_user.c:3610: remote_handle64_close: closed handle 0xb4000074e62415a0 remote handle 0x2ce7a0 name libQnnHtpV81Skel.so, refs 0, domain 100000, open_refs 0, non-domain handle list is empty
159
+
160
+ # the kit&#x27;s runs (stdout and stderr), proof lines
161
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
162
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
163
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
164
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
165
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
166
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
167
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
168
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
169
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
170
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
171
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
172
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
173
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
174
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
175
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
176
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
177
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
178
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec1536h_Qualcomm_SM8850_apply_plugin.tflite
179
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
180
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
181
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
182
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec1536h_Qualcomm_SM8850_apply_plugin.tflite
183
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
184
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
185
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
186
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec1536h_Qualcomm_SM8850_apply_plugin.tflite
187
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
188
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
189
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
190
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
191
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
192
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
193
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
194
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
195
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
196
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
197
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
198
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec1536h_Qualcomm_SM8850_apply_plugin.tflite
199
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
200
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
201
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
202
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec1536h_Qualcomm_SM8850_apply_plugin.tflite
203
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
204
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
205
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
206
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
207
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
208
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
209
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
210
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
211
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
212
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
213
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
214
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
215
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
216
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
217
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
218
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
219
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
220
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
221
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
222
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
223
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
224
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
225
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
226
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
227
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
228
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
229
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
230
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
231
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
232
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
233
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=enc16_Qualcomm_SM8850_apply_plugin.tflite
234
+ LiteRT fully accelerated on the NPU: yes (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=dec512h_Qualcomm_SM8850_apply_plugin.tflite
235
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).
236
+ VERBOSE: Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node, yielding 1 partitions for subgraph 0 (main).</pre></details><h3>benchmark_model (Google LiteRT 2.3.1)</h3><p>4 of 4 timed · 4 at 100% NPU</p><table><tr><th>graph</th><th>signature</th><th>avg ms</th><th>min ms</th><th>max ms</th><th>% on the NPU</th></tr><tr><td>dec1536h</td><td></td><td>6.689</td><td>6.602</td><td>7.248</td><td>100.0</td></tr><tr><td>dec4096h</td><td></td><td>8.7</td><td>8.634</td><td>8.898</td><td>100.0</td></tr><tr><td>dec512h</td><td></td><td>5.579</td><td>5.514</td><td>5.979</td><td>100.0</td></tr><tr><td>enc16</td><td></td><td>4.337</td><td>4.285</td><td>4.481</td><td>100.0</td></tr></table><details><summary>output</summary><pre class="mono">$ /data/local/tmp/nnopt-verify/npu-bench/benchmark_model --graph=/data/local/tmp/nnopt/port/dec1536h_Qualcomm_SM8850_apply_plugin.tflite --use_npu=true --use_gpu=false --qualcomm_htp_performance_mode=burst --dispatch_library_path=/data/local/tmp/nnopt-verify/npu-bench --num_runs=20 --warmup_runs=3 (+3 more)
237
+ dec1536h: avg 6.689 ms · min 6.602 · max 7.248 · 100.0% NPU
238
+ dec4096h: avg 8.7 ms · min 8.634 · max 8.898 · 100.0% NPU
239
+ dec512h: avg 5.579 ms · min 5.514 · max 5.979 · 100.0% NPU
240
+ enc16: avg 4.337 ms · min 4.285 · max 4.481 · 100.0% NPU
241
+
242
+ $ /data/local/tmp/nnopt-verify/npu-bench/benchmark_model --graph=/data/local/tmp/nnopt/port/dec1536h_Qualcomm_SM8850_apply_plugin.tflite --use_npu=true --use_gpu=false --qualcomm_htp_performance_mode=burst --dispatch_library_path=/data/local/tmp/nnopt-verify/npu-bench --num_runs=20 --warmup_runs=3
243
+ exit 0
244
+ [benchmark_litert_model.h:94] Model initialization: 182.51 ms
245
+ INFO: [benchmark_litert_model.h:96] Warmup (first): 10.71 ms
246
+ INFO: [benchmark_litert_model.h:98] Warmup (avg): 6.74 ms (75 runs)
247
+ INFO: [benchmark_litert_model.h:100] Inference (avg): 6.69 ms (150 runs)
248
+ INFO: [benchmark_litert_model.h:104] Inference (min): 6.60 ms
249
+ INFO: [benchmark_litert_model.h:106] Inference (max): 7.25 ms
250
+ INFO: [benchmark_litert_model.h:108] Inference (std): 0.07
251
+ INFO: [benchmark_litert_model.h:115] Throughput: 8994.25 MB/s
252
+ INFO: [benchmark_litert_model.h:124]
253
+ Memory Usage:
254
+ INFO: [benchmark_litert_model.h:126] Init footprint: 331.59 MB
255
+ INFO: [benchmark_litert_model.h:128] Overall footprint: 357.92 MB
256
+ INFO: [benchmark_litert_model.h:135] Peak memory usage not available. (peak_mem_mb &lt;= 0)
257
+ INFO: [benchmark_litert_model.h:138] ======================================
258
+
259
+ INFO: [accelerator_registry.cc:43] DestroyAccelerator: ptr=0xb400007bf7e04380, name=CpuAccelerator
260
+ INFO: [accelerator_registry.cc:43] DestroyAccelerator: ptr=0xb400007bf7e040e0, name=NpuAccelerator
261
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
262
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
263
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
264
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
265
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
266
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
267
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
268
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
269
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
270
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
271
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
272
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
273
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
274
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
275
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
276
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
277
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
278
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
279
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
280
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
281
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
282
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
283
+ 1896549000.0ms [ INFO ] Free context with QnnGraphTransformerAdapter1896556000.0ms [ INFO ] QnnGraphTransformer context freed successfully 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnContext_free started. context = 0x1
284
+ 0.0ms [WARNING] QnnDsp &lt;W&gt; m_CFBCallbackInfoObj is not initialized, return emptyList
285
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; Number of existing contexts: 0, graphs: 0
286
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnContext_free done successfully.
287
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; Exiting thread
288
+
289
+ $ /data/local/tmp/nnopt-verify/npu-bench/benchmark_model --graph=/data/local/tmp/nnopt/port/dec4096h_Qualcomm_SM8850_apply_plugin.tflite --use_npu=true --use_gpu=false --qualcomm_htp_performance_mode=burst --dispatch_library_path=/data/local/tmp/nnopt-verify/npu-bench --num_runs=20 --warmup_runs=3
290
+ exit 0
291
+ [benchmark_litert_model.h:94] Model initialization: 182.78 ms
292
+ INFO: [benchmark_litert_model.h:96] Warmup (first): 12.71 ms
293
+ INFO: [benchmark_litert_model.h:98] Warmup (avg): 8.77 ms (58 runs)
294
+ INFO: [benchmark_litert_model.h:100] Inference (avg): 8.70 ms (115 runs)
295
+ INFO: [benchmark_litert_model.h:104] Inference (min): 8.63 ms
296
+ INFO: [benchmark_litert_model.h:106] Inference (max): 8.90 ms
297
+ INFO: [benchmark_litert_model.h:108] Inference (std): 0.03
298
+ INFO: [benchmark_litert_model.h:115] Throughput: 18230.55 MB/s
299
+ INFO: [benchmark_litert_model.h:124]
300
+ Memory Usage:
301
+ INFO: [benchmark_litert_model.h:126] Init footprint: 331.96 MB
302
+ INFO: [benchmark_litert_model.h:128] Overall footprint: 402.01 MB
303
+ INFO: [benchmark_litert_model.h:135] Peak memory usage not available. (peak_mem_mb &lt;= 0)
304
+ INFO: [benchmark_litert_model.h:138] ======================================
305
+
306
+ INFO: [accelerator_registry.cc:43] DestroyAccelerator: ptr=0xb400006f6da05a10, name=CpuAccelerator
307
+ INFO: [accelerator_registry.cc:43] DestroyAccelerator: ptr=0xb400006f6da05cb0, name=NpuAccelerator
308
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
309
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
310
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
311
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
312
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
313
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
314
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
315
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
316
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
317
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
318
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
319
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
320
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
321
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
322
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
323
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
324
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
325
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
326
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
327
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
328
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
329
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
330
+ 2234137000.0ms [ INFO ] Free context with QnnGraphTransformerAdapter2234150000.0ms [ INFO ] QnnGraphTransformer context freed successfully 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnContext_free started. context = 0x1
331
+ 0.0ms [WARNING] QnnDsp &lt;W&gt; m_CFBCallbackInfoObj is not initialized, return emptyList
332
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; Number of existing contexts: 0, graphs: 0
333
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnContext_free done successfully.
334
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; Exiting thread
335
+
336
+ $ /data/local/tmp/nnopt-verify/npu-bench/benchmark_model --graph=/data/local/tmp/nnopt/port/dec512h_Qualcomm_SM8850_apply_plugin.tflite --use_npu=true --use_gpu=false --qualcomm_htp_performance_mode=burst --dispatch_library_path=/data/local/tmp/nnopt-verify/npu-bench --num_runs=20 --warmup_runs=3
337
+ exit 0
338
+ : [benchmark_litert_model.h:94] Model initialization: 178.11 ms
339
+ INFO: [benchmark_litert_model.h:96] Warmup (first): 9.50 ms
340
+ INFO: [benchmark_litert_model.h:98] Warmup (avg): 5.62 ms (89 runs)
341
+ INFO: [benchmark_litert_model.h:100] Inference (avg): 5.58 ms (180 runs)
342
+ INFO: [benchmark_litert_model.h:104] Inference (min): 5.51 ms
343
+ INFO: [benchmark_litert_model.h:106] Inference (max): 5.98 ms
344
+ INFO: [benchmark_litert_model.h:108] Inference (std): 0.07
345
+ INFO: [benchmark_litert_model.h:115] Throughput: 3627.14 MB/s
346
+ INFO: [benchmark_litert_model.h:124]
347
+ Memory Usage:
348
+ INFO: [benchmark_litert_model.h:126] Init footprint: 331.20 MB
349
+ INFO: [benchmark_litert_model.h:128] Overall footprint: 339.95 MB
350
+ INFO: [benchmark_litert_model.h:135] Peak memory usage not available. (peak_mem_mb &lt;= 0)
351
+ INFO: [benchmark_litert_model.h:138] ======================================
352
+
353
+ INFO: [accelerator_registry.cc:43] DestroyAccelerator: ptr=0xb400006e4ee0ad20, name=CpuAccelerator
354
+ INFO: [accelerator_registry.cc:43] DestroyAccelerator: ptr=0xb400006e4ee09cf0, name=NpuAccelerator
355
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
356
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
357
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
358
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
359
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
360
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
361
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
362
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
363
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
364
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
365
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
366
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
367
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
368
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
369
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
370
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
371
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
372
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
373
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
374
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
375
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
376
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
377
+ 1758580000.0ms [ INFO ] Free context with QnnGraphTransformerAdapter1758593000.0ms [ INFO ] QnnGraphTransformer context freed successfully 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnContext_free started. context = 0x1
378
+ 0.0ms [WARNING] QnnDsp &lt;W&gt; m_CFBCallbackInfoObj is not initialized, return emptyList
379
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; Number of existing contexts: 0, graphs: 0
380
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnContext_free done successfully.
381
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; Exiting thread
382
+
383
+ $ /data/local/tmp/nnopt-verify/npu-bench/benchmark_model --graph=/data/local/tmp/nnopt/port/enc16_Qualcomm_SM8850_apply_plugin.tflite --use_npu=true --use_gpu=false --qualcomm_htp_performance_mode=burst --dispatch_library_path=/data/local/tmp/nnopt-verify/npu-bench --num_runs=20 --warmup_runs=3
384
+ exit 0
385
+ .h:126] Init footprint: 254.62 MB
386
+ INFO: [benchmark_litert_model.h:128] Overall footprint: 255.24 MB
387
+ INFO: [benchmark_litert_model.h:135] Peak memory usage not available. (peak_mem_mb &lt;= 0)
388
+ INFO: [benchmark_litert_model.h:138] ======================================
389
+
390
+ INFO: [accelerator_registry.cc:43] DestroyAccelerator: ptr=0xb4000072d9406230, name=CpuAccelerator
391
+ INFO: [accelerator_registry.cc:43] DestroyAccelerator: ptr=0xb4000072d9405ac0, name=NpuAccelerator
392
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
393
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
394
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
395
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
396
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
397
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
398
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
399
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
400
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
401
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
402
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
403
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
404
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
405
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
406
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
407
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
408
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
409
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
410
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
411
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
412
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
413
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
414
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
415
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
416
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
417
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
418
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
419
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
420
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
421
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
422
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister started
423
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnMem_deRegister done. status 0x0
424
+ 1674846000.0ms [ INFO ] Free context with QnnGraphTransformerAdapter1674855000.0ms [ INFO ] QnnGraphTransformer context freed successfully 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnContext_free started. context = 0x1
425
+ 0.0ms [WARNING] QnnDsp &lt;W&gt; m_CFBCallbackInfoObj is not initialized, return emptyList
426
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; Number of existing contexts: 0, graphs: 0
427
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; QnnContext_free done successfully.
428
+ 0.0ms [ INFO ] QnnDsp &lt;I&gt; Exiting thread</pre></details></section><section><h2>Speed and memory</h2>
429
+ <p>2 warm-up runs, then 5 timed runs of 3 requests each (the first
430
+ request of each run is cold). Timed on the device's own clock.</p>
431
+ <div class="panel"><table><thead><tr><th>Metric (warm requests)</th><th>Median</th><th>p10</th><th>p90</th><th>n</th></tr></thead><tbody><tr><td>Real-time factor</td><td class=num>0.076 x</td><td class=num>0.076 x</td><td class=num>0.077 x</td><td class=num>10</td></tr><tr><td>Request time</td><td class=num>435.7 ms</td><td class=num>434.3 ms</td><td class=num>438.6 ms</td><td class=num>10</td></tr><tr><td>Decode speed</td><td class=num>40.31 tok/s</td><td class=num>40.08 tok/s</td><td class=num>40.42 tok/s</td><td class=num>10</td></tr><tr><td>Time to first token</td><td class=num>38.59 ms</td><td class=num>38.34 ms</td><td class=num>39.08 ms</td><td class=num>10</td></tr><tr><td>new_tokens</td><td class=num>17.00</td><td class=num>17.00</td><td class=num>17.00</td><td class=num>10</td></tr><tr><td>Request time (cold)</td><td class=num>441.1 ms</td><td class=num>440.8 ms</td><td class=num>450.0 ms</td><td class=num>5</td></tr><tr><td>Load time</td><td class=num>285.8 ms</td><td class=num>266.6 ms</td><td class=num>294.6 ms</td><td class=num>5</td></tr><tr><td>Process wall time</td><td class=num>1701 ms</td><td class=num>1675 ms</td><td class=num>1709 ms</td><td class=num>5</td></tr><tr><td>Peak RSS (process tree)</td><td class=num>622.8 MB</td><td></td><td></td><td></td></tr><tr><td>Peak VmHWM (process tree)</td><td class=num>622.8 MB</td><td></td><td></td><td></td></tr><tr><td>Peak memory (self-reported)</td><td class=num>621.5 MB</td><td></td><td></td><td></td></tr></tbody></table></div><p class="sub">External cross-check (paired --repeat 3 vs 1, 5 pairs, device clock): Request time: 440.8 ms; Real-time factor: 0.077 x. Graded values are capped by it.</p><dl class="kv"><dt>Decode, % of memory roofline</dt><dd>23.2% of 174.0 tok/s</dd><dt>Bytes per decoded token</dt><dd>0.402 GB: half of the 0.402 B parameters taken as the decoder (the model facts give no decoder size)</dd><dt>Specs used</dt><dd>69.93 GB/s, 18325 GFLOP/s</dd><dt>Figures</dt><dd>NPU figures; measured by lab/npu probe (NN-174CC0) on 2026-10-31: fp16 weight stream 69.93 GB/s (bw_l24), fp16 matmul 18.325 TFLOPS, int8 matmul 29.023 TOPS; LiteRT 2.3.1 + Qualcomm dispatch, QAIRT 2.50, burst</dd></dl></section><section><h2>Environment and reproducibility</h2><dl class="kv"><dt>os</dt><dd>android</dd><dt>gpu</dt><dd>Adreno 840</dd><dt>soc</dt><dd>Snapdragon 8 Elite Gen 5</dd><dt>brand</dt><dd>Samsung</dd><dt>device</dt><dd>Samsung Galaxy S26+</dd><dt>ram_gb</dt><dd>12</dd><dt>android</dt><dd>16</dd><dt>gpu_apis</dt><dd>[&#x27;OpenCL&#x27;, &#x27;Vulkan&#x27;]</dd><dt>released</dt><dd>2026-02</dd><dt>roofline</dt><dd>{&#x27;npu&#x27;: {&#x27;job&#x27;: &#x27;NN-174CC0&#x27;, &#x27;source&#x27;: &#x27;measured by lab/npu probe (NN-174CC0) on 2026-10-31: fp16 weight stream 69.93 GB/s (bw_l24), fp16 matmul 18.325 TFLOPS, int8 matmul 29.023 TOPS; LiteRT 2.3.1 + Qualcomm dispatch, QAIRT 2.50, burst&#x27;, &#x27;measured&#x27;: True, &#x27;measured_at&#x27;: &#x27;2026-10-31&#x27;, &#x27;measured_by&#x27;: &#x27;probe&#x27;, &#x27;peak_int8_tops&#x27;: 29.023, &#x27;peak_fp16_tflops&#x27;: 18.325, &#x27;mem_bandwidth_gbps&#x27;: 69.93, &#x27;mem_bandwidth_int8_gbps&#x27;: 70.46}, &#x27;spec&#x27;: {&#x27;source&#x27;: &#x27;spec-sheet estimate, not yet measured: LPDDR5X-10667 64-bit; Adreno 840 compute is a rough estimate&#x27;, &#x27;peak_int8_tops&#x27;: 6.0, &#x27;peak_fp16_tflops&#x27;: 6.0, &#x27;mem_bandwidth_gbps&#x27;: 85.3}, &#x27;source&#x27;: &#x27;measured on the device by NN-A61C46 on 2026-11-03: GPU read 72.6 GB/s (OpenCL read_v4)&#x27;, &#x27;measured&#x27;: True, &#x27;device_best&#x27;: {&#x27;cpu_job&#x27;: &#x27;NN-DA0137&#x27;, &#x27;gpu_job&#x27;: &#x27;NN-DA0137&#x27;, &#x27;cpu_read_gbps&#x27;: 74.03, &#x27;gpu_read_gbps&#x27;: 73.18, &#x27;cpu_measured_at&#x27;: &#x27;2026-10-23T04:46:29+00:00&#x27;, &#x27;gpu_measured_at&#x27;: &#x27;2026-10-23T04:46:29+00:00&#x27;}, &#x27;measured_at&#x27;: &#x27;2026-11-03&#x27;, &#x27;measured_by&#x27;: &#x27;device&#x27;, &#x27;device_probe&#x27;: {&#x27;job&#x27;: &#x27;NN-A61C46&#x27;, &#x27;measured_at&#x27;: &#x27;2026-11-03T03:40:37+00:00&#x27;, &#x27;cpu_read_gbps&#x27;: 60.38, &#x27;gpu_read_gbps&#x27;: 72.6}, &#x27;peak_int8_tops&#x27;: 6.0, &#x27;peak_fp16_tflops&#x27;: 6.0, &#x27;mem_bandwidth_gbps&#x27;: 72.6}</dd><dt>model_id</dt><dd>m2q</dd><dt>version_id</dt><dd>36</dd><dt>name</dt><dd>Samsung Galaxy S26+</dd><dt>processor</dt><dd>npu</dd><dt>executor</dt><dd>adb</dd><dt>reference python</dt><dd>3.12.3</dd><dt>reference numpy</dt><dd>2.5.4</dd><dt>reference nnopt_verify</dt><dd>0.1.0</dd><dt>reference platform</dt><dd>Linux-7.0.0-1014-gcp-x86_64-with-glibc2.39</dd></dl><p class="sub">REPRO.md, next to this report, lists the tools, the model and every step to get these numbers on your own device; reproduce.sh runs the measurement. results.csv and results.json hold every number in this report.</p></section><footer>Generated by nnopt-verify 0.1.0. Correctness is graded on all inputs; speed figures are medians of warm requests unless marked cold.</footer></main></body></html>
sm8850-npu-fp16/report/reproduce.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # Reproduce nnopt's numbers on your own device (REPRO.md). Build and deploy first (REPRO.md, steps 4 to 6).
3
+ # Needs python3, and adb (Android; ANDROID_SERIAL with several phones) or ssh (SSH_TARGET=user@host).
4
+ here=$(cd "$(dirname "$0")" && pwd)
5
+ root=$here; [ -d "$root/repro" ] || root=$(dirname "$here")
6
+ cd "$root" || exit 2
7
+ if [ ! -f repro/bench.py ]; then echo "no repro/ folder next to REPRO.md"; exit 2; fi
8
+ rc=0
9
+ python3 repro/bench.py "$@" || rc=$?
10
+ python3 repro/bench.py --check "$@" || rc=$?
11
+ exit $rc
sm8850-npu-fp16/report/results.csv ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ section,name,value,unit_or_op,threshold,passed
2
+ grade,correctness,True,,,True
3
+ grade,speed_target_met,,,,
4
+ check,cases_completed,1.0,>=,1.0,True
5
+ check,wer_vs_reference,0.0,<=,0.02,True
6
+ check,wer_delta_vs_truth,0.0,<=,0.01,True
7
+ check_metric,wer_vs_reference,0.0,,,
8
+ check_metric,wer_port_vs_truth,0.08235,,,
9
+ check_metric,wer_reference_vs_truth,0.08235,,,
10
+ check_metric,wer_delta_vs_truth,0.0,,,
11
+ check_metric,cases_with_truth,8,,,
12
+ bench,real_time_factor.median,0.0761763,x,,
13
+ bench,real_time_factor.p10,0.0759334,x,,
14
+ bench,real_time_factor.p90,0.0766807,x,,
15
+ bench,real_time_factor.min,0.0759114,x,,
16
+ bench,real_time_factor.max,0.0766964,x,,
17
+ bench,real_time_factor.n,10,x,,
18
+ bench,latency_ms.median,435.695,ms,,
19
+ bench,latency_ms.p10,434.306,ms,,
20
+ bench,latency_ms.p90,438.58,ms,,
21
+ bench,latency_ms.min,434.18,ms,,
22
+ bench,latency_ms.max,438.67,ms,,
23
+ bench,latency_ms.n,10,ms,,
24
+ bench,tokens_per_s.median,40.3124,tok/s,,
25
+ bench,tokens_per_s.p10,40.0784,tok/s,,
26
+ bench,tokens_per_s.p90,40.4153,tok/s,,
27
+ bench,tokens_per_s.min,39.999,tok/s,,
28
+ bench,tokens_per_s.max,40.4337,tok/s,,
29
+ bench,tokens_per_s.n,10,tok/s,,
30
+ bench,ttft_ms.median,38.595,ms,,
31
+ bench,ttft_ms.p10,38.342,ms,,
32
+ bench,ttft_ms.p90,39.08,ms,,
33
+ bench,ttft_ms.min,38.27,ms,,
34
+ bench,ttft_ms.max,39.44,ms,,
35
+ bench,ttft_ms.n,10,ms,,
36
+ bench,prompt_tokens.n,0,,,
37
+ bench,new_tokens.median,17.0,,,
38
+ bench,new_tokens.p10,17.0,,,
39
+ bench,new_tokens.p90,17.0,,,
40
+ bench,new_tokens.min,17.0,,,
41
+ bench,new_tokens.max,17.0,,,
42
+ bench,new_tokens.n,10,,,
43
+ bench,cold_latency_ms.median,441.09,ms,,
44
+ bench,cold_latency_ms.p10,440.832,ms,,
45
+ bench,cold_latency_ms.p90,449.974,ms,,
46
+ bench,cold_latency_ms.min,440.7,ms,,
47
+ bench,cold_latency_ms.max,454.63,ms,,
48
+ bench,cold_latency_ms.n,5,ms,,
49
+ bench,load_ms.median,285.8,ms,,
50
+ bench,load_ms.p10,266.6,ms,,
51
+ bench,load_ms.p90,294.58,ms,,
52
+ bench,load_ms.min,263.8,ms,,
53
+ bench,load_ms.max,296.5,ms,,
54
+ bench,load_ms.n,5,ms,,
55
+ bench,wall_ms.median,1701.05,ms,,
56
+ bench,wall_ms.p10,1674.92,ms,,
57
+ bench,wall_ms.p90,1709.2,ms,,
58
+ bench,wall_ms.min,1674.61,ms,,
59
+ bench,wall_ms.max,1711.91,ms,,
60
+ bench,wall_ms.n,5,ms,,
61
+ bench,peak_rss_mb,622.8,MB,,
62
+ bench,peak_hwm_mb,622.8,MB,,
63
+ bench,self_reported_peak_mem_mb,621.5,MB,,
64
+ graded,real_time_factor,0.0761763,x,,
65
+ graded,latency_ms,435.695,ms,,
66
+ graded,tokens_per_s,40.3124,tok/s,,
67
+ graded,ttft_ms,38.595,ms,,
68
+ graded,new_tokens,17.0,,,
69
+ graded,cold_latency_ms,441.09,ms,,
70
+ graded,load_ms,285.8,ms,,
71
+ graded,wall_ms,1701.05,ms,,
72
+ graded,peak_mem_mb,622.8,MB,,
73
+ roofline,mem_bandwidth_gbps,69.93,,,
74
+ roofline,peak_gflops,18325.0,,,
75
+ roofline,figures,"{'processor': 'npu', 'figures': 'npu', 'source': 'measured by lab/npu probe (NN-174CC0) on 2026-10-31: fp16 weight stream 69.93 GB/s (bw_l24), fp16 matmul 18.325 TFLOPS, int8 matmul 29.023 TOPS; LiteRT 2.3.1 + Qualcomm dispatch, QAIRT 2.50, burst'}",,,
76
+ roofline,decode_bytes_per_token,401900000.0,,,
77
+ roofline,decode_bytes_basis,half of the 0.402 B parameters taken as the decoder (the model facts give no decoder size),,,
78
+ roofline,decode_bound_tokens_per_s,174.0,,,
79
+ roofline,decode_pct_of_roofline,23.17,,,
80
+ roofline,decode_plausibility_cap,2923.0,,,
sm8850-npu-fp16/report/results.json ADDED
The diff for this file is too large to render. See raw diff
 
sm8850-npu-fp16/repro/Dockerfile ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # The machine nnopt built this deliverable on from scratch (REPRO.md, Tools): a public image and these
2
+ # packages, nothing of nnopt. build.sh fetches everything else itself. Build and use it:
3
+ # docker build --platform linux/amd64 -t build-env repro
4
+ # docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD:/src" -w /src build-env bash build.sh
5
+ FROM ubuntu:24.04@sha256:68ee22004a9109b44973313b02ff7b1de250f1de0f5ecb628d73f579aaff33ac
6
+ ENV DEBIAN_FRONTEND=noninteractive LANG=C.UTF-8 LC_ALL=C.UTF-8
7
+ RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates git curl python3 python3-venv build-essential unzip xz-utils \
8
+ && rm -rf /var/lib/apt/lists/*
sm8850-npu-fp16/repro/bench.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reproduce nnopt's numbers on your own device: the speed with nnopt's exact settings and, with --check, the outputs
3
+ on the public cases. See ../REPRO.md.
4
+
5
+ Needs python3 (3.8 or newer, no packages), sh, and adb (Android phones) or ssh and scp (a Jetson or Mac over the
6
+ network). plan.json next to this file holds the settings nnopt measured with and nnopt's numbers to compare against.
7
+
8
+ python3 repro/bench.py # speed, nnopt's settings, compared with nnopt's numbers
9
+ python3 repro/bench.py --check # outputs on the public cases, compared with the expected outputs
10
+ python3 repro/bench.py --deploy # run deploy.sh into --dir first
11
+ python3 repro/bench.py --sustained 600 # then run back to back for 10 minutes (throttling)
12
+ python3 repro/bench.py --plan repro/galaxy-s24/plan.json # measured on several phones: your phone's numbers
13
+
14
+ Connection: --serial SERIAL (adb; or $ANDROID_SERIAL), --ssh USER@HOST (or $SSH_TARGET), --local (this machine).
15
+ --dir is where deploy.sh installed the program on the device (default: plan.json's device_dir).
16
+ Exit code: 0 everything within tolerance, 1 something outside it, 2 an error.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import ast
23
+ import json
24
+ import math
25
+ import os
26
+ import re
27
+ import shlex
28
+ import shutil
29
+ import statistics
30
+ import struct
31
+ import subprocess
32
+ import sys
33
+ import tempfile
34
+ import time
35
+ from array import array
36
+ from pathlib import Path
37
+
38
+ HERE = Path(__file__).resolve().parent
39
+ ROOT = HERE.parent # the deliverable: build.sh, deploy.sh, REPRO.md
40
+ TOKEN_TYPES = ("text_to_text", "vision_language")
41
+ OUT_EXT = {"text_to_text": ".json", "speech_to_text": ".json", "text_to_speech": ".wav", "vision_detection": ".json",
42
+ "vision_language": ".json", "kernel": "", "audio_generation": ".wav"}
43
+
44
+
45
+ class Fail(Exception):
46
+ pass
47
+
48
+
49
+ # ---------------------------------------------------------------- the device
50
+
51
+ class Device:
52
+ def __init__(self, kind: str, serial: str | None = None, target: str | None = None):
53
+ self.kind, self.serial, self.target = kind, serial, target
54
+ tool = {"adb": "adb", "ssh": "ssh", "local": "sh"}[kind]
55
+ if shutil.which(tool) is None:
56
+ raise Fail(f"{tool} is not installed or not on PATH (REPRO.md, Tools)")
57
+ if kind == "ssh" and not target:
58
+ raise Fail("--ssh USER@HOST (or SSH_TARGET) is needed for this device")
59
+
60
+ def describe(self) -> str:
61
+ return {"adb": f"adb{' -s ' + self.serial if self.serial else ''}", "ssh": f"ssh {self.target}",
62
+ "local": "this machine"}[self.kind]
63
+
64
+ def _adb(self) -> list[str]:
65
+ return ["adb"] + (["-s", self.serial] if self.serial else [])
66
+
67
+ def sh(self, script: str, timeout: float = 600) -> tuple[int, str]:
68
+ argv = {"adb": self._adb() + ["shell", script], "ssh": ["ssh", "-o", "BatchMode=yes", self.target or "", script],
69
+ "local": ["sh", "-c", script]}[self.kind]
70
+ try:
71
+ p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
72
+ except subprocess.TimeoutExpired:
73
+ return 124, f"timed out after {timeout:.0f} s"
74
+ return p.returncode, p.stdout + p.stderr
75
+
76
+ def push(self, local: Path, remote: str) -> None:
77
+ argv = {"adb": self._adb() + ["push", str(local), remote],
78
+ "ssh": ["scp", "-q", "-r", str(local), f"{self.target}:{remote}"],
79
+ "local": ["cp", "-R", str(local), remote]}[self.kind]
80
+ p = subprocess.run(argv, capture_output=True, text=True)
81
+ if p.returncode != 0:
82
+ raise Fail(f"could not copy {local.name} to the device: {(p.stdout + p.stderr).strip()[-300:]}")
83
+
84
+ def pull(self, remote: str, local: Path) -> bool:
85
+ argv = {"adb": self._adb() + ["pull", remote, str(local)],
86
+ "ssh": ["scp", "-q", "-r", f"{self.target}:{remote}", str(local)],
87
+ "local": ["cp", "-R", remote, str(local)]}[self.kind]
88
+ return subprocess.run(argv, capture_output=True, text=True).returncode == 0
89
+
90
+
91
+ # Runs one command on the device: times it with the device's own clock and samples the memory (RSS) of its process
92
+ # tree, as nnopt does. Prints "REPRO START_NS END_NS EXIT PEAK_RSS_KB".
93
+ WRAP = r"""
94
+ d={io}; t={tag}
95
+ now() {{ v=$(date +%s%N 2>/dev/null); case "$v" in ''|*N*) perl -MTime::HiRes=time -e 'printf("%.0f\n", time()*1e9)' 2>/dev/null || echo "$(date +%s)000000000";; *) echo "$v";; esac; }}
96
+ if [ -d /system/bin ]; then o="PID,PPID,RSS"; else o="pid,ppid,rss"; fi
97
+ rm -f "$d/$t.rc" "$d/$t.end"
98
+ s=$(now)
99
+ ( cd {dir} && {env}sh ./run.sh {args} > "$d/$t.log" 2>&1; r=$?; now > "$d/$t.end"; echo $r > "$d/$t.rc" ) &
100
+ root=$!; peak=0
101
+ while [ ! -f "$d/$t.rc" ]; do
102
+ m=$(ps -A -o $o 2>/dev/null | awk -v r=$root 'NR>1 {{ p[$1]=$2; k[$1]=$3 }} END {{ s=0; for (x in p) {{ q=x; n=0; while (q != "" && q != r && n < 64) {{ q=p[q]; n++ }} if (q == r) s+=k[x] }} print s+0 }}')
103
+ [ "${{m:-0}}" -gt "$peak" ] 2>/dev/null && peak=$m
104
+ sleep 0.2
105
+ done
106
+ echo "REPRO $s $(cat "$d/$t.end") $(cat "$d/$t.rc") $peak"
107
+ """
108
+ _MARK = re.compile(r"^REPRO (\d+) (\d+) (-?\d+) (\d+)\s*$", re.M)
109
+
110
+
111
+ def q(s: str) -> str:
112
+ return shlex.quote(s)
113
+
114
+
115
+ class Session:
116
+ """The program deployed in `folder` on the device, inputs staged in `folder`-repro-io."""
117
+
118
+ def __init__(self, dev: Device, folder: str, model_type: str, tmp: Path):
119
+ self.dev, self.dir, self.mt, self.tmp = dev, folder.rstrip("/"), model_type, tmp
120
+ self.io = self.dir + "-repro-io"
121
+ self.n = 0
122
+ rc, out = dev.sh(f"test -f {q(self.dir)}/run.sh && mkdir -p {q(self.io)} && echo ok", 60)
123
+ if "ok" not in out:
124
+ raise Fail(f"no run.sh in {self.dir} on the device: deploy first (bash deploy.sh {self.dir}, or --deploy)")
125
+
126
+ def stage(self, local: Path) -> str:
127
+ remote = f"{self.io}/{local.name}"
128
+ self.dev.push(local, remote if local.is_file() else self.io + "/")
129
+ return remote
130
+
131
+ def run(self, args: dict, *, repeat: int = 1, fetch_out: bool = False, timeout: float = 3600,
132
+ env: dict | None = None) -> dict:
133
+ self.n += 1
134
+ tag = f"r{self.n}"
135
+ out = f"{self.io}/{tag}.out{OUT_EXT[self.mt]}"
136
+ met = f"{self.io}/{tag}.metrics.json"
137
+ line = command(self.mt, args, out=out, metrics=met, repeat=repeat)
138
+ exports = "".join(f"{k}={q(str(v))} " for k, v in (env or {}).items())
139
+ rc, text = self.dev.sh(WRAP.format(io=q(self.io), tag=tag, dir=q(self.dir), args=line, env=exports), timeout)
140
+ m = _MARK.search(text)
141
+ res = {"command": "sh ./run.sh " + line, "exit": int(m.group(3)) if m else rc, "wall_ms": None,
142
+ "peak_rss_mb": None, "metrics": None, "out": None}
143
+ if m:
144
+ res["wall_ms"] = (int(m.group(2)) - int(m.group(1))) / 1e6
145
+ res["peak_rss_mb"] = int(m.group(4)) / 1024 or None
146
+ mloc = self.tmp / f"{tag}.metrics.json"
147
+ if self.dev.pull(met, mloc) and mloc.is_file():
148
+ try:
149
+ res["metrics"] = json.loads(mloc.read_text())
150
+ except ValueError:
151
+ pass
152
+ if fetch_out:
153
+ oloc = self.tmp / Path(out).name
154
+ if self.dev.pull(out, oloc) and oloc.exists():
155
+ res["out"] = oloc
156
+ if res["exit"] != 0:
157
+ _, log = self.dev.sh(f"tail -c 2000 {q(self.io)}/{tag}.log", 60)
158
+ res["log"] = log
159
+ return res
160
+
161
+ def close(self) -> None:
162
+ self.dev.sh(f"rm -rf {q(self.io)}", 120)
163
+
164
+
165
+ def command(mt: str, a: dict, *, out: str, metrics: str, repeat: int = 1) -> str:
166
+ """run.sh's arguments for one request (CONTRACT.md)."""
167
+ mode = a.get("mode", "generate")
168
+ args: list[str] = []
169
+ if mt == "audio_generation":
170
+ args = ["--text-file", q(a["input"]), "--seed", str(int(a.get("seed") or 0)),
171
+ "--seconds", f"{float(a.get('seconds') or 10):.6f}".rstrip("0").rstrip(".")]
172
+ elif mt == "vision_detection":
173
+ for im in a["images"]:
174
+ args += ["--image", q(im)]
175
+ elif mt in TOKEN_TYPES:
176
+ if mt == "vision_language":
177
+ args += ["--image", q(a["image"])]
178
+ args += ["--prompt-file", q(a["input"]), "--max-new-tokens", str(int(a["max_new_tokens"]))]
179
+ if a.get("ignore_eos"):
180
+ args.append("--ignore-eos")
181
+ elif mt == "speech_to_text":
182
+ args = ["--audio", q(a["input"])]
183
+ elif mt == "kernel":
184
+ args = ["--inputs", q(a["input"])]
185
+ else: # text_to_speech
186
+ args = ["--text-file", q(a["input"]), "--seed", str(int(a.get("seed") or 0))]
187
+ args += ["--out", q(out), "--metrics", q(metrics)]
188
+ if repeat > 1:
189
+ args += ["--repeat", str(int(repeat))]
190
+ return " ".join(args)
191
+
192
+
193
+ # ---------------------------------------------------------------- numbers
194
+
195
+ def derive(mt: str, r: dict, audio_s: float | None, batch: int = 1) -> dict:
196
+ """One request's numbers from the port's metrics, as nnopt computes them."""
197
+ t = float(r.get("total_ms") or 0)
198
+ d: dict = {"total_ms": t}
199
+ if mt == "vision_detection":
200
+ d.update(latency_ms=t, per_image_ms=t / batch, fps=batch * 1000 / t if t > 0 else None)
201
+ elif mt in TOKEN_TYPES:
202
+ ttft, n, p = float(r.get("ttft_ms") or 0), int(r.get("new_tokens") or 0), int(r.get("prompt_tokens") or 0)
203
+ dec = t - ttft
204
+ d.update(ttft_ms=ttft, tokens_per_s=(n - 1) / (dec / 1000) if dec > 0 and n > 1 else None,
205
+ prefill_tokens_per_s=p / (ttft / 1000) if ttft > 0 else None,
206
+ e2e_tokens_per_s=n / (t / 1000) if t > 0 else None)
207
+ elif mt == "speech_to_text":
208
+ d.update(latency_ms=t, real_time_factor=t / 1000 / audio_s if audio_s else None)
209
+ elif mt == "kernel":
210
+ d["latency_ms"] = t
211
+ elif mt == "audio_generation":
212
+ n, first = int(r.get("frames") or 1), float(r.get("ttfa_ms") or 0)
213
+ per = (t - first) / (n - 1) if n > 1 else t
214
+ audio_ms = 1000 * audio_s / n if audio_s else None
215
+ d.update(time_to_first_audio_ms=first, latency_ms=t, ms_per_frame=per,
216
+ real_time_factor=per / audio_ms if audio_ms else None)
217
+ else: # text_to_speech
218
+ d.update(time_to_first_audio_ms=r.get("ttfa_ms"), latency_ms=t,
219
+ real_time_factor=t / 1000 / audio_s if audio_s else None)
220
+ return d
221
+
222
+
223
+ def pct(values: list[float], p: float) -> float:
224
+ v = sorted(values)
225
+ if len(v) == 1:
226
+ return v[0]
227
+ k = (len(v) - 1) * p / 100
228
+ f = math.floor(k)
229
+ return v[f] + (v[min(f + 1, len(v) - 1)] - v[f]) * (k - f)
230
+
231
+
232
+ def stats(values) -> dict | None:
233
+ v = [float(x) for x in values if x is not None and math.isfinite(float(x))]
234
+ if not v:
235
+ return None
236
+ return {"median": statistics.median(v), "p10": pct(v, 10), "p90": pct(v, 90), "n": len(v)}
237
+
238
+
239
+ def fmt(x) -> str:
240
+ if x is None:
241
+ return "–"
242
+ a = abs(x)
243
+ return f"{x:.0f}" if a >= 1000 else f"{x:.1f}" if a >= 10 else f"{x:.3g}"
244
+
245
+
246
+ def wav_info(path: Path) -> tuple[int, int, int, int, bytes]:
247
+ """(sample rate, channels, bits, format, data) of a RIFF WAV (PCM or float)."""
248
+ b = path.read_bytes()
249
+ if b[:4] != b"RIFF" or b[8:12] != b"WAVE":
250
+ raise Fail(f"{path.name} is not a WAV file")
251
+ i, rate, ch, bits, fmt_tag, data = 12, 0, 0, 0, 0, b""
252
+ while i + 8 <= len(b):
253
+ cid, size = b[i:i + 4], struct.unpack("<I", b[i + 4:i + 8])[0]
254
+ body = b[i + 8:i + 8 + size]
255
+ if cid == b"fmt ":
256
+ fmt_tag, ch, rate = struct.unpack("<HHI", body[:8])
257
+ bits = struct.unpack("<H", body[14:16])[0]
258
+ if fmt_tag == 0xFFFE and len(body) >= 26: # WAVE_FORMAT_EXTENSIBLE: the real format is in the GUID
259
+ fmt_tag = struct.unpack("<H", body[24:26])[0]
260
+ elif cid == b"data":
261
+ data = body
262
+ i += 8 + size + (size & 1)
263
+ if not rate or not ch or not bits:
264
+ raise Fail(f"{path.name}: no WAV format chunk")
265
+ return rate, ch, bits, fmt_tag, data
266
+
267
+
268
+ def wav_seconds(path: Path) -> float:
269
+ rate, ch, bits, _, data = wav_info(path)
270
+ return len(data) / (ch * bits // 8) / rate
271
+
272
+
273
+ def wav_rms(path: Path) -> float:
274
+ rate, ch, bits, tag, data = wav_info(path)
275
+ if tag == 3 and bits == 32:
276
+ a = array("f")
277
+ elif bits == 16:
278
+ a = array("h")
279
+ else:
280
+ return float("nan")
281
+ a.frombytes(data[: len(data) // a.itemsize * a.itemsize])
282
+ if sys.byteorder == "big":
283
+ a.byteswap()
284
+ scale = 1.0 if a.typecode == "f" else 32768.0
285
+ return math.sqrt(sum((x / scale) ** 2 for x in a) / len(a)) if len(a) else 0.0
286
+
287
+
288
+ # ---------------------------------------------------------------- speed
289
+
290
+ def speed(sess: Session, plan: dict, args: argparse.Namespace) -> dict | None:
291
+ if not plan.get("settings") or not plan.get("inputs"):
292
+ print("nnopt did not measure the speed of this deliverable (see REPRO.md)")
293
+ return None
294
+ mt, st, inp = plan["model_type"], plan["settings"], plan["inputs"]
295
+ warmup = args.warmup if args.warmup is not None else int(st["warmup"])
296
+ runs = args.runs if args.runs is not None else int(st["runs"])
297
+ repeat = int(st["repeat"])
298
+ batch = int(st.get("batch") or 1)
299
+ req: dict = {"mode": plan.get("mode", "generate")}
300
+ for k in ("max_new_tokens", "ignore_eos", "seed", "seconds"):
301
+ if st.get(k) is not None:
302
+ req[k] = st[k]
303
+ staged = {k: sess.stage(HERE / v) for k, v in inp.items() if isinstance(v, str)}
304
+ if "images" in inp:
305
+ req["images"] = [sess.stage(HERE / v) for v in inp["images"]]
306
+ req.update({k: v for k, v in staged.items()})
307
+ audio_s = None
308
+ if mt == "speech_to_text":
309
+ audio_s = wav_seconds(HERE / inp["input"])
310
+ elif mt == "audio_generation":
311
+ audio_s = float(st.get("seconds") or 10)
312
+ rest = float(st.get("rest_s") or 0)
313
+ print(f"{warmup} warm-up run{'s' * (warmup != 1)}, {runs} timed run{'s' * (runs != 1)} of {repeat} "
314
+ f"request{'s' * (repeat != 1)} each{settings_text(mt, st)}")
315
+ for i in range(warmup):
316
+ r = sess.run(req, repeat=1, timeout=args.timeout)
317
+ _ok(r, f"warm-up {i + 1}")
318
+ print(f" warm-up {i + 1}/{warmup}: {r['wall_ms'] / 1000:.1f} s" if r["wall_ms"] else f" warm-up {i + 1} done")
319
+ timed, pairs, peak = [], [], []
320
+ for i in range(runs):
321
+ if rest:
322
+ time.sleep(rest)
323
+ r = sess.run(req, repeat=repeat, fetch_out=(i == 0), timeout=args.timeout)
324
+ _ok(r, f"timed run {i + 1}")
325
+ met = r["metrics"] or {}
326
+ if not isinstance(met.get("runs"), list) or len(met["runs"]) != repeat:
327
+ raise Fail(f"timed run {i + 1}: the metrics file needs {repeat} entries in \"runs\" (--repeat {repeat})")
328
+ if i == 0 and mt == "text_to_speech" and r["out"]:
329
+ audio_s = wav_seconds(r["out"])
330
+ reqs = [derive(mt, x, audio_s, batch) for x in met["runs"]]
331
+ timed.append({"wall_ms": r["wall_ms"], "load_ms": met.get("load_ms"), "requests": reqs,
332
+ "self_peak_mem_mb": met.get("peak_mem_mb")})
333
+ if r["peak_rss_mb"]:
334
+ peak.append(r["peak_rss_mb"])
335
+ line = f" timed run {i + 1}/{runs}: {r['wall_ms'] / 1000:.1f} s" if r["wall_ms"] else f" timed run {i + 1}"
336
+ if plan.get("external_check", True):
337
+ p_req, p_rep = paired(mt, req, repeat, plan)
338
+ pr = sess.run(p_req, repeat=p_rep, timeout=args.timeout)
339
+ if pr["exit"] == 0 and pr["wall_ms"] and r["wall_ms"]:
340
+ pairs.append(r["wall_ms"] - pr["wall_ms"])
341
+ print(line)
342
+ warm = [x for t in timed for x in (t["requests"][1:] if len(t["requests"]) > 1 else t["requests"])]
343
+ keys = sorted({k for x in warm for k, v in x.items() if v is not None})
344
+ summary = {k: stats(x.get(k) for x in warm) for k in keys}
345
+ summary["load_ms"] = stats(t["load_ms"] for t in timed)
346
+ graded = {k: s["median"] for k, s in summary.items() if s}
347
+ if peak:
348
+ graded["peak_mem_mb"] = max(peak)
349
+ ext = external(mt, pairs, st, repeat, batch, audio_s, plan)
350
+ if ext:
351
+ graded.update(ext_cap(mt, graded, ext))
352
+ return {"runs": timed, "summary": summary, "graded": graded, "external": ext}
353
+
354
+
355
+ def settings_text(mt: str, st: dict) -> str:
356
+ bits = []
357
+ if mt in TOKEN_TYPES:
358
+ bits.append(f"{st['max_new_tokens']} new tokens per request" + (" (--ignore-eos)" if st.get("ignore_eos") else ""))
359
+ if st.get("prompt_tokens"):
360
+ bits.append(f"a ~{st['prompt_tokens']}-token prompt")
361
+ if mt == "vision_detection" and int(st.get("batch") or 1) > 1:
362
+ bits.append(f"{st['batch']} images per request")
363
+ if st.get("resolution"):
364
+ bits.append(f"{st['resolution']} input")
365
+ if mt == "audio_generation":
366
+ bits.append(f"{st.get('seconds')} s of audio per request")
367
+ return (": " + ", ".join(bits)) if bits else ""
368
+
369
+
370
+ def paired(mt: str, req: dict, repeat: int, plan: dict) -> tuple[dict, int]:
371
+ """The same request with the least work (one new token; one audio frame), or at --repeat 1: the difference in
372
+ wall time is the device-clock speed, which keeps the port's own timings honest."""
373
+ if mt in TOKEN_TYPES:
374
+ return {**req, "max_new_tokens": 1}, repeat
375
+ if mt == "audio_generation" and plan.get("frame_seconds"):
376
+ return {**req, "seconds": plan["frame_seconds"]}, repeat
377
+ return req, 1
378
+
379
+
380
+ def external(mt, pairs, st, repeat, batch, audio_s, plan) -> dict | None:
381
+ if not pairs:
382
+ return None
383
+ d = statistics.median(pairs)
384
+ if d <= 0:
385
+ return None
386
+ if mt in TOKEN_TYPES:
387
+ return {"tokens_per_s": (int(st["max_new_tokens"]) - 1) * repeat / (d / 1000)}
388
+ if mt == "audio_generation":
389
+ fs = plan.get("frame_seconds")
390
+ n = (max(1, round(float(st.get("seconds") or 10) / fs)) - 1) * repeat if fs else 0
391
+ return {"ms_per_frame": d / n, "real_time_factor": d / n / (1000 * fs)} if n > 0 else None
392
+ if repeat < 2:
393
+ return None
394
+ per = d / (repeat - 1)
395
+ out = {"latency_ms": per}
396
+ if mt == "vision_detection":
397
+ out["fps"] = batch * 1000 / per
398
+ if audio_s:
399
+ out["real_time_factor"] = per / 1000 / audio_s
400
+ return out
401
+
402
+
403
+ def ext_cap(mt: str, g: dict, ext: dict, tol: float = 0.15) -> dict:
404
+ """nnopt's rule: a self-reported speed more than 15% better than the device-clock measurement is replaced by it."""
405
+ out = {}
406
+ if mt in TOKEN_TYPES and ext.get("tokens_per_s") and g.get("tokens_per_s"):
407
+ if g["tokens_per_s"] > ext["tokens_per_s"] * (1 + tol):
408
+ out["tokens_per_s"] = ext["tokens_per_s"]
409
+ elif mt == "audio_generation" and ext.get("ms_per_frame") and g.get("ms_per_frame"):
410
+ if ext["ms_per_frame"] > g["ms_per_frame"] * (1 + tol):
411
+ out.update(ms_per_frame=ext["ms_per_frame"], real_time_factor=ext.get("real_time_factor"))
412
+ elif ext.get("latency_ms") and g.get("latency_ms"):
413
+ ratio = ext["latency_ms"] / g["latency_ms"]
414
+ if ratio > 1 + tol:
415
+ for k in ("latency_ms", "real_time_factor", "time_to_first_audio_ms", "per_image_ms"):
416
+ if g.get(k) is not None:
417
+ out[k] = g[k] * ratio
418
+ if g.get("fps"):
419
+ out["fps"] = g["fps"] / ratio
420
+ return out
421
+
422
+
423
+ def compare(plan: dict, mine: dict) -> tuple[list[list[str]], bool]:
424
+ rows, ok = [], True
425
+ for c in plan.get("compare") or []:
426
+ got, ref, tol = mine["graded"].get(c["key"]), c.get("nnopt"), float(c.get("tolerance_pct") or 10)
427
+ if got is None or not ref:
428
+ rows.append([c["label"], fmt(got), fmt(ref), "–", "not measured"])
429
+ continue
430
+ diff = 100 * (got - ref) / ref
431
+ within = abs(diff) <= tol
432
+ ok &= within or c.get("informational", False)
433
+ rows.append([c["label"] + (f" ({c['unit']})" if c.get("unit") else ""), fmt(got), fmt(ref), f"{diff:+.1f}%",
434
+ ("yes" if within else "NO") + f" (±{tol:g}%)"])
435
+ return rows, ok
436
+
437
+
438
+ def table(head: list[str], rows: list[list[str]]) -> str:
439
+ w = [max(len(str(r[i])) for r in [head] + rows) for i in range(len(head))]
440
+ line = lambda r: " ".join(str(x).ljust(w[i]) for i, x in enumerate(r)) # noqa: E731
441
+ return "\n".join([line(head), line(["-" * n for n in w])] + [line(r) for r in rows])
442
+
443
+
444
+ def sustained(sess: Session, plan: dict, seconds: float, args: argparse.Namespace) -> dict:
445
+ mt, st, inp = plan["model_type"], plan["settings"], plan["inputs"]
446
+ key = (plan.get("compare") or [{}])[0].get("key")
447
+ req = {"mode": plan.get("mode", "generate"), **{k: st[k] for k in ("max_new_tokens", "ignore_eos", "seed", "seconds")
448
+ if st.get(k) is not None}}
449
+ req.update({k: f"{sess.io}/{Path(v).name}" for k, v in inp.items() if isinstance(v, str)})
450
+ if "images" in inp:
451
+ req["images"] = [f"{sess.io}/{Path(v).name}" for v in inp["images"]]
452
+ audio_s = wav_seconds(HERE / inp["input"]) if mt == "speech_to_text" else (
453
+ float(st.get("seconds") or 10) if mt == "audio_generation" else None)
454
+ series, t0 = [], time.monotonic()
455
+ print(f"sustained run: {seconds:.0f} s back to back")
456
+ while time.monotonic() - t0 < seconds:
457
+ r = sess.run(req, repeat=int(st.get("sustained_repeat") or st["repeat"]), timeout=args.timeout)
458
+ _ok(r, "sustained run")
459
+ reqs = [derive(mt, x, audio_s, int(st.get("batch") or 1)) for x in (r["metrics"] or {}).get("runs") or []]
460
+ s = stats(x.get(key) for x in reqs[1:] or reqs)
461
+ if s:
462
+ series.append((time.monotonic() - t0, s["median"]))
463
+ print(f" {series[-1][0]:5.0f} s {fmt(s['median'])}")
464
+ if len(series) < 2:
465
+ return {"series": series}
466
+ first = statistics.median(v for t, v in series if t <= series[0][0] + 60)
467
+ last = statistics.median(v for t, v in series if t >= series[-1][0] - 60)
468
+ return {"series": series, "first_minute": first, "last_minute": last, "ratio": last / first if first else None}
469
+
470
+
471
+ # ---------------------------------------------------------------- outputs
472
+
473
+ def words(text: str) -> list[str]:
474
+ return re.sub(r"[^\w\s']", " ", text.lower()).split()
475
+
476
+
477
+ def edits(a: list, b: list) -> int:
478
+ prev = list(range(len(b) + 1))
479
+ for i, x in enumerate(a, 1):
480
+ cur = [i]
481
+ for j, y in enumerate(b, 1):
482
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y)))
483
+ prev = cur
484
+ return prev[-1]
485
+
486
+
487
+ def iou(a: list, b: list) -> float:
488
+ ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
489
+ iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
490
+ inter = ix * iy
491
+ union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
492
+ return inter / union if union > 0 else 0.0
493
+
494
+
495
+ NPY = {"f4": ("f", 4), "f8": ("d", 8), "i1": ("b", 1), "u1": ("B", 1), "i2": ("h", 2), "u2": ("H", 2),
496
+ "i4": ("i", 4), "u4": ("I", 4), "i8": ("q", 8), "u8": ("Q", 8), "b1": ("B", 1)}
497
+
498
+
499
+ def read_npy(path: Path) -> tuple[str, list[float]]:
500
+ """A NumPy .npy file (format 1.0/2.0, C order) as (dtype, flat values), with the standard library only."""
501
+ b = path.read_bytes()
502
+ if b[:6] != b"\x93NUMPY":
503
+ raise Fail(f"{path.name} is not a .npy file")
504
+ hl, off = (struct.unpack("<H", b[8:10])[0], 10) if b[6] == 1 else (struct.unpack("<I", b[8:12])[0], 12)
505
+ head = ast.literal_eval(b[off:off + hl].decode("latin1"))
506
+ descr, data = head["descr"], b[off + hl:]
507
+ if head.get("fortran_order"):
508
+ raise Fail(f"{path.name}: Fortran order is not supported")
509
+ kind = descr.lstrip("<>|=")
510
+ if kind == "f2":
511
+ n = len(data) // 2
512
+ return kind, list(struct.unpack(("<" if descr[0] != ">" else ">") + "e" * n, data[:2 * n]))
513
+ if kind not in NPY:
514
+ raise Fail(f"{path.name}: dtype {descr} is not supported here")
515
+ code, size = NPY[kind]
516
+ a = array(code)
517
+ if a.itemsize != size:
518
+ raise Fail(f"{path.name}: this Python has no {size}-byte {code} type")
519
+ a.frombytes(data[: len(data) // size * size])
520
+ if (descr[0] == ">") != (sys.byteorder == "big") and size > 1:
521
+ a.byteswap()
522
+ return kind, list(a)
523
+
524
+
525
+ def check(sess: Session, plan: dict, args: argparse.Namespace) -> bool:
526
+ c = plan.get("check") or {}
527
+ cases, rules, mt = c.get("cases") or [], c.get("rules") or {}, plan["model_type"]
528
+ if not cases:
529
+ print("no public cases to check outputs against")
530
+ return True
531
+ print(f"{len(cases)} public case{'s' * (len(cases) != 1)}: {c.get('what', 'expected outputs')}")
532
+ ok, rows = True, []
533
+ tot = {"edits": 0, "words": 0, "matched": 0, "ref": 0, "ours": 0, "prefix": [], "tok": 0}
534
+ for case in cases:
535
+ base = HERE / case["dir"]
536
+ req: dict = {"mode": "generate"}
537
+ for k in ("input", "image"):
538
+ if case.get(k):
539
+ req[k] = sess.stage(base / case[k])
540
+ if mt == "vision_detection":
541
+ req["images"] = [req.pop("input")]
542
+ exp_path = base / case["expected"] if case.get("expected") else None
543
+ exp = json.loads(exp_path.read_text()) if exp_path and exp_path.suffix == ".json" else None
544
+ if mt in TOKEN_TYPES:
545
+ req["max_new_tokens"] = max(1, len(exp["tokens"]))
546
+ if mt in ("text_to_speech", "audio_generation"):
547
+ req["seed"] = case.get("seed", 0)
548
+ if mt == "audio_generation":
549
+ req["seconds"] = case.get("seconds", 10)
550
+ r = sess.run(req, repeat=1, fetch_out=True, timeout=args.timeout)
551
+ if r["exit"] != 0 or not r["out"]:
552
+ ok = False
553
+ rows.append([case["id"], "run failed", (r.get("log") or "")[-120:].replace("\n", " ")])
554
+ continue
555
+ if mt in TOKEN_TYPES:
556
+ got = json.loads(Path(r["out"]).read_text())
557
+ same_prompt = got.get("prompt_tokens") == exp["prompt_tokens"]
558
+ n = 0
559
+ for a, b in zip(got.get("tokens") or [], exp["tokens"]):
560
+ if a != b:
561
+ break
562
+ n += 1
563
+ frac = n / max(1, len(exp["tokens"]))
564
+ tot["prefix"].append(frac)
565
+ tot["tok"] += same_prompt
566
+ rows.append([case["id"], "prompt tokens " + ("match" if same_prompt else "DIFFER"),
567
+ f"{n}/{len(exp['tokens'])} new tokens identical before the first difference"])
568
+ elif mt == "speech_to_text":
569
+ got = json.loads(Path(r["out"]).read_text()).get("text", "")
570
+ e = edits(words(got), words(exp["text"]))
571
+ tot["edits"] += e
572
+ tot["words"] += len(words(exp["text"]))
573
+ rows.append([case["id"], f"{e} word edit{'s' * (e != 1)}", got[:60]])
574
+ elif mt == "text_to_speech":
575
+ mine, ref = wav_seconds(Path(r["out"])), float(case["expected_seconds"])
576
+ within = abs(mine / ref - 1) <= float(rules.get("duration_ratio_tolerance", 0.05))
577
+ ok &= within
578
+ rows.append([case["id"], f"{mine:.2f} s of audio (expected {ref:.2f} s)", "ok" if within else "DIFFERS"])
579
+ elif mt == "vision_detection":
580
+ got = json.loads(Path(r["out"]).read_text())
581
+ thr, margin, need = float(rules.get("score_threshold", 0.3)), float(rules.get("score_margin", 0.05)), float(
582
+ rules.get("iou_match", 0.5))
583
+ ref = [(b, cl) for b, s, cl in zip(exp["boxes"], exp["scores"], exp["classes"]) if s >= thr]
584
+ ours = [(b, cl) for b, s, cl in zip(got.get("boxes", []), got.get("scores", []), got.get("classes", []))
585
+ if s >= thr - margin]
586
+ used, m = set(), 0
587
+ for b, cl in ref:
588
+ best = max(((iou(b, ob), j) for j, (ob, oc) in enumerate(ours) if oc == cl and j not in used),
589
+ default=(0.0, -1))
590
+ if best[0] >= need:
591
+ used.add(best[1])
592
+ m += 1
593
+ tot["matched"] += m
594
+ tot["ref"] += len(ref)
595
+ tot["ours"] += len([1 for b, s in zip(got.get("boxes", []), got.get("scores", [])) if s >= thr])
596
+ rows.append([case["id"], f"{m}/{len(ref)} expected objects found", f"{len(ours)} detected"])
597
+ elif mt == "kernel":
598
+ bad, total, worst = 0, 0, 0.0
599
+ for t in case["outputs"]:
600
+ pulled = Path(r["out"]) / f"{t['name']}.npy"
601
+ if not pulled.is_file():
602
+ ok = False
603
+ rows.append([case["id"], f"no {t['name']}.npy written", ""])
604
+ continue
605
+ kind, mine = read_npy(pulled)
606
+ _, ref = read_npy(base / t["expected"])
607
+ if len(mine) != len(ref):
608
+ ok = False
609
+ rows.append([case["id"], f"{t['name']}: {len(mine)} values, expected {len(ref)}", ""])
610
+ continue
611
+ if kind.startswith("f"):
612
+ rt, at = (float(rules.get("fp16_rtol", 1e-2)), float(rules.get("fp16_atol_scale", 1e-2))) \
613
+ if kind == "f2" or t.get("dtype") == "float16" else \
614
+ (float(rules.get("fp32_rtol", 1e-4)), float(rules.get("fp32_atol_scale", 1e-4)))
615
+ rms = math.sqrt(sum(x * x for x in ref) / len(ref)) if ref else 0.0
616
+ for a, b in zip(mine, ref):
617
+ d = abs(a - b)
618
+ worst = max(worst, d)
619
+ bad += not (d <= at * rms + rt * abs(b))
620
+ else:
621
+ lim = float(rules.get("int8_max_abs_diff", 1) if kind in ("i1", "u1") else rules.get("int_max_abs_diff", 0))
622
+ for a, b in zip(mine, ref):
623
+ worst = max(worst, abs(a - b))
624
+ bad += abs(a - b) > lim
625
+ total += len(ref)
626
+ frac = bad / total if total else 0.0
627
+ within = frac <= float(rules.get("max_mismatch_frac", 0.0))
628
+ ok &= within
629
+ rows.append([case["id"], f"{bad} of {total} values outside tolerance", f"largest difference {worst:.3g}"])
630
+ else: # audio_generation: free-running audio is random; length and level are what can be checked
631
+ dur, rms = wav_seconds(Path(r["out"])), wav_rms(Path(r["out"]))
632
+ want = float(case.get("seconds", 10))
633
+ within = abs(dur - want) <= 0.05 * want + 0.1 and (math.isnan(rms) or rms >= float(rules.get("free_run_min_rms", 0.001)))
634
+ ok &= within
635
+ rows.append([case["id"], f"{dur:.2f} s of audio, RMS {rms:.3g}", "ok" if within else "DIFFERS"])
636
+ print(table(["case", "result", ""], rows))
637
+ if mt in TOKEN_TYPES and tot["prefix"]:
638
+ mean, need = statistics.mean(tot["prefix"]), float(rules.get("greedy_prefix_min", 0.75))
639
+ tok_ok = tot["tok"] == len(tot["prefix"])
640
+ ok &= tok_ok and mean >= need
641
+ print(f"prompt tokens identical on {tot['tok']}/{len(tot['prefix'])} cases (needed: all); greedy prefix "
642
+ f"{mean:.2f} (needed: {need:g} or more)")
643
+ if mt == "speech_to_text" and tot["words"]:
644
+ wer, need = tot["edits"] / tot["words"], float(rules.get("wer_vs_reference_max", 0.02))
645
+ ok &= wer <= need
646
+ print(f"word error rate against the expected transcripts {wer:.3f} (needed: {need:g} or less)")
647
+ if mt == "vision_detection" and tot["ref"]:
648
+ rec, prec = tot["matched"] / tot["ref"], tot["matched"] / max(1, tot["ours"])
649
+ need_r, need_p = float(rules.get("recall_min", 0.97)), float(rules.get("precision_min", 0.97))
650
+ ok &= rec >= need_r and prec >= need_p
651
+ print(f"recall {rec:.3f} (needed {need_r:g}), precision {prec:.3f} (needed {need_p:g})")
652
+ print("outputs: " + ("REPRODUCED" if ok else "NOT reproduced"))
653
+ return ok
654
+
655
+
656
+ def _ok(r: dict, what: str) -> None:
657
+ if r["exit"] != 0:
658
+ raise Fail(f"{what} failed (exit {r['exit']}): {(r.get('log') or '').strip()[-800:]}\ncommand: {r['command']}")
659
+
660
+
661
+ # ---------------------------------------------------------------- main
662
+
663
+ def main(argv: list[str] | None = None) -> int:
664
+ ap = argparse.ArgumentParser(description="Reproduce nnopt's numbers on your own device (REPRO.md).")
665
+ ap.add_argument("--plan", default=str(HERE / "plan.json"))
666
+ ap.add_argument("--serial", help="the phone's serial (adb devices); default $ANDROID_SERIAL")
667
+ ap.add_argument("--ssh", help="USER@HOST of a Jetson or Mac; default $SSH_TARGET")
668
+ ap.add_argument("--local", action="store_true", help="the program runs on this machine")
669
+ ap.add_argument("--dir", help="where deploy.sh installed the program on the device")
670
+ ap.add_argument("--deploy", action="store_true", help="run bash deploy.sh DIR first")
671
+ ap.add_argument("--check", action="store_true", help="check the outputs on the public cases instead of the speed")
672
+ ap.add_argument("--warmup", type=int)
673
+ ap.add_argument("--runs", type=int)
674
+ ap.add_argument("--sustained", type=float, default=0.0, help="seconds of back-to-back runs after the timed runs")
675
+ ap.add_argument("--timeout", type=float, default=3600.0, help="seconds per run")
676
+ ap.add_argument("--json", help="also write the results to this file")
677
+ a = ap.parse_args(argv)
678
+ if not Path(a.plan).is_file(): # measured on several phones: each has its own plan (repro/<phone>/plan.json)
679
+ mine = sorted(p.parent.name for p in HERE.glob("*/plan.json"))
680
+ print(f"error: no {a.plan}" + (f"; nnopt measured this on several phones: pass --plan repro/<phone>/plan.json "
681
+ f"for yours, <phone> one of: {', '.join(mine)}" if mine else ""), file=sys.stderr)
682
+ return 2
683
+ plan = json.loads(Path(a.plan).read_text())
684
+ kind = "local" if a.local else "ssh" if a.ssh else "adb" if a.serial else plan.get("connection", "adb")
685
+ serial = a.serial or (os.environ.get("ANDROID_SERIAL") if kind == "adb" else None)
686
+ target = a.ssh or (os.environ.get("SSH_TARGET") if kind == "ssh" else None)
687
+ folder = a.dir or plan["device_dir"]
688
+ try:
689
+ dev = Device(kind, serial=serial, target=target)
690
+ if a.deploy:
691
+ print(f"deploy: bash deploy.sh {folder}")
692
+ env = {**os.environ, "NNOPT_PORT_DIR": folder, **({"ANDROID_SERIAL": serial} if serial else {})}
693
+ if subprocess.run(["bash", "deploy.sh", folder], cwd=ROOT, env=env).returncode != 0:
694
+ raise Fail("deploy.sh failed")
695
+ print(f"{plan.get('title', 'nnopt reproduction')} · {dev.describe()} · {folder}")
696
+ with tempfile.TemporaryDirectory(prefix="nnopt-repro-") as tmp:
697
+ sess = Session(dev, folder, plan["model_type"], Path(tmp))
698
+ try:
699
+ if a.check:
700
+ ok = check(sess, plan, a)
701
+ result = {"check": ok}
702
+ elif (mine := speed(sess, plan, a)) is None:
703
+ ok, result = True, {"speed": None}
704
+ else:
705
+ rows, ok = compare(plan, mine)
706
+ print()
707
+ print(table(["metric", "yours", "nnopt", "diff", "within"], rows))
708
+ if mine["graded"].get("peak_mem_mb"):
709
+ print(f"peak memory (process tree RSS): {fmt(mine['graded']['peak_mem_mb'])} MB")
710
+ result = {"speed": mine, "compared": rows, "within": ok}
711
+ if a.sustained > 0:
712
+ result["sustained"] = s = sustained(sess, plan, a.sustained, a)
713
+ if s.get("ratio"):
714
+ print(f"sustained: last minute / first minute = {s['ratio']:.2f}")
715
+ print("speed: " + ("REPRODUCED" if ok else "NOT reproduced (see REPRO.md, Expected results)"))
716
+ finally:
717
+ sess.close()
718
+ out = Path(a.json) if a.json else HERE / "results" / time.strftime("run-%Y%m%d-%H%M%S.json")
719
+ out.parent.mkdir(parents=True, exist_ok=True)
720
+ out.write_text(json.dumps(result, indent=1, default=str) + "\n")
721
+ print(f"results: {out}")
722
+ return 0 if ok else 1
723
+ except Fail as e:
724
+ print(f"error: {e}", file=sys.stderr)
725
+ return 2
726
+
727
+
728
+ if __name__ == "__main__":
729
+ sys.exit(main())
sm8850-npu-fp16/repro/inputs/input.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8c61ccb33e9da830cf8f90acd76e006e4edfc569a5f0f7bd2a560aca49209e4
3
+ size 183070
sm8850-npu-fp16/repro/plan.json ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "nnopt-repro",
3
+ "version": 1,
4
+ "title": "moonshine-ai/moonshine-streaming on Samsung Galaxy S26+",
5
+ "kind": "port",
6
+ "model_type": "speech_to_text",
7
+ "mode": "transcribe",
8
+ "connection": "adb",
9
+ "device_dir": "/data/local/tmp/nnopt/port",
10
+ "settings": {
11
+ "warmup": 2,
12
+ "runs": 5,
13
+ "repeat": 3,
14
+ "rest_s": 3.0,
15
+ "sustained_repeat": 10
16
+ },
17
+ "inputs": {
18
+ "input": "inputs/input.wav"
19
+ },
20
+ "external_check": true,
21
+ "compare": [
22
+ {
23
+ "key": "real_time_factor",
24
+ "label": "Real-time factor",
25
+ "unit": "x",
26
+ "nnopt": 0.0761763,
27
+ "p10": 0.0759334,
28
+ "p90": 0.0766807,
29
+ "tolerance_pct": 10
30
+ },
31
+ {
32
+ "key": "latency_ms",
33
+ "label": "Time per request",
34
+ "unit": "ms",
35
+ "nnopt": 435.695,
36
+ "p10": 434.306,
37
+ "p90": 438.58,
38
+ "tolerance_pct": 10
39
+ },
40
+ {
41
+ "key": "peak_mem_mb",
42
+ "label": "Peak memory",
43
+ "unit": "MB",
44
+ "nnopt": 622.8,
45
+ "tolerance_pct": 10,
46
+ "informational": true
47
+ }
48
+ ],
49
+ "check": {
50
+ "cases": [
51
+ {
52
+ "id": "p000",
53
+ "dir": "expected/p000",
54
+ "input": "input.wav",
55
+ "expected": "expected.json"
56
+ },
57
+ {
58
+ "id": "p001",
59
+ "dir": "expected/p001",
60
+ "input": "input.wav",
61
+ "expected": "expected.json"
62
+ },
63
+ {
64
+ "id": "p002",
65
+ "dir": "expected/p002",
66
+ "input": "input.wav",
67
+ "expected": "expected.json"
68
+ },
69
+ {
70
+ "id": "p003",
71
+ "dir": "expected/p003",
72
+ "input": "input.wav",
73
+ "expected": "expected.json"
74
+ },
75
+ {
76
+ "id": "p004",
77
+ "dir": "expected/p004",
78
+ "input": "input.wav",
79
+ "expected": "expected.json"
80
+ },
81
+ {
82
+ "id": "p005",
83
+ "dir": "expected/p005",
84
+ "input": "input.wav",
85
+ "expected": "expected.json"
86
+ },
87
+ {
88
+ "id": "p006",
89
+ "dir": "expected/p006",
90
+ "input": "input.wav",
91
+ "expected": "expected.json"
92
+ },
93
+ {
94
+ "id": "p007",
95
+ "dir": "expected/p007",
96
+ "input": "input.wav",
97
+ "expected": "expected.json"
98
+ },
99
+ {
100
+ "id": "p008",
101
+ "dir": "expected/p008",
102
+ "input": "input.wav",
103
+ "expected": "expected.json"
104
+ },
105
+ {
106
+ "id": "p009",
107
+ "dir": "expected/p009",
108
+ "input": "input.wav",
109
+ "expected": "expected.json"
110
+ },
111
+ {
112
+ "id": "p010",
113
+ "dir": "expected/p010",
114
+ "input": "input.wav",
115
+ "expected": "expected.json"
116
+ },
117
+ {
118
+ "id": "p011",
119
+ "dir": "expected/p011",
120
+ "input": "input.wav",
121
+ "expected": "expected.json"
122
+ },
123
+ {
124
+ "id": "p012",
125
+ "dir": "expected/p012",
126
+ "input": "input.wav",
127
+ "expected": "expected.json"
128
+ }
129
+ ],
130
+ "rules": {
131
+ "wer_vs_reference_max": 0.02,
132
+ "wer_delta_vs_truth_max": 0.01
133
+ },
134
+ "what": "the reference outputs of your reference code"
135
+ }
136
+ }
sm8850-npu-fp16/src/aot_compile.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ahead-of-time compile a .tflite for the Snapdragon 8 Elite Gen 5 NPU (SM8850, HTP v81) with ai-edge-litert's AOT
2
+ API and the Qualcomm plugin (ai-edge-litert-sdk-qualcomm 2.3.0 = QAIRT 2.50). Fails unless every op went to the NPU.
3
+
4
+ python aot_compile.py MODEL.tflite OUT_DIR -> OUT_DIR/MODEL_Qualcomm_SM8850_apply_plugin.tflite
5
+ """
6
+ import pathlib, sys
7
+
8
+ from ai_edge_litert.aot import aot_compile as aot_lib
9
+ from ai_edge_litert.aot.vendors.qualcomm import target as qnn_target
10
+
11
+
12
+ def main(model, out_dir):
13
+ res = aot_lib.aot_compile(model, output_dir=out_dir, target=[qnn_target.Target(qnn_target.SocModel.SM8850)],
14
+ keep_going=False)
15
+ report = res.compilation_report()
16
+ print(report)
17
+ outs = sorted(pathlib.Path(out_dir).glob(pathlib.Path(model).stem + "_Qualcomm_SM8850*.tflite"))
18
+ if not outs:
19
+ sys.exit("aot_compile: no compiled model written")
20
+ # all-on-NPU: the compiled model holds only DISPATCH_OP custom ops (QNN context binaries)
21
+ from ai_edge_litert import schema_py_generated as S
22
+ m = S.Model.GetRootAs(outs[-1].read_bytes(), 0)
23
+ codes = [m.OperatorCodes(i) for i in range(m.OperatorCodesLength())]
24
+ names = [c.CustomCode().decode() if c.CustomCode() else f"builtin {max(c.BuiltinCode(), c.DeprecatedBuiltinCode())}"
25
+ for c in codes]
26
+ used = [names[g.Operators(j).OpcodeIndex()] for g in (m.Subgraphs(i) for i in range(m.SubgraphsLength()))
27
+ for j in range(g.OperatorsLength())]
28
+ cpu = [n for n in used if n != "DISPATCH_OP"]
29
+ if cpu:
30
+ sys.exit(f"aot_compile: ops left off the NPU in {outs[-1]}: {cpu}")
31
+ print(f"aot_compile: {outs[-1]}: all ops DISPATCH_OP")
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main(sys.argv[1], sys.argv[2])
sm8850-npu-fp16/src/convert_ckpt.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Map the customer's original-format Moonshine Streaming checkpoint (tensilier = medium)
2
+ to the key layout of transformers' MoonshineStreamingForConditionalGeneration.
3
+ Weight-norm parametrizations are folded exactly as torch does (g * v / ||v||, norm over dims 1,2)."""
4
+ import re, torch
5
+ from safetensors.torch import load_file
6
+
7
+ def convert(path):
8
+ s = {k.removeprefix("_orig_mod."): v for k, v in load_file(path).items()}
9
+ out = {}
10
+ def put(k, v): out[k] = v.contiguous()
11
+ for k, v in s.items():
12
+ m = None
13
+ if k == "decoder.rotary.inv_freq": continue # buffer, recomputed from rope config
14
+ if k.startswith("audio_preprocessor."):
15
+ r = k[len("audio_preprocessor."):]
16
+ if ".parametrizations.weight.original" in r:
17
+ if r.endswith("original0"):
18
+ conv = r.split(".")[0]
19
+ g = v; w = s[f"audio_preprocessor.{conv}.conv.parametrizations.weight.original1"]
20
+ put(f"model.encoder.embedder.{conv}.weight", torch._weight_norm(w, g, 0))
21
+ continue
22
+ r = r.replace("conv1.conv.", "conv1.").replace("conv2.conv.", "conv2.").replace("lin.", "linear.")
23
+ put("model.encoder.embedder." + r, v); continue
24
+ if k.startswith("adapter."):
25
+ put({"adapter.pos_embed.weight": "model.decoder.pos_emb.weight",
26
+ "adapter.proj.weight": "model.decoder.proj.weight"}[k], v); continue
27
+ if k == "encoder.final_norm.gamma": put("model.encoder.final_norm.gamma", v); continue
28
+ if k == "decoder.final_norm.gamma": put("model.decoder.norm.weight", v + 1.0); continue
29
+ if k == "decoder.embedding.weight":
30
+ put("model.decoder.embed_tokens.weight", v); put("proj_out.weight", v.clone()); continue
31
+ if (m := re.match(r"encoder\.blocks\.(\d+)\.(.*)", k)):
32
+ i, r = m.groups()
33
+ r = (re.sub(r"^attn\.", "self_attn.", r).replace("out_proj", "o_proj")
34
+ .replace("ff.project_in.0", "mlp.fc1").replace("ff.project_out", "mlp.fc2")
35
+ .replace("norm1.", "input_layernorm.").replace("norm2.", "post_attention_layernorm."))
36
+ put(f"model.encoder.layers.{i}.{r}", v); continue
37
+ if (m := re.match(r"decoder\.self_attn_blocks\.(\d+)\.(.*)", k)):
38
+ i, r = m.groups()
39
+ r = re.sub(r"^attn\.", "self_attn.", r).replace("out_proj", "o_proj")
40
+ if r == "norm1.gamma": r, v = "input_layernorm.weight", v + 1.0
41
+ put(f"model.decoder.layers.{i}.{r}", v); continue
42
+ if (m := re.match(r"decoder\.cross_attn_blocks\.(\d+)\.(.*)", k)):
43
+ i, r = m.groups()
44
+ r = (re.sub(r"^attn\.", "encoder_attn.", r).replace("out_proj", "o_proj")
45
+ .replace("ff.project_in.proj", "mlp.fc1").replace("ff.project_out", "mlp.fc2"))
46
+ if r.endswith("gamma"):
47
+ # decoder norms: original gamma is an offset from 1; transformers stores 1 + gamma
48
+ r, v = {"norm_q.gamma": "post_attention_layernorm.weight", "norm2.gamma": "final_layernorm.weight"}[r], v + 1.0
49
+ put(f"model.decoder.layers.{i}.{r}", v); continue
50
+ raise KeyError(k)
51
+ return out
sm8850-npu-fp16/src/export_requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Export + AOT toolchain the shipped models were made with (x86-64 Linux, Python 3.12).
2
+ # Top-level pins; transitive dependencies resolve normally.
3
+ --extra-index-url https://download.pytorch.org/whl/cpu
4
+ torch==2.14.1
5
+ litert-torch==0.10.0
6
+ ai-edge-litert==2.3.0
7
+ ai-edge-quantizer==0.10.0
8
+ ai-edge-litert-sdk-qualcomm==2.3.0
9
+ tensorflow-cpu==2.21.0
10
+ safetensors==0.8.0
sm8850-npu-fp16/src/export_tflite.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export the Moonshine Streaming medium graphs to .tflite (litert-torch 0.10.0) and check each one on the CPU
2
+ (ai-edge-litert interpreter) against the torch module on real captured inputs.
3
+
4
+ python export_tflite.py CKPT OUTDIR --graph enc16 | dec512 | dec1536 | dec4096 [--half-cache] [--cases DIR]
5
+
6
+ Run on an x86-64 Linux machine with >= 32 GB RAM (the conversion VM: n2-highmem-16); see README.md.
7
+ """
8
+ import argparse, os, sys, time
9
+ import numpy as np
10
+ import torch
11
+
12
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
13
+ import moonshine_npu as M
14
+
15
+ DEC = {"dec512": (512, 80), "dec1536": (1536, 224), "dec4096": (4096, 544)}
16
+
17
+
18
+ def enc_args(C, case=None):
19
+ if case is not None:
20
+ z = np.load(case)
21
+ return tuple(torch.from_numpy(z[k]) for k in ["audio", "c1s", "c2s", "kst", "vst", "xst", "kmask", "pos"])
22
+ return (torch.zeros(1, C * M.SAMPLES_PER_ENC), torch.zeros(4, M.ENC_D), torch.zeros(4, 2 * M.ENC_D),
23
+ torch.zeros(M.NL_ENC, M.SMAX, 640), torch.zeros(M.NL_ENC, M.SMAX, 640),
24
+ torch.zeros(len(M.LA_LAYERS), 3, M.ENC_D), torch.zeros(M.NL_ENC, M.SMAX + C),
25
+ torch.zeros(C, dtype=torch.int32))
26
+
27
+
28
+ def dec_args(T, L, half, case=None):
29
+ dt = torch.float16 if half else torch.float32
30
+ if case is not None:
31
+ z = np.load(case)
32
+ Tc, Lc = z["ck"].shape[-1], z["sk"].shape[-1]
33
+ def fit(a, axis, n, fill=0.0):
34
+ pad = [(0, 0)] * a.ndim; pad[axis] = (0, n - a.shape[axis])
35
+ return np.pad(a, pad, constant_values=fill)
36
+ return (torch.from_numpy(z["tok"]), torch.from_numpy(z["pos"]),
37
+ torch.from_numpy(fit(z["smask"], 1, L, M.NEG)), torch.from_numpy(fit(z["cmask"], 1, T, M.NEG)),
38
+ torch.from_numpy(fit(z["sk"], 3, L)).to(dt), torch.from_numpy(fit(z["sv"], 2, L)).to(dt),
39
+ torch.from_numpy(fit(z["ck"], 3, T)).to(dt), torch.from_numpy(fit(z["cv"], 2, T)).to(dt))
40
+ return (torch.zeros(1, dtype=torch.int32), torch.zeros(1, dtype=torch.int32), torch.zeros(1, L),
41
+ torch.zeros(1, T), torch.zeros(M.NL_DEC, M.ENC_H, M.HD, L, dtype=dt),
42
+ torch.zeros(M.NL_DEC, M.ENC_H, L, M.HD, dtype=dt), torch.zeros(M.NL_DEC, M.ENC_H, M.HD, T, dtype=dt),
43
+ torch.zeros(M.NL_DEC, M.ENC_H, T, M.HD, dtype=dt))
44
+
45
+
46
+ def check(path, mod, args):
47
+ from ai_edge_litert.interpreter import Interpreter
48
+ it = Interpreter(model_path=path)
49
+ run = it.get_signature_runner()
50
+ names = sorted(it.get_signature_list()["serving_default"]["inputs"], key=lambda s: int(s.split("_")[-1]))
51
+ feed = {n: a.numpy() for n, a in zip(names, args)}
52
+ t = time.time()
53
+ out = run(**feed)
54
+ dt = time.time() - t
55
+ with torch.no_grad():
56
+ ref = mod(*args)
57
+ onames = sorted(out.keys(), key=lambda s: int(s.split("_")[-1]))
58
+ for n, r in zip(onames, ref):
59
+ o, r = out[n].astype(np.float64).ravel(), r.double().numpy().ravel()
60
+ cos = float(o @ r / (np.linalg.norm(o) * np.linalg.norm(r) + 1e-30))
61
+ snr = 10 * np.log10((r @ r + 1e-30) / (((o - r) ** 2).sum() + 1e-30))
62
+ print(f" check {os.path.basename(path)} {n} shape={out[n].shape} cos={cos:.7f} snr={snr:.1f}dB "
63
+ f"maxabs={np.abs(o - r).max():.3e}", flush=True)
64
+ print(f" cpu run {dt * 1000:.0f} ms", flush=True)
65
+
66
+
67
+ def main():
68
+ ap = argparse.ArgumentParser()
69
+ ap.add_argument("ckpt"); ap.add_argument("outdir")
70
+ ap.add_argument("--graph", required=True)
71
+ ap.add_argument("--half-cache", action="store_true")
72
+ ap.add_argument("--cases")
73
+ a = ap.parse_args()
74
+ import litert_torch
75
+ torch.set_grad_enabled(False)
76
+ os.makedirs(a.outdir, exist_ok=True)
77
+ sd = M.load_sd(a.ckpt)
78
+ t0 = time.time()
79
+ if a.graph.startswith("enc"):
80
+ C = int(a.graph[3:])
81
+ mod = M.EncoderChunk(sd, C).eval()
82
+ args = enc_args(C)
83
+ case = os.path.join(a.cases, f"enc{C}.npz") if a.cases else None
84
+ cargs = enc_args(C, case) if case and os.path.exists(case) else args
85
+ name = f"enc{C}"
86
+ else:
87
+ T, L = DEC[a.graph]
88
+ mod = M.DecoderStep(sd, T, L, half_cache=a.half_cache).eval()
89
+ args = dec_args(T, L, a.half_cache)
90
+ case = os.path.join(a.cases, "dec.npz") if a.cases else None
91
+ cargs = dec_args(T, L, a.half_cache, case) if case and os.path.exists(case) else args
92
+ name = a.graph + ("h" if a.half_cache else "")
93
+ del sd
94
+ path = os.path.join(a.outdir, name + ".tflite")
95
+ litert_torch.convert(mod, args).export(path)
96
+ print(f"exported {path} {os.path.getsize(path) / 1e6:.1f} MB in {time.time() - t0:.0f} s", flush=True)
97
+ check(path, mod, cargs)
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
sm8850-npu-fp16/src/host_stream.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Host (fp32 torch) model of the on-device streaming loop: the same chunking, state, masks, buckets and greedy
2
+ decode as runner.c, used to check the graphs against the reference before export and to make calibration data.
3
+
4
+ python host_stream.py CKPT WAV [--chunk 16] [--check-hf HF_CONFIG_DIR]
5
+ """
6
+ import argparse, json, math, os, sys, wave
7
+ import numpy as np
8
+ import torch
9
+
10
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
11
+ import moonshine_npu as M
12
+
13
+ BUCKETS = [(512, 80), (1536, 224), (4096, 544)] # (T encoder frames, L decoder positions)
14
+
15
+
16
+ def read_wav(path):
17
+ w = wave.open(path)
18
+ assert w.getframerate() == 16000 and w.getsampwidth() == 2, "16 kHz 16-bit PCM expected"
19
+ a = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(np.float32) / 32768.0
20
+ return a.reshape(-1, w.getnchannels()).mean(1)
21
+
22
+
23
+ def enc_lengths(n):
24
+ F = -(-n // M.FRAME)
25
+ n1 = -(-F // 2)
26
+ return -(-n1 // 2)
27
+
28
+
29
+ class Stream:
30
+ def __init__(self, enc, C):
31
+ self.enc, self.C = enc, C
32
+ self.D = [sum(M.LOOKAHEAD[:l]) for l in range(M.NL_ENC)]
33
+
34
+ def run_encoder(self, audio, T, on_chunk=None):
35
+ C = self.C
36
+ K = -(-(T + M.TOTAL_LAG) // C)
37
+ st = dict(c1s=torch.zeros(4, M.ENC_D), c2s=torch.zeros(4, 2 * M.ENC_D),
38
+ kst=torch.zeros(M.NL_ENC, M.SMAX, 640), vst=torch.zeros(M.NL_ENC, M.SMAX, 640),
39
+ xst=torch.zeros(len(M.LA_LAYERS), 3, M.ENC_D))
40
+ ck = torch.zeros(M.NL_DEC, T, 640)
41
+ cv = torch.zeros(M.NL_DEC, T, 640)
42
+ enc_out = torch.zeros(T, M.ENC_D)
43
+ n = len(audio)
44
+ for k in range(K):
45
+ s0, s1 = k * C * M.SAMPLES_PER_ENC, (k + 1) * C * M.SAMPLES_PER_ENC
46
+ chunk = np.zeros(C * M.SAMPLES_PER_ENC, np.float32)
47
+ seg = audio[s0:min(s1, n)]
48
+ chunk[:len(seg)] = seg
49
+ km = np.full((M.NL_ENC, M.SMAX + C), M.NEG, np.float32)
50
+ for l in range(M.NL_ENC):
51
+ a = k * C - self.D[l] - M.LOOKAHEAD[l]
52
+ f = a - M.LEFT - (M.SMAX - M.LEFT - M.LOOKAHEAD[l]) + np.arange(M.SMAX + C)
53
+ km[l][(f >= 0) & (f < T)] = 0.0
54
+ out0 = k * C - M.TOTAL_LAG
55
+ pos = np.clip(out0 + np.arange(C), 0, 4095).astype(np.int32)
56
+ r = self.enc(torch.from_numpy(chunk)[None], st["c1s"], st["c2s"], st["kst"], st["vst"], st["xst"],
57
+ torch.from_numpy(km), torch.from_numpy(pos))
58
+ st = dict(c1s=r[0], c2s=r[1], kst=r[2], vst=r[3], xst=r[4])
59
+ for i in range(C):
60
+ f = out0 + i
61
+ if 0 <= f < T:
62
+ ck[:, f], cv[:, f], enc_out[f] = r[5][:, i], r[6][:, i], r[7][i]
63
+ if on_chunk:
64
+ on_chunk(k, (chunk, km, pos), r)
65
+ return ck, cv, enc_out
66
+
67
+
68
+ def greedy(decs, ck, cv, avail, max_length):
69
+ Tb, Lb = next(b for b in BUCKETS if b[0] >= avail)
70
+ dec = decs[(Tb, Lb)]
71
+ assert max_length - 1 <= Lb, "too many tokens for the bucket"
72
+ H = M.ENC_H
73
+ ckb = torch.zeros(M.NL_DEC, H, M.HD, Tb)
74
+ cvb = torch.zeros(M.NL_DEC, H, Tb, M.HD)
75
+ ckb[:, :, :, :avail] = ck[:, :avail].reshape(M.NL_DEC, avail, H, M.HD).permute(0, 2, 3, 1)
76
+ cvb[:, :, :avail] = cv[:, :avail].reshape(M.NL_DEC, avail, H, M.HD).permute(0, 2, 1, 3)
77
+ cm = torch.full((1, Tb), M.NEG); cm[0, :avail] = 0
78
+ sk = torch.zeros(M.NL_DEC, H, M.HD, Lb); sv = torch.zeros(M.NL_DEC, H, Lb, M.HD)
79
+ toks = [1]
80
+ for i in range(max_length - 1):
81
+ sm = torch.full((1, Lb), M.NEG); sm[0, :i] = 0
82
+ logits, kn, vn = dec(torch.tensor([toks[-1]], dtype=torch.int32), torch.tensor([i], dtype=torch.int32),
83
+ sm, cm, sk, sv, ckb, cvb)
84
+ sk[:, :, :, i] = kn; sv[:, :, i, :] = vn
85
+ t = int(torch.argmax(logits[0]))
86
+ toks.append(t)
87
+ if t == 2:
88
+ break
89
+ return toks
90
+
91
+
92
+ def main():
93
+ ap = argparse.ArgumentParser()
94
+ ap.add_argument("ckpt"); ap.add_argument("wav", nargs="+")
95
+ ap.add_argument("--chunk", type=int, default=16)
96
+ ap.add_argument("--check-hf")
97
+ ap.add_argument("--tokenizer")
98
+ a = ap.parse_args()
99
+ torch.set_grad_enabled(False)
100
+ sd = M.load_sd(a.ckpt)
101
+ enc = M.EncoderChunk(sd, a.chunk).eval()
102
+ decs = {b: M.DecoderStep(sd, *b).eval() for b in BUCKETS}
103
+ tok = None
104
+ if a.tokenizer:
105
+ from tokenizers import Tokenizer
106
+ tok = Tokenizer.from_file(a.tokenizer)
107
+ for wav in a.wav:
108
+ audio = read_wav(wav)
109
+ n = len(audio)
110
+ n0 = n // M.FRAME
111
+ audio = audio.copy(); audio[n0 * M.FRAME:] = 0.0 # partial last frame is masked to zero in the reference
112
+ T = enc_lengths(n)
113
+ ck, cv, enc_out = Stream(enc, a.chunk).run_encoder(audio, T)
114
+ if a.check_hf:
115
+ from transformers import MoonshineStreamingConfig, MoonshineStreamingForConditionalGeneration
116
+ cfg = MoonshineStreamingConfig.from_pretrained(a.check_hf)
117
+ hf = MoonshineStreamingForConditionalGeneration(cfg); hf.load_state_dict(sd, strict=True); hf.eval()
118
+ x = torch.from_numpy(read_wav(wav))[None]
119
+ pad = (-x.shape[1]) % 80
120
+ am = torch.cat([torch.ones_like(x), torch.zeros(1, pad)], 1).long()
121
+ x = torch.cat([x, torch.zeros(1, pad)], 1)
122
+ ref = hf.model.encoder(x, attention_mask=am).last_hidden_state[0]
123
+ d = (ref - enc_out)
124
+ print(f"encoder vs HF: T={T} ref={tuple(ref.shape)} maxabs={d.abs().max():.3e} "
125
+ f"cos={torch.nn.functional.cosine_similarity(ref.flatten(), enc_out.flatten(), 0):.7f}")
126
+ ml = int(n * 6.5 / 16000)
127
+ toks = greedy(decs, ck, cv, T, ml)
128
+ text = tok.decode(toks, skip_special_tokens=True) if tok else ""
129
+ print(os.path.basename(wav), T, len(toks) - 1, json.dumps(text))
130
+
131
+
132
+ if __name__ == "__main__":
133
+ main()
sm8850-npu-fp16/src/make_cases.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture real inputs of the encoder chunk graph and the decoder step graph (p002) for export checks."""
2
+ import sys, os, numpy as np, torch
3
+ sys.path.insert(0, sys.argv[3])
4
+ import moonshine_npu as M, host_stream as H
5
+ torch.set_grad_enabled(False)
6
+ sd = M.load_sd(sys.argv[1]); out = sys.argv[2]
7
+ C = 16
8
+ enc = M.EncoderChunk(sd, C).eval()
9
+ audio = H.read_wav(sys.argv[4]); n = len(audio); audio[(n // 80) * 80:] = 0
10
+ T = H.enc_lengths(n)
11
+ saved = {}
12
+ def hook(k, inp, r):
13
+ if k == 10: saved["x"] = inp
14
+ st = H.Stream(enc, C)
15
+ # capture states going into chunk 10: rerun with hook that grabs state before
16
+ states = []
17
+ orig = enc.forward
18
+ def fwd(*a):
19
+ states.append([t.clone() for t in a]); return orig(*a)
20
+ enc.forward = fwd
21
+ ck, cv, eo = st.run_encoder(audio, T)
22
+ a = states[10]
23
+ np.savez(os.path.join(out, "enc16.npz"), audio=a[0].numpy(), c1s=a[1].numpy(), c2s=a[2].numpy(), kst=a[3].numpy(),
24
+ vst=a[4].numpy(), xst=a[5].numpy(), kmask=a[6].numpy(), pos=a[7].numpy())
25
+ # decoder: teacher-forced to step 6 with fp32 module at T exactly (padded later)
26
+ dec = M.DecoderStep(sd, T, 32).eval()
27
+ H.BUCKETS[:] = [(T, 32)]
28
+ toks = H.greedy({(T, 32): dec}, ck, cv, T, 8)
29
+ H_ = M.ENC_H
30
+ ckb = ck.reshape(14, T, H_, 64).permute(0, 2, 3, 1).contiguous(); cvb = cv.reshape(14, T, H_, 64).permute(0, 2, 1, 3).contiguous()
31
+ sk = torch.zeros(14, H_, 64, 32); sv = torch.zeros(14, H_, 32, 64)
32
+ for i in range(6):
33
+ sm = torch.full((1, 32), M.NEG); sm[0, :i] = 0
34
+ lg, kn, vn = dec(torch.tensor([toks[i]], dtype=torch.int32), torch.tensor([i], dtype=torch.int32), sm, torch.zeros(1, T), sk, sv, ckb, cvb)
35
+ sk[:, :, :, i] = kn; sv[:, :, i] = vn
36
+ i = 6; sm = np.full((1, 32), M.NEG, np.float32); sm[0, :i] = 0
37
+ np.savez(os.path.join(out, "dec.npz"), tok=np.array([toks[i]], np.int32), pos=np.array([i], np.int32), smask=sm,
38
+ cmask=np.zeros((1, T), np.float32), sk=sk.numpy(), sv=sv.numpy(), ck=ckb.numpy(), cv=cvb.numpy())
39
+ print("toks", toks)
sm8850-npu-fp16/src/make_vocab.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """tokenizer.json (moonshine-ai/moonshine-streaming-medium) -> vocab.bin for runner.c's detokenizer.
2
+
3
+ python make_vocab.py tokenizer.json vocab.bin
4
+
5
+ vocab.bin: "MSVOCAB1", uint32 n, then per id: uint8 flags (1 = special: skipped like skip_special_tokens=True),
6
+ uint16 length, the token's bytes after the tokenizer's decoder steps that act per token (Replace U+2581 -> ' ',
7
+ ByteFallback <0xNN> -> byte). The runner joins them (Fuse) and strips one leading space (Strip start=1).
8
+ """
9
+ import json, re, struct, sys
10
+
11
+
12
+ def main(src, dst, n=32768):
13
+ t = json.load(open(src, encoding="utf-8"))
14
+ dec = [d["type"] for d in t["decoder"]["decoders"]]
15
+ assert dec == ["Replace", "ByteFallback", "Fuse", "Strip"], dec
16
+ vocab = {i: s for s, i in t["model"]["vocab"].items()}
17
+ special = set()
18
+ for a in t["added_tokens"]:
19
+ vocab[a["id"]] = a["content"]
20
+ if a["special"]:
21
+ special.add(a["id"])
22
+ out = [b"MSVOCAB1", struct.pack("<I", n)]
23
+ for i in range(n):
24
+ s = vocab.get(i)
25
+ if s is None:
26
+ out.append(struct.pack("<BH", 1, 0)); continue
27
+ m = re.fullmatch(r"<0x([0-9A-Fa-f]{2})>", s)
28
+ b = bytes([int(m.group(1), 16)]) if m and i not in special else s.replace("▁", " ").encode("utf-8")
29
+ out.append(struct.pack("<BH", 1 if i in special else 0, len(b)) + b)
30
+ open(dst, "wb").write(b"".join(out))
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main(sys.argv[1], sys.argv[2])
sm8850-npu-fp16/src/moonshine_npu.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Moonshine Streaming (medium) as static-shape step graphs for LiteRT on the Hexagon NPU.
2
+
3
+ Two graphs, both exported from these modules (export_tflite.py):
4
+ EncoderChunk 320*C new samples -> C encoder frames (50 Hz), streaming with exact per-layer state,
5
+ plus the decoder's cross-attention K/V of those frames (adapter pos_emb + proj + k/v proj).
6
+ DecoderStep one token -> logits, self-attention KV cache and cross K/V as inputs (static T, L).
7
+
8
+ Reference: transformers 5.22.1 models/moonshine_streaming/modeling_moonshine_streaming.py (quoted per block),
9
+ weights loaded from the customer's tensilier checkpoint with convert_ckpt.py (the reference runner's convert.py).
10
+
11
+ Streaming encoder, exactness: layer l attends keys at distance 0..15 to the left and 0..r_l to the right
12
+ (sliding_windows (16, 4) -> r=3, (16, 0) -> r=0). With chunks of C frames, layer l's outputs lag its inputs by
13
+ r_l; it keeps the K/V of its last 15 + r_l input frames and the residual of its last r_l input frames as state.
14
+ The frontend's causal convs keep their last 4 input frames. Every encoder frame is therefore computed from
15
+ exactly the same inputs as in the full-utterance reference (keys before frame 0 or at/after the last frame are
16
+ masked by the runner through kmask).
17
+ """
18
+ import math
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ ENC_D, ENC_H, HD = 768, 10, 64
24
+ DEC_D, DEC_FF = 640, 2560
25
+ NL_ENC, NL_DEC = 14, 14
26
+ VOCAB = 32768
27
+ FRAME = 80 # samples per 5 ms frame
28
+ SAMPLES_PER_ENC = 320 # 4 frames -> one 50 Hz encoder frame
29
+ LOOKAHEAD = [3, 3] + [0] * 10 + [3, 3] # sliding_windows (16,4)*2, (16,0)*10, (16,4)*2: right keys q+1..q+3
30
+ LEFT = 15 # left window 16: keys q-15..q
31
+ SMAX = LEFT + 3 # K/V state rows per layer (layers with r=0 use the last 15)
32
+ TOTAL_LAG = sum(LOOKAHEAD) # 12 frames
33
+ LA_LAYERS = [i for i, r in enumerate(LOOKAHEAD) if r > 0]
34
+ ROT = 32 # partial_rotary_factor 0.5 of head_dim 64
35
+ NEG = -1.0e4
36
+ RES_S = 64.0
37
+
38
+
39
+ def layer_norm(x, gamma, eps=1e-5, mmin=1e-3):
40
+ """LayerNorm without bias, prescaled by the row max-abs so that fp16 never flushes the variance:
41
+ (x-mu)/sqrt(var+eps) == (xs-mus)/sqrt(var_s + eps/m^2) with xs = x/m (exact)."""
42
+ m = x.abs().amax(dim=-1, keepdim=True).clamp(min=mmin)
43
+ xs = x / m
44
+ d = xs - xs.mean(dim=-1, keepdim=True)
45
+ var = (d * d).mean(dim=-1, keepdim=True)
46
+ e = (eps ** 0.5) / m # eps/m^2 as (sqrt(eps)/m)^2: m*m and eps underflow fp16 for small m
47
+ return d * torch.rsqrt(var + e * e) * gamma
48
+
49
+
50
+ def asinh_fp16_safe(y):
51
+ # asinh(y) = sign(y) log(|y| + sqrt(y^2+1)); series for |y| < 0.5, where log(1+small) loses fp16 precision.
52
+ a = y.abs()
53
+ big = torch.log(a + torch.sqrt(a * a + 1.0))
54
+ y2 = y * y
55
+ small = a * (1.0 + y2 * (-1.0 / 6.0 + y2 * (3.0 / 40.0 + y2 * (-15.0 / 336.0 + y2 * (105.0 / 3456.0)))))
56
+ r = torch.where(a < 0.5, small, big)
57
+ return torch.where(y < 0, -r, r)
58
+
59
+
60
+ class EncoderChunk(nn.Module):
61
+ def __init__(self, sd, C):
62
+ super().__init__()
63
+ self.C = C
64
+ g = lambda k: sd[k].float().clone()
65
+ p = "model.encoder."
66
+ self.k_comp = float(torch.exp(sd[p + "embedder.comp.log_k"].float()))
67
+ # The residual stream runs in units of 1/RES_S (exact, a power of 2): conv2, o_proj and fc2 are divided by it
68
+ # and the norms use eps/RES_S^2. In fp32 the first frames' residuals reach 3.5e4 in the lookahead layers,
69
+ # which broke the whole HTP graph (even outputs that do not depend on them); /64 keeps them near 550.
70
+ s = RES_S
71
+ self.lin = nn.Parameter(g(p + "embedder.linear.weight")) # [768, 80]
72
+ self.c1w = nn.Parameter(g(p + "embedder.conv1.weight")) # [1536, 768, 5]
73
+ self.c1b = nn.Parameter(g(p + "embedder.conv1.bias"))
74
+ self.c2w = nn.Parameter(g(p + "embedder.conv2.weight") / s) # [768, 1536, 5]
75
+ self.c2b = nn.Parameter(g(p + "embedder.conv2.bias") / s)
76
+ L = []
77
+ for i in range(NL_ENC):
78
+ q = f"{p}layers.{i}."
79
+ L.append(nn.ParameterDict(dict(
80
+ ln1=nn.Parameter(g(q + "input_layernorm.gamma") + 1.0), # unit_offset gamma
81
+ ln2=nn.Parameter(g(q + "post_attention_layernorm.gamma") + 1.0),
82
+ wq=nn.Parameter(g(q + "self_attn.q_proj.weight")),
83
+ wk=nn.Parameter(g(q + "self_attn.k_proj.weight")),
84
+ wv=nn.Parameter(g(q + "self_attn.v_proj.weight")),
85
+ wo=nn.Parameter(g(q + "self_attn.o_proj.weight") / s),
86
+ f1w=nn.Parameter(g(q + "mlp.fc1.weight")), f1b=nn.Parameter(g(q + "mlp.fc1.bias")),
87
+ f2w=nn.Parameter(g(q + "mlp.fc2.weight") / s), f2b=nn.Parameter(g(q + "mlp.fc2.bias") / s))))
88
+ self.layers = nn.ModuleList(L)
89
+ self.fn = nn.Parameter(g(p + "final_norm.gamma") + 1.0)
90
+ d = "model.decoder."
91
+ self.pos = nn.Parameter(g(d + "pos_emb.weight")) # [4096, 768]
92
+ self.proj = nn.Parameter(g(d + "proj.weight")) # [640, 768]
93
+ self.ck = nn.Parameter(torch.stack([g(f"{d}layers.{i}.encoder_attn.k_proj.weight") for i in range(NL_DEC)]))
94
+ self.cv = nn.Parameter(torch.stack([g(f"{d}layers.{i}.encoder_attn.v_proj.weight") for i in range(NL_DEC)]))
95
+ # band masks: query i (frame a+i) vs key j (frame a-15+j); allowed i <= j <= i+15+r
96
+ bands = []
97
+ for r in LOOKAHEAD:
98
+ S = LEFT + r
99
+ i = torch.arange(C)[:, None]
100
+ j = torch.arange(S + C)[None, :]
101
+ ok = (j >= i) & (j <= i + LEFT + r)
102
+ bands.append(torch.where(ok, 0.0, NEG))
103
+ for k, b in enumerate(bands):
104
+ self.register_buffer(f"band{k}", b, persistent=False)
105
+
106
+ def forward(self, audio, c1s, c2s, kst, vst, xst, kmask, pos):
107
+ """audio [1, 320C]; c1s [4, 768] and c2s [4, 1536] conv input history; kst/vst [14, 18, 640] encoder K/V
108
+ state; xst [4, 3, 768] residual state of the lookahead layers; kmask [14, 18+C] additive key validity;
109
+ pos [C] int32 absolute encoder frame positions of the output frames (for adapter pos_emb)."""
110
+ C = self.C
111
+ # modeling_moonshine_streaming.py:297-300
112
+ # hidden_states = self.cmvn(input_values.reshape(input_values.shape[0], -1, self.frame_len))
113
+ # hidden_states = self.comp(hidden_states)
114
+ # hidden_states = nn.functional.silu(self.linear(hidden_states))
115
+ x = audio.reshape(4 * C, FRAME)
116
+ c = x - x.mean(dim=-1, keepdim=True)
117
+ m = c.abs().amax(dim=-1, keepdim=True).clamp(min=1e-3) # CMVN prescaled (exact, fp16-safe)
118
+ cs = c / m
119
+ e = 1e-3 / m # 1e-6/m^2 as (1e-3/m)^2: fp16-safe
120
+ x = cs * torch.rsqrt((cs * cs).mean(dim=-1, keepdim=True) + e * e)
121
+ x = asinh_fp16_safe(self.k_comp * x)
122
+ x = F.silu(x @ self.lin.t()) # [4C, 768]
123
+ # causal conv1 (k5, s2) and conv2 (k5, s2), lines 104-117: left pad (k-1) == state of 4 frames
124
+ h = torch.cat([c1s, x], 0) # [4C+4, 768]
125
+ new_c1s = h[-4:]
126
+ h = F.conv1d(h.t().unsqueeze(0), self.c1w, self.c1b, stride=2) # [1, 1536, 2C]
127
+ h = F.silu(h)[0].t() # [2C, 1536]
128
+ h = torch.cat([c2s, h], 0)
129
+ new_c2s = h[-4:]
130
+ h = F.conv1d(h.t().unsqueeze(0), self.c2w, self.c2b, stride=2)[0].t() # [C, 768]
131
+ new_k, new_v, new_x = [], [], []
132
+ lnr = lambda t, gm: layer_norm(t, gm, eps=1e-5 / (RES_S * RES_S), mmin=1e-3 / RES_S)
133
+ scale = HD ** -0.5
134
+ li = 0
135
+ for l, L in enumerate(self.layers):
136
+ r = LOOKAHEAD[l]
137
+ S = LEFT + r
138
+ # rows of h are frames kC - D[l] + i; frames outside [0, T) never reach a valid output (kmask hides them as
139
+ # keys), but their residual grows to ~3.5e4 with all keys masked and saturates fp16 on the HTP (garbage
140
+ # leaked into the first valid frames). Zero them: rowmask = 1 + kmask/1e4 is exactly 1 or 0.
141
+ h = h * (1.0 + kmask[l, SMAX:] * (-1.0 / NEG))[:, None]
142
+ # MoonshineStreamingEncoderLayer.forward, lines 261-280 (pre-norm attention, pre-norm GELU MLP)
143
+ hn = lnr(h, L["ln1"])
144
+ k_new = hn @ L["wk"].t() # [C, 640]
145
+ v_new = hn @ L["wv"].t()
146
+ ks = torch.cat([kst[l, SMAX - S:], k_new], 0) # [S+C, 640]
147
+ vs = torch.cat([vst[l, SMAX - S:], v_new], 0)
148
+ new_k.append(torch.cat([kst[l], k_new], 0)[-SMAX:])
149
+ new_v.append(torch.cat([vst[l], v_new], 0)[-SMAX:])
150
+ if r > 0: # queries are the frames r back: residual from state + first C-r new rows
151
+ xin = torch.cat([xst[li], h], 0) # [r+C, 768]
152
+ new_x.append(xin[-r:])
153
+ qsrc = torch.cat([lnr(xst[li], L["ln1"]), hn], 0)[:C]
154
+ resid = xin[:C]
155
+ li += 1
156
+ else:
157
+ qsrc, resid = hn, h
158
+ q = (qsrc @ L["wq"].t()).reshape(C, ENC_H, HD).transpose(0, 1) # [10, C, 64]
159
+ kh = ks.reshape(S + C, ENC_H, HD).permute(1, 2, 0) # [10, 64, S+C]
160
+ vh = vs.reshape(S + C, ENC_H, HD).transpose(0, 1) # [10, S+C, 64]
161
+ sc = (q @ kh) * scale + getattr(self, f"band{l}") + kmask[l, SMAX - S:]
162
+ pr = torch.softmax(sc, dim=-1)
163
+ a = (pr @ vh).transpose(0, 1).reshape(C, ENC_H * HD)
164
+ h = resid + a @ L["wo"].t()
165
+ hn2 = lnr(h, L["ln2"])
166
+ h = h + (F.gelu(hn2 @ L["f1w"].t() + L["f1b"]) @ L["f2w"].t() + L["f2b"])
167
+ enc = lnr(h, self.fn) # final_norm, line 429
168
+ # decoder adapter, lines 813-817: encoder_hidden_states += pos_emb(arange(T)); proj
169
+ e = (enc + self.pos[pos]) @ self.proj.t() # [C, 640]
170
+ ck = torch.einsum("cd,lod->lco", e, self.ck) # [14, C, 640]
171
+ cv = torch.einsum("cd,lod->lco", e, self.cv)
172
+ return (new_c1s, new_c2s, torch.stack(new_k), torch.stack(new_v), torch.stack(new_x), ck, cv, enc)
173
+
174
+
175
+ def rope_perm():
176
+ """Head-dim permutation applied to q_proj and k_proj rows: the interleaved rotary pairs (0,1),(2,3).. of the
177
+ first 32 dims become (0,16),(1,17).. so the graph uses the half-split rotate; q.k is unchanged."""
178
+ perm = list(range(0, ROT, 2)) + list(range(1, ROT, 2)) + list(range(ROT, HD))
179
+ return torch.tensor(perm)
180
+
181
+
182
+ def rope_tables(L, theta=10000.0):
183
+ inv = 1.0 / (theta ** (torch.arange(0, ROT, 2, dtype=torch.float) / ROT)) # [16]
184
+ f = torch.arange(L, dtype=torch.float)[:, None] * inv[None] # [L, 16]
185
+ return torch.cat([f.cos(), f.cos()], -1), torch.cat([f.sin(), f.sin()], -1) # [L, 32]
186
+
187
+
188
+ class DecoderStep(nn.Module):
189
+ def __init__(self, sd, T, L, half_cache=False):
190
+ super().__init__()
191
+ self.T, self.L, self.half_cache = T, L, half_cache
192
+ g = lambda k: sd[k].float().clone()
193
+ d = "model.decoder."
194
+ perm = rope_perm()
195
+ hperm = torch.cat([h * HD + perm for h in range(ENC_H)])
196
+ self.emb = nn.Parameter(g(d + "embed_tokens.weight")) # [32768, 640], tied proj_out
197
+ Ls = []
198
+ for i in range(NL_DEC):
199
+ q = f"{d}layers.{i}."
200
+ Ls.append(nn.ParameterDict(dict(
201
+ ln1=nn.Parameter(g(q + "input_layernorm.weight")),
202
+ ln2=nn.Parameter(g(q + "post_attention_layernorm.weight")),
203
+ ln3=nn.Parameter(g(q + "final_layernorm.weight")),
204
+ wq=nn.Parameter(g(q + "self_attn.q_proj.weight")[hperm]),
205
+ wk=nn.Parameter(g(q + "self_attn.k_proj.weight")[hperm]),
206
+ wv=nn.Parameter(g(q + "self_attn.v_proj.weight")),
207
+ wo=nn.Parameter(g(q + "self_attn.o_proj.weight")),
208
+ cq=nn.Parameter(g(q + "encoder_attn.q_proj.weight")),
209
+ co=nn.Parameter(g(q + "encoder_attn.o_proj.weight")),
210
+ f1w=nn.Parameter(g(q + "mlp.fc1.weight")), f1b=nn.Parameter(g(q + "mlp.fc1.bias")),
211
+ f2w=nn.Parameter(g(q + "mlp.fc2.weight")), f2b=nn.Parameter(g(q + "mlp.fc2.bias")))))
212
+ self.layers = nn.ModuleList(Ls)
213
+ self.norm = nn.Parameter(g(d + "norm.weight"))
214
+ cos, sin = rope_tables(L)
215
+ self.register_buffer("cos_t", cos, persistent=False)
216
+ self.register_buffer("sin_t", sin, persistent=False)
217
+
218
+ def forward(self, tok, pos, smask, cmask, sk, sv, ck, cv):
219
+ """tok [1] int32; pos [1] int32; smask [1, L], cmask [1, T] additive; sk [14,10,64,L] (K transposed,
220
+ rope dims permuted), sv [14,10,L,64]; ck [14,10,64,T], cv [14,10,T,64].
221
+ Returns logits [1, 32768], k_new [14, 10, 64], v_new [14, 10, 64] (written at slot pos by the runner)."""
222
+ if self.half_cache:
223
+ sk, sv, ck, cv = sk.float(), sv.float(), ck.float(), cv.float()
224
+ x = self.emb[tok] # [1, 640]
225
+ cos = self.cos_t[pos] # [1, 32]
226
+ sin = self.sin_t[pos]
227
+ scale = HD ** -0.5
228
+ kn, vn = [], []
229
+ for l, P in enumerate(self.layers):
230
+ # MoonshineStreamingDecoderLayer.forward, lines 725-755
231
+ h = layer_norm(x, P["ln1"])
232
+ q = (h @ P["wq"].t()).reshape(ENC_H, HD)
233
+ k = (h @ P["wk"].t()).reshape(ENC_H, HD)
234
+ v = (h @ P["wv"].t()).reshape(ENC_H, HD)
235
+ # apply_rotary_pos_emb on the first 32 (permuted) dims, half-split rotate
236
+ def rot(t):
237
+ tr, tp = t[:, :ROT], t[:, ROT:]
238
+ t1, t2 = tr[:, :ROT // 2], tr[:, ROT // 2:]
239
+ return torch.cat([tr * cos + torch.cat([-t2, t1], -1) * sin, tp], -1)
240
+ q, k = rot(q), rot(k)
241
+ kn.append(k)
242
+ vn.append(v)
243
+ s_c = (q.unsqueeze(1) @ sk[l]).squeeze(1) * scale + smask # [10, L]
244
+ s_n = (q * k).sum(-1, keepdim=True) * scale # [10, 1] (the new token itself)
245
+ s = torch.cat([s_c, s_n], -1)
246
+ p = torch.softmax(s, dim=-1)
247
+ a = (p[:, :self.L].unsqueeze(1) @ sv[l]).squeeze(1) + p[:, self.L:] * v # [10, 64]
248
+ x = x + a.reshape(1, DEC_D) @ P["wo"].t()
249
+ h = layer_norm(x, P["ln2"])
250
+ q = (h @ P["cq"].t()).reshape(ENC_H, 1, HD)
251
+ s = (q @ ck[l]).squeeze(1) * scale + cmask # [10, T]
252
+ p = torch.softmax(s, dim=-1)
253
+ a = (p.unsqueeze(1) @ cv[l]).squeeze(1) # [10, 64]
254
+ x = x + a.reshape(1, DEC_D) @ P["co"].t()
255
+ h = layer_norm(x, P["ln3"])
256
+ f = h @ P["f1w"].t() + P["f1b"]
257
+ hs, gate = f[:, :DEC_FF], f[:, DEC_FF:]
258
+ x = x + (F.silu(gate) * hs) @ P["f2w"].t() + P["f2b"]
259
+ x = layer_norm(x, self.norm)
260
+ logits = x @ self.emb.t()
261
+ return logits, torch.stack(kn), torch.stack(vn)
262
+
263
+
264
+ def load_sd(path):
265
+ import os, sys
266
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
267
+ from convert_ckpt import convert
268
+ return convert(path)
sm8850-npu-fp16/src/paths.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sourced by build.sh and deploy.sh (with ROOT and NAME set): where .deps/ and build/ live. Next to build.sh when the
2
+ # folder is writable, else under $HOME/.cache/$NAME/<short hash of the folder's path>.
3
+ if [ -w "$ROOT" ] || [ -w "$ROOT/build" ] 2>/dev/null; then
4
+ WORK_ROOT=$ROOT
5
+ DEPS=$ROOT/.deps
6
+ BUILD=$ROOT/build
7
+ else
8
+ _h=$(printf '%s' "$ROOT" | python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest()[:12])')
9
+ WORK_ROOT=$HOME/.cache/$NAME/$_h
10
+ DEPS=$WORK_ROOT/.deps
11
+ BUILD=$WORK_ROOT/build
12
+ fi
sm8850-npu-fp16/src/port.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "contract": 1,
3
+ "model_type": "speech_to_text",
4
+ "model": "Moonshine v2 Streaming Medium (moonshine-ai/moonshine-streaming, tensilier checkpoint)",
5
+ "runtime": "LiteRT 2.3.1, Qualcomm dispatch, QNN 2.50.0",
6
+ "litert_version": "2.3.1",
7
+ "backend": "litert-qnn",
8
+ "soc": "SM8850",
9
+ "htp_arch": "v81",
10
+ "qairt_version": "2.50.0",
11
+ "precision": "fp16",
12
+ "cpu_fallback": false,
13
+ "graphs": ["enc16_Qualcomm_SM8850_apply_plugin.tflite", "dec512h_Qualcomm_SM8850_apply_plugin.tflite",
14
+ "dec1536h_Qualcomm_SM8850_apply_plugin.tflite", "dec4096h_Qualcomm_SM8850_apply_plugin.tflite"]
15
+ }
sm8850-npu-fp16/src/run.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Moonshine v2 Streaming Medium on the Hexagon NPU (LiteRT 2.3.1, QNN 2.50, SM8850).
2
+ # sh ./run.sh --audio IN.wav --out OUT.json [--metrics M.json] [--repeat R] [--partial-every SEC] [--realtime]
3
+ cd "$(dirname "$0")" || exit 1
4
+ export LD_LIBRARY_PATH="$PWD:/system/lib64:/vendor/lib64"
5
+ export ADSP_LIBRARY_PATH="$PWD/dsp;$PWD;/vendor/lib/rfsa/adsp;/vendor/dsp/cdsp;/system/lib/rfsa/adsp;/vendor/dsp"
6
+ exec ./moonshine_stream "$@"
sm8850-npu-fp16/src/runner.c ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // moonshine_stream: streaming speech to text with Moonshine v2 Streaming Medium on the Hexagon NPU (LiteRT 2.3.1 C
2
+ // API, Qualcomm dispatch, models compiled ahead of time for SM8850). Every model graph runs on the HTP; this program
3
+ // only reads the WAV, cuts it into 320 ms chunks, carries the streaming state between graph runs (memcpy), scatters
4
+ // the cross-attention K/V into the decoder's inputs, takes the argmax and detokenizes.
5
+ //
6
+ // moonshine_stream --audio IN.wav --out OUT.json [--metrics M.json] [--repeat R] [--models DIR]
7
+ // [--partial-every SEC] [--realtime] [--quiet]
8
+ //
9
+ // The host model of this loop (same chunking, masks, buckets and greedy decode) is src/host_stream.py; the graphs are
10
+ // src/moonshine_npu.py (EncoderChunk, DecoderStep) exported by src/export_tflite.py.
11
+ #include <math.h>
12
+ #include <stdbool.h>
13
+ #include <stdint.h>
14
+ #include <stdio.h>
15
+ #include <stdlib.h>
16
+ #include <string.h>
17
+ #include <sys/resource.h>
18
+ #include <time.h>
19
+ #include <unistd.h>
20
+
21
+ #include "litert/c/litert_any.h"
22
+ #include "litert/c/litert_common.h"
23
+ #include "litert/c/litert_compiled_model.h"
24
+ #include "litert/c/litert_environment.h"
25
+ #include "litert/c/litert_environment_options.h"
26
+ #include "litert/c/litert_model.h"
27
+ #include "litert/c/litert_opaque_options.h"
28
+ #include "litert/c/litert_options.h"
29
+ #include "litert/c/litert_tensor_buffer.h"
30
+ #include "litert/c/litert_tensor_buffer_requirements.h"
31
+
32
+ // moonshine_npu.py constants
33
+ #define ENC_D 768
34
+ #define NH 10
35
+ #define HD 64
36
+ #define KVD 640 // NH * HD
37
+ #define NL 14 // encoder and decoder layers
38
+ #define NLA 4 // lookahead layers (0, 1, 12, 13)
39
+ #define VOCAB 32768
40
+ #define FRAME 80 // samples per frontend frame
41
+ #define SPE 320 // samples per encoder frame (50 Hz)
42
+ #define C 16 // encoder frames per chunk (enc16 graph)
43
+ #define CHUNK (C * SPE) // 5120 samples = 320 ms
44
+ #define LEFT 15
45
+ #define SMAX 18
46
+ #define TOTAL_LAG 12
47
+ #define MAXPOS 4096
48
+ #define PART_AUDIO_PER_TOK 0.04 // s of audio between partials per decoded token (decoder 5.5-10 ms/token)
49
+ #define NEG (-1.0e4f)
50
+ #define BOS 1
51
+ #define EOS 2
52
+ static const int LOOKAHEAD[NL] = {3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3};
53
+
54
+ static const struct { int T, L; const char* file; } BUCKETS[] = {
55
+ {512, 80, "dec512h_Qualcomm_SM8850_apply_plugin.tflite"},
56
+ {1536, 224, "dec1536h_Qualcomm_SM8850_apply_plugin.tflite"},
57
+ {4096, 544, "dec4096h_Qualcomm_SM8850_apply_plugin.tflite"},
58
+ };
59
+ #define NBUCKETS 3
60
+ static const char* ENC_FILE = "enc16_Qualcomm_SM8850_apply_plugin.tflite";
61
+
62
+ static double now_ms(void) {
63
+ struct timespec ts;
64
+ clock_gettime(CLOCK_MONOTONIC, &ts);
65
+ return ts.tv_sec * 1e3 + ts.tv_nsec / 1e6;
66
+ }
67
+
68
+ static int g_quiet = 0;
69
+ static FILE* g_dump = NULL; // MOONSHINE_DUMP=FILE: debugging dump of the encoder output
70
+ #define LOG(...) do { if (!g_quiet) { fprintf(stderr, __VA_ARGS__); fflush(stderr); } } while (0)
71
+ #define DIE(...) do { fprintf(stderr, "moonshine_stream: " __VA_ARGS__); fprintf(stderr, "\n"); exit(1); } while (0)
72
+
73
+ // ---------------------------------------------------------------- LiteRT graphs
74
+ #define MAXIO 16
75
+ typedef struct {
76
+ const char* name;
77
+ LiteRtModel model;
78
+ LiteRtOptions opts; // kept alive until the compiled model is destroyed (the Qualcomm dispatch reads it)
79
+ LiteRtCompiledModel cm;
80
+ int ni, no;
81
+ LiteRtTensorBuffer in[MAXIO], out[MAXIO]; // in signature order args_0.., output_0..
82
+ LiteRtElementType in_t[MAXIO], out_t[MAXIO];
83
+ size_t in_n[MAXIO], out_n[MAXIO];
84
+ } Graph;
85
+
86
+ static int suffix(const char* s) {
87
+ const char* u = strrchr(s, '_');
88
+ return u ? atoi(u + 1) : 0;
89
+ }
90
+
91
+ static void graph_load(Graph* g, LiteRtEnvironment env, const char* dir, const char* file) {
92
+ char path[1024];
93
+ snprintf(path, sizeof path, "%s/%s", dir, file);
94
+ g->name = file;
95
+ if (LiteRtCreateModelFromFile(env, path, &g->model) != kLiteRtStatusOk) DIE("cannot load model %s", path);
96
+ LiteRtCreateOptions(&g->opts);
97
+ LiteRtSetOptionsHardwareAccelerators(g->opts, kLiteRtHwAcceleratorNpu); // the NPU alone: no CPU fallback
98
+ LiteRtOpaqueOptions q = NULL;
99
+ LiteRtCreateOpaqueOptions("qualcomm", strdup("htp_performance_mode = 2\nlog_level = 1\n"), free, &q); // 2 = burst; QNN logs: errors only
100
+ if (q) LiteRtAddOpaqueOptions(g->opts, q);
101
+ LiteRtStatus s = LiteRtCreateCompiledModel(env, g->model, g->opts, &g->cm);
102
+ if (s != kLiteRtStatusOk) DIE("compiling %s on the NPU failed (status %d)", file, (int)s);
103
+ bool noncpu = false;
104
+ LiteRtCompiledModelIsNonCpuFullyAccelerated(g->cm, &noncpu);
105
+ printf("LiteRT fully accelerated on the NPU: %s (LiteRtCompiledModelIsNonCpuFullyAccelerated) model=%s\n",
106
+ noncpu ? "yes" : "no", file);
107
+ fflush(stdout);
108
+ if (!noncpu) DIE("%s is not fully on the NPU", file);
109
+ LiteRtSignature sig;
110
+ if (LiteRtGetModelSignature(g->model, 0, &sig) != kLiteRtStatusOk) DIE("%s: no signature", file);
111
+ LiteRtParamIndex ni = 0, no = 0;
112
+ LiteRtGetNumSignatureInputs(sig, &ni);
113
+ LiteRtGetNumSignatureOutputs(sig, &no);
114
+ if (ni > MAXIO || no > MAXIO) DIE("%s: too many tensors", file);
115
+ g->ni = (int)ni;
116
+ g->no = (int)no;
117
+ for (int pass = 0; pass < 2; ++pass) {
118
+ int n = pass ? g->no : g->ni;
119
+ for (int i = 0; i < n; ++i) {
120
+ const char* nm = NULL;
121
+ LiteRtTensor t;
122
+ if (pass) {
123
+ LiteRtGetSignatureOutputName(sig, i, &nm);
124
+ LiteRtGetSignatureOutputTensorByIndex(sig, i, &t);
125
+ } else {
126
+ LiteRtGetSignatureInputName(sig, i, &nm);
127
+ LiteRtGetSignatureInputTensorByIndex(sig, i, &t);
128
+ }
129
+ int k = suffix(nm ? nm : ""); // args_10 sorts before args_2 by name: order by the numeric suffix
130
+ if (k < 0 || k >= n) DIE("%s: unexpected tensor name %s", file, nm ? nm : "?");
131
+ LiteRtRankedTensorType tt;
132
+ LiteRtGetRankedTensorType(t, &tt);
133
+ LiteRtTensorBufferRequirements req;
134
+ s = pass ? LiteRtGetCompiledModelOutputBufferRequirements(g->cm, 0, i, &req)
135
+ : LiteRtGetCompiledModelInputBufferRequirements(g->cm, 0, i, &req);
136
+ LiteRtTensorBuffer b = NULL;
137
+ if (s == kLiteRtStatusOk) s = LiteRtCreateManagedTensorBufferFromRequirements(env, &tt, req, &b);
138
+ if (s != kLiteRtStatusOk) DIE("%s: buffer for %s failed (%d)", file, nm ? nm : "?", (int)s);
139
+ size_t bytes = 0;
140
+ LiteRtGetTensorBufferPackedSize(b, &bytes);
141
+ if (pass) {
142
+ g->out[k] = b; g->out_t[k] = tt.element_type; g->out_n[k] = bytes;
143
+ } else {
144
+ g->in[k] = b; g->in_t[k] = tt.element_type; g->in_n[k] = bytes;
145
+ }
146
+ }
147
+ }
148
+ }
149
+
150
+ static void graph_free(Graph* g) {
151
+ for (int i = 0; i < MAXIO; ++i) {
152
+ if (g->in[i]) LiteRtDestroyTensorBuffer(g->in[i]);
153
+ if (g->out[i]) LiteRtDestroyTensorBuffer(g->out[i]);
154
+ }
155
+ if (g->cm) LiteRtDestroyCompiledModel(g->cm);
156
+ if (g->opts) LiteRtDestroyOptions(g->opts);
157
+ if (g->model) LiteRtDestroyModel(g->model);
158
+ memset(g, 0, sizeof *g);
159
+ }
160
+
161
+ static void* lock_w(LiteRtTensorBuffer b) {
162
+ void* p = NULL;
163
+ if (LiteRtLockTensorBuffer(b, &p, kLiteRtTensorBufferLockModeWrite) != kLiteRtStatusOk || !p) DIE("lock failed");
164
+ return p;
165
+ }
166
+ static void* lock_r(LiteRtTensorBuffer b) {
167
+ void* p = NULL;
168
+ if (LiteRtLockTensorBuffer(b, &p, kLiteRtTensorBufferLockModeRead) != kLiteRtStatusOk || !p) DIE("lock failed");
169
+ return p;
170
+ }
171
+ static void unlock(LiteRtTensorBuffer b) { LiteRtUnlockTensorBuffer(b); }
172
+
173
+ static void graph_run(Graph* g) {
174
+ LiteRtStatus s = LiteRtRunCompiledModel(g->cm, 0, g->ni, g->in, g->no, g->out);
175
+ if (s != kLiteRtStatusOk) DIE("running %s failed (status %d)", g->name, (int)s);
176
+ }
177
+
178
+ static void zero_input(Graph* g, int i) {
179
+ memset(lock_w(g->in[i]), 0, g->in_n[i]);
180
+ unlock(g->in[i]);
181
+ }
182
+
183
+ // out[o] -> in[i]: state fed back by copy (never swap buffers: QNN re-registers them with the DSP on every run)
184
+ static void copy_state(Graph* g, int o, int i) {
185
+ if (g->out_n[o] != g->in_n[i]) DIE("%s: state size mismatch out %d in %d", g->name, o, i);
186
+ void* src = lock_r(g->out[o]);
187
+ void* dst = lock_w(g->in[i]);
188
+ memcpy(dst, src, g->in_n[i]);
189
+ unlock(g->in[i]);
190
+ unlock(g->out[o]);
191
+ }
192
+
193
+ // ---------------------------------------------------------------- WAV
194
+ static float* read_wav(const char* path, int* n_out) {
195
+ FILE* f = fopen(path, "rb");
196
+ if (!f) DIE("cannot open %s", path);
197
+ unsigned char h[12];
198
+ if (fread(h, 1, 12, f) != 12 || memcmp(h, "RIFF", 4) || memcmp(h + 8, "WAVE", 4)) DIE("%s: not a RIFF WAVE file", path);
199
+ int fmt = 0, ch = 0, rate = 0, bits = 0;
200
+ float* a = NULL;
201
+ for (;;) {
202
+ unsigned char ck[8];
203
+ if (fread(ck, 1, 8, f) != 8) break;
204
+ uint32_t sz = ck[4] | ck[5] << 8 | ck[6] << 16 | (uint32_t)ck[7] << 24;
205
+ if (!memcmp(ck, "fmt ", 4)) {
206
+ unsigned char b[40] = {0};
207
+ size_t r = sz < sizeof b ? sz : sizeof b;
208
+ if (fread(b, 1, r, f) != r) DIE("%s: short fmt chunk", path);
209
+ if (sz > r) fseek(f, (long)(sz - r), SEEK_CUR);
210
+ fmt = b[0] | b[1] << 8;
211
+ ch = b[2] | b[3] << 8;
212
+ rate = b[4] | b[5] << 8 | b[6] << 16 | b[7] << 24;
213
+ bits = b[14] | b[15] << 8;
214
+ if (fmt == 0xFFFE && sz >= 26) fmt = b[24] | b[25] << 8; // WAVE_FORMAT_EXTENSIBLE subformat
215
+ } else if (!memcmp(ck, "data", 4)) {
216
+ if (!ch) DIE("%s: data before fmt", path);
217
+ if (rate != 16000) DIE("%s: %d Hz, 16000 Hz expected", path, rate);
218
+ int bps = bits / 8;
219
+ if (!((fmt == 1 && bits == 16) || (fmt == 3 && bits == 32))) DIE("%s: 16-bit PCM or 32-bit float WAV expected", path);
220
+ unsigned char* raw = malloc(sz ? sz : 1);
221
+ size_t got = fread(raw, 1, sz, f);
222
+ int n = (int)(got / (size_t)(bps * ch));
223
+ a = malloc(sizeof(float) * (size_t)(n ? n : 1));
224
+ for (int i = 0; i < n; ++i) {
225
+ double acc = 0;
226
+ for (int c = 0; c < ch; ++c) {
227
+ const unsigned char* p = raw + ((size_t)i * ch + c) * bps;
228
+ if (fmt == 1) acc += (int16_t)(p[0] | p[1] << 8) / 32768.0;
229
+ else { float v; memcpy(&v, p, 4); acc += v; }
230
+ }
231
+ a[i] = (float)(acc / ch);
232
+ }
233
+ free(raw);
234
+ *n_out = n;
235
+ break;
236
+ } else {
237
+ fseek(f, (long)(sz + (sz & 1)), SEEK_CUR);
238
+ }
239
+ }
240
+ fclose(f);
241
+ if (!a) DIE("%s: no data chunk", path);
242
+ return a;
243
+ }
244
+
245
+ // ---------------------------------------------------------------- tokenizer (vocab.bin from make_vocab.py)
246
+ typedef struct { unsigned char flags; unsigned short len; const unsigned char* s; } Tok;
247
+ static Tok g_vocab[VOCAB];
248
+ static unsigned char* g_vocab_data;
249
+
250
+ static void load_vocab(const char* dir) {
251
+ char path[1024];
252
+ snprintf(path, sizeof path, "%s/vocab.bin", dir);
253
+ FILE* f = fopen(path, "rb");
254
+ if (!f) DIE("cannot open %s", path);
255
+ fseek(f, 0, SEEK_END);
256
+ long n = ftell(f);
257
+ fseek(f, 0, SEEK_SET);
258
+ g_vocab_data = malloc((size_t)n);
259
+ if (fread(g_vocab_data, 1, (size_t)n, f) != (size_t)n) DIE("short read %s", path);
260
+ fclose(f);
261
+ if (n < 12 || memcmp(g_vocab_data, "MSVOCAB1", 8)) DIE("%s: bad header", path);
262
+ uint32_t cnt;
263
+ memcpy(&cnt, g_vocab_data + 8, 4);
264
+ const unsigned char* p = g_vocab_data + 12;
265
+ for (uint32_t i = 0; i < cnt && i < VOCAB; ++i) {
266
+ g_vocab[i].flags = p[0];
267
+ g_vocab[i].len = (unsigned short)(p[1] | p[2] << 8);
268
+ g_vocab[i].s = p + 3;
269
+ p += 3 + g_vocab[i].len;
270
+ }
271
+ }
272
+
273
+ // Join the token bytes (special tokens skipped), strip one leading space, replace invalid UTF-8 by U+FFFD.
274
+ static char* detok(const int* toks, int n) {
275
+ size_t cap = 16;
276
+ for (int i = 0; i < n; ++i) cap += g_vocab[toks[i]].len;
277
+ unsigned char* raw = malloc(cap);
278
+ size_t m = 0;
279
+ for (int i = 0; i < n; ++i) {
280
+ const Tok* t = &g_vocab[toks[i]];
281
+ if (t->flags & 1) continue;
282
+ memcpy(raw + m, t->s, t->len);
283
+ m += t->len;
284
+ }
285
+ size_t st = (m > 0 && raw[0] == ' ') ? 1 : 0;
286
+ char* out = malloc(3 * m + 4);
287
+ size_t o = 0;
288
+ for (size_t i = st; i < m;) {
289
+ unsigned char c = raw[i];
290
+ int len = c < 0x80 ? 1 : (c >> 5) == 6 ? 2 : (c >> 4) == 14 ? 3 : (c >> 3) == 30 ? 4 : 0;
291
+ bool ok = len > 0 && i + len <= m;
292
+ for (int k = 1; ok && k < len; ++k) ok = (raw[i + k] & 0xC0) == 0x80;
293
+ if (ok) {
294
+ memcpy(out + o, raw + i, (size_t)len);
295
+ o += len;
296
+ i += len;
297
+ } else {
298
+ memcpy(out + o, "\xEF\xBF\xBD", 3);
299
+ o += 3;
300
+ i += 1;
301
+ }
302
+ }
303
+ out[o] = 0;
304
+ free(raw);
305
+ return out;
306
+ }
307
+
308
+ static void json_str(FILE* f, const char* s) {
309
+ fputc('"', f);
310
+ for (; *s; ++s) {
311
+ unsigned char c = (unsigned char)*s;
312
+ if (c == '"' || c == '\\') fprintf(f, "\\%c", c);
313
+ else if (c == '\n') fputs("\\n", f);
314
+ else if (c < 0x20) fprintf(f, "\\u%04x", c);
315
+ else fputc(c, f);
316
+ }
317
+ fputc('"', f);
318
+ }
319
+
320
+ // ---------------------------------------------------------------- the stream
321
+ typedef struct {
322
+ Graph enc, dec;
323
+ int Tb, Lb;
324
+ bool half; // decoder cache inputs in fp16
325
+ } Engine;
326
+
327
+ // Encoder graph I/O (EncoderChunk.forward): in 0 audio[1,5120] 1 c1s[4,768] 2 c2s[4,1536] 3 kst[14,18,640]
328
+ // 4 vst[14,18,640] 5 xst[4,3,768] 6 kmask[14,34] 7 pos[16] int32; out 0..4 the new states, 5 ck[14,16,640]
329
+ // 6 cv[14,16,640] 7 enc[16,768].
330
+ // Decoder graph I/O (DecoderStep.forward): in 0 tok[1] 1 pos[1] int32, 2 smask[1,L] 3 cmask[1,T] fp32,
331
+ // 4 sk[14,10,64,L] 5 sv[14,10,L,64] 6 ck[14,10,64,T] 7 cv[14,10,T,64] (fp16); out 0 logits[1,32768] fp32,
332
+ // 1 knew[14,10,64] 2 vnew[14,10,64].
333
+
334
+ static inline void put(void* base, bool half, size_t idx, float v) {
335
+ if (half) ((__fp16*)base)[idx] = (__fp16)v;
336
+ else ((float*)base)[idx] = v;
337
+ }
338
+
339
+ typedef struct {
340
+ int toks[1024];
341
+ int n;
342
+ double ms;
343
+ int steps;
344
+ } Decode;
345
+
346
+ // Greedy decode over the first `avail` encoder frames (HF generate: start from BOS, at most max_length - 1 new tokens,
347
+ // stop at EOS). host_stream.py greedy().
348
+ static void greedy(Engine* e, int avail, int max_length, Decode* d) {
349
+ Graph* g = &e->dec;
350
+ double t0 = now_ms();
351
+ float* cm = lock_w(g->in[3]);
352
+ for (int t = 0; t < e->Tb; ++t) cm[t] = t < avail ? 0.f : NEG;
353
+ unlock(g->in[3]);
354
+ d->toks[0] = BOS;
355
+ d->n = 1;
356
+ int steps = max_length - 1;
357
+ if (steps > e->Lb) DIE("%d decoder steps exceed the bucket's %d positions", steps, e->Lb);
358
+ for (int i = 0; i < steps; ++i) {
359
+ int32_t* tok = lock_w(g->in[0]);
360
+ tok[0] = d->toks[d->n - 1];
361
+ unlock(g->in[0]);
362
+ int32_t* pos = lock_w(g->in[1]);
363
+ pos[0] = i;
364
+ unlock(g->in[1]);
365
+ float* sm = lock_w(g->in[2]);
366
+ for (int j = 0; j < e->Lb; ++j) sm[j] = j < i ? 0.f : NEG;
367
+ unlock(g->in[2]);
368
+ graph_run(g);
369
+ const float* kn = lock_r(g->out[1]);
370
+ const float* vn = lock_r(g->out[2]);
371
+ bool kh = g->out_t[1] == kLiteRtElementTypeFloat16;
372
+ void* sk = lock_w(g->in[4]);
373
+ void* sv = lock_w(g->in[5]);
374
+ for (int lh = 0; lh < NL * NH; ++lh)
375
+ for (int dd = 0; dd < HD; ++dd) {
376
+ float k = kh ? (float)((const __fp16*)kn)[lh * HD + dd] : kn[lh * HD + dd];
377
+ float v = kh ? (float)((const __fp16*)vn)[lh * HD + dd] : vn[lh * HD + dd];
378
+ put(sk, e->half, ((size_t)lh * HD + dd) * e->Lb + i, k);
379
+ put(sv, e->half, ((size_t)lh * e->Lb + i) * HD + dd, v);
380
+ }
381
+ unlock(g->in[5]);
382
+ unlock(g->in[4]);
383
+ unlock(g->out[2]);
384
+ unlock(g->out[1]);
385
+ const float* lg = lock_r(g->out[0]);
386
+ int best = 0;
387
+ for (int v = 1; v < VOCAB; ++v)
388
+ if (lg[v] > lg[best]) best = v; // ties to the lowest id
389
+ unlock(g->out[0]);
390
+ d->toks[d->n++] = best;
391
+ if (best == EOS) break;
392
+ }
393
+ d->steps = d->n - 1;
394
+ d->ms = now_ms() - t0;
395
+ }
396
+
397
+ typedef struct {
398
+ double total_ms, first_partial_ms, first_partial_audio_s, enc_ms_sum, dec_ms, part_ms;
399
+ int chunks, new_tokens, dec_steps, partials;
400
+ double* chunk_ms; // encoder run + state copy + K/V scatter, per chunk
401
+ double* latency_ms; // --realtime: chunk arrival to its work (and partial) done
402
+ char* text;
403
+ char** ptext;
404
+ double* paudio;
405
+ } RunResult;
406
+
407
+ static void run_stream(Engine* e, const float* audio_in, int n, double partial_every, bool realtime, RunResult* rr) {
408
+ double t_start = now_ms();
409
+ memset(rr, 0, sizeof *rr);
410
+ rr->first_partial_ms = -1;
411
+ int n0 = n / FRAME;
412
+ int F = (n + FRAME - 1) / FRAME, n1 = (F + 1) / 2, T = (n1 + 1) / 2;
413
+ int K = (T + TOTAL_LAG + C - 1) / C;
414
+ rr->chunk_ms = calloc((size_t)K + 1, sizeof(double));
415
+ rr->latency_ms = calloc((size_t)K + 1, sizeof(double));
416
+ int maxp = (int)(n / 16000.0 / (partial_every > 0 ? partial_every : 1e9)) + 2;
417
+ rr->ptext = calloc((size_t)maxp, sizeof(char*));
418
+ rr->paudio = calloc((size_t)maxp, sizeof(double));
419
+ Graph* g = &e->enc;
420
+ for (int i = 1; i <= 5; ++i) zero_input(g, i); // fresh streaming state for every request
421
+ int D[NL];
422
+ for (int l = 0, s = 0; l < NL; ++l) { D[l] = s; s += LOOKAHEAD[l]; }
423
+ double next_partial = partial_every > 0 ? partial_every * 16000.0 : 1e30;
424
+ Decode dec;
425
+ for (int k = 0; k < K; ++k) {
426
+ long s0 = (long)k * CHUNK;
427
+ if (realtime) { // wait until this chunk would have arrived from a live microphone
428
+ double arrive = t_start + (double)((s0 + CHUNK < n) ? s0 + CHUNK : n) / 16.0; // padding chunks arrive with the end
429
+ while (now_ms() < arrive) usleep(1000);
430
+ }
431
+ double t0 = now_ms();
432
+ float* a = lock_w(g->in[0]);
433
+ for (int i = 0; i < CHUNK; ++i) {
434
+ long j = s0 + i;
435
+ a[i] = (j < (long)n0 * FRAME) ? audio_in[j] : 0.f; // the partial last 80-sample frame is masked to zero
436
+ }
437
+ unlock(g->in[0]);
438
+ float* km = lock_w(g->in[6]);
439
+ for (int l = 0; l < NL; ++l) {
440
+ int r = LOOKAHEAD[l];
441
+ int av = k * C - D[l] - r;
442
+ for (int jj = 0; jj < SMAX + C; ++jj) {
443
+ int f = av - LEFT - (SMAX - LEFT - r) + jj;
444
+ km[l * (SMAX + C) + jj] = (f >= 0 && f < T) ? 0.f : NEG;
445
+ }
446
+ }
447
+ unlock(g->in[6]);
448
+ int out0 = k * C - TOTAL_LAG;
449
+ int32_t* pos = lock_w(g->in[7]);
450
+ for (int i = 0; i < C; ++i) {
451
+ int p = out0 + i;
452
+ pos[i] = p < 0 ? 0 : p >= MAXPOS ? MAXPOS - 1 : p;
453
+ }
454
+ unlock(g->in[7]);
455
+ graph_run(g);
456
+ if (g_dump) { // debugging: the encoder output rows of every chunk, appended as raw fp32 [16, 768]
457
+ fwrite(lock_r(g->out[7]), sizeof(float), (size_t)C * 768, g_dump);
458
+ unlock(g->out[7]);
459
+ }
460
+ for (int i = 0; i < 5; ++i) copy_state(g, i, i + 1);
461
+ // new cross-attention K/V rows -> decoder inputs ck[l][h][d][t], cv[l][h][t][d]
462
+ const float* ck = lock_r(g->out[5]);
463
+ const float* cv = lock_r(g->out[6]);
464
+ void* dk = lock_w(e->dec.in[6]);
465
+ void* dv = lock_w(e->dec.in[7]);
466
+ for (int i = 0; i < C; ++i) {
467
+ int f = out0 + i;
468
+ if (f < 0 || f >= T) continue;
469
+ for (int l = 0; l < NL; ++l) {
470
+ const float* kr = ck + ((size_t)l * C + i) * KVD;
471
+ const float* vr = cv + ((size_t)l * C + i) * KVD;
472
+ for (int h = 0; h < NH; ++h)
473
+ for (int dd = 0; dd < HD; ++dd) {
474
+ size_t lh = (size_t)l * NH + h;
475
+ put(dk, e->half, (lh * HD + dd) * e->Tb + f, kr[h * HD + dd]);
476
+ put(dv, e->half, (lh * e->Tb + f) * HD + dd, vr[h * HD + dd]);
477
+ }
478
+ }
479
+ }
480
+ unlock(e->dec.in[7]);
481
+ unlock(e->dec.in[6]);
482
+ unlock(g->out[6]);
483
+ unlock(g->out[5]);
484
+ double t1 = now_ms();
485
+ rr->chunk_ms[k] = t1 - t0;
486
+ rr->enc_ms_sum += t1 - t0;
487
+ long seen = s0 + CHUNK < n ? s0 + CHUNK : n;
488
+ int avail = (k + 1) * C - TOTAL_LAG;
489
+ if (avail > T) avail = T;
490
+ if (k < K - 1 && seen < n && (double)(s0 + CHUNK) >= next_partial && avail > 0) {
491
+ greedy(e, avail, (int)(seen * 6.5 / 16000.0), &dec);
492
+ // a partial re-decodes everything heard so far: wait at least PART_AUDIO_PER_TOK s of audio per token it took,
493
+ // so partials cost at most ~25% of the audio's duration on long inputs (deterministic: counts tokens, not time)
494
+ while (next_partial <= (double)(s0 + CHUNK)) next_partial += partial_every * 16000.0;
495
+ double tok_next = (double)(s0 + CHUNK) + dec.steps * PART_AUDIO_PER_TOK * 16000.0;
496
+ if (tok_next > next_partial) next_partial = tok_next;
497
+ char* txt = detok(dec.toks, dec.n);
498
+ double tp = now_ms();
499
+ if (rr->partials == 0) {
500
+ rr->first_partial_ms = tp - t_start;
501
+ rr->first_partial_audio_s = seen / 16000.0;
502
+ }
503
+ rr->paudio[rr->partials] = seen / 16000.0;
504
+ rr->ptext[rr->partials++] = txt;
505
+ rr->part_ms += dec.ms;
506
+ LOG("PARTIAL %6.2fs (%5.1f ms, %d tok): %s\n", seen / 16000.0, dec.ms, dec.steps, txt);
507
+ }
508
+ rr->latency_ms[k] = now_ms() - t0;
509
+ rr->chunks = k + 1;
510
+ }
511
+ int ml = (int)(n * 6.5 / 16000.0);
512
+ greedy(e, T, ml, &dec);
513
+ rr->text = detok(dec.toks, dec.n);
514
+ rr->new_tokens = dec.steps;
515
+ rr->dec_ms = dec.ms;
516
+ rr->dec_steps = dec.steps;
517
+ rr->total_ms = now_ms() - t_start;
518
+ if (rr->first_partial_ms < 0) {
519
+ rr->first_partial_ms = rr->total_ms;
520
+ rr->first_partial_audio_s = n / 16000.0;
521
+ }
522
+ LOG("FINAL %6.2fs (%5.1f ms, %d tok): %s\n", n / 16000.0, dec.ms, dec.steps, rr->text);
523
+ }
524
+
525
+ static void free_result(RunResult* rr) {
526
+ for (int i = 0; i < rr->partials; ++i) free(rr->ptext[i]);
527
+ free(rr->ptext);
528
+ free(rr->paudio);
529
+ free(rr->chunk_ms);
530
+ free(rr->latency_ms);
531
+ free(rr->text);
532
+ }
533
+
534
+ static int cmpd(const void* a, const void* b) {
535
+ double x = *(const double*)a, y = *(const double*)b;
536
+ return x < y ? -1 : x > y;
537
+ }
538
+ static double median(const double* v, int n) {
539
+ if (n <= 0) return 0;
540
+ double* t = malloc(sizeof(double) * (size_t)n);
541
+ memcpy(t, v, sizeof(double) * (size_t)n);
542
+ qsort(t, (size_t)n, sizeof(double), cmpd);
543
+ double m = n % 2 ? t[n / 2] : 0.5 * (t[n / 2 - 1] + t[n / 2]);
544
+ free(t);
545
+ return m;
546
+ }
547
+
548
+ static void usage(void) {
549
+ fprintf(stderr,
550
+ "usage: moonshine_stream --audio IN.wav --out OUT.json [--metrics M.json] [--repeat R] [--models DIR]\n"
551
+ " [--partial-every SEC (default 1.0, 0 = no partials)] [--realtime] [--quiet]\n");
552
+ }
553
+
554
+ int main(int argc, char** argv) {
555
+ double t_proc = now_ms();
556
+ const char *wav = NULL, *out = NULL, *metrics = NULL, *models = NULL;
557
+ int repeat = 1;
558
+ double partial_every = 1.0;
559
+ bool realtime = false;
560
+ for (int i = 1; i < argc; ++i) {
561
+ const char* a = argv[i];
562
+ const char* v = i + 1 < argc ? argv[i + 1] : NULL;
563
+ #define TAKE(x) do { if (!v) { usage(); return 1; } x; ++i; } while (0)
564
+ if (!strcmp(a, "--audio")) TAKE(wav = v);
565
+ else if (!strcmp(a, "--out")) TAKE(out = v);
566
+ else if (!strcmp(a, "--metrics")) TAKE(metrics = v);
567
+ else if (!strcmp(a, "--repeat")) TAKE(repeat = atoi(v));
568
+ else if (!strcmp(a, "--models")) TAKE(models = v);
569
+ else if (!strcmp(a, "--partial-every")) TAKE(partial_every = atof(v));
570
+ else if (!strcmp(a, "--realtime")) realtime = true;
571
+ else if (!strcmp(a, "--quiet")) g_quiet = 1;
572
+ else { fprintf(stderr, "moonshine_stream: unknown argument %s\n", a); usage(); return 1; }
573
+ #undef TAKE
574
+ }
575
+ if (!wav || !out || repeat < 1) { usage(); return 1; }
576
+ char exe_dir[1024];
577
+ ssize_t len = readlink("/proc/self/exe", exe_dir, sizeof exe_dir - 1);
578
+ exe_dir[len > 0 ? len : 0] = 0;
579
+ char* sl = strrchr(exe_dir, '/');
580
+ if (sl) *sl = 0; else strcpy(exe_dir, ".");
581
+ if (!models) models = exe_dir;
582
+ if (!getenv("ADSP_LIBRARY_PATH")) {
583
+ char p[4096];
584
+ snprintf(p, sizeof p, "%s/dsp;%s;/vendor/lib/rfsa/adsp;/vendor/dsp/cdsp;/system/lib/rfsa/adsp;/vendor/dsp", exe_dir,
585
+ exe_dir);
586
+ setenv("ADSP_LIBRARY_PATH", p, 1);
587
+ }
588
+
589
+ if (getenv("MOONSHINE_DUMP")) g_dump = fopen(getenv("MOONSHINE_DUMP"), "wb");
590
+ int n = 0;
591
+ float* audio = read_wav(wav, &n);
592
+ int F = (n + FRAME - 1) / FRAME, n1 = (F + 1) / 2, T = (n1 + 1) / 2;
593
+ int b = 0;
594
+ while (b < NBUCKETS && BUCKETS[b].T < T) ++b;
595
+ if (b == NBUCKETS)
596
+ DIE("%.1f s of audio is %d encoder frames; the model's position table and the largest bucket hold %d (81.9 s)",
597
+ n / 16000.0, T, MAXPOS);
598
+ load_vocab(models);
599
+
600
+ LiteRtEnvironment env = NULL;
601
+ LiteRtEnvOption eo[2];
602
+ eo[0].tag = kLiteRtEnvOptionTagDispatchLibraryDir;
603
+ eo[0].value.type = kLiteRtAnyTypeString;
604
+ eo[0].value.str_value = exe_dir;
605
+ eo[1].tag = kLiteRtEnvOptionTagMinLoggerSeverity;
606
+ eo[1].value.type = kLiteRtAnyTypeInt;
607
+ eo[1].value.int_value = 3; // errors only (1 = info: QNN logs every buffer registration)
608
+ if (LiteRtCreateEnvironment(2, eo, &env) != kLiteRtStatusOk) DIE("LiteRtCreateEnvironment failed");
609
+ Engine e;
610
+ memset(&e, 0, sizeof e);
611
+ e.Tb = BUCKETS[b].T;
612
+ e.Lb = BUCKETS[b].L;
613
+ LOG("loading %s and %s (T=%d frames, %.2f s audio)\n", ENC_FILE, BUCKETS[b].file, T, n / 16000.0);
614
+ graph_load(&e.enc, env, models, ENC_FILE);
615
+ graph_load(&e.dec, env, models, BUCKETS[b].file);
616
+ e.half = e.dec.in_t[6] == kLiteRtElementTypeFloat16;
617
+ if (e.enc.ni != 8 || e.enc.no != 8 || e.dec.ni != 8 || e.dec.no != 3 || e.enc.out_t[5] != kLiteRtElementTypeFloat32 ||
618
+ e.enc.out_t[6] != kLiteRtElementTypeFloat32 || e.dec.out_t[0] != kLiteRtElementTypeFloat32 ||
619
+ e.dec.in_t[2] != kLiteRtElementTypeFloat32 || e.dec.in_t[3] != kLiteRtElementTypeFloat32 ||
620
+ e.enc.in_t[0] != kLiteRtElementTypeFloat32 || e.enc.in_t[6] != kLiteRtElementTypeFloat32)
621
+ DIE("unexpected graph signature (tensor count or dtype)");
622
+ for (int i = 0; i < e.dec.ni; ++i) zero_input(&e.dec, i); // masked cache slots must still be finite
623
+ double load_ms = now_ms() - t_proc;
624
+ LOG("ready in %.0f ms\n", load_ms);
625
+
626
+ RunResult* runs = calloc((size_t)repeat, sizeof(RunResult));
627
+ for (int r = 0; r < repeat; ++r) {
628
+ run_stream(&e, audio, n, partial_every, realtime, &runs[r]);
629
+ LOG("run %d: total %.1f ms, encoder %.2f ms/chunk (%d chunks), final decode %d tok in %.1f ms, partials %d in "
630
+ "%.1f ms, RTF %.3f\n",
631
+ r, runs[r].total_ms, median(runs[r].chunk_ms, runs[r].chunks), runs[r].chunks, runs[r].dec_steps,
632
+ runs[r].dec_ms, runs[r].partials, runs[r].part_ms, runs[r].total_ms / (n / 16.0));
633
+ }
634
+ RunResult* last = &runs[repeat - 1];
635
+ FILE* f = fopen(out, "w");
636
+ if (!f) DIE("cannot write %s", out);
637
+ fputs("{\"text\": ", f);
638
+ json_str(f, last->text);
639
+ fputs(", \"partials\": [", f);
640
+ for (int i = 0; i < last->partials; ++i) {
641
+ fprintf(f, "%s{\"audio_s\": %.2f, \"text\": ", i ? ", " : "", last->paudio[i]);
642
+ json_str(f, last->ptext[i]);
643
+ fputc('}', f);
644
+ }
645
+ fputs("]}\n", f);
646
+ fclose(f);
647
+ if (metrics) {
648
+ struct rusage ru;
649
+ getrusage(RUSAGE_SELF, &ru);
650
+ f = fopen(metrics, "w");
651
+ if (!f) DIE("cannot write %s", metrics);
652
+ fprintf(f, "{\"load_ms\": %.1f, \"runs\": [", load_ms);
653
+ for (int r = 0; r < repeat; ++r) {
654
+ RunResult* x = &runs[r];
655
+ fprintf(f,
656
+ "%s{\"total_ms\": %.2f, \"ttft_ms\": %.2f, \"first_partial_ms\": %.2f, \"first_partial_audio_s\": %.2f, "
657
+ "\"new_tokens\": %d, \"audio_s\": %.3f, \"rtf\": %.4f, \"chunks\": %d, \"chunk_ms_median\": %.3f, "
658
+ "\"final_decode_ms\": %.2f, \"decode_ms_per_token\": %.3f, \"partials\": %d, \"partial_decode_ms\": %.2f, "
659
+ "\"end_latency_ms\": %.2f, \"realtime\": %s, \"chunk_ms\": [",
660
+ r ? ", " : "", x->total_ms, x->first_partial_ms, x->first_partial_ms, x->first_partial_audio_s,
661
+ x->new_tokens, n / 16000.0, x->total_ms / (n / 16.0), x->chunks, median(x->chunk_ms, x->chunks),
662
+ x->dec_ms, x->dec_steps ? x->dec_ms / x->dec_steps : 0.0, x->partials, x->part_ms,
663
+ realtime ? x->total_ms - n / 16.0 : x->total_ms, realtime ? "true" : "false");
664
+ for (int k = 0; k < x->chunks; ++k) fprintf(f, "%s%.3f", k ? ", " : "", x->chunk_ms[k]);
665
+ fputs("], \"chunk_latency_ms\": [", f);
666
+ for (int k = 0; k < x->chunks; ++k) fprintf(f, "%s%.3f", k ? ", " : "", x->latency_ms[k]);
667
+ fputs("]}", f);
668
+ }
669
+ fprintf(f, "], \"peak_mem_mb\": %.1f}\n", ru.ru_maxrss / 1024.0);
670
+ fclose(f);
671
+ }
672
+ for (int r = 0; r < repeat; ++r) free_result(&runs[r]);
673
+ free(runs);
674
+ graph_free(&e.dec); // compiled models before their options (graph_free order), then the environment
675
+ graph_free(&e.enc);
676
+ LiteRtDestroyEnvironment(env);
677
+ free(audio);
678
+ free(g_vocab_data);
679
+ return 0;
680
+ }
sm8850-npu-fp16/src/vm_pipeline.sh ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Model pipeline (x86-64 Linux, Python 3.12, >= 64 GB RAM; made on a 16 vCPU / 128 GB machine): weights from Hugging
3
+ # Face -> .tflite (export_tflite.py, checked on CPU) -> AOT compile for SM8850 (aot_compile.py). Not run by build.sh:
4
+ # its outputs ship in models/.
5
+ # bash src/vm_pipeline.sh WORKDIR GRAPH... (GRAPH: enc16 dec512h dec1536h dec4096h; suffix h = fp16 cache inputs)
6
+ # CASES=DIR (optional): real graph inputs from make_cases.py, used by export_tflite.py's CPU check
7
+ set -u
8
+ SRC=$(cd "$(dirname "$0")" && pwd)
9
+ WORK=${1:?usage: bash vm_pipeline.sh WORKDIR GRAPH...}; shift
10
+ mkdir -p "$WORK" && cd "$WORK" || exit 1
11
+ VENV=$WORK/.venv
12
+ if [ ! -f "$VENV/.ok" ]; then
13
+ python3 -m venv "$VENV" && "$VENV/bin/pip" install -q -r "$SRC/export_requirements.txt" && touch "$VENV/.ok" || exit 1
14
+ fi
15
+ PY=$VENV/bin/python
16
+ REV=da30bae714913eb0057e733bccb4700104afb1b0
17
+ CKPT=m/tensilier/model.safetensors
18
+ if [ ! -f "$CKPT" ]; then
19
+ mkdir -p m/tensilier
20
+ curl -fL --retry 3 -o "$CKPT" \
21
+ "https://huggingface.co/moonshine-ai/moonshine-streaming/resolve/$REV/tensilier/model.safetensors" || exit 1
22
+ fi
23
+ echo "6a454dd0a064151946c7076d7b89c79d42a02eb41fc261083392a0349a34d86f $CKPT" | sha256sum -c - || exit 1
24
+ mkdir -p out aot logs
25
+ pids=()
26
+ for g in "$@"; do
27
+ case "$g" in *h) gg=${g%h}; extra=--half-cache ;; *) gg=$g; extra= ;; esac
28
+ ( /usr/bin/time -v $PY "$SRC/export_tflite.py" "$CKPT" out --graph $gg $extra ${CASES:+--cases "$CASES"} \
29
+ > logs/exp_$g.log 2>&1
30
+ echo "export $g rc=$?" >> logs/exp_$g.log
31
+ $PY "$SRC/aot_compile.py" out/$g.tflite aot > logs/aot_$g.log 2>&1; echo "aot $g rc=$?" >> logs/aot_$g.log ) &
32
+ pids+=($!)
33
+ done
34
+ for p in "${pids[@]}"; do wait $p; done
35
+ for g in "$@"; do echo "=== $g"; grep -E "exported|check|cpu run|rc=|Maximum resident" logs/exp_$g.log; tail -n 15 logs/aot_$g.log; done
36
+ ls -la out aot
sm8850-npu-fp16/vendor/litert/2.3.1/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
sm8850-npu-fp16/vendor/litert/2.3.1/SHA256SUMS ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 ./LICENSE
2
+ c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 ./include/LICENSE
3
+ 6e69a0cab0a4743d12c5c365784b0faed0d66e39f83b6abe0338e525e508e493 ./include/litert/build_common/build_config.h
4
+ 1f990a6cb0e146fac26525fe790afd3ea1a57743a8a09e22b4fb3dad0ca8e56f ./include/litert/build_common/config/build_config_cpu_only.h
5
+ 43957016e5f78881be3a53f57b3e2678278bd6d77d00314553bafe204d022b62 ./include/litert/build_common/config/build_config_gpu.h
6
+ 6e69a0cab0a4743d12c5c365784b0faed0d66e39f83b6abe0338e525e508e493 ./include/litert/build_common/config/build_config_gpu_npu.h
7
+ 69eeb0d5968d6e718f9b0510a5aa2057a5776ac825a7c12582030b5b26a593df ./include/litert/build_common/config/build_config_npu.h
8
+ 5eb13c71f45711ab66c95e9189e97b34d1609e733fcaf36f92ff7a261d8fd1c5 ./include/litert/c/internal/litert_abi_header.h
9
+ 41058dd791b4f2f8a5157edb6c7fbff8cda0611d515c15dad330cb2c1c736d97 ./include/litert/c/internal/litert_accelerator.h
10
+ 25a681f0447a586bb323b1cea22b9c4c34e8ba02421306cb2cce031187ac9396 ./include/litert/c/internal/litert_accelerator_def.h
11
+ 25ba68e1a8506de2b0abe9c369b1136a0331d343a9f310f2a4e58ddae3c505bd ./include/litert/c/internal/litert_accelerator_registration.h
12
+ dc3bc20117b8b048ebc576b418dbba8cfb9490613b9558508159c57e8acefe85 ./include/litert/c/internal/litert_compiler_context.h
13
+ 4e7126626f6c598c01cd51719418e454eaa02d7888c870f71ba6660181d48323 ./include/litert/c/internal/litert_custom_tensor_buffer_handlers_def.h
14
+ 3f6f33ee97719da33237d02d1de990634f55cd7a99753b529eff051f877faae0 ./include/litert/c/internal/litert_delegate_wrapper.h
15
+ b88e715bf538f6001723b087341723cfb8c6f1787e0fde03131808a43bf263f2 ./include/litert/c/internal/litert_dispatch_delegate.h
16
+ 1095fec726935ef71ba701b3c8eeeb46c4566bd9d55eec701be8cb762d26b1b9 ./include/litert/c/internal/litert_external_litert_buffer_context.h
17
+ 69bad1fda590ad1afa659159f9fd39cf27a823b487e071230060472165a479e3 ./include/litert/c/internal/litert_logging.h
18
+ 366cfb40f43ffd4bc0646b4871abdec10081cf7eac0541e099395ff6e31cf139 ./include/litert/c/internal/litert_logging_helper.h
19
+ bbafa8fcfcf1b43333286972542635fa8cdbf916e9eb65c55575c14958d8af64 ./include/litert/c/internal/litert_logging_helper_with_compiler_context.h
20
+ 4bce7433ede32b23fdd0c48ebac0fd1fba0870fd0202805cce1922df50400d2c ./include/litert/c/internal/litert_logging_helper_with_runtime_context.h
21
+ 2a7a07f4c9c602bd30b992c9988c1678437b0768ff0469b1babd4f42c05c701a ./include/litert/c/internal/litert_options_helper.h
22
+ 4cee98886bb0b0f506928b3df07d162a4e16b8a5ac44e6f17261eb6fa4bcc99c ./include/litert/c/internal/litert_runtime_api_export.h
23
+ 943e40fc2d91c8ed94d6427d1644cb7d70c3f16d39b3a3aae813e27561ff9b84 ./include/litert/c/internal/litert_runtime_builtin.h
24
+ 060c21ceb94b8bcebc467e3a0257f129a1cd3d3b0c17dca5de90381206cc9b16 ./include/litert/c/internal/litert_runtime_c_api.h
25
+ fe2ca1df2a866d9681c028a5b2e482e646a15a619e7b377d2a7739d1dd234b18 ./include/litert/c/internal/litert_runtime_context.h
26
+ b9076085c64234d90f693cd9017329652bcff605858f084771d4ddd0af37e9ca ./include/litert/c/internal/litert_scheduling_info.h
27
+ f77a5bb57d9479035c900b726a9b9a5c7eaca42fe4cc53faeb93dbcc87e4487a ./include/litert/c/internal/litert_tensor_buffer_registry.h
28
+ e10779327820f395eaad8ab6984f9f763943c07b0f17a18f3dbadd3d431f91dd ./include/litert/c/litert_any.h
29
+ 9cc8fbcf1b963f2414cb5abdb26c5983b3124b53b5fbc3151efc4a4986f29ff7 ./include/litert/c/litert_builder.h
30
+ 42717402ae835f2276bf85eb5666709fb0b3bcdc09b49dbdeecb0191c94a369f ./include/litert/c/litert_common.h
31
+ e613c98b5299b0c3c130c883963d29f98a6f0b2dccc66c73b8a10bdccdcac13b ./include/litert/c/litert_compiled_model.h
32
+ 57f5081cb96d40ce0d63a9b31e96e5816c6847a4d11a85abfa2cbdd4759f52f7 ./include/litert/c/litert_custom_op_kernel.h
33
+ 70464c92ef72b20f67ad5898148cd9bb31ae995a411e5e233fc90aab4fbd2783 ./include/litert/c/litert_custom_tensor_buffer.h
34
+ a83820ef9e68bd175db75a7ef155ce67f5bab2e7ad04e6b046affe9ee3366b3d ./include/litert/c/litert_environment.h
35
+ 4e2acf5b5c78cae99fb0db40312556d348c32fd1c67f033f86e8a67968ccc995 ./include/litert/c/litert_environment_options.h
36
+ c15850184b3908ba1d9b5a53b8ef99004071208bc17d915296d5cf963247a696 ./include/litert/c/litert_event.h
37
+ 7a6756dc2995d103fc632e06cb15648b24daed99297b7de37b00792d8ebced50 ./include/litert/c/litert_event_type.h
38
+ e0ecbd8d410bc8790419c2f01794a8de0b06721fd55d003cd96e8e101764fc49 ./include/litert/c/litert_gl_types.h
39
+ c16011a88f7487fa6d3e386905317cf9491d1666d5c7a7ed33e07a9f8b4cf514 ./include/litert/c/litert_layout.h
40
+ fa9f0057830c58cf7b57e0f8ccb75dd034294132f5c4c8f44b2e886e72be3a3c ./include/litert/c/litert_metrics.h
41
+ c409c985fc79b9f967890e475e28ab77c1fe7776874197a598438a7b2d916d8b ./include/litert/c/litert_model.h
42
+ 01cf6ea792a7f6f55690fe7acfd8d41f5a707c8ea7cb7418f71e44c84d45757a ./include/litert/c/litert_model_types.h
43
+ 9937e456e6212efe1164c9c4ca8b1abb645d0dd9220cfefe0b4eca13cb18c49e ./include/litert/c/litert_op_code.h
44
+ 5c5d7ff7b25e46a939855bd381bdd2377061c7bf96cf6358f07ae78872986df2 ./include/litert/c/litert_op_options.h
45
+ 33116f5f4a121b785c9b8a313c4ce065088ba322c279776c33542a19e62192c1 ./include/litert/c/litert_opaque_options.h
46
+ 2cb880623b4d4eb86d242d4b246a14dd42b5fbebf297ceb9bb4012fed6a208b4 ./include/litert/c/litert_opencl_types.h
47
+ d7ff502b26c7f54574b351a5afbc247e639843bcb4270d0615d38abbde503d9a ./include/litert/c/litert_options.h
48
+ 5e3e943ab23621154ee94a71b50a6fdf12504d2ca35ee10b68c948b0020604af ./include/litert/c/litert_platform_support.h
49
+ 41ba3f580d6c12030053d10698d15ae47264c0f15269c21714da61ecc1156f9a ./include/litert/c/litert_profiler.h
50
+ 7ed4d79a8f9b1a13188c45066452ff818319b97c70937b0e340801bd485b915c ./include/litert/c/litert_profiler_event.h
51
+ 30132533f7b0aa09cc56cc28a1f3c49da547592ab8b80718cc91585142a9c568 ./include/litert/c/litert_profiler_types.h
52
+ 2e45153e2d8510e2570f7965b2c46403445786b535c542f077ac9afda78b1274 ./include/litert/c/litert_tensor_buffer.h
53
+ f71921b6bd7959ad4c24808296f53a56c8c1c3677a8cbaf48d5d611e02490387 ./include/litert/c/litert_tensor_buffer_requirements.h
54
+ 5fa19ae0438f270b3c09281358b9cdfad04c47782cc97582e0af582ec7888450 ./include/litert/c/litert_tensor_buffer_types.h
55
+ 944030a82f2737b1436893fc5ececfef06ea8cc61580d0c93caa787a5763c011 ./include/litert/c/litert_webgpu_types.h
56
+ 79e594c0662980b3b74e4d51a4d1ac533b8a6261c82bdf0d4328bc1552417967 ./include/litert/c/options/litert_arm_options.h
57
+ ce3272bdb9b6c7e7237f697d9481f099915a4ccda7483ed7508c209900fddd3d ./include/litert/c/options/litert_compiler_options.h
58
+ 73e13527e760aae2884374323fa7adcd58731b4d8741f852277e738703a7617c ./include/litert/c/options/litert_cpu_options.h
59
+ 56998e715d276bea00baea697940e2c7e98a5ebf2e434b910a9320aea7d57938 ./include/litert/c/options/litert_google_tensor_options.h
60
+ 81467d9148ac1fb6d6ed265c39f33436e6063c9e7d3bbbf1eba8fd62d541f4af ./include/litert/c/options/litert_google_tensor_options_type.h
61
+ 34071b35dda03892e926ca2a99ad985ddc2dd39c9bfbf02f620785aa6b4620bb ./include/litert/c/options/litert_gpu_options.h
62
+ 54d0a38d32ae00fa406b36e6db87adfd4185f5bb1854f34d5aa1ba57d58a8081 ./include/litert/c/options/litert_intel_openvino_options.h
63
+ 83c39ba75163f78c08c9108bcca3f3edccc30d382868b81f7dc58d3e35d1c8f5 ./include/litert/c/options/litert_mediatek_options.h
64
+ 6da0edefa30e1dc1447b1ae60b4996085f71b1f9fb6a951c46ee39c72b7bb7e8 ./include/litert/c/options/litert_qualcomm_options.h
65
+ 69e5abf6fb7ff77810573a0aea6ee1c6bdffc1aa5434a41479597eba8f3d4535 ./include/litert/c/options/litert_runtime_options.h
66
+ 05526e6d4b8918d32ebaba5f4ce92e54d65cace15b8f2420802fd7b3b7c85392 ./include/litert/c/options/litert_samsung_options.h
67
+ 9c6bf33ffb14cfe00a2484e246c00749cbe2b65708fb5de085f03f41c92f2424 ./include/litert/c/options/litert_webnn_options.h
68
+ 9ad1a5072b09087bddeb3d7be22854350191b21239136b78ebee2120443c7305 ./libLiteRt.so
69
+ ab6a581ef26d83f60d03ff4ce2436d9a75b7d0c0b276357787a865e5e9dd4b7d ./libLiteRtDispatch_Qualcomm.so
sm8850-npu-fp16/vendor/litert/2.3.1/include/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
sm8850-npu-fp16/vendor/litert/2.3.1/include/litert/build_common/build_config.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 Google LLC.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ #ifndef LITERT_BUILD_COMMON_BUILD_CONFIG_H_
16
+ #define LITERT_BUILD_COMMON_BUILD_CONFIG_H_
17
+
18
+ #endif // LITERT_BUILD_COMMON_BUILD_CONFIG_H_