Adopting Two Supervisors for Efficient Use of Large-Scale Remote Deep
  Neural Networks
Recent decades have seen the rise of large-scale Deep Neural Networks (DNNs)
to achieve human-competitive performance in a variety of artificial
intelligence tasks. Often consisting of hundreds of millions, if not hundreds
of billion parameters, these DNNs are too large to be deployed to, or
efficiently run on resource-constrained devices such as mobile phones or IoT
microcontrollers. Systems relying on large-scale DNNs thus have to call the
corresponding model over the network, leading to substantial costs for hosting
and running the large-scale remote model, costs which are often charged on a
per-use basis. In this paper, we propose BiSupervised, a novel architecture,
where, before relying on a large remote DNN, a system attempts to make a
prediction on a small-scale local model. A DNN supervisor monitors said
prediction process and identifies easy inputs for which the local prediction
can be trusted. For these inputs, the remote model does not have to be invoked,
thus saving costs, while only marginally impacting the overall system accuracy.
Our architecture furthermore foresees a second supervisor to monitor the remote
predictions and identify inputs for which not even these can be trusted,
allowing to raise an exception or run a fallback strategy instead. We evaluate
the cost savings, and the ability to detect incorrectly predicted inputs on
four diverse case studies: IMDB movie review sentiment classification, Github
issue triaging, Imagenet image classification, and SQuADv2 free-text question
answering
Michael Weiss, Paolo Tonella
# Adopting Two Supervisors for Efficient Use of Large-Scale Remote Deep Neural Networks

###### Abstract.

Recent decades have seen the rise of large-scale Deep Neural Networks (DNNs) to achieve human-competitive performance in a variety of artificial intelligence tasks. Often consisting of hundreds of millions, if not hundreds of billion parameters, these DNNs are too large to be deployed to, or efficiently run on resource-constrained devices such as mobile phones or IoT microcontrollers. Systems relying on large-scale DNNs thus have to call the corresponding model over the network, leading to substantial costs for hosting and running the large-scale remote model, costs which are often charged on a per-use basis. In this paper, we propose BiSupervised, a novel architecture, where, before relying on a large remote DNN, a system attempts to make a prediction on a small-scale local model. A DNN supervisor monitors said prediction process and identifies easy inputs for which the local prediction can be trusted. For these inputs, the remote model does not have to be invoked, thus saving costs, while only marginally impacting the overall system accuracy. Our architecture furthermore foresees a second supervisor to monitor the remote predictions and identify inputs for which not even these can be trusted, allowing to raise an exception or run a fallback strategy instead. We evaluate the cost savings, and the ability to detect incorrectly predicted inputs on four diverse case studies: IMDB movie review sentiment classification, Github issue triaging, Imagenet image classification, and SQuADv2 free-text question answering.

Keywords:**C** Computer systems organization Embedded systems; _Redundancy_; Robotics; **Networks** Network reliability. +
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

+
Footnote †: 2: 4000 tokens on a fine-tuned davinci-model (0.12$ per 1000 tokens). See beta.openai.com.

## 1. Introduction

In the last decades, we have seen a steady rise of _Deep Neural Network_ (DNN) components in modern software systems, so-called _Deep Learning based Systems_ (DLS): For example, buyers are intelligently assisted when buying products online1, customer service is performed and analyzed using bots (Botton et al., 2016), Github issues can be automatically triaged (Srivastava et al., 2015) and medical diagnosis is made or supported by automated processes (Krizhevsky et al., 2014) (sometimes runnable even on a smartphone (Srivastava et al., 2014)).

Footnote 1: E.g. [https://hellorep.ai/](https://hellorep.ai/)

To achieve ever better predictive accuracy, the size of the best-performing DNN models has increased enormously for many tasks, with some models now consisting of trillions of parameters. Large models have to be hosted in server centers, amongst others due to their challenging hardware requirements. Client facing-applications thus have to make a choice between small, low-accuracy models running locally on the client's device (e.g. a browser or a mobile phone) or to offload their prediction tasks to a large model in the cloud, which amongst other disadvantages introduces latency and imposes a substantial financial cost to the software provider for hosting their model, or for using a third-party model. For example, a single request to the popular GPT-3 model (Botton et al., 2016), hosted by the Non-Profit organization OpenAI for anyone to use, is billed up to $0.48\({}^{2}\).

Even state-of-the-art models, given their typically intractably large input space and stochastic nature, will occasionally make wrong predictions. Here, typical machine learning evaluation metrics, such as high accuracy, are not sufficient to justify the inclusion of the model in many risk-averse settings. Instead, software architects and software engineers have to defend against the
imperfections of state-of-the-art DNN models and prevent system failure even when faced with rare, mispredicted inputs. This led to the proposition and evaluation of various _DNN supervisors_ in the recent software engineering literature (e.g. 4; 40; 54; 55; 59; 62; 64). A DNN supervisor is a software component implemented to monitor a DNN at runtime and to detect inputs for which the models' prediction cannot be trusted. For such inputs, the system would default to a predefined domain-specific backup strategy (e.g. forwarding the request to a human operator) or to refuse to produce any output. Our work suggests using such supervisors not only to prevent system failure but also to reduce cost and latency in applications running on resource constraint devices.

Specifically, we propose BiSupervised, a novel software architecture that combines the advantages of cheap and fast local DNN with the advantages of using a highly accurate but costly remote DNN. Specifically, BiSupervised leverages a first supervisor to discriminate between inputs that can reliably be predicted locally on a small model, and only leverage the large remote model when the input is too challenging for the local model. A second supervisor is then used to filter out highly uncertain remote predictions. Specifically, our contributions are the following:

**Architecture**: We propose a novel architecture that combines small, local models with large remote ones, allowing us to fine-tune an optimal cost-reliability trade-off.
**Evaluation of Cost Savings**: We empirically evaluate the trade-off between cost saving (in terms of the number of requests to the remote model) and system accuracy enabled by our architecture. Specifically, we evaluate if our architecture allows significant cost savings while maintaining a system-level accuracy at most marginally lower than the one of the remote model. We found that for all case studies, when reducing costs by 50%, BiSupervised achieved a system-level accuracy which is barely lower than the one of the large-scale remote model. Moreover, in two case studies, BiSupervised even achieved an accuracy exceeding the one of the large-scale remote models, due to complementarities in the local and remote models capabilities.
**Evaluation of Supervised Performance**: We assess BiSupervised in a supervised setting, i.e., including the detection of inputs for which even the remote DNN prediction is not reliable enough to be trusted and for which thus a system-specific healing strategy should be triggered. We compare the supervised performance of our system against that of a locally supervised model. We found that in the vast majority of the tested configurations, the supervised performance of BiSupervised is similar or exceeds the one of the locally supervised model.

## 2. Background

### The trend towards huge DNN

_From 1 thousand to 1.6 trillion parameters in 33 years_. In 1989, LeCun et al. (1989) proposed a DNN achieving state-of-the-art classification performance on handwritten digits, marking one of the earliest real-world applications of a neural net trained end-to-end with backpropagation (LeCun et al., 2010). Consisting of only 1000 parameters, it is orders of magnitude smaller than what we use nowadays to achieve state-of-the-art (SOTA) performance on challenging tasks. After 1989, we were still a long way from widespread adoption of DNNs for practical tasks: Training DNNs is a highly computation-intensive task and thus for a long time, faster classical methods of AI, such as Support Vector Machines continued to achieve better results on nontrivial tasks, still winning, for example, the image classification benchmark (ILSVRC), in 2010 and 2011 (Zhou et al., 2011). This changed with an innovation that would make the training of DNNs much faster, thus allowing for much larger DNNs: Starting in 2010, the first successful application of plain backpropagation on a GPU achieved a speedup of 50 over CPUs (Beng et al., 2011), training networks of up to 12 million parameters. Shortly thereafter, AlexNet, a 60 million parameter DNN (Krizhevsky et al., 2012) won ILSVRC2012, marking a "turning point for large-scale object
recognition" [47]. As of this writing, CoCa, the SOTA model for the same task consists of 2.1 billion parameters3[70].

Footnote 3: According to [https://paperswithcode.com/sota/image-classification-on-imagenet](https://paperswithcode.com/sota/image-classification-on-imagenet), accessed on July 21, 2022

In other domains, such as Natural Language Processing (NLP), we observe even larger dimensions: GPT-2 (1.5B parameters) in 2019 [43] and GPT-3 (175B parameters) in 2020 [2] led to global media coverage, due to their good performance in generating naturally-appearing text. Within the last two years, they have again been overtaken by even larger models, for example by Megatron (530B parameters, 2022) [50]. To the best of our knowledge, the currently largest well-known DNN is SwitchTransformer with a parameter count of 1.6T [12].

Cost of large modelsThe large computational requirements of such large models when inferencing (i.e., predicting) present a major challenge to their adoption [39], as they require a large amount of memory, energy, and powerful CPUs or GPUs to make predictions. This can make their deployment impractical if not impossible, especially regarding customer-facing, resource-constrained devices, and platforms such as web browsers, internet of things (IOT) microcontrollers, or mobile phones. Large-scale, highly accurate DNNs are thus typically deployed in server centers, providing a remote inference service. There is a range of services facilitating such predictions, such as the HuggingFace Inference API4, OpenAIs APIs to GPT-35 or Google's Vertex AI6. Not only can already a single inference to a large model on such a service lead to high cost, the cost of such remote inferences also scales badly, as it increases quasi proportionally with the number of inference requests - providing essentially no economies of scale.

Footnote 4: [https://huggingface.co/inference-api](https://huggingface.co/inference-api)

Footnote 5: [https://openai.com/api/](https://openai.com/api/)

Footnote 6: [https://cloud_google.com/vertex-ai/docs/start/introduction-unified-platform](https://cloud_google.com/vertex-ai/docs/start/introduction-unified-platform)

### Running DNNs in Resource-Constrained Environments

Advantages of smaller but local modelsA substantially different approach is hence to run DNNs locally on the client devices, which constrains the size and complexity of the models, eventually leading to an inferior level of accuracy.7 Such locally deployed models have a range of advantages, among which a much lower energy consumption, faster inference (due to the smaller model, but also as there is no need to do a network roundtrip), no dependency on a stable internet connection, and, as explained above, no per-inference cost to the software provider.

Means towards efficient modelsThere is thus much interest in making local models as efficient as possible, aiming to fit more parameters into the capacities of a resource-constrained system, or to optimize the performance of a model while keeping its number of parameters as low as possible. The following provides a non-comprehensive selection of some recent work and frameworks aiming to facilitate the use of DNN models in resource-constrained environments.

* _Small Model Architectures:_ A range of works proposes specific DNN architectures or training procedures aiming to specifically facilitate deployment to resource-constrained devices. Examples are TinyBERT [22] and MobileNet[18; 19; 49]. These models, which are comparably small for their tasks (NLP and Imagenet classification, respectively) are intended to be used as starting point to fine-tune a model to other specific use-cases, thus making them widely useful.
* _Smaller Sibling Models:_ Various recent releases of new, large-scale SOTA models were accompanied by a set of similar, but smaller models. The architectural choices and innovations
proposed to create the flagship large-scale SOTA models are applied also to a set of smaller models. This allows users to make an accuracy vs model-size trade-off. Examples include efficientnet(Wang et al., 2018), OPT (Wang et al., 2018) and GPT-38(Beng et al., 2019). Footnote 8: Models are not publicly released, but access is allowed through an API.
* _Model Tuning and Postprocessing_: Literature provides a range of techniques to make a given large DNN architecture fit for lower system requirements, allowing to deploy it on resource-constrained devices. The most popular such approach is _Quantization_, where a full-precision DNN is converted into a low-bitwidth integer version, thus reducing computational and memory requirements (Wang et al., 2018). Another technique is DNN pruning where the number of weights is reduced in a guided way, aiming to only minimally reduce the model accuracy (Wang et al., 2018).
* _Custom Frameworks_: A typical software stack used to build and train a DNN cannot easily be applied when deploying the DNN to an environment such as a mobile phone or web browser which, besides hardware constraints, also imposes constraints on the software stack. To this end, dedicated frameworks have been proposed, among which the most popular is tf-lite9, allowing to convert a standard tensorflow model into one that can be deployed on specific platforms, such as Android, iOS and Linux edge devices. A dedicated version, tf-lite micro targets even particularly small embedded devices (Beng et al., 2019). Footnote 9: [https://www.tensorflow.org/lite](https://www.tensorflow.org/lite)

Naturally, none of these techniques allows us to deploy huge SOTA models in resource-constrained environments, thus not replacing the need for remote predictions when aiming for optimal prediction accuracy. They do however support and extend the possibility to deploy smaller models on local or edge devices in cases where suboptimal accuracy is acceptable.

## 3. Related Work

### Smart Offloading in Edge Computing

The idea to delegate computationally intensive tasks from resource-constrained devices to the edge or to the cloud, denoted as _offloading_, is not limited to DNNs. Recent work - which is not specific to DNNs - discusses the idea of intelligently deciding on the local device which tasks can be computed locally, and which inputs have to be forwarded to the remote computation API. Amongst other approaches, some work proposes to use a local DNN to categorize inputs to make said decision (Surveys, 2017; Wang et al., 2018). These architectures thus naturally show some high-level similarity with BiSupervised, specifically with the 1st level supervisor. However, our architecture, which is specific to DNN inference tasks, includes a 1st level supervisor that is tightly integrated with the local model, allowing us to efficiently compute both a local prediction and the decision on whether a remote invocation is needed. Specifically, we leverage the possibility of quantifying the uncertainty of the DNN at inference time - a possibility that does not generalize to arbitrary computations in local devices. To the best of our knowledge, ours is the first approach that supports smart offloading for DNNs running in a local, resource-constrained device.

### Network Supervision

To account for the practically unavoidable imperfections in DNN predictions, the detection of inputs for which the corresponding prediction is likely to be wrong is a crucial component of Machine Learning safety (Han et al., 2017). This task, which we denote as _supervision_ (sometimes also refered to as _monitoring_(Han et al., 2017), _prediction validation_(Beng et al., 2019) or _misbehavior prediction_(Wang et al., 2018; Wang et al., 2018)) allows to ignore the DNNs prediction and instead run a fallback process (sometimes denoted healing process (Wang et al., 2018)).
#### 3.2.1. Supervisors Used in Related Literature

The literature offers a range of techniques that can be used for supervision. In the following, we provide a brief overview. While we make some recommendations in subsection 4.2, this overview aims to help the reader make an informed selection of supervisors to use in BiSupervised.

**Softmax-Likelihood Based**: Most DNN classifiers use a _Softmax_-normalized output layer: Let \(sm\) denote the activations of such a softmax output layers, and let \(C\) denote the set of classes. We have that \(length(sm)=|C|\) and \(\sum_{c\in C}sm_{c}=1\). The models prediction is \(argmax_{c\in C}sm_{c}\), with the assigned likelihood \(max_{c\in C}sm_{c}\).10 Given a softmax output array, the simplest softmax-based supervisor, _Vanilla Softmax_ or _MaxSoftmax_[16], simply trusts a prediction if its softmax value is above some threshold. To that extent, other supervisors use functions of the entire softmax array, such as the prediction-confidence-score (the difference between the two highest likelihoods) [73], the entropy in the predicted likelihoods [65] or the Gini impurity in the predicted likelihoods [13]. Outlier Exposure [17] is a technique to further strengthen the capabilities of Softmax-Likelihood-based supervisors during model training.

Footnote 10: It is worth noting that \(sm_{c}\) is not an appropriate approximation of \(c\) actually being correct; it is well known that - if not deliberately calibrated - DNNs overestimate such likelihoods [16].
**Monte-Carlo Dropout (MC-Dropout)**: MC-Dropout is a simple way to implement a _Bayesian Neural Network_, i.e., a network that allows predicting a distribution over outputs instead of just a single "point" prediction [23]. To this extent, it leverages multiple, randomized predictions to estimate the spread in the prediction and thus its the degree of uncertainty [14]. The randomness in the prediction process comes from enabling _dropout_ layers [51] at prediction time, i.e., layers that randomly drop some nodes' activations, which are typically used for regularization during DNN training. Then, there is a range of techniques to quantify the models' uncertainty given the samples, such as the predictions _variation ratio_ or _mutual information_. MC-Dropout has been widely used in the literature [e.g. 4, 5, 40, 73].
**Ensembles**: Similar to MC-Dropout, Ensembles [33] estimate the models' uncertainty by measuring the agreement between sampled predictions for a given input. Here, however, the randomness in the prediction process comes from using a range of different DNNs, all sharing the same architecture, but trained using differently initialized weights and biases. Intuitively, inputs for which the different models disagree more are quantified with higher uncertainty. Here, the same quantifiers as the ones for MC-Dropout can be used.
**Surprise Adequacy**: Instead of the approaches described above, which aim to quantify the models uncertainties, surprise adequacy (SA) [28] aims to quantify how _surprising_ (i.e., _novel_ or _out-of-distribution_) an input is with respect to its activation traces in the supervised model. There are different variants of surprise adequacy, such as _Distance-based SA (DSA)_[28], _Likelihood-based SA (LSA)_[28]_ and Mahalanobis-distance-based SA (MDSA)_[29, 30]_, some of which can be used in a multimodal setting [31], and we refer to the corresponding papers for a detailed description.
**Autoencoders**: A more direct, black-box [45] approach to supervision is taken by Autoencoder based supervision [52, 53, 54, 55]. Autoencoders are DNNs aiming to first compress and then reconstruct an input. If trained on the same data as the supervised DNN, an autoencoder can detect out-of-distribution inputs at runtime: As such data was by definition not well represented in the training data, it is likely to have a higher reconstruction error.
**Other Supervisors**: Alternative, less frequently used approaches include, _Dissector_[59] which makes per-layer predictions and measures there disagreement, _DeepRoad_[71] a principal component analysis (PCA) based approach on the model's activation traces, _Learnt Assertions_[37] which aims to automatically learn to recognize inputs that are likely to be mispredicted
from the associated activations, and _NIRVANA_[5] which combines multiple MC-Dropout quantifiers outputs in a support-vector machine (SVM).

#### 3.2.2. Comparison of Supervisors Regarding Computational Overhead

In resource-constrained environments, the overhead imposed by a supervisor, i.e., the additional computation cost imposed by running the supervisor might be an important concern. Here, we see substantial differences between the supervisors: Clearly, Softmax-based approaches are the fastest approaches, as they do not require any additional predictions. Instead, the quantification of uncertainty from the softmax array requires just a few floating point operations. In the case of MaxSoftmax, there's actually just a single array value read required (the softmax likelihood for the predicted class), the associated overhead being clearly minimal. MC-Dropout (and thus also NIRVANA) and Ensembles require substantially more time, as various predictions for the same input have to be collected. While in an existing tool [65], we provide utilities to perform such predictions very efficiently, it still remains a show-blocker for very resource-constrained applications.

Autoencoders can also be considered quite fast and efficient, as there is only a single additional prediction (the autoencoder forward pass) required. Moreover, such additional prediction can actually be done at the same time or even before the prediction on the supervised model is made. Should the autoencoder-based supervisor thus decide that a prediction for a given input is not to be trusted, the prediction does not even have to be made. When originally proposed, the performance gain of using autoencoder-based supervision compared to the then state-of-the-arte DeepRoad was one of its major advantages [54]. The overhead of surprise adequacy much depends on its specific type: DSA and LSA suffer from major performance bottlenecks when large training sets are used. There are some ways to mitigate these problems, e.g. by using only a subsample of the training set and fast, vectorized implementations [62], but even with such improvements, the use of these techniques in many real-world applications on devices such as microcontrollers remains prohibitive. In such domains, only the latest variant of SA, MDSA provides a low enough overhead [66].

#### 3.2.3. Comparison of Supervisors Regarding Supervision Performance

Faced with the wide range of techniques applicable for supervision, a range of empirical studies has been performed comparing them [1, 63, 64, 66, 67, 73]. Summarized, they all find that no single technique works as a dominant supervisor, i.e., no technique consistently outperforms all other approaches. Some studies highlight that ensembles provide often - but not always - a better supervision performance than all other techniques [41, 64, 67] as they not only give an accurate uncertainty estimate, but often better prediction in the first place. Softmax-based approaches also often provide good supervision performance and in a recent study we found no statistical difference between the performance to detect misclassified inputs between the different variants of softmax-based supervisors. Thus the simple MaxSoftmax might be a good choice in many situations. Surprise Adequacies, while generally performing a bit worse than Softmax-based supervisors [63, 66], have the advantage that they can be applied to any DNN, not just to classification models. Lastly, autoencoders perform well as long as the training set is relatively sparse in the input feature space. Instead, with feature-rich datasets autoencoders start to generalize too well for supervision, as they learn to also reconstruct outliers consisting of the same features [63, 46]

#### 3.2.4. Comparison of Supervisors Regarding Robustness

It is important that supervisors detect root causes of DNN failures, such as adversarial inputs, corrupted inputs, invalid inputs or ambiguous inputs. In a recent study, we compared the capabilities of various supervisors in detecting these specific root causes of uncertainty [63]. Summarized, we found that all supervisors show some weaknesses. E.g., surprise adequacy, which tends to work well in detecting corrupted, adversarial and invalid inputs, fails to detect in-distribution ambiguous inputs (i.e., inputs with only aleatoric,
but no epistemic uncertainty). Softmax-based supervisors can in principle detect all root causes, but are are vulnerable to adversarial attacks, which typically aim to modify the values of the output layer and can thus easily be configured to create high-confidence but wrong predictions.

## 4. Bispupervised: Our Proposed Architecture

An overview of BiSupervised is illustrated in Figure 1. The goal of our architecture is as follows: (1) Attempt a prediction on a small, fast and cost-free _local surrogate model_ (short: _local model_). (2) Leverage a supervisor, denoted as _1st level supervisor_, to identify inputs for which the local prediction cannot be trusted. (3) For those inputs, and only for those inputs, collect prediction and confidence from a large, highly accurate remote model. (4) Identify predictions for which not even the remote prediction can be trusted, based on the reported prediction and confidence in a _2nd level supervisor_ and raise a warning or return a default (fallback) value for those inputs. Intuitively, this architecture attempts only to make costly remote predictions for _difficult_ inputs, where the simple local model is not sufficiently well trained. The 2nd level supervisor furthermore allows handling inputs for which not even the highly accurate remote model can make a trustworthy prediction, such as invalid or ambiguous inputs.

Algorithm 1 outlines BiSupervised with threshold-based supervisors as pseudocode: On line 2-3 the local model makes a prediction and the 1st level supervisor quantifies the confidence of the prediction. To mitigate the computational effort required to execute lines 2-3, the corresponding input might be reduced in dimensionality (e.g. reducing the size of an image) to allow for smaller local models (line 1). If the confidence of this locally computed prediction is above some predefined threshold \(t_{l}\), the prediction is returned (lines 4-6). Otherwise, the original input is sent to the remote prediction server, which returns the remote prediction amongst some metadata (e.g. prediction logits), from which the 2nd level supervisor can calculate a confidence (lines 7-8). The remote prediction is returned, if the corresponding confidence is considered high enough. Otherwise, an exception is raised (lines 9-13).

A specific example highlighting how BiSupervised could be implemented and used in a practical application is given in Example 4.1

Example 4.1 (Use of BiSupervised in a Wildlife Camera): Let us consider a wildlife camera in a national park, installed to monitor the presence of wild animals and to report it to the park administration. Every 15 seconds, it takes an image that is classified according to the animal visible on the image, e.g. _no-animal, deer, wolfe, human_, etc. Using BiSupervised, the classification works

Figure 1. BiSupervised: Proposed Architecture for a Supervised Combination of Local and Remote Predictions
as follows: First, the wildlife camera locally tries to classify the image. In doing so, it collects its full softmax output arrays, from which the 1st level supervisor can easily read the model's confidence [(16)]. If the confidence is high, the prediction is reported to the wildlife park's server. Otherwise, a remote model is leveraged: the wildlife camera sends the image to a highly reliable 3rd party image classification service, such as IBM's Watson11, which returns its prediction and alongside the prediction logits. The 2nd level supervisor then determines if the remote prediction can be trusted based on the remote model confidence (which can be determined based on the prediction logits). If the remote prediction is trustworthy, the prediction is reported to the wildlife-park server. Otherwise, a warning is submitted to the park administration, alongside the unclassifiable image. The following scenarios may thus happen for different images:

Footnote 11: [https://www.ibm.com/no-en/cloud/watson-visual-recognition/pricing](https://www.ibm.com/no-en/cloud/watson-visual-recognition/pricing)

* **Nominal Image** Assume no animal stands in front of the camera. The local model confidently detects _no-animal_, with low surprise adequacy. No remote model invocation is needed, which thus saves money.
* **Rare Image** Assume there's fog, a condition which is not well represented in the local models' training set, thus leading to a non-trustworthy prediction of _Beaver_. The local supervisor detects the surprising input and thus ignores the local prediction, but forwards the image to the large-scale remote model, which generalizes better to such rare conditions and clearly detects a _deer_ in the fog. "_Deer_" is thus reported to the park administration.
* **Invalid Image** A storm caused the camera to be partially covered by mud, in a way that neither the local nor the remote model can make confident predictions, which both supervisors detect. A warning is sent to the park administration. With several such warnings reported in a short time, a park administrator double-checks the reported images and notifies a ranger to clean up the camera.

In the following, we will explain each of the components in our architecture in more detail.

### Design of Local Surrogate Model

The local model's objective is to make high-confidence predictions for as many inputs as possible in a very constrained environment: Our architecture aims to be applicable to even tiny devices, such as microcontrollers, and as such, the design possibilities for the local model are limited, especially
with respect to the number of model parameters. We refer to subsection 2.2 for an overview of techniques to create such a model, but in the scope of our architecture, there's an additional measure that _optionally_ can be taken to allow a reduced model size, which we call _Input Domain Reduction_: Optionally, we may design a local model to handle a reduced input space instead of the original, possibly large, one: we can reduce the dimensionality of the input space, potentially losing some information, which may prevent optimal predictions on a few inputs, but generally allows the local model to be much smaller in size. For example, in NLP tasks, we may use a much smaller dictionary or clip the length of the input. For easy inputs, the information loss induced by the input domain reduction is unlikely to cause much uncertainty. For all other inputs, we leverage a remote prediction on the large original input domain. E.g., in Example 4.1, we could train the local surrogate model on small grayscale images, and compress their inputs accordingly. Simple classifications, e.g. when no animal is around would still be possible with high confidence, but at the same time this would allow us to use a much smaller DNN.

### Design of 1st Level Supervisor

In principle, our architecture is not tied to any specific supervision technique, thus all those listed in Section 3.2 could potentially be used as 1st level supervisor. However, as the 1st level supervisor runs in the local, resource-constrained environment, one should make a choice that does not come with notable computational requirements during inference. In our recent works [63; 64; 66], we empirically compared a range of supervision techniques. Our results suggest the use of two specific techniques, as they both show a good supervision accuracy, while only causing negligible additional computational cost: For classification problems, where the local model makes softmax-normalized predictions, simply taking the highest softmax value (i.e., the softmax value of the predicted class) [16] as a confidence score shows good practical supervision performance. For other models, without a softmax output, _Mahalanobis-Distance based Surprise Adequacy (MDSA)_[29] reliably detects out-of-distribution inputs. We refer to subsection 3.2 for a detailed discussion of different supervisors, their complementarities, weaknesses, strengths and overhead.

### Use of Remote Model or System and Design of 2nd-Level Supervisor

Our architecture does not have any specific requirements on the architecture of the remote model. Indeed, the remote model is considered a "black box" and may consist of more than just a DNN: in general, it might be a fully fledged, complex multi-component system (in this paper, we use the intuitive term _remote model_ for simplicity). However, the 2nd level supervision can be heavily facilitated when the remote model is a DNN returning also its confidence (or related metrics, such as uncertainty) alongside its prediction. This may not be possible for all remote models, or may have to be specifically configured. For example, using OpenAI's GPT-3, one can configure a request to return not just the sequence of tokens representing the model's maximum posterior, but a sequence of most likely options for each returned tokens, alongside their negative log-likelihood. This additional information about the model's prediction, which does not cause any additional cost, allows the straightforward implementation of a 2nd level supervisor. Alternatively, a black-box or data-box [45] supervisor (respectively, one with access to just the input/output of the remote model or also to the training data used to train the remote model) would have to be employed as 2nd level supervisor to select inputs that not even the remote model can handle. While this comes with yet another cost saving (the supervisor can run before the remote model, thus allowing to not collect remote predictions which will then be rejected), we do not recommend the use of such black- and data-box supervisors in this use case: They are likely to cause substantial additional load on the local resource-constrained platform, they typically do not detect aleatoric uncertainty caused by
ambiguity (Rasmal et al., 2017) and lastly, in the case of data-box supervision, they require access to the training data of the remote model, which is typically not available or to too large to be easily processed.

### Superaccurate Performance

The primary goal of our architecture is to allow a tradeoff between a cheap, low-accuracy model and an expensive, highly accurate remote model. As such, we expect the combined cost and accuracy to always lay between the ones of the local/remote model. However, for what regards accuracy, our architecture may - under specific circumstances - even lead to accuracies above the one of the remote model, while still leading to reduced cost. If the local and remote models' prediction capabilities are complementary (i.e., the set of inputs that the local model can correctly predict is not a subset of the inputs the remote model can predict), and the 1st level supervisor reliably trusts correct predictions by the local model, some inputs which would be incorrectly predicted by the remote model would be correctly predicted with our architecture. With large complementarities, this could substantially increase the overall system accuracy, at a reduced cost. We denote such improved overall system accuracy as _superaccurate performance_. However, aiming for complementarities between local and remote models might be infeasible, due to the constraints on the choice of models that can reasonably run on the local device: In this paper, the main goal is to achieve cost-reduction with as little accuracy decrease as possible. Thus, while we might occasionally observe superaccurate performance empirically, its occurrence is more a (nice to have) side effect than an explicit design goal.

### Threshold Selection for Supervisors

We strongly recommend the use of single-threshold supervisors in conjunction with BiSupervised. Such supervisors are based on a single confidence (or uncertainty12) score, and a configurable threshold. Inputs are trusted if and only if the confidence for said input is above a configurable threshold. Modifying the threshold allows to gradually change the proportion of untrusted/trusted inputs. In BiSupervised, a carefully tuned threshold in the 1st level supervisor thus allows the selection of the desired percentage of inputs for which a remote prediction is collected (thus defining the cost savings). Similarly, a carefully tuned threshold in the 2nd level supervisor allows to regulate the percentage of inputs for which the system refuses to make a prediction. Viewing the 2nd level supervisor as a misprediction detector, changing the threshold allows to trade-off false positives vs false negatives. Here, especially in domains which are not safety-critical, we can imagine that different users or different use-cases show varying degrees of risk-aversion. In a more risk-averse setting, the threshold can thus be tuned to allow more raised exceptions, possibly requiring manual intervention, while other use-cases may actually favor some mispredictions over downsides from a too frequently raised exception or too frequently called fallback (such as a decreased user experience due to overly frequent warnings).

Footnote 12: We consider confidence and uncertainty as perfect complements (Rasmal et al., 2017), and for what regards DNN supervision, one is easily converted into the other by applying any order-reversing transformation to the value (Rasmal et al., 2017)

Existing Techniques to Threshold Selection.Stocco et. al. (Stocco et al., 2017) propose to fit the distribution supervision scores of nominal, correctly classified validation set inputs (Stocco et al., 2017). This allows selecting a threshold with a specific false positive rate (i.e., expected percentage of false alarms), assuming that the distribution of inputs in production is the same as the one of the validation set. The big advantage of this approach is that no dataset of outliers is needed and a nominal validation set is sufficient to calculate the threshold. An alternative approach for threshold selection in test input validators was proposed by Dola et. al. (2021) (Dola et al., 2021). They propose to choose a threshold by calculating supervision scores for both a nominal and an invalid dataset and then choose a threshold
that separates these two distributions optimally. While they proposed these techniques for test data validations, it can clearly also be used for supervisors. However, here, it is worth noting that a realistic invalid dataset may not always be available. BiSupervised is agnostic to the way the threshold is set. We refer to Riccio et. al. (2023) (Ricio et al., 2023) for a more in-depth comparison of the two approaches discussed here.

Runtime Configuration of ThresholdBoth approaches described above consider the threshold a constant, which is defined before deployment. For BiSupervised, we suggest that in practice, a more dynamic way to set the threshold may be beneficial: Here, the threshold could be considered a configuration variable that can be changed or tuned in production, for example using remote information (Ricevic et al., 2023) or based specifically on the inputs observed on a specific user's local device. Such dynamic threshold selection allows to quickly adapt the supervisor behavior, for example in cases where the input distribution changes, where more or less conservative supervision is desired (e.g. due to a change of cost in remote predictions), or where users specify their preferences in their user settings. To account for this diversity in our paper, we evaluate our architecture using a range of different thresholds.

### Extensions of BiSupervised

BiSupervised allows for some extensions of its architecture and use, which go beyond the scope of this paper but are worth mentioning. First, edge nodes, where available, allow for an extension including a third supervised DNN on an edge node, with capabilities laying somewhere between the minimal local model and the huge remote model. As such, BiSupervised (which would effectively become TriSupervised), would invoke the model on the edge node if the local prediction cannot be trusted. Then, if also the edge model would face high uncertainty, the edge node could in turn forward the prediction to the remote model.

Second, we note that active learning could be easily integrated into BiSupervised: As the 1st level supervisor detects inputs for which the local model is (yet) insufficiently trained, collecting these inputs, labeling them (maybe even automatically using the remote model), and adding them to the local model's training set would allow for much more robust generation of the next local model: In our recent work (Ricio et al., 2023), we have shown that simple supervisors such as MaxSoftmax and MDSA, which we recommend in BiSupervised as 1st level supervisor, are also great techniques for such purpose. Consequently, such an active learning setup would essentially allow a continuous improvement of the local model, thus further reducing the share of remote predictions needed in future versions of the software using BiSupervised.

## 5. Empirical Evaluation of Bisupervised

Our empirical evaluation aims to answer the following research questions:

**RQ1: Cost Savings**: Using BiSupervised, can we reduce the number of remote predictions while only slightly impacting the overall prediction accuracy?
**RQ2: Supervision Performance**: Provided with a given percentage of inputs to be used in remote predictions, how does BiSupervised perform in terms of _supervised performance_(Ricio et al., 2023), compared to a standalone, supervised local model?

RQ1 is the main research question behind this work, as it aims at quantifying the trade off between cost saving and possibly reduced accuracy. This RQ ignores 2nd level supervision, as its focus is solely on the reduction of costly remote invocations, with no regard to the degree of confidence in the remotely produced prediction.

RQ2 aims at comparing the performance of a single local supervisor with that delivered by the two local/remote supervisors envisioned by BiSupervised. An ideal supervisor is one that blocks
all and only inputs on which the model would otherwise exhibit poor accuracy. With RQ2 we check whether the proposed architecture, in addition to reducing the remote execution costs, can also improve the supervision performance.

### Assessment Metrics for RQ1

All the supervisors used in our case studies work based on a single uncertainty score, which, if above a threshold, indicates that a prediction should not be trusted. We answer RQ1 in a threshold-agnostic way: Our results show the cost-accuracy tradeoff across all possible thresholds, i.e., for any chosen proportion of inputs for which a remote prediction is collected.

Requests-Accuracy-Curve.Changing the threshold of the 1st level supervisor allows a trade-off between the percentage of inputs forwarded for remote prediction (fewer means lower cost) and high system accuracy (associated with many remote predictions). We visualize our results for RQ1 using a plot that we call _Request-Accuracy-Curve_ where the \(x\) axis shows the percentage of inputs forwarded to the remote model and the \(y\) axis shows the overall system accuracy (ignoring 2nd level supervision). The curve thus allows to quickly read cost savings and accuracy change when using our architecture with a specifically chosen 1st level supervisor threshold. We will furthermore annotate selected points (e.g. knee points and superaccurate performances, if present) with the corresponding values, for even better readability of the plot.

Area Under Curve and Random Baseline.The Request-Accuracy-Curve allows to visually compare against the random baseline, which is a straight line between the performance using all-local or all-remote predictions: If successful, the curve produced by our architecture should be mostly above this line. To quantitatively compare the random baseline against BiSupervised we measure the _area under the curve of the Request-Accuracy-Curve_ (AUC-RAC). Specifically, we take the mean of all accuracies when setting the threshold to the value of each input, and normalize it on the accuracies observed for remote-only and local-only predictions. Let \(\text{ACC}_{\text{SYS}}(r)\) denote the system performance for a given system and test set when a proportion of \(r\in[0,1]\) of all inputs are forwarded to the remote model (thus, \(r\) is a point in the \(x\) axis on the Request-Accuracy-Curve) and let \(n\) denote the number of inputs in the test set. The AUC-RAC is then formally defined as:

\[\frac{\frac{1}{n}\sum_{i=0}^{n}\text{ACC}_{\text{SYS}}(\frac{i}{n})-\text{ ACC}_{\text{SYS}}(0)}{\text{ACC}_{\text{SYS}}(1)-\text{ACC}_{\text{SYS}}(0)} \tag{1}\]

This assumes that the remote model exhibits a higher accuracy than the local model, i.e., \(\text{ACC}_{\text{SYS}}(1)>\text{ACC}_{\text{SYS}}(0)\), which is a prerequisite for our experiments. The expected AUC-RAC from random supervision is 0.5. Note that, contrary to other AUCs, such as AUC-ROC, the proposed AUC-RAC can be below 0 in case of very bad supervision, or above 1 in case of very large superaccurate performance, due to normalization. Both of these are edge cases we do not expect to see frequently.

### Assessment Metrics for RQ2

RQ2 considers the performance of BiSupervised in a supervised setting, i.e., including both supervisors to identify inputs for which neither local nor remote predictions can be trusted. To compare our architecture against a supervised local model, we use the following three metrics which we proposed and designed specifically to compare pairs of different supervised models:

* _Supervised Accuracy_ (\(\overline{ACC}\)): The accuracy considering only the trusted predictions. Higher is better. Typically, the more conservative a supervisor, the higher \(\overline{ACC}\).
* _Acceptance Rate_ (\(\Delta\)): The percentage of trusted inputs. Higher is better. Typically, the more conservative a supervisor, the lower \(\Delta\).
* _S-Beta Score_ (\(S_{\beta}\)). The geometric mean between (normalized) supervised accuracy and acceptance rate. \(\beta\) is the weight parameter in the geometric mean. We will assess \(S_{0.5}\), \(S_{1}\), \(S_{2}\).

We provide a detailed explanation of these metrics in Weiss and Tonella (2018).

Threshold SelectionThus, for RQ2, we need to choose thresholds for both the 1st and 2nd level supervisor. For what regards the former, we use meaningful knee points identified in RQ1. For what regards the latter, in line with related literature (Beng et al., 2018; Wang et al., 2018; Wang et al., 2018), we choose a threshold such that a targeted (overall) false positive rate (FPR) is reached. Specifically, for each of the previously identified knee points, we will conduct three separate evaluations, in which we will tune the second-level supervisor's threshold such that FPRs of 0.01, 0.05, and 0.1 are met, respectively. As a baseline, we will assess the supervised performance of a system consisting of only the local model and supervisor using again thresholds chosen to lead to the same FPRs. This also reflects our targeted use case where thresholds are runtime-tunable parameters, allowing them to be fine-tuned and adjusted as inputs (and shifts of inputs) are observed after deployment, while still allowing for a fair comparison with the baseline.

### Case Studies

We evaluate our architecture on four case studies. They were chosen to reflect diverse problem types (text classification, image classification, and question answering) and to allow the inclusion of various different architectures as local and remote models. An overview of the case studies is provided in Table 1, and they are described below. For implementation details, such as used hyperparameters and exact data pre-processing, we refer to our replication package, described in section 8.

#### 5.3.1. IMDB Sentiment Classification (Text Classification)

The IMDB sentiment classification benchmark (Zhu et al., 2017) is a common case study for NLP classification approaches. Given an English-language movie review, a classifier is to decide whether the rating by the user is positive or negative. We use the following components for our architecture:

* **Local Model:** For input domain reduction, we trim inputs to consist only of the first 100 words and use a small dictionary of only the 2000 most frequent words. We use a small model,

\begin{table}
\begin{tabular}{l l l l l l l} \hline \hline Name & Domain & & Architecture & \#Params & Metric & Value \\ \hline imdb & Text Class. & Local Remote & Custom & 79K & \multirow{2}{*}{Accuracy} & 79.4\% \\  & & Local Remote & GPT-3-curie (Beng et al., 2018) & 13B \({}^{*}\) & & 89.5\% \\ issues & Text Class. & Local Remote & Custom & 223K & \multirow{2}{*}{Micro Avg. F1} & 71.1\% \\  & & Local Remote & CatIss (Kal
consisting of one transformer block, a pooling, and two dense layers. For regularization, dropout layers have been added before the dense layers. The resulting local model has 78'558 parameters.
* **1st level supervisor:** As our local model is a softmax-based classifier, we can use vanilla softmax as the 1st-level supervisor.
* **Remote Model:** As remote model, we use a few-shot learning approach on the _curie_ model of the GPT-3 [2] family. With its estimated 13 billion parameters, it is more than 160'000 times larger than our local model. We use a simple prompt, shown in Listing 1. This leads to an accuracy of 89.5%, which is more than 9% better than our local model.
* **2nd Level Supervisor:** Any valid response to our prompt consists of only one additional token. We configured our remote request to provide us with a list of 100 most likely tokens with their corresponding negative log-likelihood (easily transformable into likelihoods). We sum up the likelihood for known, hard-coded equivalent tokens (e.g. _"Negative"_, _"negative"_ and _"bad"_). This total likelihood is then used to determine whether or not the supervisor should reject the input.

We used the IMDB case study in a pilot experiment [61], presented at the ESEC/FSE student research competition 2022. While showing encouraging results, motivating the writing of this paper, that pilot experiment answers only parts of RQ1, and considers a simpler architecture (not including a 2nd level supervisor), hence also not addressing RQ2.

```
Pleaseclassifythefollowingmoviereviewsintothefollowingsentiments:Negative,Positive. --- Text:IhatethismovieLabel:Negative--- Text:IhikethismovieLabel:Positive--- Text:<thereviewwewwanttoclassify> Label:
```

Listing 1: Few-shot GPT-3Promptfor IMDB case study.

#### 5.3.2. Github Issue Classifier (Text Classification)

The Github Issue Classifier reflects a real-world use case: As new issues are reported to a github repository, maintainers typically triage the issues (are they a question, a bug report, an improvement request, etc.). TicketTagger[25] is an open source bot performing such triage by automatically labeling each input. Run in a CI/CD environment, the "local environment" for such automated triager is typically quite resource-constraint. Recently, Kallis et al.[24] released a corresponding benchmark dataset as part of the NLBSE'22 tool competition: Given a few attributes of Github issues, amongst which title and description, issues have to be classified into one of the classes _[bug, enhancement, question]_. The dataset is unbalanced, heterogeneous (e.g., it contains outliers such as non-English issues), and contains some truly ambiguous inputs (i.e., issues for which the ground truth is not certain even to an experienced developer). This makes this case study a particularly well-motivated setting for RQ2, as unclear inputs should better remain unclassified and handled by a repository maintainer performing manual triaging. Upon adopting BiSupervised, TicketTagger could assign a fallback label _"manual triage required"_ to inputs rejected by both supervisors.

To measure the model and system performance of this case study, we use a micro-average F1-score, which takes into account the class imbalance in this case study, as described in the tool competition [24]. We then use the following components for our architecture:
* **Local Model:** We use a similar transformer-based classifier as for IMDB, using the same type of layers, but with hyperparameters chosen to take the higher complexity of the problem into account (e.g., the hidden dense layer contains of 100 instead of 20 nodes) and with an increased dictionary size of 2000. As input we use the issue description concatenated to the issue title, truncated to the first 200 words.
* **Remote Model:** As remote model, we use CatIss, the winning model of the NLBSE'22 tool competition [21]. It is based on a finetuned Roberta model [36]. As far as we know, this is the best available model for the issue classification dataset. We expect that by fine-tuning even larger Roberta instances, one may further improve the overall performance.
* **1st and 2nd level supervisor:** We use vanilla softmax as 1st and 2nd level supervisors.

#### 5.3.3. Imagenet (Image Classification)

Imagenet [47] is one of the most widely used image classification benchmarks in the literature. Its images represent 1000 different classes, some of which very closely related to each other (e.g. 119 breeds of dogs [11]). As such, it represents a challenging machine learning problem, where even large-scale state of the art models do not yet achieve accuracies above 91% [70]. Provided that a wide range of Imagenet models are available through standard model repositories, and that such models are typically DNNs with a softmax output layer, choosing the components for our architecture is not difficult:

* **Local Model:** We use MobilenetV3 [18] as local model. MobilenetV3 is the third and latest generation Mobilenet Imagenet model which is specifically designed to work in resource constrained environemnts. Various versions (differing in size) of MobilenetV3 exist. We use'mobilenetv3_small_1.0_224', i.e., the model with 2.9 million parameters and an accuracy of 67.8%1 Footnote 13: See [https://www.tensorflow.org/api_docs/python/tf/keras/applications/MobileNetV3Small](https://www.tensorflow.org/api_docs/python/tf/keras/applications/MobileNetV3Small)
* **Remote Model:** We use EfficientNetV2L [57] as large-scale remote model. With its 119 million parameters and an accuracy of 85.2, it is the third-largest and most accurate Imagenet classifier available from Keras applications14. Footnote 14: [https://keras.io/api/applications/](https://keras.io/api/applications/), as of July 31st, 2022
* **1st and 2nd level supervisor:** We use vanilla softmax as 1st and 2nd level supervisor.

#### 5.3.4. The Stanford Question Answering Dataset (Free-Text Question Answering)

Our fourth case study considers _question answering_, specifically the 2nd version of the _The Stanford Question Answering Dataset_ (SQuADv2)_[44]. Faced with a title and paragraph of English-language Wikipedia, and a list of questions about the said paragraph, a model is supposed to provide a short answer, consisting of substrings of the paragraph (thus essentially free text), to each of the questions. SQuADv2 provides a set of correct answers for each question. For example, the question _"What century did the Normans first gain their separate identity?"_ lists _"10th century"_, _"the first half of the 10th century"_ and _"10th"_ as correct answers.15 We use the _Exact Match (EM)_[44] metric to assess the performance of our models and architecture, i.e., the percentage of predictions that exactly match one of the answers in the SQuADv2 ground truth answers. In addition to the questions described above, SQuADv2 also contains _unanswerable_ questions, i.e. questions for which the answer cannot be found in the provided paragraph. They are ideal to test the models in a supervised setting. We ignore these unanswerable questions for RQ1 (which explicitly does not assess the 2nd level supervisor) but include them for RQ2 where they should be detected by the 2nd level supervisor. Here, it is worth mentioning that much related literature using SQuADv2 considers an unanswerable input as correctly answered if the models' uncertainty is above the threshold (i.e., if
the input is detected as unanswerable by the supervisor). We argue that this is not a realistic setting in practice (a refused prediction is certainly not equivalent to a correct one). Our assessment of RQ1 (EM only on answerable questions) and RQ2 (\(\overline{ACC}\), \(\Delta\) and \(S_{\beta}\)) are better suited. However, for this reason, the accuracies we find in RQ1, and the supervised accuracies we find in RQ2 are not consistent with the ones mentioned in the related literature for the same models.

* **Local Model:*
* We use a fine-tuned version of Bert-Tiny [58], a miniature version of the popular _Bidirectional Encoder Representations from Transformers_ (BERT) model [9], well suited for deployment in resource-constrained environments. Fine-tuning to the SQuADv2 dataset has been performed by the Huggingface team16. Footnote 16: [https://huggingface.co/mrm8488/bert-tiny-5-finetuned-squadv2](https://huggingface.co/mrm8488/bert-tiny-5-finetuned-squadv2)
* **1st level supervisor:*
* Alongside the predicted tokens representing our local model answer, we collect an uncertainty score for each predicted token. We consider multiple ways suitable to reduce these scores into a single one, which can be used for threshold-based supervision, with the product and the minimum being the most obvious candidates. Indeed, we find that the literature mostly uses the product of these uncertainties. We do not consider this ideal for supervision: Given the very large amount of tokens, predicted probabilities, even for the simplest of inputs are likely to be much lower than one, which would naturally make the overall confidence in answers consisting of multiple tokens exponentially smaller than the confidence in single token predictions. Thus, for our experiments, we use the _minimum_ of all predicted likelihoods of all predicted tokens.
* **Remote Model:** As remote model, we use a one-shot learning approach on the _davinci_ model of the GPT-3 [2] family. With its 165 billion parameters, it is the largest model in the GPT-3 family and thus often understood as _the_ GPT-3 model. Upon its first publication, the authors of GPT-3 assessed the model on the SQuADv2 dataset, where it showed good performance, in particular considering the one-shot (not fine-tuned) setting. We build our prompt equivalent to the one built when assessing GPT-3. In short, the prompt is initiated with the title, followed by the paragraph and a single, answerable question with the correct answer (which is consequently removed from the test set) and finally the question for which we assess the answering capability (see example prompt in Figure G.28 of Brown et al. [2]).
* **2nd level supervisor:** As explained in the IMDB case study, we can configure our requests to GPT-3 to collect a likelihood for every predicted token. We can then continue equivalently to the 1st level supervisor to reduce this array of likelihoods into a single confidence score, allowing threshold-based supervision.

For the Github issue classification and Imagenet case studies, we run the remote models on our highly-performing workstation used for our experimentation, as in our setting we can afford the required hardware, which is not the case in most client-based applications for which we propose BiSupervised.

### Results

#### 5.4.1. Changes to Evaluation Setup

The evaluation setup described above was peer-reviewed as a registered report before results were collected17. The experiments have been conducted as anticipated, with the exception of the following two minor deviations:

Footnote 17: [https://dl.acm.org/journal/tosem/registered-papers](https://dl.acm.org/journal/tosem/registered-papers)

1. **Imdb Remote Supervisor:** We planned to use the sum of the likelihoods of equivalent tokens (e.g. _"negative"_, _"Negative"_ and _"bad"_) amongst the **100** most likely tokens. However, the OpenAI API restricts this information to the **5** most likely tokens18 - which we thus use
for our experiments. In general, we observe that subsequent equivalent tokens, in general, have a very low likelihood assigned. This is expected, as our prompt (see Listing 1) suggests a specific spelling. Thus, we do not expect that the here-described change has any notable influence on the results.
2. **SQuADv2 Prompt:** We anticipated using the same prompt as the authors of the original paper proposing GPT-3 when conducting their SQuADv2 assessment (see example prompt in Figure G.28 of Brown et al. [2]). During development, we found that using this prompt, GPT-3 would often give verbose, full-sentence answers. As such answers are not part of the SQuADv2 answer dataset, this could have led to a misrepresentative low EM (exact match) metric. We thus extended the prompt stating explicitly that answers should be an "_extraction from background, as short as possible_". Here, background refers to the context given in the prompt, in line with the originally anticipated prompt. This obvious fix is one which realistically any practitioner would have done and we thus decided to include it. As GPT-3 is a closed source model, with unknown prompt-preprocessing, we do not know if the problem we observed was already present when Brown et. al. [2] conducted their experiments. Given their decent results, we assume that the verbose sentences GPT-3 we observed when re-using their prompt might be caused by deliberate recent changes to the GPT-3 service (in most use-cases, verbose answers might be perceived as better), as otherwise, we would have expected Brown et. al. [2] to adapt their prompt in a similar fashion as we did. While it is unclear what effect this change has on our results, it is likely that our changes actually lead to a stronger baseline for BiSupervised and overall a more ambitious experimental setup: With the anticipated higher EM of the standalone remote model, outperforming or performing similarly well - as measured in RQ1 - becomes a more challenging task.

#### 5.4.2 Results for RQ1: Cost Savings.

_Imdb._ The RAC for the Imdb case study is presented in Figure 2. It shows a mild superaccurate performance: At 68% remote requests, the system-level accuracy (ignoring the 2nd-level supervisor) reaches its peak, which is mildly better than if only remote predictions are made. With 55% remote requests, thus at 45% remote prediction cost savings, BiSupervised achieves the same system-level performance as if only the remote model was used.

Figure 2. Request-Accuracy Curve (RAC) for Imdb
_Github Issue Classification._ The RAC for the GitHub Issue Classification case study is presented in Figure 3. Here, BiSupervised allows to save a large part of remote-prediction costs while maintaining a system-level F1 similar to the one observed on the standalone remote model: With any threshold leading to at least 60% remote predictions, the system-level F1 remains practically constant. BiSupervised thus allows saving 40% remote prediction cost at essentially no negative impact on the system level F1. Overall, the AUC-RAC of the plot is 0.775, thus clearly outperforming the random baseline (expected AUC-RAC 0.5).

_Imagenet._ The RAC for the Imagenet case study, presented in Figure 4 is similar to the one for the Github Issue Case study. While there is no notable superaccurate performance, we observe again that BiSupervised allows saving 40% remote prediction cost at essentially no negative impact on the system level accuracy. At the same time, the steep increase of the RAC for small percentages of remote predictions highlights the potential BiSupervised has for applications that currently use MobilenetV3 (the production-ready mobile-friendly model we use as a local model): With just a low percentage of predictions to a larger model (which may be placed on the edge or a remote server), the system-level accuracy is easily improved.

Figure 4: Request-Accuracy Curve (RAC) for Imagenet

Figure 5: Request-Accuracy Curves (RAC) for SQuADv2 dataset. BiSupervised achieves superaccurate performances for both a clean dataset consisting of only valid (i.e., answerable) questions and for the full dataset.

Figure 3: Request-Accuracy Curve (RAC) for Issues
_SQuADv2_. As anticipated in the empirical setup, for what regards RQ1, the SQuADv2 dataset _without_ invalid inputs is of primary interest. The corresponding RAC is shown in Figure 4(a). Clearly, BiSupervised shows large superaccurate performance: At its peak, it achieves an EM of 0.722, which is more than.02 better than the standalone remote model (0.695). At that point, only 59% remote predictions are needed, thus also saving 41% of remote prediction cost. At only 38% of the cost, BiSupervised achieves the same performance as the standalone remote model, clearly achieving the goal of cost savings. Overall, BiSupervised achieves an AUC-RAC of 1.021. For completeness, we also calculated the RAC for the full SQuADv2 dataset, including all invalid questions, shown in Figure 4(b). While these results are slightly inferior compared to the ones without invalid inputs, the plot still shows superaccurate performance.

Summary of RQ1 (Cost-Saving)

The results clearly show BiSupervised's capability to save prediction cost while maintaining high accuracy:

For two case studies, superaccurate performances were achieved, i.e., BiSupervised allows to get a better system-level prediction accuracy, at a much lower cost, compared to using only the large-scale remote model, or equivalent performance for 38% or 55% of the remote prediction cost, respectively. In the other two case studies, where the models showed fewer complementarities, BiSupervised allowed saving roughly 40% of remote prediction cost (dependent on the case study) while still achieving comparable system-level performance.

In all case studies, BiSupervised achieved an AUC-RAC substantially above the one associated with a random baseline.

#### 5.4.3. Results for RQ2: Supervision Performance

The results for RQ2 are presented in Tables 2, 3, 4, 5 and 6. The RACs observed in RQ1 are smooth, which benefits our evaluation of RQ2 as the exact choice of 1st level supervisor becomes less critical: Small deviations in the threshold, i.e., in the percentage of inputs for which a remote prediction is made, do not have a major influence in the observed results. This allows us to choose thresholds for the 1st level supervisor for our evaluation of RQ2 in a generic way:

* For case studies where we observe superaccurate performance (Imdb and SQuADv2) we use the thresholds leading to the highest performance, as well as the threshold corresponding to as few as possible remote predictions, leading to an overall performance equivalent to the one of the standalone remote model (denoted _remote-even_).
* For case studies without superaccurate performance (Issue Classification and Imagenet) we choose thresholds for the 1st level supervisor corresponding to 30%, 50%, and 70% remote predictions, which gives a good coverage of the observed curves, by considering both a point (30%) with clearly reduced accuracy and one (70%) with comparable overall accuracy, compared to a standalone remote model.

_Imdb Case Study._ The results for the Imdb base study are shown in Table 2. For all targeted false positive rates (FPR) and all tested local thresholds, i.e., for both the threshold leading to a remote-even system-level and best accuracy in RQ1, respectively, BiSupervised clearly outperforms the local baseline. The system-level acceptance rate (\(\Delta\)) is comparable to the local baseline in all cases, but the supervised accuracy (\(\overline{obj}\)) improves up to 11% when using BiSupervised. Thus, for all weightings of \(\Delta\) and \(\overline{obj}\), their arithmetic mean, i.e., \(S_{\beta}\) also outperforms the baseline.
_Github Issues and Imagenet Case Studies_. Same as for RQ1, the Github Issue and Imagenet case study show very similar results for RQ2 - presented in Tables 3 and 4 respectively. For all tested thresholds and different \(\beta\) in \(S_{\beta}\), BiSupervised clearly outperforms the baseline. Compared to a standalone supervised local model, the use of the remote model in BiSupervised not only improves the system-level supervised accuracy \(\overline{obj}\), but in most cases it leads also to a higher system-level acceptance rate \(\Delta\).

_SQuADv2 Case Study._ Considering only SQuADv2's valid answers (Table 5), the results show a similar picture as for the Imdb case study in that BiSupervised consistently and clearly outperforms the baseline. The picture is less clear, however, for the case which regards all inputs, i.e., including invalid inputs for which it is impossible for any model to give a correct answer. Here, for 63% of the inputs, neither the local nor the remote model was able to make a correct prediction. The supervised performance of BiSupervised then depends on the targeted FPR: With a low FPR

\begin{table}
\begin{tabular}{l l c c c c c c} \hline \hline  & & remote \(\Delta\) & \(\Delta\) & \(\overline{obj}\) & \(S_{0.5}\) & \(S_{1}\) & \(S_{2}\) \\ \cline{2-9} FPR & remote requests & & & & & & \\ \hline \multirow{3}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.98 & 0.80 & 0.83 & 0.88 & 0.94 \\  & 0.55 (remote-even) & 0.96 & 0.98 & 0.91 & 0.92 & 0.94 & 0.96 \\  & 0.68 (best) & 0.97 & 0.98 & 0.91 & 0.92 & 0.94 & 0.96 \\ \hline \multirow{3}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.93 & 0.82 & 0.83 & 0.87 & 0.90 \\  & 0.55 (remote-even) & 0.86 & 0.92 & 0.92 & 0.92 & 0.92 & 0.92 \\  & 0.68 (best) & 0.88 & 0.92 & 0.93 & 0.93 & 0.92 & 0.92 \\ \hline \multirow{3}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.86 & 0.83 & 0.83 & 0.85 & 0.86 \\  & 0.55 (remote-even) & 0.76 & 0.87 & 0.93 & 0.91 & 0.90 & 0.88 \\ \cline{1-1}  & 0.68 (best) & 0.8 & 0.87 & 0.94 & 0.92 & 0.90 & 0.88 \\ \hline \hline \end{tabular}
\end{table}
Table 2. System-Level Supervised Assessment for imdb

\begin{table}
\begin{tabular}{l l c c c c c c} \hline \hline  & & remote \(\Delta\) & \(\Delta\) & \(\overline{obj}\) & \(S_{0.5}\) & \(S_{1}\) & \(S_{2}\) \\ \cline{2-9} FPR & remote requests & & & & & \\ \hline \multirow{3}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.98 & 0.72 & 0.76 & 0.83 & 0.91 \\  & 0.30 & 0.94 & 0.98 & 0.80 & 0.83 & 0.88 & 0.94 \\  & 0.50 & 0.96 & 0.98 & 0.82 & 0.85 & 0.89 & 0.94 \\  & 0.70 & 0.97 & 0.98 & 0.83 & 0.86 & 0.90 & 0.95 \\ \hline \multirow{3}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.91 & 0.74 & 0.77 & 0.82 & 0.87 \\  & 0.30 & 0.75 & 0.92 & 0.82 & 0.84 & 0.87 & 0.90 \\  & 0.50 & 0.84 & 0.92 & 0.84 & 0.86 & 0.88 & 0.90 \\  & 0.70 & 0.88 & 0.92 & 0.86 & 0.87 & 0.89 & 0.91 \\ \hline \multirow{3}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.84 & 0.77 & 0.78 & 0.80 & 0.83 \\  & 0.30 & 0.55 & 0.86 & 0.82 & 0.83 & 0.84 & 0.86 \\ \cline{1-1}  & 0.50 & 0.71 & 0.85 & 0.86 & 0.86 & 0.86 & 0.86 \\ \cline{1-1}  & 0.70 & 0.79 & 0.85 & 0.88 & 0.87 & 0.87 & 0.86 \\ \hline \hline \end{tabular}
\end{table}
Table 3. System-Level Supervised Assessment for Issues
of 0.01, BiSupervised still outperforms the local baseline as it succeeds in maintaining a higher acceptance rate \(\Delta\) with similar or even mildly better system-level accuracy as the standalone local model. However, as we increase the targeted FPR, especially with an FPR of 0.1, the supervised accuracy using BiSupervised improves less than it does for the local model while maintaining a much higher system-level acceptance rate \(\Delta\). Presumably, this is caused by the fact that we achieve a given target FPR by manipulating only the remote supervisor's threshold while keeping the 1st level supervisor's threshold constant: As such, we remove some correct remote predictions (quickly reaching the targeted FPR), while the wrong but accepted local predictions negatively impact \(\overline{obj}\). Thus, in this case study, which of the approaches performs better in a supervised setting depends on the risk-adverseness of the user, i.e., the \(\beta\) chosen in \(S_{\beta}\): While BiSupervised, in the configuration tested by us, for FPR 0.1, outperforms the baseline for \(S_{2}\), it fails to beat the baseline for \(S_{0.5}\). Overall, SQuADv2 (including invalid inputs) is the only case study with results that are not conclusively

\begin{table}
\begin{tabular}{l l c c c c c c} \hline \hline  & & remote \(\Delta\) & \(\Delta\) & \(\overline{obj}\) & \(S_{0.5}\) & \(S_{1}\) & \(S_{2}\) \\ FPR & remote requests & & & & & & \\ \hline \multirow{4}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.96 & 0.70 & 0.74 & 0.81 & 0.89 \\  & 0.30 & 0.93 & 0.98 & 0.81 & 0.84 & 0.89 & 0.94 \\  & 0.50 & 0.96 & 0.98 & 0.85 & 0.87 & 0.91 & 0.95 \\  & 0.70 & 0.97 & 0.98 & 0.86 & 0.88 & 0.92 & 0.95 \\ \hline \multirow{4}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.86 & 0.75 & 0.77 & 0.80 & 0.84 \\  & 0.30 & 0.73 & 0.92 & 0.83 & 0.85 & 0.87 & 0.90 \\  & 0.50 & 0.84 & 0.92 & 0.87 & 0.88 & 0.89 & 0.91 \\  & 0.70 & 0.89 & 0.92 & 0.87 & 0.88 & 0.90 & 0.91 \\ \hline \multirow{4}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.77 & 0.79 & 0.79 & 0.78 & 0.78 \\  & 0.30 & 0.53 & 0.86 & 0.84 & 0.84 & 0.85 & 0.86 \\ \cline{1-1}  & 0.50 & 0.69 & 0.85 & 0.89 & 0.88 & 0.87 & 0.85 \\ \cline{1-1}  & 0.70 & 0.78 & 0.85 & 0.90 & 0.89 & 0.87 & 0.86 \\ \hline \hline \end{tabular}
\end{table}
Table 4. System-Level Supervised Assessment for ImageNet

\begin{table}
\begin{tabular}{l l c c c c c c} \hline \hline  & & remote \(\Delta\) & \(\Delta\) & \(\overline{obj}\) & \(S_{0.5}\) & \(S_{1}\) & \(S_{2}\) \\ FPR & remote requests & & & & & \\ \hline \multirow{4}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.97 & 0.64 & 0.69 & 0.77 & 0.88 \\  & 0.33 (remote-even) & 0.94 & 0.98 & 0.70 & 0.74 & 0.82 & 0.91 \\  & 0.58 (best) & 0.96 & 0.98 & 0.73 & 0.77 & 0.84 & 0.92 \\ \hline \multirow{4}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.90 & 0.67 & 0.70 & 0.77 & 0.84 \\  & 0.33 (remote-even) & 0.79 & 0.93 & 0.71 & 0.75 & 0.81 & 0.88 \\  & 0.58 (best) & 0.87 & 0.93 & 0.74 & 0.77 & 0.82 & 0.88 \\ \hline \multirow{4}{*}{\(\overline{obj}\)} & 0.00 (baseline) & n/a & 0.81 & 0.70 & 0.72 & 0.75 & 0.79 \\  & 0.33 (remote-even) & 0.62 & 0.87 & 0.72 & 0.74 & 0.79 & 0.84 \\ \cline{1-1}  & 0.58 (best) & 0.78 & 0.87 & 0.75 & 0.77 & 0.80 & 0.84 \\ \hline \hline \end{tabular}
\end{table}
Table 5. System-Level Supervised Assessment for SQuADv2 (possible only)
in favor of BiSupervised, while still showing a positive tendency: Out of 18 assessed settings (target FPR, \(S_{\beta}\) and 1st level supervisor threshold), BiSupervised shows a result outperforming the baseline in 13 cases; it has inferior \(S_{\beta}\) scores in 5 cases.

### Threats

_Internal validity threats:_ Two case studies, namely IMDB and SQuADv2, use GPT-3 as remote model, which was trained on a large (unknown) set of texts collected using web crawling. It is possible that these texts may contain entries from our test set (this is sometimes called _test set pollution_). First, we deem this unlikely and not different from a realistic usage of a large-scale remote model such as GPT-3. Thus, it is not expected to impact the validity of our result w.r.t. a real-world usage of BiSupervised. Second, for SQuADv2, on which GPT-3 was originally assessed, the authors measured the impact of test set pollution and found it to not have any major influence on the observed capabilities (Bauer et al., 2017).

Motivated by our use case, in particular the possibility of runtime adaptive configuration of supervisor thresholds, we did not choose the thresholds for our evaluation before running the experiments. In RQ1, we perform a threshold-independent analysis (AUC-RAC) _and_ we also plot the curves. Smooth curves indicate that the selection of a threshold in practice is easy (no extreme local optima). Indeed, the curves we observed in RQ1 show no big fluctuations and are comparably smooth. Regarding RQ2, where a threshold independent metric is not possible, we chose a wide range of different thresholds for both supervisors, based on the findings of RQ1, and fixed FPR for the 2nd level supervisor. The likelihood that a majority of them would end up in small local optima (which would invalidate our results) is thus negligible.

\begin{table}
\begin{tabular}{l l c c c c c c} \hline \hline  & & remote \(\Delta\) & \(\Delta\) & \(\overline{obj}\) & \(S_{0.5}\) & \(S_{1}\) & \(S_{2}\) \\ FPR & remote requests & & & & & & \\ \hline \multirow{3}{*}{\(\overline{\text{FPR}}\)} & 0.00 (baseline) & n/a & 0.89 & 0.31 & 0.36 & 0.46 & 0.65 \\  & 0.51 (remote-even) & 0.93 & 0.96 & 0.32 & 0.37 & 0.48 & 0.68 \\  & 0.72 (best) & 0.94 & 0.96 & 0.33 & 0.38 & 0.49 & 0.69 \\ \hline \multirow{3}{*}{\(\overline{\text{FPR}}\)} & 0.00 (baseline) & n/a & 0.76 & 0.35 & 0.39 & 0.48 & 0.61 \\  & 0.51 (remote-even) & 0.79 & 0.89 & 0.33 & 0.38 & 0.48 & 0.66 \\  & 0.72 (best) & 0.86 & 0.90 & 0.34 & 0.39 & 0.49 & 0.68 \\ \hline \multirow{3}{*}{\(\overline{\text{FPR}}\)} & 0.00 (baseline) & n/a & 0.65 & 0.39 & 0.42 & 0.49 & 0.57 \\  & 0.51 (remote-even) & 0.62 & 0.81 & 0.34 & 0.39 & 0.48 & 0.64 \\ \cline{1-1}  & 0.72 (best) & 0.78 & 0.84 & 0.34 & 0.39 & 0.49 & 0.65 \\ \hline \hline \end{tabular}
\end{table}
Table 6. System-Level Supervised Assessment for SQuADv2 (all)
_Construct validity threats_: Quantification of the cost-accuracy trade off and of the supervisors' performance is not straightforward and no consolidated metrics exist for such task. We defined the AUC-RAC metric for the former quantification, as it provides a threshold independent quantification suitable for visual display as a request-accuracy-curve that can be easily interpreted by humans. For the latter we adopted the S-Beta score, as proposed in recent work about supervisor assessment (Wang et al., 2019).

_External validity threats_: We considered only four case studies. To choose models representative of a variety of application domains, we included models designed for text classification, image classification and question answering. However, the validity of our findings beyond the considered case studies should be assessed empirically by replicating our study on different domains/models.

### Advantages beyond Cost Savings

Besides the cost savings achieved by our architecture, making fewer remote predictions has a range of other advantages. Those are however very dependent on the used infrastructure, and we thus discuss them conceptually instead of empirically.

_Lower Latency_. Latency of distributed systems, such as our architecture, depends on many factors such as network speed, bandwidth, used hardware, and system load. We can reasonably assume that requests over a network are time-wise quite costly and that large-scale DNNs take more time to make a prediction than small-scale DNNs. While the latter can, to some extent, be mitigated by using very fast hardware for the large-scale model, the former is an unavoidable truth using today's networks. In an abstract model of latency in BiSupervised, let \(t_{l}\) be the average time required to locally preprocess the input, make a prediction on the local model and run the first-level supervisor. Similarly let \(t_{r}\) denote the average time required to make a remote prediction (including time for network communication, and supervision of the remote prediction). Let \(r\) be the rate of inputs for which BiSupervised triggers a remote prediction. BiSupervised then shows, on average, lower latency if

\[t_{r}>t_{l}+rt_{r} \tag{2}\]

This is true whenever \((1-r)t_{r}>t_{l}\).

We measure the latencies induced from using local and remote models, which allows us to quantify potential latency improvements from using BiSupervised over using the remote model. All measurements include all required computation, including data preprocessing, inference, supervision, and network requests, where applicable. To collect our results, we used a workstation equipped with an AMD Ryzen Threadripper 1920X CPU and a wired internet connection. No GPU was used. Clearly, the measured times highly depend on this configuration, as well as additional influences such as remote server load. Thus, our reported times should be seen as an illustration, without a claim of generalizability. Here it is worth noting that, while we present the time measurements for all case studies, they are most meaningful for the Imdb and SQuADv2 case studies, which use a truly remote model accessed through the OpenAI API. For Github Issue classification and Imagenet, the large scale "remote" model was emulated locally, thus leading to no networking overhead, but also not leveraging dedicated hardware. We still report the latter results for completeness.

For all case studies, our measurements confirm the huge potential BiSupervised shows with regards to latency: With a 1st-level supervisor configured such that less than 85% of requests are forwarded to the remote model, the average latency is lower than the baseline which uses only a remote model, thus fully compensating the additional overhead induced by the local inference and supervision. For Imagenet and SQuADv2 case studies, this break-even point lays even above 96%. Consequently, all evaluation points we discussed in RQ1 and RQ2 would reduce average latency in practice. Thus, BiSupervised not only saves cost, but it also reduces the average inference time,
all while increasing robustness in a supervised setting and keeping the same accuracy or, in some cases, even increasing the system level accuracy.

Lower Energy Consumption.Large models, naturally, require more energy to make predictions than small models, due to the substantially higher number of arithmetic operations to perform to make a single prediction. In addition, sending the request to a remote server also causes an energy consumption overhead. Thus, similar to the latency discussed above, we can expect the small overhead introduced by making a local inference and 1st level supervision (which are designed to be energy efficient), to be amortized by the lower number of remote requests even with a relatively low fraction of exclusively-local predictions.

## 6. Future Work

At the moment, BiSupervised assumes that for all inputs where the local prediction is highly uncertain, the remote architecture potentially has a lower uncertainty. However, this may not always be the case: In some domains, _aleatoric uncertainty_, i.e., the uncertainty inherent in the input for which a prediction has to be made (such as noise or ambiguity) is a major cause of wrong predictions (Krishnan et al., 2017). Here, we notice that only in cases where the local model exhibits _epistemic uncertainty_, such as uncertainty caused by insufficient training data or model architecture, forwarding the input to a much larger, thus presumably more capable DNN is justified. For future work, we thus propose to attempt to discriminate between aleatoric and epistemic uncertainty in the local supervisor and only make remote predictions for inputs that show a high level of epistemic uncertainty, as opposed to a high level of general uncertainty.

We conducted our experiments under nominal data, i.e., data that is mostly in-distribution of the training datasets. Reproduction of our results using outlier data to assess BiSupervised is needed to assess its robustness.

\begin{table}
\begin{tabular}{c c c c c c} \hline \hline Case Study & Local & Remote & Break Even & Eval Points (vs. Remote Only) & Remarks \\ \hline imdb & 0.05s & 0.32s & 85.68\% & 55\%: 0.23s (-30.7\%) & \\  & & & & 67\%: 0.26s (-18.5\%) & \\  & & & & 30\%: 0.41s (-61.5\%) & \\ Issues & 0.09s & 1.08s & 91.53\% & 50\%: 0.63s (-41.5\%) & Remote model emulated locally. \\  & & & & 70\%: 0.84s (-21.5\%) & \\  & & & & 30\%: 0.23s (-66.3\%) & Remote model emulated locally. \\ ImageNet & 0.02s & 0.68s & 96.35\% & 50\%: 0.36s (-46.3\%) & Both models use batched inference. \\  & & & & 70\%: 0.50s (-26.3\%) & \\  & & & & 33\%: 0.25s (-64.4\%) & \\ (possible only) & 0.02s & 0.71s & 97.42\% & 59\%: 0.44s (-38.1\%) & \\  & & & & 49\%: 0.39s (-47.6\%) & \\  & & & & 71\%: 0.55s (-25.9\%) & \\ \hline \hline \end{tabular} (*) Break even point: the fraction of remote calls at which the BiSupervised latency equals the latency of the remote-only approach. For any 1st level supervisor threshold leading to fewer remote predictions, BiSupervised is faster than using the standalone remote model. Hence, higher is better.

\end{table}
Table 7. Average Prediction and Supervision Latency per Input
## 7. Conclusion

In this paper, we proposed BiSupervised, a novel architecture that addresses the challenge of using large-scale Deep Neural Networks (DNNs) from resource-constrained devices - a problem that is often solved by using costly and high-latency prediction on a remote server. Our proposed architecture combines a small-scale local model with a large-scale remote model, and includes two supervisors that monitor the prediction process, identifying inputs for which the local prediction can be trusted, and those that require the remote model to be invoked.

We evaluated the effectiveness of BiSupervised on four diverse case studies, including Imdb movie review sentiment classification, Github issue triaging, Imagenet image classification, and SQuADv2 free-text question answering. Our results demonstrate that BiSupervised can achieve superaccurate performance for Imdb and SQuADv2, i.e., the accuracy achieved by BiSupervised exceeds the one from the large-scale remote model. For the other case studies, the remote inference cost can be reduced by up to 50% while maintaining a comparable system-level accuracy.

To assess the ability of BiSupervised in a supervised setting, i.e., when identifying inputs for which not even the remote prediction can be trusted, we compared it against the standalone supervised local model and found that BiSupervised performs similar or better in the majority of the tested configurations.

Furthermore, we measured the average prediction latency and showed that BiSupervised leads to reduced latency even with a small percentage of remote calls avoided, due to the large difference in latency between local and remote inference. Overall, our results demonstrate that BiSupervised can be a cost-effective and accurate solution for systems relying on large-scale remote models, particularly on resource-constrained devices.

## 8. Data Availability

The full replication package for this paper is made available on Github, and archived on Zenodo:

* [https://github.com/testingautomated-usi/bisupervised](https://github.com/testingautomated-usi/bisupervised)
* [https://zenodo.org/record/7767383](https://zenodo.org/record/7767383)

The replication package contains all scripts we used to calculate our results, as well as a Docker file allowing us to easily re-create the environment to run these scripts. The replication package also contains scripts to download and process third-party artifacts, such as models and datasets, automatically wherever possible. All our code and artifacts are permissively MIT licensed. A corresponding TOSEM replicated computational results (RCR) report is currently under review.

###### Acknowledgements.

 This work was partially supported by the H2020 project PRECRIME, funded under the ERC Advanced Grant 2017 Program (ERC Grant Agreement n. 787703).
