fhueni commited on
Commit
92a645b
·
0 Parent(s):

initial clean commit

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 +4 -0
  2. .github/workflows/sync-to-hf-hub.yml +24 -0
  3. .gitignore +53 -0
  4. CITATION.cff +16 -0
  5. LICENSE.txt +201 -0
  6. README.md +202 -0
  7. data/ag_news_test.csv +3 -0
  8. data/boolq_validation.csv +3 -0
  9. data/imdb_dataset.csv +3 -0
  10. data/lorem_ipsum_dataset.csv +3 -0
  11. data/spam_ham_dataset.csv +3 -0
  12. index.html +221 -0
  13. notebooks/.python-version +1 -0
  14. notebooks/00_preprocess_datasets.ipynb +3 -0
  15. notebooks/01_generate_lorem_ipsum_dataset.ipynb +3 -0
  16. notebooks/02_analyse_baseline_experiments.ipynb +3 -0
  17. notebooks/03_analyse_queueing_behaviour.ipynb +3 -0
  18. notebooks/04_design_routing_policies.ipynb +3 -0
  19. notebooks/05_analyse_HERO_performance.ipynb +3 -0
  20. notebooks/README.md +18 -0
  21. notebooks/plots/characters_distribution_per_dataset.pdf +3 -0
  22. notebooks/plots/characters_vs_inference_time_Granite_model.pdf +3 -0
  23. notebooks/plots/characters_vs_inference_time_Llama_model.pdf +3 -0
  24. notebooks/plots/policy_comparison_AG-News.pdf +3 -0
  25. notebooks/plots/policy_comparison_Spam_Ham.pdf +3 -0
  26. notebooks/plots/policy_comparison_agnews_big.pdf +3 -0
  27. notebooks/plots/policy_comparison_boolq.pdf +3 -0
  28. notebooks/plots/policy_comparison_boolq_big.pdf +3 -0
  29. notebooks/plots/policy_comparison_legend.pdf +3 -0
  30. notebooks/plots/policy_comparison_spam_big.pdf +3 -0
  31. notebooks/plots/threshold_comparison_20260626T173024.pdf +3 -0
  32. notebooks/plots/threshold_method_different_lambdas.pdf +3 -0
  33. notebooks/plots/time_prediction_error.pdf +3 -0
  34. notebooks/pyproject.toml +15 -0
  35. notebooks/utils.py +1395 -0
  36. notebooks/uv.lock +0 -0
  37. results/baseline_experiments/cloud/ag-news_raw_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-01-31T18-36-02.csv +0 -0
  38. results/baseline_experiments/cloud/ag-news_raw_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-02-01T12-19-04.csv +0 -0
  39. results/baseline_experiments/cloud/ag-news_stats_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-01-31T18-36-02.csv +4 -0
  40. results/baseline_experiments/cloud/ag-news_stats_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-02-01T12-19-04.csv +4 -0
  41. results/baseline_experiments/cloud/boolq_raw_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-02-04T09-33-25.csv +0 -0
  42. results/baseline_experiments/cloud/boolq_raw_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-01-31T19-51-47.csv +0 -0
  43. results/baseline_experiments/cloud/boolq_stats_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-02-04T09-33-25.csv +4 -0
  44. results/baseline_experiments/cloud/boolq_stats_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-01-31T19-51-47.csv +4 -0
  45. results/baseline_experiments/cloud/lorem-ipsum_raw_experiment_meta-llama-llama-3-2_always_cloud_once-per-sec.csv +0 -0
  46. results/baseline_experiments/cloud/lorem-ipsum_raw_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec.csv +0 -0
  47. results/baseline_experiments/cloud/spam_raw_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-01-31T17-54-44.csv +0 -0
  48. results/baseline_experiments/cloud/spam_raw_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-02-01T08-09-41.csv +0 -0
  49. results/baseline_experiments/cloud/spam_stats_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-01-31T17-54-44.csv +4 -0
  50. results/baseline_experiments/cloud/spam_stats_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-02-01T08-09-41.csv +4 -0
.gitattributes ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ data/*.csv filter=lfs diff=lfs merge=lfs -text
2
+ notebooks/*.ipynb filter=lfs diff=lfs merge=lfs -text
3
+ *.png filter=lfs diff=lfs merge=lfs -text
4
+ *.pdf filter=lfs diff=lfs merge=lfs -text
.github/workflows/sync-to-hf-hub.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ workflow_dispatch:
6
+
7
+ jobs:
8
+ sync-to-hub:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ with:
13
+ fetch-depth: 0
14
+ lfs: tru
15
+
16
+ - name: Install and Pull Git LFS objects
17
+ run: |
18
+ git lfs install
19
+ git lfs pull
20
+
21
+ - name: Push to hub
22
+ env:
23
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
24
+ run: git push https://fhueni:$HF_TOKEN@huggingface.co/spaces/fhueni/HERO main --force
.gitignore ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Project specific
2
+ analyse/plots/
3
+
4
+ # macOS system files
5
+ .DS_Store
6
+ .AppleDouble
7
+ .LSOverride
8
+ ._*
9
+
10
+ # Node.js
11
+ node_modules/
12
+ npm-debug.log
13
+ yarn-debug.log*
14
+ yarn-error.log*
15
+
16
+ # Python
17
+ __pycache__/
18
+ *.py[cod]
19
+ *$py.class
20
+ .env
21
+ .venv
22
+ env/
23
+ venv/
24
+ ENV/
25
+ *.egg-info/
26
+ dist/
27
+ build/
28
+
29
+ # IDE specific files
30
+ .idea/
31
+ .vscode/
32
+ *.swp
33
+ *.swo
34
+ *.swn
35
+ *.bak
36
+
37
+ # Logs and databases
38
+ *.log
39
+ *.sqlite
40
+ *.db
41
+
42
+ # Environment variables
43
+ .env
44
+ .env.local
45
+ .env.*.local
46
+
47
+ # Compiled files
48
+ *.com
49
+ *.class
50
+ *.dll
51
+ *.exe
52
+ *.o
53
+ *.so
CITATION.cff ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ message: "If you use this framework or results, please cite the associated paper as below."
3
+ authors:
4
+ - family-names: "Kehl"
5
+ given-names: "Philip"
6
+ - family-names: "Hüni"
7
+ given-names: "Fabian"
8
+ - family-names: "Lewandowski"
9
+ given-names: "Basile"
10
+ - family-names: "Chen"
11
+ given-names: "Lydia Y."
12
+ title: "Hero: Hybrid Edge Routing for In-Browser Small Language Models"
13
+ type: conference-paper
14
+ collection-title: "Proceedings of the 2026 IEEE International Conference on Autonomic Computing and Self-Organizing Systems Companion (ACSOS-C)"
15
+ year: 2026
16
+ notes: "To appear"
LICENSE.txt 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.
README.md ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: On Device Vs Cloud Llm Inference
3
+ emoji: 📉
4
+ colorFrom: indigo
5
+ colorTo: yellow
6
+ sdk: static
7
+ pinned: false
8
+ ---
9
+
10
+ # HERO: Hybrid Edge-Cloud Routing Orchestrator for Browser-Based LLM Inference
11
+
12
+ This repository contains the research artefact accompanying a conference paper on **HERO** — a hybrid request-routing
13
+ system that dynamically dispatches language model inference jobs to either an on-device (browser-local) model or a
14
+ cloud-hosted model, with the goal of minimising end-to-end latency under realistic load conditions.
15
+
16
+ ---
17
+
18
+ ## Overview
19
+
20
+ Recent advances in WebGPU and the [Transformers.js](https://github.com/xenova/transformers.js) library have made it
21
+ feasible to run small language models (SLMs) entirely in the browser. While on-device inference avoids network
22
+ round-trips, cloud inference can be faster when the local device is saturated. HERO bridges both worlds by continuously
23
+ estimating the expected latency on each backend and routing each incoming request to whichever backend is predicted to
24
+ respond sooner.
25
+
26
+ The project covers the full research pipeline:
27
+
28
+ 1. **Experiment Framework** — a browser application (`index.html` + `src/`) that generates synthetic request streams with
29
+ Poisson-distributed inter-arrival times, routes requests to on-device or cloud backends, measures latency, and
30
+ records structured results.
31
+ 2. **Dataset preparation & analysis** — Jupyter notebooks (`notebooks/`) that pre-process datasets, characterise
32
+ baseline performance, model queueing behaviour, and evaluate HERO's routing policies.
33
+ 3. **Results** — raw and aggregated CSV artefacts from experiments conducted on multiple real devices.
34
+
35
+ ### Routing Strategies
36
+
37
+ The `RequestManager` supports the following routing strategies:
38
+
39
+ | Strategy | Description |
40
+ |-----------------|----------------------------------------------------------------------------------------------------------------------------------------|
41
+ | `always_cloud` | All requests are sent to the cloud backend |
42
+ | `always_device` | All requests are processed on-device |
43
+ | `probabilistic` | Each request goes to the cloud with a configurable probability |
44
+ | `roundrobin` | Requests alternate between cloud and device |
45
+ | `hero` | Our **HERO** policy — predicts latency on both backends using a Bayesian linear model (Thompson Sampling) and routes to the faster one |
46
+
47
+ `hero` is the core of HERO: it maintains online linear performance models for both backends and uses Thompson Sampling
48
+ to balance exploration and exploitation as load conditions change.
49
+
50
+ ---
51
+
52
+ ## Repository Structure
53
+
54
+ ```
55
+ .
56
+ ├── index.html # Browser-based experiment runner (entry point)
57
+ ├── src/ # JavaScript source code
58
+ │ ├── main.js # Application logic: wires UI, scheduler, and request manager
59
+ │ ├── scheduler.js # JobScheduler: emits requests with configurable arrival patterns
60
+ │ ├── requestManager.js # RequestManager: routing logic, queue management, statistics
61
+ │ ├── evaluator.js # Evaluator: exact-match accuracy and throughput metrics
62
+ │ ├── datasetLoader.js # Loads datasets from CSV files in the browser
63
+ │ ├── utils.js # Shared utilities (timing helpers, sleep, etc.)
64
+ │ └── services/
65
+ │ ├── cloudService.js # Cloud inference via OpenRouter API
66
+ │ └── onDeviceService.js # On-device inference via Transformers.js + WebGPU
67
+ ├── data/ # Datasets used in experiments (CSV)
68
+ │ ├── boolq_validation.csv # BoolQ yes/no question answering
69
+ │ ├── ag_news_test.csv # AG News topic classification
70
+ │ ├── imdb_dataset.csv # IMDB sentiment classification
71
+ │ ├── spam_ham_dataset.csv # Spam/ham email classification
72
+ │ └── lorem_ipsum_dataset.csv # Synthetic Lorem Ipsum dataset (length-controlled prompts)
73
+ ├── notebooks/ # Python analysis environment
74
+ │ ├── 00_preprocess_datasets.ipynb # Dataset pre-processing and balancing
75
+ │ ├── 01_generate_lorem_ipsum_dataset.ipynb # Generate the synthetic Lorem Ipsum dataset
76
+ │ ├── 02_analyse_baseline_experiments.ipynb # Baseline on-device vs cloud latency analysis
77
+ │ ├── 03_analyse_queueing_behaviour.ipynb # Queueing dynamics under varying arrival rates
78
+ │ ├── 04_design_routing_policies.ipynb # Policy design and parameter calibration
79
+ │ ├── 05_analyse_HERO_performance.ipynb # End-to-end HERO performance evaluation
80
+ │ ├── utils.py # Shared Python utilities
81
+ │ ├── pyproject.toml # Python project metadata and dependencies
82
+ │ └── plots/ # Generated figures (output of notebooks)
83
+ └── results/ # Experiment result artefacts (CSV)
84
+ ├── baseline_experiments/ # Per-device baseline measurements (cloud, desktop, m2air, m4pro, zenbook, …)
85
+ ├── policy_experiments/ # Results from routing policy experiments
86
+ └── policy_simulations/ # Simulation results comparing policies across datasets
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Setup
92
+
93
+ ### Browser Experiment Runner
94
+
95
+ The experiment runner is a static web application. No build step is required. A short tutorial video is available on [YouTube](https://www.youtube.com/watch?v=zvwa7xPAYkc&t=64s)
96
+
97
+ **Prerequisites**
98
+
99
+ - A modern browser with **WebGPU** support (we recommend brave or chrome, which were used for our experiments).
100
+ - An [OpenRouter](https://openrouter.ai/) API key for cloud inference.
101
+ - Git, Python, UV and Git Large File Storage (Git LFS: `git lfs install`) installed
102
+
103
+ **Steps**
104
+
105
+ 1. Serve the repository root over HTTP (browsers block local file imports for ES modules):
106
+ ```bash
107
+ # Python ≥ 3
108
+ python -m http.server 8080
109
+ # or Node.js
110
+ npx serve .
111
+ ```
112
+ 2. Open `http://localhost:8080` in your browser.
113
+ 3. In the UI, enter your **OpenRouter API key** and select the desired cloud model.
114
+ 4. Optionally configure the on-device model name.
115
+ 5. Set the arrival rate (λ), dataset, routing strategy, and if desired, HERO linear-model parameters.
116
+ 6. Click **Load Model** to download and cache the on-device model (first run may take several minutes depending on model
117
+ size and network speed).
118
+ 7. Click **Start Experiment** to begin. Results are logged to the browser console and can be exported as CSV.
119
+
120
+ ### Python Analysis Notebooks
121
+
122
+ The notebooks use [`uv`](https://github.com/astral-sh/uv) for dependency management and require **Python 3.11**.
123
+
124
+ **Prerequisites**
125
+
126
+ - Python 3.11
127
+ - `uv` ([installation guide](https://github.com/astral-sh/uv#installation))
128
+
129
+ **Steps**
130
+
131
+ ```bash
132
+ # Navigate to the notebooks directory
133
+ cd notebooks
134
+
135
+ # Install dependencies (creates a virtual environment automatically)
136
+ uv sync
137
+
138
+ # Launch Jupyter (or use your preferred IDE with implemented jupyter support)
139
+ uv run jupyter notebook
140
+ ```
141
+
142
+ All notebooks are self-contained and read from the `../results/` and `../data/` directories relative to the `notebooks/`
143
+ folder. Run them in numerical order (`00_` → `05_`) when reproducing the full analysis from scratch.
144
+
145
+ ---
146
+
147
+ ## Datasets
148
+
149
+ | Dataset | Task | Source |
150
+ |---------------------|-------------------------------------|-----------------------------------------------------------------------------|
151
+ | BoolQ | Yes/no question answering | [Google / HuggingFace](https://huggingface.co/datasets/google/boolq) |
152
+ | AG News | 4-class news topic classification | [HuggingFace](https://huggingface.co/datasets/ag_news) |
153
+ | IMDB (not in paper) | Binary sentiment classification | [Kaggle / HuggingFace](https://huggingface.co/datasets/stanfordnlp/imdb) |
154
+ | Spam/Ham | Binary spam detection | [Kaggle](https://www.kaggle.com/datasets/uciml/sms-spam-collection-dataset) |
155
+ | Lorem Ipsum | Synthetic length-controlled prompts | Generated (see `notebooks/01_generate_lorem_ipsum_dataset.ipynb`) |
156
+
157
+ Raw datasets were pre-processed using `notebooks/00_preprocess_datasets.ipynb`, which adds a stable `id` column and
158
+ creates balanced sub-samples.
159
+
160
+ ---
161
+
162
+ ## Results Structure
163
+
164
+ Each experiment produces two CSV files per configuration:
165
+
166
+ - `*_raw_experiment_*.csv` — one row per request, including job ID, routing decision, queueing time, inference time,
167
+ total latency, model response, and exact-match accuracy.
168
+ - `*_stats_experiment_*.csv` — aggregated summary statistics for the experiment run.
169
+
170
+ File names encode the dataset, arrival rate (λ), on-device model, cloud model, routing strategy, arrival pattern, and
171
+ timestamp, e.g.:
172
+
173
+ ```
174
+ boolq_lambda10_raw_experiment_Llama-3-2-1B-Instruct-ONNX_meta-llama-llama-3-2-1b-instruct_jseq_exponential-arrival_2026-02-26T20-21-56.csv
175
+ ```
176
+
177
+ Baseline results are organised by device under `results/baseline_experiments/` (
178
+ subdirectories: `cloud`, `desktop`, `m2air`, `m4pro`, `zenbook`, etc.).
179
+
180
+ ---
181
+
182
+ ## Key Dependencies
183
+
184
+ | Component | Technology |
185
+ |---------------------|-----------------------------------------------------------------------|
186
+ | On-device inference | [Transformers.js](https://github.com/xenova/transformers.js) (WebGPU) |
187
+ | Cloud inference | [OpenRouter](https://openrouter.ai/) REST API |
188
+ | UI styling | [Tailwind CSS](https://tailwindcss.com/) (CDN) |
189
+ | Data analysis | Python 3.11, pandas, NumPy, SciPy, Matplotlib, Seaborn, Jupyter |
190
+ | Package management | [uv](https://github.com/astral-sh/uv) |
191
+
192
+ ---
193
+ ## Note
194
+
195
+ Please note that during development the HERP policy was preliminary called jseq. This is why in some files (csv and notebooks)
196
+ variables and columns can still be called jseq. We keep this to not break the analysis of existing results.
197
+ ---
198
+
199
+
200
+ ## Citation
201
+
202
+ > *Citation details to be added upon paper publication.*
data/ag_news_test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d44e499f92d9a6d252110272ca3a152c5e46f666511e6805f289f91a0588f306
3
+ size 247183
data/boolq_validation.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fdf1f8adfb140ef10794eb3a34ae716759c5c74b5cb6f51814fc8c595b85ffb
3
+ size 608096
data/imdb_dataset.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed375cb5a7acbb67b582f4aac6e5b222952af5ba0a0f0ebe8f9cdaeb68a1e046
3
+ size 1305921
data/lorem_ipsum_dataset.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7effa566fe1878d108bd5efd74a593e1ebd3daa9ad8bbcff81f9bc31379f6e7
3
+ size 7581309
data/spam_ham_dataset.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b65351c2bdde7eac6d1f5ed43d304396cae41a5d51350f492fbed646b740634
3
+ size 1381794
index.html ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
6
+ <title>Browser LLM Evaluation</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ </head>
9
+ <body class="bg-gray-100 text-gray-900 min-h-screen">
10
+ <main class="max-w-6xl mx-auto p-6">
11
+ <h1 class="text-3xl font-bold mb-6 text-center">Browser LLM Evaluation</h1>
12
+ <p class="mb-6 text-gray-700 text-center">
13
+ This project explores how in-browser LLM inference behaves compared to cloud-based inference in terms of
14
+ latency.
15
+ The goal is to model different request incoming patterns and routing strategies between cloud and on-device
16
+ models.
17
+ For the prompts and evaluation of the accuracy the <a href="https://huggingface.co/datasets/google/boolq" target="_blank">BooIQ</a> dataset is used.
18
+ The project is currently under development and does not aim to provide accurate LLM responses, but rather to
19
+ measure performance differences.
20
+ To run the cloud based inference, you need to bring your own OpenRouter API key.
21
+ </p>
22
+
23
+ <section class="grid grid-cols-1 md:grid-cols-3 gap-6">
24
+ <!-- Cloud Card -->
25
+ <div class="bg-white p-6 rounded-2xl shadow-xl border border-gray-200 flex flex-col">
26
+ <div>
27
+ <h2 class="text-xl font-semibold mb-4">Cloud (OpenRouter)</h2>
28
+ <label class="block mb-4 text-sm font-medium">Model
29
+ <select id="cloudModel"
30
+ class="w-full mb-4 px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none">
31
+ <option value="meta-llama/llama-3.2-1b-instruct">meta-llama/llama-3.2-1b-instruct</option>
32
+ <option value="ibm-granite/granite-4.0-h-micro">ibm-granite/granite-4.0-h-micro</option>
33
+ <option value="qwen/qwen3-4b:free">qwen/qwen3-4b</option>
34
+ <option value="openai/gpt-4o-mini">openai/gpt-4o-mini</option>
35
+ <option value="openai/gpt-5-mini">openai/gpt-5-mini</option>
36
+ <option value="openai/gpt-4.1-mini">openai/gpt-4.1-mini</option>
37
+ <option value="google/gemma-3n-e2b-it:free">google/gemma-3n-e2b-it:free</option>
38
+ <option value="meta-llama/llama-3.2-3b-instruct">meta-llama/llama-3.2-3b-instruct</option>
39
+ </select>
40
+ </label>
41
+
42
+ <label class="block mb-4 text-sm font-medium">API Key OpenRouter
43
+ <input id="cloudApiKey" type="text" placeholder="Key..."
44
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none"/>
45
+ </label>
46
+ </div>
47
+
48
+ <div class="mt-auto">
49
+ <h3 class="text-lg font-semibold mt-4 mb-2">Linear Model for HERO (cloud)</h3>
50
+ <div class="grid grid-cols-2 gap-4">
51
+ <div>
52
+ <label class="block text-sm font-medium">Slope (ms/char)
53
+ <input id="cloudSlope" type="number" step="0.001" value="0.0"
54
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none"/>
55
+ </label>
56
+ </div>
57
+ <div>
58
+ <label class="block text-sm font-medium">Intercept (ms)
59
+ <input id="cloudIntercept" type="number" step="1" value="0.0"
60
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none"/>
61
+ </label>
62
+ </div>
63
+ </div>
64
+ </div>
65
+ </div>
66
+
67
+ <!-- On-Device Card -->
68
+ <div class="bg-white p-6 rounded-2xl shadow-xl border border-gray-200 flex flex-col">
69
+ <div>
70
+ <h2 class="text-xl font-semibold mb-4">On-Device</h2>
71
+
72
+ <label class="block text-sm font-medium">Model (transformers.js)
73
+ <select id="deviceModel"
74
+ class="w-full mb-2 px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none">
75
+ <option value='{"modelName": "onnx-community/gemma-3-270m-it-ONNX", "quantization": "fp32"}'>gemma-3-270m-it-ONNX (fp32)</option>
76
+ <option value='{"modelName": "onnx-community/granite-4.0-350m-ONNX-web", "quantization": "fp32"}'>granite-4.0-350m-ONNX-web (fp32)</option>
77
+ <option value='{"modelName": "onnx-community/Llama-3.2-1B-Instruct-ONNX", "quantization": "fp32"}'>Llama-3.2-1B-Instruct-ONNX (fp32)</option>
78
+ <option value='{"modelName": "onnx-community/granite-4.0-micro-ONNX-web", "quantization": "q4f16"}'>granite-4.0-micro-ONNX-web (q4f16, 3B)</option>
79
+ <option value='{"modelName": "onnx-community/Qwen3-4B-ONNX", "quantization": "q4f16"}'>Qwen3-4B-ONNX (q4f16)</option>
80
+ <!-- <option disabled value='{"modelName": "onnx-community/Qwen3-0.6B-ONNX", "quantization": "fp32"}'>Qwen3-0.6B-ONNX</option>
81
+ <option disabled value='{"modelName": "onnx-community/gemma-3-1b-it-ONNX-GQA", "quantization": "q4f16"}'>gemma-3-1b-it-ONNX-GQA (q4f16)</option>
82
+ <option disabled value='{"modelName": "onnx-community/Llama-3.2-3B-Instruct-ONNX", "quantization": "fp32"}'>Llama-3.2-3B-Instruct-ONNX (not
83
+ working)
84
+ </option>
85
+ <option disabled value='{"modelName": "onnx-community/gemma-3-1b-it-ONNX", "quantization": "fp32"}'>gemma-3-1b-it-ONNX (fp32)</option>-->
86
+ </select>
87
+ </label>
88
+
89
+ <button id="loadDeviceModelBtn"
90
+ class="mt-4 w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 transition">Load Model
91
+ </button>
92
+
93
+ <div id="deviceStatus" class="text-gray-700 text-sm my-4">Not loaded</div>
94
+
95
+ <div id="deviceLoadingContainer" class="w-full max-w-xs my-2">
96
+ <div id="deviceLoadingBar" class="h-2 bg-green-500 transition-all duration-200 w-0"></div>
97
+ <span id="deviceLoadingText" class="text-xs text-gray-600"></span>
98
+ </div>
99
+ </div>
100
+
101
+ <div class="mt-auto">
102
+ <h3 class="text-lg font-semibold mt-4 mb-2">Linear Model for HERO (on-device)</h3>
103
+ <div class="grid grid-cols-2 gap-4">
104
+ <div>
105
+ <label class="block text-sm font-medium">Slope (ms/char)
106
+ <input id="deviceSlope" type="number" step="0.001" value="0.0"
107
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none"/>
108
+ </label>
109
+ </div>
110
+ <div>
111
+ <label class="block text-sm font-medium">Intercept (ms)
112
+ <input id="deviceIntercept" type="number" step="1" value="0.0"
113
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none"/>
114
+ </label>
115
+ </div>
116
+ </div>
117
+ </div>
118
+
119
+ </div>
120
+
121
+ <!-- Request Pattern Card -->
122
+ <div class="bg-white p-6 rounded-2xl shadow-xl border border-gray-200">
123
+ <h2 class="text-xl font-semibold mb-4">Request Pattern & Routing</h2>
124
+
125
+ <label class="block mb-4 text-sm font-medium">Dataset
126
+ <select id="dataset"
127
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none">
128
+ <option value="boolq_validation">BoolQ</option>
129
+ <option value="spam_ham_dataset">Spam</option>
130
+ <option value="imdb_dataset">IMDB</option>
131
+ <option value="ag_news_test">AG News</option>
132
+ <option value="lorem_ipsum_dataset">Lorem ipsum</option>
133
+ </select>
134
+ </label>
135
+
136
+ <label class="block mb-4 text-sm font-medium">Load Pattern
137
+ <select id="patternSelect"
138
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none">
139
+ <option value="once-per-sec">1 request / sec</option>
140
+ <option value="every-ten-sec">Every 10 sec 1 request</option>
141
+ <option value="exponential-arrival">Exponential arrival time</option>
142
+ </select>
143
+ </label>
144
+
145
+ <label class="block mb-4 text-sm font-medium">Route strategy
146
+ <select id="routeStrategy"
147
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none">
148
+ <option value="always_device">Always device</option>
149
+ <option value="always_cloud">Always cloud</option>
150
+ <option value="roundrobin">Round Robin</option>
151
+ <option value="probabilistic">Probabilistic (p to cloud)</option>
152
+ <option value="hero">HERO (Stateful)</option>
153
+ </select>
154
+ </label>
155
+
156
+ <label class="block mb-4 text-sm font-medium">Cloud probability (for probabilistic)
157
+ <input id="cloudProb" type="number" min="0" max="1" step="0.1" value="0.5"
158
+ class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none"/>
159
+ </label>
160
+
161
+ <label class="block mb-4 text-sm font-medium">Interarrival Time Lambda (for exponential arrival)
162
+ <input id="interArrivalTimeLambda" type="number" min="0" step="0.1" value="2" class="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none"/>
163
+ </label>
164
+
165
+ <div class="flex gap-3 mt-4">
166
+ <button id="startBtn" class="flex-1 bg-green-600 text-white py-2 rounded-lg hover:bg-green-700 transition">
167
+ Start
168
+ </button>
169
+ <button id="stopBtn" disabled class="flex-1 bg-gray-400 text-white py-2 rounded-lg">Stop</button>
170
+ <button id="start1000Btn" class="flex-1 bg-purple-600 text-white py-2 rounded-lg hover:bg-purple-700 transition">
171
+ Start 500
172
+ </button>
173
+ </div>
174
+ </div>
175
+
176
+ <!-- Log Card -->
177
+ <div class="bg-white p-6 rounded-2xl shadow-xl border border-gray-200 md:col-span-3">
178
+ <h2 class="text-xl font-semibold mb-4">Live Log & Results</h2>
179
+ <div class="block w-full h-64 overflow-scroll">
180
+ <table id="log"
181
+ class="w-full h-64 overflow-scroll bg-gray-50 p-3 rounded-lg border border-gray-200 text-sm">
182
+ <thead>
183
+ <tr>
184
+ <th class="text-left">ID</th>
185
+ <th class="text-left">Time</th>
186
+ <th class="text-left">Route</th>
187
+ <th class="text-left">Total Latency (ms)</th>
188
+ <th class="text-left">Queue (ms)</th>
189
+ <th class="text-left">Inference (ms)</th>
190
+ <th class="text-left">Question</th>
191
+ <th class="text-left">Answer</th>
192
+ <th class="text-left">Correct</th>
193
+ </tr>
194
+ </thead>
195
+ <tbody id="log-table-body"></tbody>
196
+ </table>
197
+ </div>
198
+
199
+ <div id="stats" class="mt-4 text-sm text-gray-800"></div>
200
+ <div class="flex flex-col md:flex-row gap-4 mt-4">
201
+ <button id="downloadStatsCsv"
202
+ class="mt-4 w-full bg-purple-600 text-white py-2 rounded-lg hover:bg-purple-700 transition">
203
+ Download Runs as CSV
204
+ </button>
205
+ </div>
206
+
207
+ </div>
208
+ </section>
209
+
210
+ <footer class="mt-12 text-center text-gray-600 text-sm">
211
+ <p>Developed by
212
+ <a href="https://www.linkedin.com/in/fabian-h%C3%BCni/" target="_blank" class="text-blue-500 hover:underline">Fabian Hüni</a>,
213
+ <a href="https://www.linkedin.com/in/philip-kehl/" target="_blank" class="text-blue-500 hover:underline">Philip Kehl</a> and
214
+ <a href="https://www.linkedin.com/in/nicolas-wyss-6b172428b/" target="_blank" class="text-blue-500 hover:underline">Nicolas Wyss</a>.
215
+ </p>
216
+ </footer>
217
+ </main>
218
+
219
+ <script type="module" src="./src/main.js"></script>
220
+ </body>
221
+ </html>
notebooks/.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.11
notebooks/00_preprocess_datasets.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed0a600f3bab9cdcc8194c749ec053f7767565f540e58b10a30ae9fdb2ea924d
3
+ size 16131
notebooks/01_generate_lorem_ipsum_dataset.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b0ae44b0ba77861e4e570160c53ec961bd09dbea85547c855cb4c5041106ff4
3
+ size 689040
notebooks/02_analyse_baseline_experiments.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0127b5883618004c287a9bb396f6e979659a65536f78d617c9ee59ab0d6806e
3
+ size 1018122
notebooks/03_analyse_queueing_behaviour.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9dab3e4078fda67b4023a379949e4876e0d1d15cfde724ae07442fc5d2242ab0
3
+ size 136262
notebooks/04_design_routing_policies.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6cd90d95164ce072ca32f8ebb2ad9dd298471a631388e23e08742f9b661fa75
3
+ size 680175
notebooks/05_analyse_HERO_performance.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56f3430aa2f16a5d2875942157b9a643b8c3071404abe1e5a5b1139f3804470c
3
+ size 198613
notebooks/README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HERO Notebooks
2
+ These notebooks support dataset preparation and the analysis of HERO experiment results.
3
+
4
+ ## Setup
5
+ This project uses `uv` as the package manager. Ensure `uv` is installed, then navigate to this folder and run:
6
+
7
+ ```bash
8
+ uv sync
9
+ ```
10
+
11
+ ## Notebooks
12
+ The following notebooks are available in this folder:
13
+ - **`00_preprocess_datasets.ipynb`**: Preprocess the raw public available dataset to match our experiments (add id column and create balanced subdataset)
14
+ - **`01_generate_lorem_ipsum_dataset.ipynb`**: Generate our introduced lorem ipsum dataset
15
+ - **`02_analyse_baseline_experiments.ipynb`**: Analyse the baseline experiments to understand the performance of on device and cloud inference
16
+ - **`03_analyse_queueing_behaviour.ipynb`**: Analyse the queueing behaviour of the conduced experiments
17
+ - **`04_design_routing_policies.ipynb`**: Design proposed routing policies
18
+ - **`05_analyse_HERO_performance.ipynb`**: Analyse the performance of HERO
notebooks/plots/characters_distribution_per_dataset.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d61eca9fac51c872092d65595fdff004542b67b6e0bc83c26fff965ada97af4
3
+ size 21046
notebooks/plots/characters_vs_inference_time_Granite_model.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b68b1dcfd6b461bcd3908241108c232641ab052691c7b333ad2d549fecbab478
3
+ size 467193
notebooks/plots/characters_vs_inference_time_Llama_model.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:737b1b455acec959d8bf3a7dd0ec07a59c2eb9e77f7f3f6533bc06db5837aff7
3
+ size 477166
notebooks/plots/policy_comparison_AG-News.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0658a2b4478f9b7614f26db7255737db7fdae7958761c15b2994ca4b7cd06ee6
3
+ size 23364
notebooks/plots/policy_comparison_Spam_Ham.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b29ce70da8b79f460b07e3bb6e8ec6c8489e1c132064eec03168cdec181b9d9e
3
+ size 19419
notebooks/plots/policy_comparison_agnews_big.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e81da6239714485e3dc060653eab05ea6670833453167aa0dccfd12db95dc9b
3
+ size 32935
notebooks/plots/policy_comparison_boolq.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f67391bedc26f6e5d707b11d2c8686a6154d1e0ce74b4aa221a9a503b88d3e3
3
+ size 21279
notebooks/plots/policy_comparison_boolq_big.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14510c143e620e59d2d7f93bd7cc27bc03e910492e543ed2128eb2218a846669
3
+ size 33818
notebooks/plots/policy_comparison_legend.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75fc7573d431efee3ddb2ddf485721da128cb97b35606cf79ec598bb7ff6f264
3
+ size 16945
notebooks/plots/policy_comparison_spam_big.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c5b8c9312cdabb908eb85ef88c15e3de5f4ecf6e36bee688f8d828c063cae724
3
+ size 31726
notebooks/plots/threshold_comparison_20260626T173024.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0721c55e3a77767b4206471e77b258516e2c5e5050a4a1c07f3c6f5f98fb1cad
3
+ size 32823
notebooks/plots/threshold_method_different_lambdas.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eea15b05f92b799ccce73e28f06373a8e0f1c8e341a00fb003c572f4a1c69ba2
3
+ size 44799
notebooks/plots/time_prediction_error.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:125e293c708ab67a8284cfc65b71a57ed4e3be45103aae6a462a46ef0bd578f6
3
+ size 24298
notebooks/pyproject.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "hero-notebooks"
3
+ version = "1.0.0"
4
+ description = "A collection of Jupyter notebooks for data analysis and visualization of the HERO experiments."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "jupyter>=1.1.1",
9
+ "lorem-text>=3.0",
10
+ "matplotlib>=3.11.0",
11
+ "numpy>=2.4.6",
12
+ "pandas>=3.0.3",
13
+ "scipy>=1.17.1",
14
+ "seaborn>=0.13.2",
15
+ ]
notebooks/utils.py ADDED
@@ -0,0 +1,1395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import random
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List, Optional, Tuple, Union
7
+
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+ import pandas as pd
11
+ import seaborn as sns
12
+ from IPython.display import display
13
+ from scipy import stats
14
+
15
+
16
+ def parse_experiment_string(s: str) -> Dict[str, str]:
17
+ """
18
+ Parse an experiment identifier string (name of the files) into a named dictionary.
19
+
20
+ The expected format of the string is:
21
+ "device/dataset_raw_experiment_model_executionmode_frequency_timestamp"
22
+
23
+ Notes:
24
+ - Some of the results do not have a timestamp at the end, so we will ignore that part for now.
25
+ - The execution mode is a combination of two parts in the filename. Since the files
26
+ are unfortunately named with `_` in the execution mode, we will combine those
27
+ two parts to get the execution mode (e.g. always_device or always_cloud).
28
+ """
29
+ # Normalize path separator
30
+ s = s.replace("\\", "/")
31
+
32
+ # Split path and filename
33
+ device, rest = s.split("/", 1)
34
+ parts = rest.split("_")
35
+
36
+ if len(parts) < 7:
37
+ raise ValueError("Unexpected experiment string format")
38
+
39
+ dataset = parts[0]
40
+ model = parts[3]
41
+ # Workaround due to inconsistent file naming: always_device to always-device
42
+ # or always-cloud to always-cloud
43
+ execution_mode = parts[4] + "-" + parts[5]
44
+ frequency = parts[6]
45
+
46
+ return {
47
+ "device": device,
48
+ "dataset": dataset,
49
+ "model": model,
50
+ "execution_mode": execution_mode,
51
+ "frequency": frequency,
52
+ }
53
+
54
+
55
+ def plot_characters_vs_inference_time(
56
+ experiment_data: List[List[pd.DataFrame]],
57
+ labels: List[List[str]],
58
+ subplot_names: List[str],
59
+ model: str
60
+ ) -> None:
61
+ """
62
+ Plots scatter plots of number of input characters vs inference time with shared axes.
63
+ """
64
+ # Okabe-Ito Palette Colors
65
+ COLOR_MAP = {
66
+ 'spam': '#56B4E9', # Sky Blue
67
+ 'ag-news': '#009E73', # Bluish Green
68
+ 'boolq': '#D55E00', # Vermillion
69
+ 'lorem-ipsum': '#E69F00' # Orange
70
+ }
71
+ DEFAULT_COLOR = 'black'
72
+ MARKER_MAP = {'spam': 'o', 'ag-news': '^', 'boolq': 's', 'lorem-ipsum': 'D'}
73
+
74
+ # Custom size mapping to compensate for marker geometry and visual weight
75
+ SIZE_MAP = {'spam': 35, 'ag-news': 60, 'boolq': 30, 'lorem-ipsum': 25}
76
+ DEFAULT_SIZE = 20
77
+
78
+ sns.set(style="whitegrid")
79
+
80
+ rows = len(experiment_data) // 2 + len(experiment_data) % 2
81
+
82
+ # Enable shared axes: share x across columns, share y across rows
83
+ fig, axes = plt.subplots(nrows=rows, ncols=2, figsize=(14, rows * 4.5), sharex='col', sharey='row')
84
+ axes_flat = axes.flatten()
85
+
86
+ # Loop through each model/device combination
87
+ for idx, (ax, model_experiments, model_labels, model_name) in enumerate(zip(axes_flat, experiment_data, labels, subplot_names)):
88
+
89
+ # Determine subplot positioning in the grid
90
+ is_left_col = (idx % 2 == 0)
91
+ is_bottom_row = (idx >= (rows - 1) * 2)
92
+
93
+ # Sort model_experiments and model_labels so smaller datasets are plotted last (on top)
94
+ sorted_zip = sorted(zip(model_experiments, model_labels), key=lambda x: len(x[0]), reverse=True)
95
+ # Loop through each DataFrame and plot
96
+ for df, label in sorted_zip:
97
+ if 'number_of_characters' in df.columns and 'inference_time_ms' in df.columns:
98
+ # Use the size mapping dictionary to determine marker-specific size
99
+ base_size = SIZE_MAP.get(label.lower(), DEFAULT_SIZE)
100
+ size = np.ones(len(df)) * base_size
101
+ color = COLOR_MAP.get(label.lower(), DEFAULT_COLOR)
102
+ ax.scatter(df['number_of_characters'], df['inference_time_ms'],
103
+ marker=MARKER_MAP.get(label.lower(), 'o'),
104
+ color=color, alpha=0.6, label=label, s=size,
105
+ edgecolors='white', linewidths=0.2)
106
+
107
+ ax.set_title(model_name, fontsize=25)
108
+
109
+ # Only add X label to the bottom row subplots
110
+ if is_bottom_row:
111
+ ax.set_xlabel('Input Characters', fontsize=22)
112
+ else:
113
+ ax.set_xlabel('')
114
+
115
+ # Only add Y label and keep ticks on the left column subplots
116
+ if is_left_col:
117
+ ax.set_ylabel('Inference Time (ms)', fontsize=22)
118
+ else:
119
+ ax.set_ylabel('')
120
+ # Explicitly turn off tick labels for the right column
121
+ ax.yaxis.set_tick_params(labelleft=False)
122
+
123
+ # Set scale types and tick sizes inside the loop
124
+ ax.set_yscale('log')
125
+ ax.set_xscale('log')
126
+ ax.tick_params(axis='both', which='major', labelsize=22)
127
+ ax.grid(True, which="both", ls="-", alpha=0.5)
128
+
129
+ if idx == 0:
130
+ leg = ax.legend(fontsize=22, loc='lower right')
131
+ for lh in leg.legend_handles:
132
+ lh.set_alpha(1.0)
133
+ lh.set_sizes([150])
134
+
135
+ # Remove last unused subplot if applicable BEFORE setting global limits
136
+ if len(experiment_data) % 2 != 0:
137
+ fig.delaxes(axes_flat[-1])
138
+
139
+ # ---> CRITICAL FIX: Apply uniform limits globally to all remaining axes <---
140
+ for ax in fig.axes:
141
+ ax.set_xlim(300, 30000)
142
+ ax.set_ylim(80, 20000)
143
+
144
+ plt.tight_layout()
145
+ plt.savefig(f'./plots/characters_vs_inference_time_{model}_model.pdf', dpi=300, bbox_inches='tight')
146
+ plt.show()
147
+
148
+
149
+ def plot_input_character_distribution(
150
+ datasets: List[pd.DataFrame],
151
+ dataset_names: List[str]
152
+ ) -> None:
153
+ """
154
+ Plots the distribution of the number of input characters for each dataset in a single figure with 3 subplots.
155
+
156
+ Args:
157
+ datasets: List of DataFrames, each containing a 'number_of_characters' column for a specific dataset.
158
+ dataset_names: The name of the datasets corresponding to each DataFrame, used for labeling the plots.
159
+ """
160
+ import matplotlib.ticker as ticker
161
+ fig, axes = plt.subplots(1, 3, figsize=(14, 4.5), sharey=True)
162
+
163
+ COLOR_MAP = {
164
+ 'Spam/Ham': '#56B4E9', # Sky Blue
165
+ 'AG News': '#009E73', # Bluish Green
166
+ 'BoolQ': '#D55E00', # Vermillion
167
+ 'lorem-ipsum': '#E69F00' # Orange
168
+ }
169
+
170
+ for i, (dataset, name) in enumerate(zip(datasets, dataset_names)):
171
+ ax = axes[i]
172
+ color = COLOR_MAP.get(name, 'gray')
173
+
174
+ sns.histplot(
175
+ data=dataset.dropna(),
176
+ color=color,
177
+ alpha=0.9,
178
+ kde=True,
179
+ ax=ax
180
+ )
181
+
182
+ ax.set_title(f"{name}", fontsize=25, pad=12)
183
+ ax.set_xlabel('Number of Characters', fontsize=22, labelpad=10)
184
+
185
+ # Only put the Y label on the first column plot
186
+ if i == 0:
187
+ ax.set_ylabel('Frequency', fontsize=22)
188
+ else:
189
+ ax.set_ylabel('')
190
+
191
+ # Fix the cluttered x-ticks by forcing a maximum of 4 clean intervals
192
+ ax.xaxis.set_major_locator(ticker.MaxNLocator(nbins=4))
193
+
194
+ ax.tick_params(axis='both', which='major', labelsize=20)
195
+
196
+ # Enable clean horizontal grid lines; keep vertical lines soft
197
+ ax.grid(True, axis='y', ls='-', alpha=0.5)
198
+ ax.grid(False, axis='x')
199
+
200
+ # Add explicit horizontal padding between subplots to stop numbers from bumping into each other
201
+ plt.tight_layout(pad=2.0, w_pad=0.3)
202
+ plt.savefig(f'./plots/characters_distribution_per_dataset.pdf', format='pdf', dpi=300)
203
+ plt.show()
204
+
205
+
206
+ def extract_basic_metrics(df: pd.DataFrame, name: str = "Server") -> Dict[str, float]:
207
+ """
208
+ Extracts basic queuing metrics from a raw experiment dataframe.
209
+ Uses columns: 'job_start_ts', 'inference_end_ts', 'inference_time_ms', 'total_latency_ms'
210
+ """
211
+ # Work on a copy to avoid modifying the original dataframe
212
+ df = df.copy()
213
+ df = df.sort_values('job_start_ts')
214
+
215
+ # Arrival Rate (Lambda)
216
+ # Total time window of the experiment (observed from first arrival to last completion)
217
+ start_time = df['job_start_ts'].min()
218
+ end_time = df['inference_end_ts'].max()
219
+ experiment_duration_sec = (end_time - start_time) / 1000.0
220
+
221
+ num_requests = len(df)
222
+ arrival_rate = num_requests / experiment_duration_sec if experiment_duration_sec > 0 else 0
223
+
224
+ # Mean Service Demand (S_bar)
225
+ # inference_time_ms is the pure processing time (service time, no queueing)
226
+ service_times_sec = df['inference_time_ms'] / 1000.0
227
+ mean_service_demand = service_times_sec.mean()
228
+
229
+ # Empirical Response Time (R)
230
+ # total_latency_ms = inference_end_ts - job_start_ts (includes queueing + service)
231
+ response_times_sec = df['total_latency_ms'] / 1000.0
232
+
233
+ mean_response_time = response_times_sec.mean()
234
+ p50_response = response_times_sec.median()
235
+ p95_response = response_times_sec.quantile(0.95)
236
+ p99_response = response_times_sec.quantile(0.99)
237
+
238
+ # Utilization (rho)
239
+ # Utilization Law: rho = lambda * S
240
+ utilization = arrival_rate * mean_service_demand
241
+
242
+ print(f"--- Metrics for {name} ---")
243
+ print(f" Count: {num_requests}")
244
+ print(f" Duration: {experiment_duration_sec:.2f} s")
245
+ print(f" Arrival Rate (λ): {arrival_rate:.4f} req/s")
246
+ print(f" Mean Service Demand (S): {mean_service_demand:.4f} s")
247
+ print(f" Mean Response Time (R): {mean_response_time:.4f} s")
248
+ print(f" Response Time P95: {p95_response:.4f} s")
249
+ print(f" Utilization (ρ = λ*S): {utilization:.2%}")
250
+ print("-" * 30)
251
+
252
+ return {
253
+ 'lambda': float(arrival_rate),
254
+ 'mean_service_time': float(mean_service_demand),
255
+ 'mean_response_time': float(mean_response_time),
256
+ 'p95_response_time': float(p95_response),
257
+ 'utilization': float(utilization)
258
+ }
259
+
260
+
261
+ def estimate_linear_relationship(
262
+ df: pd.DataFrame,
263
+ label: str = "Model",
264
+ plot: bool = True
265
+ ) -> Tuple[float, float, float]:
266
+ """
267
+ Estimates the linear relationship between input characters and inference time.
268
+ Returns (slope, intercept, std_dev_of_residuals).
269
+ """
270
+ x = df['number_of_characters']
271
+ y = df['inference_time_ms'] / 1000.0
272
+
273
+ slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
274
+
275
+ predicted_y = slope * x + intercept
276
+ residuals = y - predicted_y
277
+ std_dev_residuals = np.std(residuals)
278
+
279
+ print(f"--- {label} ---")
280
+ print(f"Slope: {slope:.6f} s/char")
281
+ print(f"Intercept: {intercept:.6f} s")
282
+ print(f"R-squared: {r_value**2:.4f}")
283
+ print(f"Std Dev of Residuals (Noise): {std_dev_residuals:.6f} s")
284
+
285
+ if plot:
286
+ plt.figure(figsize=(8, 5))
287
+ plt.scatter(x, y, alpha=0.3, label='Data Points')
288
+ plt.plot(x, slope * x + intercept, color='red', label=f'Fit: y={slope:.5f}x + {intercept:.3f}')
289
+ plt.xlabel('Input Characters')
290
+ plt.ylabel('Inference Time (s)')
291
+ plt.title(f'Linear Fit: {label}')
292
+ plt.legend()
293
+ plt.grid(True, alpha=0.3)
294
+ plt.show()
295
+
296
+ return slope, intercept, std_dev_residuals
297
+
298
+
299
+ def plot_system_performance(systems_to_analyze: List[Tuple[str, pd.DataFrame]]) -> List[float]:
300
+ """
301
+ Plots a Kingman's Approximation analysis for given systems and calculates the mu values.
302
+ """
303
+ fig, axes = plt.subplots(1, len(systems_to_analyze), figsize=(18, 7), sharey=True)
304
+ if len(systems_to_analyze) == 1:
305
+ axes = [axes]
306
+
307
+ fig.suptitle('G/G/1 Performance Analysis', fontsize=16)
308
+
309
+ all_finite_latencies = []
310
+ mus = []
311
+
312
+ for i, (system_name, df_single_system) in enumerate(systems_to_analyze):
313
+ ax = axes[i]
314
+
315
+ service_times_s = df_single_system['inference_time_ms'] / 1000.0
316
+ mean_service_time = service_times_s.mean()
317
+ std_dev_service_time = service_times_s.std()
318
+ mu = 1.0 / mean_service_time
319
+ mus.append(mu)
320
+ cs = std_dev_service_time / mean_service_time
321
+
322
+ print(f"--- Analyzing: {system_name} ---")
323
+ print(f"Mean Service Time (E[S]): {mean_service_time:.4f} s")
324
+ print(f"Service Rate (μ): {mu:.2f} req/s")
325
+ print(f"Service Time CoV (cs): {cs:.2f}\n")
326
+
327
+ lambda_range = np.linspace(0.01, mu * 0.999, 1000)
328
+
329
+ scenarios = {
330
+ "Deterministic Arrivals (ca=0)": 0.0,
331
+ "Poisson Arrivals (ca=1)": 1.0
332
+ }
333
+ results = {}
334
+
335
+ for scenario_name, ca in scenarios.items():
336
+ response_times = []
337
+ for lam in lambda_range:
338
+ rho = lam * mean_service_time
339
+ if rho >= 1:
340
+ mean_response_time = float('inf')
341
+ else:
342
+ mean_wait_time = (rho / (1 - rho)) * ((ca**2 + cs**2) / 2) * mean_service_time
343
+ mean_response_time = mean_wait_time + mean_service_time
344
+ response_times.append(mean_response_time)
345
+ results[scenario_name] = response_times
346
+ all_finite_latencies.extend([r for r in response_times if r < float('inf')])
347
+
348
+ for scenario_name, latencies in results.items():
349
+ ax.plot(lambda_range, latencies, label=scenario_name, linewidth=2)
350
+
351
+ ax.axvline(x=mu, color='r', linestyle='--', label=f'Saturation Point (μ = {mu:.2f} req/s)')
352
+ ax.set_xlabel('Arrival Rate λ (requests/second)')
353
+ ax.set_title(f'Performance of {system_name}')
354
+ ax.legend()
355
+ ax.grid(True, alpha=0.3)
356
+
357
+ axes[0].set_ylabel('Mean Response Time (s)')
358
+
359
+ if all_finite_latencies:
360
+ upper_limit = np.percentile(all_finite_latencies, 99) * 1.2
361
+ plt.ylim(bottom=0, top=upper_limit)
362
+
363
+ plt.tight_layout(rect=[0, 0.03, 1, 0.95])
364
+ plt.show()
365
+ return mus
366
+
367
+
368
+ def simulate_routing_synthetic(
369
+ thresholds: Union[List[int], range],
370
+ lambda_total: float,
371
+ num_jobs: int = 10000,
372
+ ca: float = 1.0,
373
+ char_params: Tuple[float, float] = (500.0, 200.0),
374
+ dev_model: Tuple[float, float, float] = (0.001, 0.1, 0.0),
375
+ cloud_model: Tuple[float, float, float] = (0.0005, 0.05, 0.0),
376
+ add_noise: bool = False
377
+ ) -> pd.DataFrame:
378
+ """
379
+ Synthetic simulation that generates data on-the-fly using a linear model.
380
+ Service Time = Slope * Chars + Intercept + Noise
381
+ """
382
+ mean_inter_arrival = 1.0 / lambda_total if lambda_total > 0 else 1.0
383
+ results = []
384
+
385
+ char_mu, char_sigma = char_params
386
+ slope_d, int_d, std_res_d = dev_model
387
+ slope_c, int_c, std_res_c = cloud_model
388
+
389
+ for T in thresholds:
390
+ t_now = 0.0
391
+ server_free_dev = 0.0
392
+ server_free_cloud = 0.0
393
+ total_response_time = 0.0
394
+
395
+ random.seed(42)
396
+
397
+ for _ in range(num_jobs):
398
+ # Generate Arrival
399
+ if ca == 0.0:
400
+ inter_arrival = mean_inter_arrival
401
+ elif ca == 1.0:
402
+ inter_arrival = random.expovariate(lambda_total)
403
+ else:
404
+ alpha = 1.0 / (ca**2)
405
+ beta = mean_inter_arrival / alpha
406
+ inter_arrival = random.gammavariate(alpha, beta)
407
+
408
+ t_now += inter_arrival
409
+
410
+ # Generate Synthetic Job (Correlated)
411
+ chars = max(10, random.gauss(char_mu, char_sigma))
412
+
413
+ # Calculate Service Times based on Linear Model + Random Noise
414
+ noise = 0.0
415
+ if add_noise:
416
+ # Noise represents variability not explained by length
417
+ noise = random.gauss(0, 0.05) # 50ms noise
418
+ s_dev = max(0.01, (slope_d * chars + int_d) + noise)
419
+ s_cloud = max(0.01, (slope_c * chars + int_c) + noise)
420
+
421
+ # Routing & Queueing
422
+ if chars <= T:
423
+ start_service = max(t_now, server_free_dev)
424
+ completion = start_service + s_dev
425
+ server_free_dev = completion
426
+ response = completion - t_now
427
+ else:
428
+ start_service = max(t_now, server_free_cloud)
429
+ completion = start_service + s_cloud
430
+ server_free_cloud = completion
431
+ response = completion - t_now
432
+
433
+ total_response_time += response
434
+
435
+ avg_latency = total_response_time / num_jobs
436
+ results.append({'threshold': T, 'sim_latency': avg_latency})
437
+
438
+ return pd.DataFrame(results)
439
+
440
+
441
+ def plot_threshold_comparisons(
442
+ test_lambdas: List[float],
443
+ thresholds: Union[List[int], range],
444
+ char_params: Tuple[float, float],
445
+ dev_model: Tuple[float, float, float],
446
+ cloud_model: Tuple[float, float, float]
447
+ ) -> None:
448
+ """
449
+ Plots the impact of the threshold choice across different lambdas and arrival patterns.
450
+ """
451
+ scenarios = {
452
+ r"Deterministic Arrivals ($c_{a}=0.0$)": 0.0,
453
+ r"Poisson Arrivals ($c_{a}=1.0$)": 1.0
454
+ }
455
+
456
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
457
+ colors = plt.cm.viridis(np.linspace(0, 1, len(test_lambdas)))
458
+ all_finite_latencies = []
459
+
460
+ for i, (title, ca_val) in enumerate(scenarios.items()):
461
+ ax = axes[i]
462
+ print(f"--- Running simulations for {title} ---")
463
+
464
+ for j, lam in enumerate(test_lambdas):
465
+ print(f" -> Simulating λ = {lam:.1f} req/s")
466
+
467
+ sim_res = simulate_routing_synthetic(
468
+ thresholds=thresholds,
469
+ lambda_total=lam,
470
+ num_jobs=50000,
471
+ ca=ca_val,
472
+ char_params=char_params,
473
+ dev_model=dev_model,
474
+ cloud_model=cloud_model
475
+ )
476
+
477
+ ax.plot(sim_res['threshold'], sim_res['sim_latency'],
478
+ label=f'λ = {lam:.1f}', color=colors[j], linewidth=2)
479
+
480
+ finite_vals = sim_res[sim_res['sim_latency'] != float('inf')]['sim_latency']
481
+ all_finite_latencies.extend(finite_vals.dropna().tolist())
482
+
483
+ ax.set_xlabel('Threshold (Characters)')
484
+ ax.set_title(title)
485
+ ax.grid(True, which="both", linestyle='--', linewidth=0.5)
486
+ ax.set_yscale('log')
487
+
488
+ axes[0].set_ylabel('Mean Response Time (s) [Log Scale]')
489
+ axes[0].legend(title="Arrival Rate (req/s)")
490
+
491
+ if all_finite_latencies:
492
+ positive_latencies = [l for l in all_finite_latencies if l > 0]
493
+ if positive_latencies:
494
+ upper_lim = np.percentile(positive_latencies, 99) * 1.5
495
+ lower_lim = min(positive_latencies) * 0.9
496
+ plt.ylim(lower_lim, upper_lim)
497
+
498
+ plt.tight_layout(rect=[0, 0.03, 1, 0.95])
499
+
500
+ out_dir = Path('./plots')
501
+ out_dir.mkdir(parents=True, exist_ok=True)
502
+ timestamp = datetime.now().strftime('%Y%m%dT%H%M%S')
503
+ filename = out_dir / f'threshold_comparison_{timestamp}.pdf'
504
+ plt.savefig(filename, format='pdf', dpi=300)
505
+ print(f"Saved plot: {filename}")
506
+
507
+ plt.show()
508
+
509
+
510
+ def compare_policy_performance_with_table(
511
+ test_lambdas: List[float],
512
+ policies_to_test: List[str],
513
+ char_params: Tuple[float, float],
514
+ dev_model: Tuple[float, float, float],
515
+ cloud_model: Tuple[float, float, float],
516
+ name_device: str,
517
+ name_cloud: str,
518
+ table_and_plot: bool = True,
519
+ num_sim_requests: int = 500000,
520
+ char_pool: Optional[Union[pd.Series, np.ndarray]] = None
521
+ ) -> List[Dict[str, Any]]:
522
+ """
523
+ Compares the simulated performance of various routing policies and returns the statistics.
524
+ """
525
+ detailed_results = []
526
+ print("--- Running simulations for different arrival rates ---")
527
+
528
+ for lam in test_lambdas:
529
+ print(f"\n>>> Simulating for λ = {lam:.2f} req/s...")
530
+
531
+ request_stream = []
532
+ current_time = 0.0
533
+
534
+ if char_pool is not None and not (isinstance(char_pool, pd.Series) and char_pool.empty):
535
+ print(" -> Using empirical character distribution from provided data pool.")
536
+ input_sizes = np.random.choice(char_pool, size=num_sim_requests, replace=True)
537
+ else:
538
+ print(" -> WARNING: No character pool provided. Falling back to synthetic Normal distribution.")
539
+ char_mean, char_std = char_params
540
+ input_sizes = [int(max(1, np.random.normal(char_mean, char_std))) for _ in range(num_sim_requests)]
541
+
542
+ for i in range(num_sim_requests):
543
+ inter_arrival_time = random.expovariate(lam)
544
+ current_time += inter_arrival_time
545
+ request_stream.append({'id': i, 'arrival_time': current_time, 'size': input_sizes[i]})
546
+
547
+ optimal_T_stateless = 0
548
+ if 'Stateless Threshold' in policies_to_test:
549
+ thresholds_scan = range(0, 10000, 1) # Scan thresholds to find the best one
550
+ sim_results_for_T = simulate_routing_synthetic(
551
+ thresholds_scan, lam, num_jobs=2000, ca=1.0,
552
+ char_params=char_params,
553
+ dev_model=dev_model,
554
+ cloud_model=cloud_model
555
+ )
556
+ optimal_T_stateless = sim_results_for_T.loc[sim_results_for_T['sim_latency'].idxmin()]['threshold']
557
+ print(f" Optimal stateless T for λ={lam:.2f} is {optimal_T_stateless} chars.")
558
+
559
+ schedulers: Dict[str, Any] = {}
560
+ for policy_name in policies_to_test:
561
+ if 'Always Device' in policy_name:
562
+ schedulers[policy_name] = HeroPolicyScheduler(
563
+ dev_model=dev_model, cloud_model=cloud_model, force_policy='device'
564
+ )
565
+ elif 'Always Cloud' in policy_name:
566
+ schedulers[policy_name] = HeroPolicyScheduler(
567
+ dev_model=dev_model, cloud_model=cloud_model, force_policy='cloud'
568
+ )
569
+ elif policy_name == 'Round Robin 2x Cloud':
570
+ schedulers[policy_name] = MultiServerScheduler(
571
+ model=cloud_model, num_servers=2
572
+ )
573
+ elif policy_name == 'Round Robin 2x Device':
574
+ schedulers[policy_name] = MultiServerScheduler(
575
+ model=dev_model, num_servers=2
576
+ )
577
+ elif policy_name == 'Round Robin (Device/Cloud)':
578
+ schedulers[policy_name] = HeroPolicyScheduler(
579
+ dev_model=dev_model, cloud_model=cloud_model, force_policy='round_robin'
580
+ )
581
+ else:
582
+ schedulers[policy_name] = HeroPolicyScheduler(
583
+ dev_model=dev_model, cloud_model=cloud_model
584
+ )
585
+
586
+ for policy_name in policies_to_test:
587
+ stats = run_detailed_policy_simulation(
588
+ policy_name,
589
+ schedulers[policy_name],
590
+ request_stream,
591
+ stateless_threshold=optimal_T_stateless
592
+ )
593
+ df_stats = pd.DataFrame(stats)
594
+
595
+ df_stats['total_latency'] = df_stats['wait_time'] + df_stats['service_time']
596
+
597
+ avg_service_time = df_stats['service_time'].mean()
598
+ avg_total_latency = df_stats['total_latency'].mean()
599
+ std_total_latency = df_stats['total_latency'].std()
600
+ std_service_time = df_stats['service_time'].std()
601
+
602
+ # Calculation of total_simulation_time
603
+ df_stats['finish_time'] = df_stats['wait_time'] + df_stats['service_time'] + pd.Series([r['arrival_time'] for r in request_stream])
604
+ total_simulation_time = df_stats['finish_time'].max()
605
+
606
+ df_stats['decision_clean'] = df_stats['decision'].str.strip().str.lower()
607
+ device_stats = df_stats[df_stats['decision_clean'] == 'device']
608
+ cloud_stats = df_stats[df_stats['decision_clean'] == 'cloud']
609
+
610
+
611
+ # Calculate effective arrival rate to each queue
612
+ lambda_device = len(device_stats) / total_simulation_time if total_simulation_time > 0 else 0
613
+ lambda_cloud = len(cloud_stats) / total_simulation_time if total_simulation_time > 0 else 0
614
+
615
+ # Calculate average wait time in each queue
616
+ avg_wait_device = device_stats['wait_time'].mean() if not device_stats.empty else 0
617
+ avg_wait_cloud = cloud_stats['wait_time'].mean() if not cloud_stats.empty else 0
618
+
619
+ # This is the application of Little's Law: Lq = λq * Wq
620
+ # If avg_wait_device is non-zero, this will produce a non-zero queue length.
621
+ avg_q_len_device = lambda_device * avg_wait_device
622
+ avg_q_len_cloud = lambda_cloud * avg_wait_cloud
623
+
624
+ detailed_results.append({
625
+ 'Lambda': lam,
626
+ 'Policy': policy_name,
627
+ 'Total Latency (s)': avg_total_latency,
628
+ 'Total Latency std (s)': std_total_latency,
629
+ 'Avg Inference Time (s)': avg_service_time,
630
+ 'Inference Time std (s)': std_service_time,
631
+ 'Avg Device Queue Length': avg_q_len_device,
632
+ 'Avg Cloud Queue Length': avg_q_len_cloud
633
+ })
634
+ print(f" - {policy_name:<20}: Done.")
635
+
636
+ if table_and_plot:
637
+ results_df = pd.DataFrame(detailed_results)
638
+
639
+ for policy in policies_to_test:
640
+ print(f"\n\n--- Results for: {policy} ---")
641
+ policy_df = results_df[results_df['Policy'] == policy].set_index('Lambda')
642
+ display(policy_df[[
643
+ 'Total Latency (s)',
644
+ 'Avg Inference Time (s)',
645
+ 'Avg Device Queue Length',
646
+ 'Avg Cloud Queue Length'
647
+ ]].style.format({
648
+ 'Total Latency (s)': '{:.4f}',
649
+ 'Avg Inference Time (s)': '{:.4f}',
650
+ 'Avg Device Queue Length': '{:.2f}',
651
+ 'Avg Cloud Queue Length': '{:.2f}'
652
+ }).background_gradient(
653
+ cmap='viridis',
654
+ subset=['Total Latency (s)', 'Avg Device Queue Length', 'Avg Cloud Queue Length']
655
+ ))
656
+
657
+ sns.set_theme(style="whitegrid")
658
+
659
+ g = sns.FacetGrid(results_df, col="Policy", col_wrap=2, height=5, aspect=1.2, sharey=False)
660
+ g.map_dataframe(sns.lineplot, x="Lambda", y="Avg Device Queue Length", color='#1f77b4', marker='o', label="Device Queue")
661
+ g.map_dataframe(sns.lineplot, x="Lambda", y="Avg Cloud Queue Length", color='#2ca02c', marker='x', label="Cloud Queue")
662
+
663
+ g.set_axis_labels("Arrival Rate λ (req/s)", "Average Queue Length (Lq)")
664
+ g.set_titles(col_template="{col_name} Policy")
665
+ g.add_legend(title="Queue Type")
666
+ sns.move_legend(g, "lower center", bbox_to_anchor=(0.475, 0.9))
667
+
668
+ g.fig.suptitle('Average Queue Length vs. Arrival Rate for Each Policy', y=1.03, fontsize=16)
669
+ plt.tight_layout(rect=[0, 0, 0.9, 0.97])
670
+ plt.show()
671
+
672
+ return detailed_results
673
+
674
+
675
+ class HeroPolicyScheduler:
676
+ """
677
+ HERO: A stateful scheduler that uses the 'Join the Shortest Expected Queue' (JSEQ) policy.
678
+ It keeps track of when each server (device and cloud) will be free and routes
679
+ incoming requests to the server that is predicted to finish the job first.
680
+ """
681
+ def __init__(
682
+ self,
683
+ dev_model: Tuple[float, float, float],
684
+ cloud_model: Tuple[float, float, float],
685
+ force_policy: Optional[str] = None
686
+ ) -> None:
687
+ self.dev_model = dev_model
688
+ self.cloud_model = cloud_model
689
+ self.device_free_at = 0.0
690
+ self.cloud_free_at = 0.0
691
+ self.rr_next_is_device = True
692
+
693
+ if force_policy and force_policy not in ['device', 'cloud', 'round_robin']:
694
+ raise ValueError("force_policy must be 'device', 'cloud', 'round_robin', or None.")
695
+ self.force_policy = force_policy
696
+
697
+ def reset(self) -> None:
698
+ """Resets the scheduler's state by clearing the queues."""
699
+ self.device_free_at = 0.0
700
+ self.cloud_free_at = 0.0
701
+ self.rr_next_is_device = False
702
+
703
+ def _predict_service_time(self, size: float, model: Tuple[float, float, float]) -> float:
704
+ """
705
+ Predicts the service time in seconds for a given job size.
706
+ """
707
+ slope, intercept, _ = model
708
+ predicted_s = slope * size + intercept
709
+ return max(0.0, predicted_s)
710
+
711
+ def decide_at_time(self, size: float, arrival_time: float) -> str:
712
+ """
713
+ Makes a routing decision for a new request based on the JSEQ policy.
714
+ """
715
+ if self.force_policy == 'device':
716
+ return "Device"
717
+ if self.force_policy == 'cloud':
718
+ return "Cloud"
719
+ if self.force_policy == 'round_robin':
720
+ if self.rr_next_is_device:
721
+ self.rr_next_is_device = False
722
+ return "Device"
723
+ else:
724
+ self.rr_next_is_device = True
725
+ return "Cloud"
726
+
727
+ st_dev = self._predict_service_time(size, self.dev_model)
728
+ st_cloud = self._predict_service_time(size, self.cloud_model)
729
+
730
+ finish_dev = max(arrival_time, self.device_free_at) + st_dev
731
+ finish_cloud = max(arrival_time, self.cloud_free_at) + st_cloud
732
+
733
+ if finish_dev <= finish_cloud:
734
+ return "Device"
735
+ else:
736
+ return "Cloud"
737
+
738
+ def update_server_state(self, decision: str, actual_finish_time: float) -> None:
739
+ """
740
+ Updates the state of the chosen server with the actual finish time.
741
+ """
742
+ if decision == "Device":
743
+ self.device_free_at = actual_finish_time
744
+ elif decision == "Cloud":
745
+ self.cloud_free_at = actual_finish_time
746
+ # If round-robin was used, the decision will already be 'Device' or 'Cloud'.
747
+
748
+ def route_to_device(self, size: float, arrival_time: float) -> Tuple[str, float, float]:
749
+ """Routes a job to the device and returns its stats."""
750
+ st_dev = self._predict_service_time(size, self.dev_model)
751
+ start_dev = max(arrival_time, self.device_free_at)
752
+ finish_dev = start_dev + st_dev
753
+ self.device_free_at = finish_dev
754
+ return "Device", start_dev, finish_dev
755
+
756
+ def route_to_cloud(self, size: float, arrival_time: float) -> Tuple[str, float, float]:
757
+ """Routes a job to the cloud and returns its stats."""
758
+ st_cloud = self._predict_service_time(size, self.cloud_model)
759
+ start_cloud = max(arrival_time, self.cloud_free_at)
760
+ finish_cloud = start_cloud + st_cloud
761
+ self.cloud_free_at = finish_cloud
762
+ return "Cloud", start_cloud, finish_cloud
763
+
764
+
765
+ class MultiServerScheduler:
766
+ """
767
+ A scheduler for a pool of 'c' identical servers, routing via round-robin.
768
+ This is used to simulate policies like '2x Cloud' or '2x Device'.
769
+ """
770
+ def __init__(self, model: Tuple[float, float, float], num_servers: int = 2) -> None:
771
+ self.model = model
772
+ self.num_servers = num_servers
773
+ self.server_free_times = [0.0] * num_servers
774
+ self.next_server_idx = 0
775
+ self.last_assigned_server_idx = -1
776
+
777
+ def reset(self) -> None:
778
+ """Resets the scheduler's state."""
779
+ self.server_free_times = [0.0] * self.num_servers
780
+ self.next_server_idx = 0
781
+ self.last_assigned_server_idx = -1
782
+
783
+ def _predict_service_time(self, size: float, model: Tuple[float, float, float]) -> float:
784
+ """Predicts the service time in seconds for a given job size."""
785
+ slope, intercept, _ = model
786
+ predicted_s = slope * size + intercept
787
+ return max(0.0, predicted_s)
788
+
789
+ def decide_at_time(self, size: float, arrival_time: float) -> str:
790
+ """
791
+ Makes a routing decision using round-robin. ONLY decides.
792
+ """
793
+ server_idx = self.next_server_idx
794
+ self.last_assigned_server_idx = server_idx
795
+ self.next_server_idx = (self.next_server_idx + 1) % self.num_servers
796
+ return "Multi-Server"
797
+
798
+ def update_server_state(self, decision: str, actual_finish_time: float) -> None:
799
+ """
800
+ Updates the state of the chosen server with the actual finish time.
801
+ """
802
+ if decision == "Multi-Server" and self.last_assigned_server_idx != -1:
803
+ self.server_free_times[self.last_assigned_server_idx] = actual_finish_time
804
+
805
+
806
+ def run_detailed_policy_simulation(
807
+ policy_name: str,
808
+ scheduler: Union[HeroPolicyScheduler, MultiServerScheduler],
809
+ requests: List[Dict[str, float]],
810
+ stateless_threshold: Optional[int] = None
811
+ ) -> List[Dict[str, Union[float, str]]]:
812
+ """
813
+ Runs a simulation and returns detailed statistics for each request.
814
+ """
815
+ request_stats = []
816
+ scheduler.reset()
817
+
818
+ stateless_state = {'device_free_at': 0.0, 'cloud_free_at': 0.0}
819
+
820
+ dev_model = getattr(scheduler, 'dev_model', None)
821
+ cloud_model = getattr(scheduler, 'cloud_model', None)
822
+ multi_server_model = getattr(scheduler, 'model', None)
823
+
824
+ for req in requests:
825
+ arrival_time = req['arrival_time']
826
+ size = req['size']
827
+
828
+ is_stateless = 'Stateless Threshold' in policy_name
829
+ if is_stateless and stateless_threshold is not None:
830
+ decision = "Device" if size <= stateless_threshold else "Cloud"
831
+ else:
832
+ decision = scheduler.decide_at_time(size, arrival_time)
833
+
834
+ actual_service_time = 0.0
835
+ start_time = 0.0
836
+
837
+ if decision == "Device" and dev_model:
838
+ slope, intercept, std_dev = dev_model
839
+ base_time = slope * size + intercept
840
+ noise = random.gauss(0, std_dev) if std_dev > 0 else 0
841
+ actual_service_time = max(0.01, base_time + noise)
842
+
843
+ free_at_time = stateless_state['device_free_at'] if is_stateless else getattr(scheduler, 'device_free_at', 0.0)
844
+ start_time = max(arrival_time, free_at_time)
845
+
846
+ elif decision == "Cloud" and cloud_model:
847
+ slope, intercept, std_dev = cloud_model
848
+ base_time = slope * size + intercept
849
+ noise = random.gauss(0, std_dev) if std_dev > 0 else 0
850
+ actual_service_time = max(0.01, base_time + noise)
851
+
852
+ free_at_time = stateless_state['cloud_free_at'] if is_stateless else getattr(scheduler, 'cloud_free_at', 0.0)
853
+ start_time = max(arrival_time, free_at_time)
854
+
855
+ elif decision == "Multi-Server" and multi_server_model:
856
+ slope, intercept, std_dev = multi_server_model
857
+ base_time = slope * size + intercept
858
+ noise = random.gauss(0, std_dev) if std_dev > 0 else 0
859
+ actual_service_time = max(0.01, base_time + noise)
860
+ server_idx = getattr(scheduler, 'last_assigned_server_idx', 0)
861
+ server_times = getattr(scheduler, 'server_free_times', [0.0])
862
+ start_time = max(arrival_time, server_times[server_idx])
863
+
864
+ finish_time = start_time + actual_service_time
865
+
866
+ if is_stateless:
867
+ if decision == "Device":
868
+ stateless_state['device_free_at'] = finish_time
869
+ else:
870
+ stateless_state['cloud_free_at'] = finish_time
871
+ else:
872
+ scheduler.update_server_state(decision, finish_time)
873
+
874
+ wait_time = start_time - arrival_time
875
+ request_stats.append({'wait_time': wait_time, 'service_time': actual_service_time, 'decision': decision})
876
+
877
+ return request_stats
878
+
879
+
880
+ def plot_policy_comparison(
881
+ detailed_results: List[Dict[str, Any]],
882
+ policies_to_test: List[str],
883
+ dataset_name: str = "unspecified",
884
+ add_errorbars: bool = False,
885
+ show_x_axis: bool = True
886
+ ) -> None:
887
+ """
888
+ Plots the final line graph mapping mean response times against the arrival rate lambdas.
889
+ Updated for strict black-and-white print compliance and high contrast, with fixed color matching.
890
+ """
891
+ results_df = pd.DataFrame(detailed_results)
892
+ results_df = results_df[results_df['Policy'].isin(policies_to_test)]
893
+
894
+ is_experimental = results_df['Policy'].str.contains("(Experiment)", regex=False)
895
+ standard_policies_df = results_df[~is_experimental]
896
+ experimental_policies_df = results_df[is_experimental]
897
+
898
+ sim_policies = standard_policies_df['Policy'].unique().tolist()
899
+ experimental_policy_names = experimental_policies_df['Policy'].unique().tolist()
900
+
901
+ # Okabe-Ito high-contrast, colorblind-safe palette
902
+ okabe_ito = ['#E69F00', '#56B4E9', '#009E73', '#CC79A7', '#D55E00', '#0072B2', '#F0E442', '#000000']
903
+
904
+ # Map each simulation policy to a specific color so we can reuse it for experimental points
905
+ sim_color_dict = dict(zip(sim_policies, okabe_ito[:len(sim_policies)]))
906
+
907
+ # Distinct markers for grayscale separation
908
+ marker_shapes = ['o', 's', '^', 'D', 'v', 'p', '*'][:len(sim_policies)]
909
+
910
+ sns.set_theme(style="whitegrid")
911
+ fig, ax = plt.subplots(figsize=(6, 4))
912
+
913
+ # 1. Add the clear, non-bolded title requested by the reviewer with exact casing
914
+ TITLE_MAP = {
915
+ 'boolq': 'BoolQ',
916
+ 'ag-news': 'AG News',
917
+ 'spam/ham': 'Spam/Ham',
918
+ }
919
+
920
+ if dataset_name != "unspecified":
921
+ clean_name = dataset_name.lower().strip()
922
+ # Look up exact casing, fallback to the generic .title() if not found
923
+ title_text = TITLE_MAP.get(clean_name, dataset_name.replace('_', ' ').title())
924
+ else:
925
+ title_text = "Dataset Performance"
926
+
927
+ ax.set_title(title_text, fontweight='normal', fontsize=15, pad=10)
928
+
929
+ if not standard_policies_df.empty:
930
+ sns.lineplot(
931
+ data=standard_policies_df,
932
+ legend='full',
933
+ x='Lambda',
934
+ y='Total Latency (s)',
935
+ hue='Policy',
936
+ hue_order=sim_policies,
937
+ style='Policy',
938
+ style_order=sim_policies,
939
+ ax=ax,
940
+ palette=sim_color_dict,
941
+ markers=marker_shapes, # Forces distinct geometric shapes
942
+ dashes=True, # Forces distinct line styles (solid, dashed, dotted)
943
+ markersize=6,
944
+ linewidth=2.5,
945
+ errorbar='sd'
946
+ )
947
+
948
+ if add_errorbars and 'Total Latency std (s)' in standard_policies_df.columns:
949
+ for policy in sim_policies:
950
+ if (policy == 'HERO') & False:
951
+ policy_data = standard_policies_df[standard_policies_df['Policy'] == policy]
952
+ if not policy_data.empty:
953
+ ax.errorbar(
954
+ x=policy_data['Lambda'],
955
+ y=policy_data['Total Latency (s)'],
956
+ yerr=policy_data['Total Latency std (s)'],
957
+ fmt='none',
958
+ color=sim_color_dict.get(policy),
959
+ capsize=5,
960
+ alpha=0.6
961
+ )
962
+
963
+ # 2. Plot all the EXPERIMENTAL data mapped to their parent colors
964
+ if not experimental_policies_df.empty:
965
+ for policy_name in experimental_policy_names:
966
+ policy_data = experimental_policies_df[experimental_policies_df['Policy'] == policy_name]
967
+ y_err_col = 'Total Latency std (s)' if 'Total Latency std (s)' in policy_data.columns else None
968
+
969
+ # Extract the base policy name (e.g., "Always Device (Experiment)" -> "Always Device")
970
+ base_name = policy_name.replace(' (Experiment)', '').strip()
971
+
972
+ # -> CRITICAL FIX: Robust substring match to find the parent color <-
973
+ matched_color = '#000000' # Default fallback
974
+ for sim_pol, color in sim_color_dict.items():
975
+ if base_name in sim_pol:
976
+ matched_color = color
977
+ break
978
+
979
+ ax.errorbar(
980
+ x=policy_data['Lambda'],
981
+ y=policy_data['Total Latency (s)'],
982
+ yerr=policy_data[y_err_col].values if y_err_col else None,
983
+ label=policy_name,
984
+ fmt='X',
985
+ color=matched_color,
986
+ markersize=8,
987
+ markeredgecolor='black',
988
+ markeredgewidth=0.5,
989
+ capsize=4,
990
+ elinewidth=1.5,
991
+ zorder=10
992
+ )
993
+
994
+ ax.set_ylabel('Mean Response Time (s)', fontsize=15)
995
+ ax.set_xlabel('Arrival Rate λ (req/s)', fontsize=15)
996
+ ax.set_ylim(0, 2.5)
997
+ ax.set_xlim(0, 16)
998
+ ax.tick_params(axis='both', which='major', labelsize=14)
999
+
1000
+ ax.grid(axis='y', linestyle='-', alpha=0.5)
1001
+ ax.grid(axis='x', linestyle='-', alpha=0.5)
1002
+
1003
+ if show_x_axis:
1004
+ ax.set_xlabel('Arrival Rate λ (req/s)', fontsize=15)
1005
+ else:
1006
+ ax.set_xlabel('')
1007
+ ax.tick_params(axis='x', which='both', labelbottom=False) # Hides the numbers
1008
+
1009
+ # Force Matplotlib to generate the legend based on the plot content
1010
+ temp_leg = ax.legend()
1011
+ handles = temp_leg.legend_handles
1012
+ labels = [text.get_text() for text in temp_leg.get_texts()]
1013
+ temp_leg.remove()
1014
+
1015
+ plt.tight_layout()
1016
+
1017
+ out_dir = Path('./plots')
1018
+ out_dir.mkdir(parents=True, exist_ok=True)
1019
+
1020
+ safe_ds = "".join(c if c.isalnum() or c in (' ', '-', '_') else '_' for c in str(dataset_name)).strip().replace(' ', '_')
1021
+ filename = out_dir / f'policy_comparison_{safe_ds}.pdf'
1022
+ plt.savefig(filename, format='pdf', dpi=300)
1023
+ print(f"Saved plot: {filename}")
1024
+
1025
+ plot_legend_only(handles, labels, out_dir)
1026
+ plt.show()
1027
+
1028
+
1029
+ def plot_legend_only(
1030
+ handles: List[Any],
1031
+ labels: List[str],
1032
+ out_dir: Path
1033
+ ) -> None:
1034
+ """
1035
+ Creates and saves a plot containing only the legend.
1036
+ """
1037
+ import matplotlib.lines as mlines
1038
+
1039
+ fig_legend = plt.figure(figsize=(8, 4))
1040
+
1041
+ # Manually rebuild the handles for the experimental data to guarantee the 'X' marker shows
1042
+ fixed_handles = []
1043
+ for h, label in zip(handles, labels):
1044
+ if "(Experiment)" in label:
1045
+ # extract the color from the original handle container
1046
+ if hasattr(h, 'lines'): # It's an ErrorbarContainer
1047
+ color = h.lines[0].get_color()
1048
+ elif hasattr(h, 'get_color'): # It's a standard Line2D
1049
+ color = h.get_color()
1050
+ else:
1051
+ color = 'black' # Fallback
1052
+
1053
+ # Build a custom proxy handle with the 'X' marker, matching the exact styling
1054
+ proxy = mlines.Line2D(
1055
+ [], [],
1056
+ color=color,
1057
+ marker='X',
1058
+ markersize=8,
1059
+ markeredgecolor='black',
1060
+ markeredgewidth=0.5,
1061
+ linestyle='None' # Removes the trailing line, leaving just the marker
1062
+ )
1063
+ fixed_handles.append(proxy)
1064
+ else:
1065
+ fixed_handles.append(h)
1066
+
1067
+ legend = fig_legend.legend(
1068
+ fixed_handles,
1069
+ labels,
1070
+ loc='center',
1071
+ frameon=False,
1072
+ title=r"Applied Policy",
1073
+ title_fontproperties={'size': 14},
1074
+ ncol=1,
1075
+ fontsize=12
1076
+ )
1077
+ plt.tight_layout()
1078
+
1079
+ plt.axis('off')
1080
+
1081
+ legend_filename = out_dir / f'policy_comparison_legend.pdf'
1082
+
1083
+ fig_legend.savefig(
1084
+ legend_filename,
1085
+ format='pdf',
1086
+ dpi=300,
1087
+ bbox_inches='tight',
1088
+ pad_inches=0.0,
1089
+ bbox_extra_artists=(legend,)
1090
+ )
1091
+ print(f"Saved complete legend-only plot: {legend_filename}")
1092
+
1093
+ plt.show()
1094
+ plt.close(fig_legend)
1095
+
1096
+
1097
+ def load_and_plot_policy_results(
1098
+ file_path_str: Union[str, Path],
1099
+ augment_with_jseq: bool = False,
1100
+ augment_with_baseline: bool = False,
1101
+ dataset_name_for_exp: Optional[str] = None,
1102
+ dataset_name_title: str = "unspecified",
1103
+ show_x_axis: bool = True
1104
+ ) -> None:
1105
+ """
1106
+ Loads policy simulation results from a CSV, optionally augments them with
1107
+ experimental JSEQ data, and then plots the comparison.
1108
+ """
1109
+ file_path = Path(file_path_str)
1110
+
1111
+ try:
1112
+ results_df = pd.read_csv(file_path)
1113
+ if 'Policy' not in results_df.columns:
1114
+ print(f"[ERROR]: The required 'Policy' column was not found in {file_path}.")
1115
+ return
1116
+
1117
+ detailed_results = results_df.to_dict('records')
1118
+ policies_to_test = results_df['Policy'].unique().tolist()
1119
+
1120
+ policies_to_test = [
1121
+ p for p in policies_to_test
1122
+ if not p.startswith('Round Robin 2x Device') and not p.startswith('Round Robin 2x Cloud')
1123
+ ]
1124
+
1125
+ print(f"[SUCCESS]: Loaded data from {file_path}")
1126
+ print(f" Found {len(detailed_results)} records and {len(policies_to_test)} policies to plot.")
1127
+
1128
+ except FileNotFoundError:
1129
+ print(f"[ERROR]: The file was not found at {file_path}")
1130
+ return
1131
+ except Exception as e:
1132
+ print(f"An unexpected error occurred while loading the base CSV: {e}")
1133
+ return
1134
+
1135
+ if augment_with_baseline and dataset_name_for_exp:
1136
+ always_cloud_exp_dir = Path('../results/baseline_experiments/desktop-cloud-exp')
1137
+ always_device_exp_dir = Path('../results/baseline_experiments/desktop-device-exp')
1138
+ always_cloud_policy_name = 'Always Cloud (Experiment)'
1139
+ always_device_policy_name = 'Always Device (Experiment)'
1140
+
1141
+ if not always_device_exp_dir.exists():
1142
+ print(f" [WARNING]: Always Device experiment directory not found at {always_device_exp_dir}.")
1143
+ else:
1144
+ print(f"\nLoading experimental Always Device results for '{dataset_name_for_exp}'...")
1145
+ # Look for RAW files instead of stats files
1146
+ always_device_raw_files = sorted(always_device_exp_dir.glob(f'{dataset_name_for_exp}*raw*.csv'))
1147
+
1148
+ if not always_device_raw_files:
1149
+ print(f" [WARNING]: No Always Device raw files found for dataset '{dataset_name_for_exp}'.")
1150
+ else:
1151
+ always_device_data_added = False
1152
+ print(" --- Sanity Check: Always Device Experimental Values ---")
1153
+ for raw_file in always_device_raw_files:
1154
+ try:
1155
+ parts = raw_file.stem.split('_')
1156
+ lambda_str = parts[1].replace('lambda', '')
1157
+ lambda_val = float(lambda_str)
1158
+
1159
+ raw_df = pd.read_csv(raw_file)
1160
+ raw_df.columns = raw_df.columns.str.strip()
1161
+
1162
+ latencies_ms = raw_df['total_latency_ms']
1163
+ avg_latency_ms = latencies_ms.mean()
1164
+ std_latency_ms = latencies_ms.std()
1165
+
1166
+ avg_latency_s = avg_latency_ms / 1000.0
1167
+ std_latency_s = std_latency_ms / 1000.0
1168
+
1169
+ print(f" - Lambda: {lambda_val:<4} -> Avg: {avg_latency_s:.4f}s, Std: {std_latency_s:.4f}s")
1170
+
1171
+ detailed_results.append({
1172
+ 'Policy': always_device_policy_name,
1173
+ 'Lambda': lambda_val,
1174
+ 'Total Latency (s)': avg_latency_s,
1175
+ 'Total Latency std (s)': std_latency_s
1176
+ })
1177
+ always_device_data_added = True
1178
+ except (ValueError, IndexError, KeyError) as e:
1179
+ print(f" [ERROR]: Could not parse or process {raw_file.name}: {e}")
1180
+ print(" --------------------------------------------")
1181
+
1182
+ if always_device_data_added and always_device_policy_name not in policies_to_test:
1183
+ policies_to_test.append(always_device_policy_name)
1184
+ print(f"\nAppended '{always_device_policy_name}' to policies_to_test.")
1185
+
1186
+ if not always_cloud_exp_dir.exists():
1187
+ print(f" [WARNING]: Always Cloud experiment directory not found at {always_cloud_exp_dir}.")
1188
+ else:
1189
+ print(f"\nLoading experimental Always Cloud results for '{dataset_name_for_exp}'...")
1190
+ # Look for RAW files instead of stats files
1191
+ always_cloud_raw_files = sorted(always_cloud_exp_dir.glob(f'{dataset_name_for_exp}*raw*.csv'))
1192
+
1193
+ if not always_cloud_raw_files:
1194
+ print(f" [WARNING]: No Always Cloud raw files found for dataset '{dataset_name_for_exp}'.")
1195
+ else:
1196
+ always_cloud_data_added = False
1197
+ print(" --- Sanity Check: Always Cloud Experimental Values ---")
1198
+ for raw_file in always_cloud_raw_files:
1199
+ try:
1200
+ parts = raw_file.stem.split('_')
1201
+ lambda_str = parts[1].replace('lambda', '')
1202
+ lambda_val = float(lambda_str)
1203
+
1204
+ raw_df = pd.read_csv(raw_file)
1205
+ raw_df.columns = raw_df.columns.str.strip()
1206
+
1207
+ latencies_ms = raw_df['total_latency_ms']
1208
+ avg_latency_ms = latencies_ms.mean()
1209
+ std_latency_ms = latencies_ms.std()
1210
+
1211
+ avg_latency_s = avg_latency_ms / 1000.0
1212
+ std_latency_s = std_latency_ms / 1000.0
1213
+
1214
+ print(f" - Lambda: {lambda_val:<4} -> Avg: {avg_latency_s:.4f}s, Std: {std_latency_s:.4f}s")
1215
+
1216
+ detailed_results.append({
1217
+ 'Policy': always_cloud_policy_name,
1218
+ 'Lambda': lambda_val,
1219
+ 'Total Latency (s)': avg_latency_s,
1220
+ 'Total Latency std (s)': std_latency_s
1221
+ })
1222
+ always_cloud_data_added = True
1223
+ except (ValueError, IndexError, KeyError) as e:
1224
+ print(f" [ERROR]: Could not parse or process {raw_file.name}: {e}")
1225
+ print(" --------------------------------------------")
1226
+
1227
+ if always_cloud_data_added and always_cloud_policy_name not in policies_to_test:
1228
+ policies_to_test.append(always_cloud_policy_name)
1229
+ print(f"\nAppended '{always_cloud_policy_name}' to policies_to_test.")
1230
+
1231
+ if augment_with_jseq and dataset_name_for_exp:
1232
+ jseq_exp_dir = Path('../results/policy_experiments')
1233
+ jseq_policy_name = 'HERO (Experiment)'
1234
+
1235
+ if not jseq_exp_dir.exists():
1236
+ print(f" [WARNING]: JSEQ experiment directory not found at {jseq_exp_dir}.")
1237
+ else:
1238
+ print(f"\nLoading experimental JSEQ results for '{dataset_name_for_exp}'...")
1239
+ # Look for RAW files instead of stats files
1240
+ jseq_raw_files = sorted(jseq_exp_dir.glob(f'{dataset_name_for_exp}*raw*.csv'))
1241
+
1242
+ if not jseq_raw_files:
1243
+ print(f" [WARNING]: No JSEQ raw files found for dataset '{dataset_name_for_exp}'.")
1244
+ else:
1245
+ jseq_data_added = False
1246
+ print(" --- Sanity Check: JSEQ Experimental Values ---")
1247
+ for raw_file in jseq_raw_files:
1248
+ try:
1249
+ parts = raw_file.stem.split('_')
1250
+ lambda_str = parts[1].replace('lambda', '')
1251
+ lambda_val = float(lambda_str)
1252
+
1253
+ raw_df = pd.read_csv(raw_file)
1254
+ raw_df.columns = raw_df.columns.str.strip()
1255
+
1256
+ latencies_ms = raw_df['total_latency_ms']
1257
+ avg_latency_ms = latencies_ms.mean()
1258
+ std_latency_ms = latencies_ms.std()
1259
+
1260
+ avg_latency_s = avg_latency_ms / 1000.0
1261
+ std_latency_s = std_latency_ms / 1000.0
1262
+
1263
+ print(f" - Lambda: {lambda_val:<4} -> Avg: {avg_latency_s:.4f}s, Std: {std_latency_s:.4f}s")
1264
+
1265
+ detailed_results.append({
1266
+ 'Policy': jseq_policy_name,
1267
+ 'Lambda': lambda_val,
1268
+ 'Total Latency (s)': avg_latency_s,
1269
+ 'Total Latency std (s)': std_latency_s
1270
+ })
1271
+ jseq_data_added = True
1272
+ except (ValueError, IndexError, KeyError) as e:
1273
+ print(f" [ERROR]: Could not parse or process {raw_file.name}: {e}")
1274
+ print(" --------------------------------------------")
1275
+
1276
+ if jseq_data_added and jseq_policy_name not in policies_to_test:
1277
+ policies_to_test.append(jseq_policy_name)
1278
+ print(f"\nAppended '{jseq_policy_name}' to policies_to_test.")
1279
+
1280
+ try:
1281
+ print("\nAttempting to plot results...")
1282
+ plot_policy_comparison(detailed_results, policies_to_test, dataset_name_title, show_x_axis=show_x_axis)
1283
+ print("Plot generated successfully.")
1284
+ except Exception as e:
1285
+ print(f"[ERROR]: An unexpected error occurred during plotting: {e}")
1286
+ print(" Please check the structure of 'detailed_results' and 'policies_to_test'.")
1287
+
1288
+
1289
+ def run_multi_run_analysis(
1290
+ file_list: List[Union[str, Path]],
1291
+ show_scatter: bool = True,
1292
+ show_evolution: bool = True
1293
+ ) -> None:
1294
+ """
1295
+ Analyzes and plots total error deviations across multiple experiment runs.
1296
+ """
1297
+ if not file_list:
1298
+ print("Error: The file list is empty.")
1299
+ return
1300
+
1301
+ all_data = []
1302
+ for file_path in file_list:
1303
+ if not os.path.exists(file_path):
1304
+ print(f"Warning: File not found at {file_path}, skipping.")
1305
+ continue
1306
+
1307
+ df = pd.read_csv(file_path)
1308
+ df = df.sort_values('dataset_item_id')
1309
+
1310
+ df['pred_inf'] = df.apply(lambda x: x['jseq_predicted_cloud_inference_time'] if x['route'] == 'cloud'
1311
+ else x['jseq_predicted_device_inference_time'], axis=1)
1312
+ df['pred_total'] = df.apply(lambda x: x['jseq_predicted_cloud_total_time'] if x['route'] == 'cloud'
1313
+ else x['jseq_predicted_device_total_time'], axis=1)
1314
+
1315
+ df['abs_inf_err'] = (df['inference_time_ms'] - df['pred_inf']).abs()
1316
+ df['abs_total_err'] = (df['total_latency_ms'] - df['pred_total']).abs()
1317
+
1318
+ all_data.append(df[['dataset_item_id', 'abs_inf_err', 'abs_total_err', 'total_latency_ms', 'pred_total', 'route']].copy())
1319
+
1320
+ if not all_data:
1321
+ print("Error: No valid files were processed.")
1322
+ return
1323
+
1324
+ combined_df = pd.concat(all_data)
1325
+
1326
+ agg_df = combined_df.groupby('dataset_item_id')[['abs_inf_err', 'abs_total_err']].agg(['mean', 'std']).reset_index()
1327
+ agg_df.columns = ['_'.join(col).strip() if col[1] else col[0] for col in agg_df.columns.values]
1328
+
1329
+ print(f"\nAnalyzing {len(file_list)} runs...")
1330
+
1331
+ if show_scatter:
1332
+ first_run_df = all_data[0]
1333
+ plt.figure(figsize=(10, 6))
1334
+ for route in ['cloud', 'device']:
1335
+ subset = first_run_df[first_run_df['route'] == route]
1336
+ if not subset.empty:
1337
+ plt.scatter(subset['pred_total'], subset['total_latency_ms'], label=f'{route} (Total)', alpha=0.5)
1338
+
1339
+ limit = max(first_run_df['total_latency_ms'].max(), first_run_df['pred_total'].max())
1340
+ plt.plot([0, limit], [0, limit], 'r--', label='Ideal')
1341
+ plt.title('Total Latency: Predicted vs Actual (Example from first run)')
1342
+ plt.xlabel('Predicted Total (ms)')
1343
+ plt.ylabel('Actual Total (ms)')
1344
+ plt.legend()
1345
+ plt.grid(True, which="both", ls="--", alpha=0.15)
1346
+ plt.show()
1347
+
1348
+ if show_evolution:
1349
+ plt.figure(figsize=(8.5, 4.2))
1350
+
1351
+ # Colors selected directly from Okabe-Ito guidelines
1352
+ color_total = '#009E73' # Bluish Green
1353
+ color_inf = '#D55E00' # Vermillion
1354
+
1355
+ # 1. Plot Mean Total Error (Solid Line Layout with cleaned labels)
1356
+ plt.plot(
1357
+ agg_df['dataset_item_id'], agg_df['abs_total_err_mean'],
1358
+ color=color_total, linestyle='-', lw=1.5,
1359
+ label='Mean Total Error (Inference + Queueing)'
1360
+ )
1361
+
1362
+ # 2. Plot Mean Inference Error (Dashed Line for clear B&W contrast)
1363
+ plt.plot(
1364
+ agg_df['dataset_item_id'], agg_df['abs_inf_err_mean'],
1365
+ color=color_inf, linestyle='--', lw=1.5,
1366
+ label='Mean Inference Error'
1367
+ )
1368
+
1369
+ # Sizing and framing layout optimization
1370
+ plt.yscale('log')
1371
+ plt.xlabel('Dataset Item ID', fontsize=14, labelpad=8)
1372
+ plt.ylabel('Absolute Error (ms) [Log Scale]', fontsize=14, labelpad=8)
1373
+ plt.tick_params(axis='both', which='major', labelsize=12)
1374
+
1375
+ # Soft baseline grid integration
1376
+ plt.grid(True, which="major", axis="both", ls="-", alpha=0.4)
1377
+ plt.grid(False, which="minor", axis="y")
1378
+
1379
+ # Clean, compact legend
1380
+ plt.legend(fontsize=12, loc='upper right', frameon=True, framealpha=0.9)
1381
+
1382
+ out_dir = Path('./plots')
1383
+ out_dir.mkdir(parents=True, exist_ok=True)
1384
+
1385
+ filename = out_dir / f'time_prediction_error.pdf'
1386
+
1387
+ plt.savefig(filename, format='pdf', dpi=300, bbox_inches='tight')
1388
+ print(f"Saved plot: {filename}")
1389
+
1390
+ plt.show()
1391
+
1392
+ final_mae_total = combined_df['abs_total_err'].mean()
1393
+ final_mae_inf = combined_df['abs_inf_err'].mean()
1394
+ print(f"Overall MAE Inference (across all runs): {final_mae_inf:.2f} ms")
1395
+ print(f"Overall MAE Total (across all runs): {final_mae_total:.2f} ms")
notebooks/uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/ag-news_raw_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-01-31T18-36-02.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/ag-news_raw_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-02-01T12-19-04.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/ag-news_stats_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-01-31T18-36-02.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ route, total_requests, accuracy_percent, avg_latency_ms, avg_total_latency_ms, avg_queueing_time_ms, avg_inference_time_ms
2
+ overall, 500, 26.20, 346.31, 360.85, 13.77, 347.08
3
+ device, 0, 0.00, 0.00, 0.00, 0.00, 0.00
4
+ cloud, 500, 26.20, 346.31, 360.85, 13.77, 347.08
results/baseline_experiments/cloud/ag-news_stats_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-02-01T12-19-04.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ route, total_requests, accuracy_percent, avg_latency_ms, avg_total_latency_ms, avg_queueing_time_ms, avg_inference_time_ms
2
+ overall, 500, 86.40, 631.30, 709.75, 78.43, 631.32
3
+ device, 0, 0.00, 0.00, 0.00, 0.00, 0.00
4
+ cloud, 500, 86.40, 631.30, 709.75, 78.43, 631.32
results/baseline_experiments/cloud/boolq_raw_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-02-04T09-33-25.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/boolq_raw_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-01-31T19-51-47.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/boolq_stats_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-02-04T09-33-25.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ route, total_requests, accuracy_percent, avg_latency_ms, avg_total_latency_ms, avg_queueing_time_ms, avg_inference_time_ms
2
+ overall, 500, 55.20, 281.39, 313.73, 32.34, 281.40
3
+ device, 0, 0.00, 0.00, 0.00, 0.00, 0.00
4
+ cloud, 500, 55.20, 281.39, 313.73, 32.34, 281.40
results/baseline_experiments/cloud/boolq_stats_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-01-31T19-51-47.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ route, total_requests, accuracy_percent, avg_latency_ms, avg_total_latency_ms, avg_queueing_time_ms, avg_inference_time_ms
2
+ overall, 500, 83.80, 654.33, 1099.40, 445.04, 654.36
3
+ device, 0, 0.00, 0.00, 0.00, 0.00, 0.00
4
+ cloud, 500, 83.80, 654.33, 1099.40, 445.04, 654.36
results/baseline_experiments/cloud/lorem-ipsum_raw_experiment_meta-llama-llama-3-2_always_cloud_once-per-sec.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/lorem-ipsum_raw_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/spam_raw_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-01-31T17-54-44.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/spam_raw_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-02-01T08-09-41.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/baseline_experiments/cloud/spam_stats_experiment_meta-llama-llama-3-2-1b-instruct_always_cloud_once-per-sec_2026-01-31T17-54-44.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ route, total_requests, accuracy_percent, avg_latency_ms, avg_total_latency_ms, avg_queueing_time_ms, avg_inference_time_ms
2
+ overall, 500, 37.20, 363.95, 423.96, 60.04, 363.92
3
+ device, 0, 0.00, 0.00, 0.00, 0.00, 0.00
4
+ cloud, 500, 37.20, 363.95, 423.96, 60.04, 363.92
results/baseline_experiments/cloud/spam_stats_experiment_openai-gpt-4-1-mini_always_cloud_once-per-sec_2026-02-01T08-09-41.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ route, total_requests, accuracy_percent, avg_latency_ms, avg_total_latency_ms, avg_queueing_time_ms, avg_inference_time_ms
2
+ overall, 500, 97.00, 659.35, 779.08, 119.73, 659.36
3
+ device, 0, 0.00, 0.00, 0.00, 0.00, 0.00
4
+ cloud, 500, 97.00, 659.35, 779.08, 119.73, 659.36