diff --git "a/abs_29K_G/test_abstract_long_2405.04700v1.json" "b/abs_29K_G/test_abstract_long_2405.04700v1.json" new file mode 100644--- /dev/null +++ "b/abs_29K_G/test_abstract_long_2405.04700v1.json" @@ -0,0 +1,414 @@ +{ + "url": "http://arxiv.org/abs/2405.04700v1", + "title": "Robust Implementation of Retrieval-Augmented Generation on Edge-based Computing-in-Memory Architectures", + "abstract": "Large Language Models (LLMs) deployed on edge devices learn through\nfine-tuning and updating a certain portion of their parameters. Although such\nlearning methods can be optimized to reduce resource utilization, the overall\nrequired resources remain a heavy burden on edge devices. Instead,\nRetrieval-Augmented Generation (RAG), a resource-efficient LLM learning method,\ncan improve the quality of the LLM-generated content without updating model\nparameters. However, the RAG-based LLM may involve repetitive searches on the\nprofile data in every user-LLM interaction. This search can lead to significant\nlatency along with the accumulation of user data. Conventional efforts to\ndecrease latency result in restricting the size of saved user data, thus\nreducing the scalability of RAG as user data continuously grows. It remains an\nopen question: how to free RAG from the constraints of latency and scalability\non edge devices? In this paper, we propose a novel framework to accelerate RAG\nvia Computing-in-Memory (CiM) architectures. It accelerates matrix\nmultiplications by performing in-situ computation inside the memory while\navoiding the expensive data transfer between the computing unit and memory. Our\nframework, Robust CiM-backed RAG (RoCR), utilizing a novel contrastive\nlearning-based training method and noise-aware training, can enable RAG to\nefficiently search profile data with CiM. To the best of our knowledge, this is\nthe first work utilizing CiM to accelerate RAG.", + "authors": "Ruiyang Qin, Zheyu Yan, Dewen Zeng, Zhenge Jia, Dancheng Liu, Jianbo Liu, Zhi Zheng, Ningyuan Cao, Kai Ni, Jinjun Xiong, Yiyu Shi", + "published": "2024-05-07", + "updated": "2024-05-07", + "primary_cat": "cs.LG", + "cats": [ + "cs.LG", + "cs.AI", + "cs.DC", + "cs.IR" + ], + "label": "Original Paper", + "paper_cat": "Retrieval AND Augmented AND Generation AND RAG", + "gt": "Large Language Models (LLMs) deployed on edge devices learn through\nfine-tuning and updating a certain portion of their parameters. Although such\nlearning methods can be optimized to reduce resource utilization, the overall\nrequired resources remain a heavy burden on edge devices. Instead,\nRetrieval-Augmented Generation (RAG), a resource-efficient LLM learning method,\ncan improve the quality of the LLM-generated content without updating model\nparameters. However, the RAG-based LLM may involve repetitive searches on the\nprofile data in every user-LLM interaction. This search can lead to significant\nlatency along with the accumulation of user data. Conventional efforts to\ndecrease latency result in restricting the size of saved user data, thus\nreducing the scalability of RAG as user data continuously grows. It remains an\nopen question: how to free RAG from the constraints of latency and scalability\non edge devices? In this paper, we propose a novel framework to accelerate RAG\nvia Computing-in-Memory (CiM) architectures. It accelerates matrix\nmultiplications by performing in-situ computation inside the memory while\navoiding the expensive data transfer between the computing unit and memory. Our\nframework, Robust CiM-backed RAG (RoCR), utilizing a novel contrastive\nlearning-based training method and noise-aware training, can enable RAG to\nefficiently search profile data with CiM. To the best of our knowledge, this is\nthe first work utilizing CiM to accelerate RAG.", + "main_content": "INTRODUCTION The emerging Large Language Models (LLMs) are deployed primarily on centralized cloud platforms [1, 2] (Cloud LLMs), raising concerns about user privacy and trustworthy issues [3]. These issues become even more prominent in areas such as healthcare [4], companionship [5], and personal assistance [6], where the user privacy and trustworthiness of LLMs are crucial. To address these issues, the cloud LLMs will eventually transform into personalized LLMs, capable of generating personalized responses, deployed on edge devices (Edge LLMs), where users can keep all their private data and the model learns from those data locally. To better suit the needs of individual users, Edge LLMs must learn from user interactions. However, their capability of learning is constrained by their limited RAM and computational power. Similar to Cloud LLMs, the Edge LLMs primarily learn by finetuning their model parameters. Yet, given that these models often contain over 3 billion parameters, updates can be challenging, even with numerous efforts to accelerate them [7\u20139]. For example, using the experimental high-performance embedded system like NVIDIAAGX, the pockengine method [9] can still take 90 hours to learn from a middle-sized dataset Alpaca with only 52k documents, making this option impractical for normal users. E x : \u201cI am sick?\u201d Sentence Embedding Model E(x) User Query Profile Data Embedding Space S \u2026 P(x, d83) P(x, d29) P(x, d37) Top k (k = 1) DAC ADC \u2026 CiM E(d83) Data: d83, d29, d37 User Query LLM Output NVM Digital Logic \ud835\udc6c(\ud835\udc99) \u2219\ud835\udc6c(\ud835\udc85\ud835\udc8a) = \ud835\udc0f(\ud835\udc31, \ud835\udc85\ud835\udc8a) E(d1) E(d2) E(d3) E(d4) E(dn) Document 2 Document 1 Document n \u2026 Figure 1: The workflow of RAG on edge-based CiM. CiM performs max inner product search (MIPS) to retrieve the top-ranked documents, concatenating them with user query to allow the LLM to generate personalized responses. Retrieval-augmented generation (RAG), on the other hand, is a more resource-efficient choice [10], and hence becoming the de facto learning method for Edge LLMs. In a typical RAG system, it consists of a retriever and a generator. The retriever is commonly backed by max inner product search (MIPS). When the retriever receives a user query, it will retrieve the most relevant document from profile data, as shown in Figure 1. The profile data has many documents, and each document \ud835\udc51\ud835\udc56contains specific information that may be relevant to user queries. The generator can be seen as a LLM, which takes the user query \ud835\udc65and retriever-obtained documents as a prompt and generates a corresponding response. For every document\ud835\udc51\ud835\udc56and the user query \ud835\udc65, RAG utilizes a sentence embedding model shown in Figure 1 to convert them into vectors (i.e., \ud835\udc38(\ud835\udc51\ud835\udc56) and \ud835\udc38(\ud835\udc65), respectively). The vectors for documents can be named as document embeddings and stored as a matrix as shown in Figure 1. The vector for user query, named query embedding \ud835\udc38(\ud835\udc65), will be used in MIPS to perform inner product with every document embedding. The larger the product \ud835\udc43(\ud835\udc65,\ud835\udc51\ud835\udc56), the more semantic similar it will be between the user query and the document. Using RAG, Edge LLMs can provide user-preferred responses by retrieving relevant documents from profile data, and the profile data can be incrementally updated with new documents. This is an efficient learning process without costly updating the model parameters via fine-tuning [11]. Other than the inevitable LLM inference cost, the primary computational cost of RAG is about retrieval, which is more than ten times less than the cost of updating model parameters. While the computational cost of RAG is more edge-friendly, there still exist two issues impeding RAG from being deployed for real-time user interaction on Edge LLMs. Firstly, the growing profile data as stored cannot be unlimited without affecting the access time. If the size of the profile data exceeds the RAM capacity, arXiv:2405.04700v1 [cs.LG] 7 May 2024 \fRuiyang Qin1, Zheyu Yan1, Dewen Zeng1, Zhenge Jia1, Dancheng Liu2, Jianbo Liu1, Ahmed Abbasi1,Zhi Zheng1, Ningyuan Cao1, Kai Ni1, Jinjun Xiong2, Yiyu Shi1 it will need to be offloaded into the storage, such as a hard disk drive (HDD) or solid-state drive (SSD). Accessing data from HDD or SSD will significantly increase the data transfer latency [12], rendering real-time user interaction impractical. Secondly, the core retrieval method of RAG, MIPS, may experience decreased efficiency as profile data grows, and it can become potentially prohibitive when dealing with overwhelmingly large datasets. For example, on Raspberry Pi 4B, MIPS can take 5 minutes to find one appropriate profile data among 21M documents [10], which is even longer than the 2-minute inference time of an Edge LLM. Unfortunately, few efforts have been made to optimize RAG towards Edge LLMs. Thus, we propose to utilize the Computing-in-Memory (CiM) architecture to address this issue. As shown in Figure 1, CiM architectures using memory arrays have shown substantial promise in accelerating matrix-vector multiplication [13], which is the key operation of MIPS. The CiM architectures often utilize massive parallel processing to perform computations directly within the memory array where the data is stored, such that they can minimize the data movement through in-situ data access and significantly increase the throughput [14]. Given the same amount of documents, CiM can finish computation within 50ms [15], which is negligible compared to the computation latency on normal edge devices. Furthermore, by incorporating non-volatile memory (NVM) devices, such as phase-change memories (PCMs), resistive random-access memories (RRAMs), and ferroelectric field-effect transistors (FeFETs), CiM can outperform conventional MOSFET-based designs in terms of energy efficiency [16]. 0.00 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 Level of noise ( ) 0.0 0.2 0.4 0.6 0.8 1.0 Accuracy Citation Movie Rating News DBLP Figure 2: The impact on MIPS accuracy when the RAG\u2019s document embedding is perturbed by various levels of Gaussian noise caused by the device variations. An accurate retrieval means the document retrieved under the impact of the noise is the same as that retrieved without noise. Unfortunately, simply changing the underlying hardware is not enough, as the non-idealities of the NVM devices in CiM array could greatly deteriorate the RAG performance. First, the operations performed in CiM architectures are susceptible to various sources of noise, including electronic noise (thermal, shot, and flicker), deviceto-device variability, and line noise from the supporting circuitry [17]. These noise sources can corrupt the computations, especially when the signal levels are close to the noise floor, which is a common scenario in high-precision tasks. Such noise issues are critical in RAG applications where the accuracy and quality of the generated content heavily rely on the precision of the underlying computations. Additionally, the CiM architecture is primarily designed and optimized for low-resolution computation [18]. Moreover, CiM arrays are typically sized at a fixed dimension, such as 64x64 [19], which is different from the documents\u2019 embedding dimension (e.g., 128). Therefore, both RAG\u2019s data precision (typically FP32) and its embedding dimension need to be reduced to fit in the size of CiM\u2019s crossbar arrays. To illustrate the impact of these on RAG, as an example, we present a preliminary study on MIPS performance in Figure 2, where we use a simple yet representative Gaussian noise to simulate the noise from the device variations in CiM. As shown in Figure 2, as the noise level increases, MIPS accuracy (specified in section 4.1.3) drops dramatically, approaching random guessing. To address these issues, we further propose a novel optimization framework for CiM-backed RAG, called Robust CiM-backed RAG (RoCR). The framework consists of three parts. The first part is a contrastive learning method. We use it to optimize the document embedding model. The second part is a novel data construction method to generate both positively and negatively labeled data pairs for contrastive learning. For the profile data, they can be either labeled to indicate the explicit user-preferred response to certain input, or simply statements without explicit labels that only implicitly indicate user preferences. Our data construction method is capable of dealing with both types of profile data. The third part is a noise-aware training method. It goes in tandem with contrastive learning to obtain a sentence embedding model that can generate document and user query embeddings with high noise-resilient capability, while such embeddings can fit into CiM architectures under different designs and configurations. Our major contributions can be summarized as: \u2022 We propose the first work to harvest CiM advantages for RAG acceleration on the edge. We provide a pathway to utilize emerging CiM devices to expand the Edge LLMs\u2019 capability in terms of storing a high volume of profile data with fast MIPS computing. \u2022 We introduce noise-aware training to enhance the noiseresilient capabilities of RAG\u2019s document embedding. The resulting noise-resilient embeddings can be reused robustly, saving resources needed to calibrate and regenerate embeddings. \u2022 Our experiments on various datasets show that our proposed framework can improve the RAG performance on multiple CiM devices up to 35%, approaching to the theoretical RAG performance. Across a wide device variation (noise) range on a single CiM device, our proposed framework can still improve the RAG performance. 2 RELATED WORK 2.1 CiM Architectures and their NVMs As shown in the middle part of Figure 1, memory arrays are the key component for vector-matrix multiplication. In this array, matrix values are stored at NVM cells, such as emerging NVM technologies like PCMs, RRAMs, and FeFETs, at the cross-points of vertical and horizontal lines. Simultaneously, vector values flow along the horizontal lines of the array. Operations within the memory array take place in the analog domain by exploiting law of physics directly. However, for other essential functions like shift-and-add for multiple bits and sorting to find the top-k ranked values would be done in the digital domain. Thus, digital-to-analog and analog-to-digital \fRobust Implementation of Retrieval-Augmented Generation on Edge-based Computing-in-Memory Architectures profile data Data Construction Module positive examples anchor examples \u2026 Reshape Module embeddings Contrastive Learning close far Device Variation NVMs Sentence Embedding Model negative examples Flexible Noise-aware Training Module optimize constraints Figure 3: Overview of the proposed Robust CiM-backed RAG framework (RoCR). It optimizes the sentence embedding model to adapt different types of NVMs utilized by CiM. converters (DACs and ADCs) are used to connect these different components. CiM arrays suffer from various sources of variations and noises. Two major ones include spatial variations and temporal variations. Spatial variations result from fabrication defects and have both local and global correlations. FeFET devices also suffer from temporal variations due to the stochasticity in memory switching and also aging, which causes fluctuations in conductance when programmed at different times. Temporal variations are typically independent from device to device and are irrelevant to the value to be programmed [20]. In this work, as a proof of concept, we focus on the impact of temporal variations in the programming process on DNN performance. Temporal variation makes the programmed resistance of a device deviate from what is expected. The proposed framework can also be extended to other sources of variations with modification. Measurement results [21, 22] show that the noise on DNN weights caused by device variations can be safely modeled as a Gaussian noise with zero mean, each with a standard deviation associated with the weight value. A detailed representation is given by: v = v0 + \u0394v, \u0394v \u223cN (0, \ud835\udf0e\ud835\udc63) (1) where v is the actual embedding deployed on the accelerators, v0 is the target embedding value, and \ud835\udf0e\ud835\udc63is a value measured by the experiments. We collect the measurement results from RRAM and FeFET devices and the specific value will be discussed in Section 4.1. 2.2 Past Noise Mitigation Methods Several strategies have been introduced to tackle the challenge of device variations in CiM accelerators. These methods can be separated into software and hardware-based techniques. The software-based techniques are generally developed to obtain more robust DNN models [19, 22\u201324] or recommendation systems [25], and are thus not suitable for generating more robust MIPS solutions. For the hardware techniques, the write-verify procedure [26, 27] is one of the most commonly used approach during programming. Initially, a NVM device is programmed to a set state via a designated pulse pattern. Subsequent to this, the device\u2019s value is verified to ascertain if its conductance aligns with a stipulated range of the desired value, essentially assessing its accuracy. If discrepancies arise, a supplemental update pulse is initiated to reset the device conductance nearer to the target. This loop persists until the disparity between the programmed device value and the target value diminishes to a satisfactory margin, typically taking a handful of cycles. Cutting-edge research suggests that by selectively applying write-verify to a subset of pivotal devices, one can uphold the average accuracy of a DNN [21]. Additionally, a variety of circuit design initiatives [18, 28] have been put forth to counteract device variations. 3 PROPOSED WORK 3.1 Framework Overview As shown in Figure 3, our proposed framework, Robust CiM-backed RAG (RoCR), consists of three stages. First, we apply contrastive learning to utilize the training data to optimize the training module. To do that, in the second stage, we take the profile data and construct via a data construction module to obtain contrastive training data pairs, which are then used in the flexible noise-aware training module. In the third stage, we obtain the constraints of NVMs in CiM via profiling. These constraints will be encoded into the flexible noise-aware training module and used to train the sentence embedding model so that it can generate embedding that are robust against device variation of the target NVMs. After training, the training module can be turned into a new sentence embedding model and generate CiM-friendly embeddings. 3.2 Contrastive Learning: Triplet Loss Function When we apply RAG using CiM, we first need to store embeddings into NVMs as shown in Figure 1. Such embeddings are generated by the sentence embedding model, and they are the numerical representations of profile data. Each single document in the profile data can have its unique embedding, which is a vector. The embeddings stored on NVMs can consist of a matrix as the orange blocks shown in Figure 1. Given a user query, which will also be converted into an embedding, CiM can operate MIPS between this user query embedding and all profile embeddings simultaneously via vector-matrix multiplication. The top-ranked values in the product will be used as the index to retrieve the corresponding document data, as the pink block shown in Figure 1. This retrieved user-relevant document is the output of MIPS. However, as we have explained in Section 2.1, writing the document embeddings into NVMs can cause them to suffer from temporal variations (device variations). Then, the NVM-stored embeddings will be different from the original sentence embedding model generated embeddings. As shown in Figure 4, the vanilla embedding model generates desired embedding, which will deviate to the noise embedding under device variation, such that the irrelevant embedding is ranked higher than desired embedding due to its larger inner product. Contrastive learning can learn the representations via push away dissimilar examples and pull close similar examples [29]. In particular, the contrastive loss function can be used to increase the distance between dissimilar examples. In our work, we propose to improve the noise-resilient capability by contrastive learning. By increasing the distance between \fRuiyang Qin1, Zheyu Yan1, Dewen Zeng1, Zhenge Jia1, Dancheng Liu2, Jianbo Liu1, Ahmed Abbasi1,Zhi Zheng1, Ningyuan Cao1, Kai Ni1, Jinjun Xiong2, Yiyu Shi1 noise embedding irrelevant embedding query retrieve the wrong data irrelevant embedding query NVMs Device Variation lead to Vanilla CiM-backed RAG Robust CiM-backed RAG Our embedding model noise-resilient embeddings user profile data NVMs Device Variation desired embedding vanilla embedding model user profile data retrieve the desired data embeddings Figure 4: Improvement by our Robust CiM-backed RAG. Our framework generates noise-resilient embeddings, as shown the orange and blue point in right subfigure dissimilar examples, as shown the right subfigure in Figure 4, deviated desired embedding will still have a larger inner product with the query compared to the irrelevant embedding. Our contrastive learning loss function is based on Weinberger et al. [30]. For each example \ud835\udc65\ud835\udc56in a mini-batch of N anchor examples, our data construction method will construct \ud835\udc3epositive and \ud835\udc3enegative examples corresponding to \ud835\udc65\ud835\udc56. We can have {{(\ud835\udc65\ud835\udc56,\ud835\udc65\u2212 \ud835\udc56,\ud835\udc65+ \ud835\udc56)\ud835\udc58}\ud835\udc56=1,...,\ud835\udc41}\ud835\udc58=1,...,\ud835\udc3e, in which \ud835\udc65\u2212and \ud835\udc65+ are negative and positive examples corresponding to \ud835\udc65\ud835\udc56, where \ud835\udc65\ud835\udc56is closer to \ud835\udc65+ \ud835\udc56compared to \ud835\udc65\u2212 \ud835\udc56. Also, \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56) represents the learned embedding of \ud835\udc65\ud835\udc56. Then the loss function L can be defined as: L = \ud835\udc41 \u2211\ufe01 \ud835\udc56=1 1 \ud835\udc3e \ud835\udc3e \u2211\ufe01 \ud835\udc58=1 max \u0010 0, d(\ud835\udc65\ud835\udc56,\ud835\udc65\u2212 \ud835\udc56(\ud835\udc58)) \u2212d(\ud835\udc65\ud835\udc56,\ud835\udc65+ \ud835\udc56(\ud835\udc58)) + \ud835\udc5a \u0011 , d(\ud835\udc65\ud835\udc4e,\ud835\udc65\ud835\udc4f) = sim(emb(\ud835\udc65\ud835\udc4e), emb(\ud835\udc65\ud835\udc4f)) (2) The distance \ud835\udc51(\ud835\udc65\ud835\udc4e,\ud835\udc65\ud835\udc4f) is calculated by the Euclidean distance between embeddings of two data \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc4e) and \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc4f). The function \ud835\udc60\ud835\udc56\ud835\udc5a() calculate the semantic similarity. 3.3 Data Construction To train the sentence embedding model via contrastive learning, it is critical to construct pairs of examples where the positive examples and negative examples need to be distinct from each other [31]. In our work, since we use triplet contrastive loss, instead of pairs of examples, we will construct trios of examples where each triplet contains an anchor, positive, and negative example. We use profile data to construct triplets of examples. For the profile data, it is generated by the user during the user-LLM interaction and contains the user preference information. There exists two situations for such data. First, the profile data can contain explicit labels indicating the user preferred response to the corresponding content. Second, the profile data also can be statements containing the user-related information but without explicit user preferences As shown in Figure 5, to deal with the two situations, we come up with two data construction methods: Construction Data with Explicit labels (CDE) and Construction Data with Implicit labels (CDI). \u201cJake Blues, just released from prison, puts his old band back together to save the Catholic home where he and his brother Elwood were raised.\u201d is \u201cdystopia\u201d negative r = 0.1 r = 0 r = 0 \u201cFresh out of prison, Jake Blues rallies his old band to save their childhood Catholic home\u201d is \u201cclassic\u201d positive example (embedding) \u201cJake Blues, just released\u2026\u201d is \u201cclassic\u201d anchor example (embedding) \u201cJake Blues, just released \u2026\u201d is \u201cdystopia\u201d negative example (embedding) r = 0.1 \u201cVictims of traumatized \u2026\u201d r = 0 r = 0.9 CDE CDI E anchor/positive example negative example \u201cTwo victims of traumatized childhoods become lovers and serial murderers irresponsibly glorified by the mass media.\u201d anchor/positive/negative example \u201cTwo people with traumatic pasts turn into a couple on a crime spree, mistakenly idolized by the media.\u201d \u201cIndividuals, mired in traumas, unite *() crime-ridden bond, enthrall\u2606\u2609\u00a7ing the media's distorted spotlight.\" \u201cJake Blues, just released from prison, puts his old band back together to save the Catholic home where he and his brother Elwood were raised.\u201d is \u201cclassic\u201d explicit label Statement/implicit label Figure 5: Examples of the two data construction methods. For data with explicit labels, CDE is used to construct the training data. For data without explicit labels (implicit labeled data), CDI is used to construct the training data. 3.3.1 Construction Trios via Data with Explicit Labels (CDE). For the data with explicit labels, each of the data consists of a textual content c and its corresponding label l which indicates the user preferred response regarding to the content c. As shown in the CDE part in Figure 5, there exists explicit label circled by dashed line. Using the profile data, we will construct triplet examples in the format of (\ud835\udc65\ud835\udc56,\ud835\udc65\u2212 \ud835\udc56,\ud835\udc65+ \ud835\udc56). Given a dataset D with size of \ud835\udc5bprofile documents, each piece of data consists of a content \ud835\udc50\ud835\udc56and the corresponding label \ud835\udc59\ud835\udc56where \ud835\udc56\u2208{1, 2, ...,\ud835\udc5b}. The anchor example \ud835\udc65\ud835\udc56can be constructed as: \ud835\udc65\ud835\udc56= \ud835\udc50\ud835\udc56\u2295\ud835\udc59\ud835\udc56, for \ud835\udc56= 1, 2, . . . ,\ud835\udc5b (3) where \u2295denotes a concatenation operation, specifically used here to combine label and content. Negative examples \ud835\udc65\u2212 \ud835\udc56can be constructed by concatenating \ud835\udc50\ud835\udc56with a random label \ud835\udc59\ud835\udc57that is different from \ud835\udc59\ud835\udc56as follows: \ud835\udc65\u2212 \ud835\udc56= \ud835\udc50\ud835\udc56\u2295\ud835\udc59\ud835\udc57, where \ud835\udc59\ud835\udc56\u2260\ud835\udc59\ud835\udc57. (4) Randomly assigning a different label ensures diversity in the negative examples while maintaining the same content from the anchor. Different from constructing anchor and its negative examples, it is challenging to construct positive examples corresponding to the anchor examples since it is more difficult to formalize semantically similar data than to formalize semantically dissimilar data. To construct positive examples, we follow the SimCSE method [32] to add a dropout rate \ud835\udc5finto the sentence embedding model M. The process for constructing positive examples involves two main steps. First, the textual positive example is formalized as: \ud835\udc65+ \ud835\udc56= \ud835\udc65\ud835\udc56, for \ud835\udc56= 1, 2, ...,\ud835\udc5b (5) where we align each anchor with the corresponding positive example. This step effectively duplicates the anchor data as a starting point for generating the embeddings. \fRobust Implementation of Retrieval-Augmented Generation on Edge-based Computing-in-Memory Architectures Second, the embedding generation process varies based on the dropout rate applied within the model M. When model M is utilized to generate embeddings for anchor and negative examples, the dropout rate is set to 0. In contrast, for generating embeddings for positive examples, a non-zero dropout rate \ud835\udc5fis used. The anchor, negative, positive examples, as shown in Figure 5, can be constructed as: \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56) = M(\ud835\udc65\ud835\udc56,\ud835\udc51\ud835\udc5f\ud835\udc5c\ud835\udc5d\ud835\udc5c\ud835\udc62\ud835\udc61= 0) \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\u2212 \ud835\udc56) = M(\ud835\udc65\u2212 \ud835\udc56,\ud835\udc51\ud835\udc5f\ud835\udc5c\ud835\udc5d\ud835\udc5c\ud835\udc62\ud835\udc61= 0) \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65+ \ud835\udc56) = M(\ud835\udc65+ \ud835\udc56,\ud835\udc51\ud835\udc5f\ud835\udc5c\ud835\udc5d\ud835\udc5c\ud835\udc62\ud835\udc61= \ud835\udc5f) (6) The condition of \ud835\udc5f\u22600 can induce variation in the embeddings, enhancing the model\u2019s ability to recognize semantically similar yet variably expressed content. Given the construction factor \ud835\udc3e, we can construct the triplet data examples as: D\ud835\udc61\ud835\udc5f\ud835\udc56\ud835\udc5d\ud835\udc59\ud835\udc52\ud835\udc61= \ud835\udc41 \u00d8 \ud835\udc56=1 n (\ud835\udc65\ud835\udc56(\ud835\udc58),\ud835\udc65\u2212 \ud835\udc56(\ud835\udc58),\ud835\udc65+ \ud835\udc56(\ud835\udc58)) : \ud835\udc58= 1, 2, . . . , \ud835\udc3e o (7) For the triplet data examples D\ud835\udc61\ud835\udc5f\ud835\udc56\ud835\udc5d\ud835\udc59\ud835\udc52\ud835\udc61, their embeddings for each augmentation \ud835\udc58are given by: E = \ud835\udc41 \u00d8 \ud835\udc56=1 n (\ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56(\ud835\udc58)),\ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\u2212 \ud835\udc56(\ud835\udc58)),\ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65+ \ud835\udc56(\ud835\udc58)) : \ud835\udc58= 1, 2, . . . , \ud835\udc3e o (8) As shown in Figure 5, for data with explicit labels, a content\ud835\udc50can concatenate with its corresponding label \ud835\udc59to formalize the positive and anchor example. That content \ud835\udc50can also concatenate with other labels \ud835\udc59\u2032 to formalize the negative example. The positive example can be finally obtained from the sentence embedding model with dropout rate \ud835\udc5f. The anchor and negative example can be finally obtained from the sentnece embedding model with \ud835\udc5f= 0. 3.3.2 Construction Trios via Data with Implicit Labels (CDI). For data with implicit labels, each of the data consists of solely textual content c. As shown of the CDI part in Figure 5, there is no explicit label to indicate user preferences. Instead, the data can be seen as a statement containing some user-related information. To construct the anchor examples and positive examples, we can use the exact same method in EDC. Given a dataset D with size of n profile data, each piece of data consits of a content \ud835\udc50\ud835\udc56. The anchor data \ud835\udc65\ud835\udc56can be constructed as: \ud835\udc65\ud835\udc56= \ud835\udc50\ud835\udc56, for \ud835\udc56= 1, 2, . . . ,\ud835\udc5b (9) For each anchor data \ud835\udc65\ud835\udc56, constructing its corresponding negative example is not as simple as merely concatenating the content\ud835\udc50\ud835\udc56with a non-corresponding label \ud835\udc59\ud835\udc58. To construct negative examples, we employ a reciprocal approach with the positive examples, applying a similar method to both. We first initialize the negative example and positive example following the equation 5: \ud835\udc65\u2212 \ud835\udc56= \ud835\udc65+ \ud835\udc56= \ud835\udc65\ud835\udc56, for \ud835\udc56= 1, 2, . . . ,\ud835\udc5b (10) For the positive example \ud835\udc65+ \ud835\udc56, it can be finalized by incorporating a dropout rate \ud835\udc5finto the sentence embedding model M, where a rate of 0 < \ud835\udc5f\u22640.2 can generate a sentence embedding with a semantic representation similar to \ud835\udc65\ud835\udc56and ensure good model training performance [32]. Increasing the dropout rate to a higher value, such as 0.5, can distort the semantic representation of \ud835\udc65+ \ud835\udc56, making it dissimilar to that of \ud835\udc65\ud835\udc56. Training the model with such positive examples can result in poorer performance. For positive examples in training the sentence embedding model, the higher dropout rate performs more like a noise rather than a data augmentation method. In our work, we train the sentence embedding model to generate embeddings that maintain their integrity under noisy conditions, such as during writing into Compute-in-Memory (CiM). The noise can alter or fragment the original semantic representations. For instance, as illustrated in Figure 5, using a high dropout rate \ud835\udc5f= 0.9 can lead to a negative example with a corrupted representation. Although it may lack certain informative content, this negative example becomes semantically distinct from both the anchor and positive examples, effectively simulating the effect of CiM corruption. This approach not only differentiates the negative examples semantically but also aligns them with the corrupted data scenarios for noise-aware training. Given the triple examples (\ud835\udc65\ud835\udc56,\ud835\udc65\u2212 \ud835\udc56,\ud835\udc65+ \ud835\udc56), for \ud835\udc56= 1, 2, ...,\ud835\udc5bas shown in equation 10, we have the dropout rate \ud835\udc5ffor formalizing the positive examples where 0 < \ud835\udc5f\u22640.2. Correspondingly, the dropout rate for formailzing the negative examples can be 1 \u2212\ud835\udc5f. Given the sentence embedding model M, the anchor example, positive example, and negative example can be constructed as: emb(\ud835\udc65\ud835\udc56) = M(\ud835\udc65\ud835\udc56, dropout = 0) emb(\ud835\udc65\u2212 \ud835\udc56) = M(\ud835\udc65\u2212 \ud835\udc56, dropout = 1 \u2212\ud835\udc5f) emb(\ud835\udc65+ \ud835\udc56) = M(\ud835\udc65+ \ud835\udc56, dropout = \ud835\udc5f) (11) 3.4 Flexible Noise-aware Training In the previous two stages, we construct the data to train the sentence embedding model based on contrastive learning. Meanwhile, the training can be more effective when injecting the simulated device variation [33] so that the model can be optimized with consideration of the device variation. Additionally, the sentence embedding model needs to produce embeddings that can fit with the different CiMs, which might have various NVM designs. To do that, we need the sentence embedding model reshapes its output embeddings into certain dimensions and precision. Hence, we propose a flexible noise-aware training method, which can generate the noise-resilient embedding, fitting to various CiMs. As shown in Figure 3, in the flexible noise-aware training module, the embedding generated by sentence embedding model will be shaped based on the CiM\u2019s NVMs constraints where required dimension is \ud835\udc51and required precision is \ud835\udc5d, and being injected device variation to formalize the embeddings. The reshape module, shown in Figure 3, seen as an autoencoder to reconstruct its input embedding [34], can be expressed as \ud835\udc60\u210e\ud835\udc5d(), initialized by \ud835\udc51 and \ud835\udc5d, takes the anchor embedding \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56) as input. We can have \ud835\udc60\u210e\ud835\udc5d(\ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)) = \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)\ud835\udc51\u2217\ud835\udc5d. Based on the device variation shown as Table 2, we can have: \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)\ud835\udc51\u2217\ud835\udc5d \ud835\udf0e = (\ud835\udc52\u2032 \u2217\ud835\udc3f0 + \ud835\udc52\u2032 \u2217\ud835\udc3f1 + \ud835\udc52\u2032 \u2217\ud835\udc3f2 + \ud835\udc52\u2032 \u2217\ud835\udc3f3) \u2217\ud835\udf0e, (12) \fRuiyang Qin1, Zheyu Yan1, Dewen Zeng1, Zhenge Jia1, Dancheng Liu2, Jianbo Liu1, Ahmed Abbasi1,Zhi Zheng1, Ningyuan Cao1, Kai Ni1, Jinjun Xiong2, Yiyu Shi1 Table 1: Performance comparison between our framework and four baselines on five CiM devices with device variation specified in Table 2 across five datasets. Evaluate the performance of our framework using EDC (RoCR-EDC) and using IDC (RoCR-IDC) to optimize the performance of RAG, which utilizes Gemma-2 as its LLM. Dataset Citation Movie Rating News DBLP CiM Method Acc \u2191 F1 \u2191 Acc \u2191 F1 \u2191 MAE \u2193 RMSE \u2193 ROUGE-1 \u2191 ROUGE-L \u2191 ROUGE-1 \u2191 ROUGE-L \u2191 Device-1 SWV 0.4208 0.3339 0.1305 0.1974 0.3850 0.8093 0.0754 0.0731 0.1709 0.1590 CxDNN 0.4223 0.3576 0.1516 0.1762 0.4404 0.9135 0.0640 0.0632 0.1646 0.1449 CorrectNet 0.4155 0.3791 0.0996 0.1305 0.3609 0.7071 0.0512 0.0764 0.1603 0.1538 Vanilla RAG 0.4401 0.3476 0.1017 0.0838 0.3903 0.8944 0.0754 0.0731 0.1731 0.1473 RoCR-CDE 0.5536 0.3956 0.2242 0.2303 0.3108 0.6856 0.1041 0.0987 0.2066 0.1924 RoCR-CDI 0.5409 0.5117 0.2273 0.2487 0.2767 0.6083 0.0831 0.0808 0.2317 0.2176 Device-2 SWV 0.1831 0.1552 0.1992 0.1957 0.4205 0.8775 0.0296 0.0289 0.1968 0.1874 CxDNN 0.4013 0.3557 0.2167 0.2019 0.4423 0.8367 0.0604 0.0791 0.1517 0.1401 CorrectNet 0.3827 0.3209 0.1625 0.1909 0.3762 0.8062 0.0513 0.0505 0.2042 0.1945 Vanilla RAG 0.4801 0.3462 0.1576 0.2079 0.4153 0.9354 0.0296 0.0289 0.1618 0.1353 RoCR-CDE 0.5407 0.4396 0.2924 0.2509 0.2553 0.5385 0.1209 0.0946 0.2025 0.1906 RoCR-CDI 0.5299 0.4591 0.2971 0.2386 0.2124 0.5763 0.0884 0.0853 0.2240 0.2098 Device-3 SWV 0.2450 0.2564 0.1695 0.1641 0.3460 0.7416 0.0725 0.069 0.1018 0.0954 CxDNN 0.4811 0.4006 0.2367 0.2113 0.2851 0.6928 0.0761 0.0707 0.1425 0.1111 CorrectNet 0.4510 0.3918 0.0792 0.1029 0.3704 0.7937 0.0585 0.0555 0.1715 0.1346 Vanilla RAG 0.4852 0.3618 0.1614 0.1636 0.3255 0.7649 0.0725 0.0690 0.1647 0.1437 RoCR-CDE 0.5139 0.4116 0.2242 0.2215 0.3208 0.6481 0.0825 0.0805 0.1893 0.1754 RoCR-CDI 0.5515 0.4984 0.2152 0.2131 0.2916 0.6245 0.1099 0.1049 0.2294 0.2140 Device-4 SWV 0.5135 0.4260 0.1271 0.1178 0.3610 0.8196 0.0259 0.0256 0.1871 0.1786 CxDNN 0.4733 0.3964 0.1267 0.2158 0.3468 0.7616 0.0646 0.0634 0.1603 0.1538 CorrectNet 0.4628 0.4019 0.1592 0.1847 0.4013 0.9274 0.0705 0.0750 0.1628 0.1292 Vanilla RAG 0.2101 0.2401 0.1219 0.2019 0.4015 0.8544 0.0505 0.0489 0.1929 0.1814 RoCR-CDE 0.5836 0.5555 0.1706 0.2817 0.3139 0.6856 0.0873 0.0851 0.1984 0.1882 RoCR-CDI 0.5352 0.4289 0.1642 0.2445 0.2706 0.5916 0.1154 0.1128 0.2148 0.1978 Device-5 SWV 0.4320 0.3541 0.1250 0.1076 0.3652 0.7616 0.0434 0.0427 0.0985 0.0923 CxDNN 0.4301 0.0538 0.0751 0.0458 0.3503 0.8185 0.0707 0.0682 0.2042 0.1945 CorrectNet 0.4145 0.3926 0.1083 0.1395 0.5526 0.8185 0.0735 0.0776 0.2096 0.1879 Vanilla RAG 0.4256 0.3522 0.0847 0.0863 0.3951 0.8515 0.0676 0.0653 0.2018 0.1846 RoCR-CDE 0.5698 0.5223 0.2152 0.1669 0.2959 0.6245 0.0936 0.0891 0.1946 0.1844 RoCR-CDI 0.5254 0.4504 0.2394 0.2458 0.2624 0.6325 0.0799 0.0764 0.2238 0.2095 where \ud835\udc52\u2032 = \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)\ud835\udc51\u2217\ud835\udc5d. The device variation, as noise, is injected into embeddings to formalize \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)\ud835\udc51\u2217\ud835\udc5d \ud835\udf0e , which will be used in contrastive learning to train the sentence embedding model, as shown in Figure 3. 4 EXPERIMENTAL EVALUATION 4.1 Experimental Setup 4.1.1 Datasets. To demonstrate our robust CiM-backed RAG, we employ five datasets with different tasks and domains, including Citation Identification [35] (Citation), Movie Tagging [36] (Movie), Product Rating [37] (Rationg), News Headline Generation [38] (News), and DBLP-Citation-network V14 [39] (DBLP) to evaluate the proposed framework. The data in each dataset consists of query data and profile data. In our evaluation, the profile data will be used to formalize user history, and the profile corresponding query data will be used as the user input. The first three datasets contain binary, five-class, and fifteen-class classification tasks respectively. The last two datasets contain text generation tasks. In the Citation Identification dataset, every piece of query data consists of a paper title and two references, and the correct reference is provided. RAG uses the profile data corresponding to the paper titles with their detailed contents to choose the appropriate reference. In the Movie Tagging dataset, each query data contains a description of a movie, and RAG uses a similar description and its corresponding tag in the profile data to tag the query data. The Product Rating dataset has a similar structure as the Movie Tagging dataset. In News Headline Generation and DBLP datasets, each query data contains an abstract, which can be summarized into a title. RAG uses a similar abstract and its corresponding title in profile data to generate the title for query data. All five datasets have labels in their query data. 4.1.2 Default Experimental Setting. Our framework chooses all-MiniLM-L6-v2 [40] as the sentence embedding model. For each dataset, we randomly select 2000 documents from profile data as the anchor examples. To examine the data construction method of CDE, we set the augmentation factor \ud835\udc58= 5 to obtain 10000 negative and positive examples. We set dropout rate as 0.1 to obtain the positive examples while maintain it as 0 when process anchor and negative examples. To examine the data construction method CDI, we set dropout rate for positive examples as 0.1 and dropout rate for negative examples as 0.9. To align with experiments for CDE, we also set \ud835\udc58= 5 in the experiments for CDI. For the experimental results, we run five times and get the average. In experiments, we set the device variation \ud835\udf0e= 0.1 and shape embeddings into dimension of 64 with precision of \ud835\udc56\ud835\udc5b\ud835\udc618. The learning rate is 2\ud835\udc52\u22125. In all experiments, we adhere to the device variation model previously described. The specific parameters are abstracted and then simplified from three representative NVM devices, two of them \fRobust Implementation of Retrieval-Augmented Generation on Edge-based Computing-in-Memory Architectures D-1 D-2 D-3 D-4 D-5 0.2 0.4 0.6 0.8 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (a) Citation on Gemma-2B D-1 D-2 D-3 D-4 D-5 0.2 0.4 0.6 0.8 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (b) Citation on Phi-2 D-1 D-2 D-3 D-4 D-5 0.2 0.4 0.6 0.8 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (c) Citation on Mistral-7B D-1 D-2 D-3 D-4 D-5 0.2 0.4 0.6 0.8 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (d) Citation on Llama-2-3B D-1 D-2 D-3 D-4 D-5 0.0 0.1 0.2 0.3 0.4 0.5 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (e) Movie on Gemma-2B D-1 D-2 D-3 D-4 D-5 0.0 0.1 0.2 0.3 0.4 0.5 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (f) Movie on Phi-2 D-1 D-2 D-3 D-4 D-5 0.0 0.1 0.2 0.3 0.4 0.5 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (g) Movie on Mistral-7B D-1 D-2 D-3 D-4 D-5 0.0 0.1 0.2 0.3 0.4 0.5 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (h) Movie on Llama-2-3B Figure 6: Performance comparison between our framework and four baselines on RAG utilizing the LLMs including Gemma-2B, Phi-2, Mistral-7B, and Llama-2-3B with device variation specified in Table 2, given dataset \ud835\udc36\ud835\udc56\ud835\udc61\ud835\udc4e\ud835\udc61\ud835\udc56\ud835\udc5c\ud835\udc5band \ud835\udc40\ud835\udc5c\ud835\udc63\ud835\udc56\ud835\udc52. Table 2: Device non-ideality modeling for different real and synthesized devices. For devices with more than two levels, the device variation for each level is depicted as \ud835\udc3f\ud835\udc65. Name # of Levels Device Variations \ud835\udf0e\ud835\udc63 \ud835\udc3f0 \ud835\udc3f1 \ud835\udc3f2 \ud835\udc3f3 \ud835\udc45\ud835\udc45\ud835\udc34\ud835\udc401 (Device-1) 1 0.0100 0.0100 0.0100 0.0100 \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc472 (Device-2) 4 0.0067 0.0135 0.0135 0.0067 \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc473 (Device-3) 4 0.0049 0.0146 0.0146 0.0049 \ud835\udc45\ud835\udc45\ud835\udc34\ud835\udc404 (Device-4) 4 0.0038 0.0151 0.0151 0.0038 \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc476 (Device-5) 4 0.0026 0.0155 0.0155 0.0026 are resistive random-access memory (RRAM) devices extracted from [27, 41] and the other is a ferroelectric field effect transistor (FeFET) device extracted from [42]. We name them \ud835\udc45\ud835\udc45\ud835\udc34\ud835\udc401, \ud835\udc45\ud835\udc45\ud835\udc34\ud835\udc404 and \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc472, respectively. We also extrapolate the modeling data to obtain two synthesized \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc473 and \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc476 devices. Detailed device modeling results are demonstrated in Table 2. A \ud835\udc65-level device means this device can represent \ud835\udc65distinct values and \ud835\udf0e\ud835\udc3f2 = 0.01 means the variation of this device is 0.01 when it is representing the level value 2. Using the device variations obtained from real CiM devices, we perform our experiments on a single Nvidia A10 GPU. Document embeddings are shaped based on different CiM devices and stored as parallel arrays, similar to how they would be mapped to multiple NVM devices in practical scenarios. For example, if an embedding is shaped to contain all uint8 values, when it is mapped to 4-level (2-bit) devices such as \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc472, each element of the vector is represented by four devices. 4.1.3 Evaluation Methods. Our first three datasets examine the model classification capability, and the rest of two datasets examine the text generation capability. In particular, dataset \ud835\udc36\ud835\udc56\ud835\udc61\ud835\udc4e\ud835\udc61\ud835\udc56\ud835\udc5c\ud835\udc5band \ud835\udc40\ud835\udc5c\ud835\udc63\ud835\udc56\ud835\udc52has two and fifteen labels respectively. We can examine the binary and multiclass classification capabilities of the LLMs enhanced by our framework. In this way, we use accuracy to examine the ability of the models to correctly classify instances across different classes, and we use F1 score to examine the balance between precision and recall in classification tasks. For dataset \ud835\udc45\ud835\udc4e\ud835\udc61\ud835\udc56\ud835\udc5b\ud835\udc54, while it has five labels and also examine the multiclass classification, we use mean absolute error (MAE) and root mean square error (RMSE) to evaluate from from a regression perspective [43]. For MAE, it measures the average magnitude of errors in the predictions, providing a straightforward assessment of the model\u2019s overall accuracy in predicting the rating values. For RMSE, it captures the square root of the average squared differences between predicted and actual ratings, offering a metric sensitive to larger errors, which can highlight significant discrepancies between the model\u2019s predictions and true values. For dataset \ud835\udc41\ud835\udc52\ud835\udc64\ud835\udc60and \ud835\udc37\ud835\udc35\ud835\udc3f\ud835\udc43, their labels are sentences. Such datasets examine the text generation capabilities. We use ROUGE1 and ROUGE-L to evaluate the overlap between generated texts and reference texts [44], capturing both the precision and recall of individual words (ROUGE-1) and the longest matching sequence (ROUGE-L), ensuring a comprehensive evaluation of the text generation quality. For accuracy, F1, ROUGE-1 and ROUGE-L, their higher values reflect the better performance. For MAE and RMSE, their lower value represent the better performance. Additionally, we use accuracy to measure the MIPS performance (MIPS accuracy), representing the ratio of MIPS results under device variation and MIPS results without device variation (references). 4.1.4 Baselines. As this is the first work to improve the RAG robustness on Edge-based CiM, we do not have state-of-the-art for comparison. As such, we construct baselines from the past noise mitigation methods originally designed to boost DNN robustness. The first baseline is selective write verify [21] (SWV). While it originally utilizes the second derivation to evaluate the device variation impact on neural network weights, we use the second derivation to measure the embedding deviation between the ground truth embedding and the embedding under device variation. The second baseline is (CxDNN) [45]. While they use compensation factor to improve the robustness of vector-matrix multiplication, we use the compensation factor the calibrate the embedding impacted by device variation. The third baseline is CorrectNet [46], where it utilizes the cross entropy loss and regularization to improve the robustness of neural networks in CiM. To use it as a baseline, we also use the cross entropy loss the regularization as the loss function to \fRuiyang Qin1, Zheyu Yan1, Dewen Zeng1, Zhenge Jia1, Dancheng Liu2, Jianbo Liu1, Ahmed Abbasi1,Zhi Zheng1, Ningyuan Cao1, Kai Ni1, Jinjun Xiong2, Yiyu Shi1 calibrate the device output embedding. Additionally, we examine the Vanilla RAG, which contains no noise mitigation methods, as our fourth baseline. The baselines use the same experimental setting as our framework does. 4.2 Results For RAG, it can be simplified as the combination of MIPS and LLM, where the MIPS as a retriever searches the appropriate information and the LLM as a generator processes the searched results. Hence, in our experiments, we first evaluate the performance of MIPS under the device variation of device-1. We take the MIPS results obtained without device variation as the references (i.e., ground truth). Using the metric of MIPS accuracy, we examine how many MIPS results under device variation will match the references. Since the quality of retrieved content largely depends on the base sentence embedding model, and we focus on mitigating the device variation impact on the embedding model, we do not assess the quality of references. As shown in Table 3, our framework using the two data construction methods outperforms the four baselines across five datasets. It shows that our framework can mitigate the embedding perturbation due to device variation. These results can also correspond to the preliminary study shown in Figure 2, where the increment of \ud835\udf0e in naive Gaussian noise will jeopardize the MIPS performance. Table 3: Performance (MIPS accuracy) comparison between our framework and baselines. Accuracy is computed based on MIPS-retrieved documents under device variation of device-1 and the these retrieved without device variation. Dataset Citation Movie Rating News DBLP SWV 0.4200 0.1728 0.1050 0.0855 0.2295 CxDNN 0.4401 0.2017 0.0503 0.0754 0.1681 CorrectNet 0.4013 0.0699 0.0509 0.0533 0.1609 Vanilla RAG 0.4547 0.1694 0.0933 0.0649 0.1747 RoCR-CDE 0.9231 0.4639 0.1583 0.1921 0.2750 RoCR-CDI 0.9344 0.4355 0.1266 0.1708 0.2905 After we compare the MIPS performance of our framework and baselines, we further present a comprehensive evaluation to show the RAG performance of them. We use Gemma-2B as the LLM in RAG. Additionally, with Gemma-2B, we run RAG without device variation to obverse its ideal performance, where we get 0.5200 of accuracy for Citation, 0.3728 of accuracy for Movie, 0.3150 of MAE for Rating, 0.0855 of ROUGE-1 for News, and 0.2295 of ROUGE-1 for DBLP. On five CiM devices, whose device variations have been shown in Table 2, we examine RAG with five datasets. As shown in Table 1, given the same datasets, it is clear that each device variation significantly compromises the RAG robustness, whereas our framework can mitigate the different device variation. For example, the RAG performance for Citation dataset on Device-2 can range from 0.18 to 0.48, while our framework can boost the accuracy performance of Citation dataset above 0.5 for all five devices. Compared to the four baselines whose performances are relatively worse than the ideal performance, our framework significantly approaches and sometimes outperforms the ideal performance via generating better sentence embeddings. This is because RoCR also serves as a regularization to improve the model\u2019s generalization. In addition, we evaluate the impact of different LLMs on the performance of our framework. As Figure 1 shown, the LLM takes the concatenation of MIPS searched data and user query as the input and generates the response regarding the user query. Since different LLMs may have different response given the same query, we select four emerging edge-friendly medium-size LLMs in our experiments to examine the performance of our framework. Gemma-2B [47] is a new SOTA open model introduced by Google, with 4.95G model weights. According to Google, Gemma can outperform the same sized Llama-2 in reasoning capabilities. Hence, we also use Llama2-3B [48], one of the earliest open LLMs introduced by Meta, with 6.85G model weights. Similarly, Phi-2 [49] released by Microsoft, is a powerful small LLM with 5G model weights. Additionally, Mistral7B-GPTQ [50] made by Mistral AI, is a well-performed LLM after Llama model. We select dataset \ud835\udc36\ud835\udc56\ud835\udc61\ud835\udc4e\ud835\udc61\ud835\udc56\ud835\udc5c\ud835\udc5band dataset \ud835\udc40\ud835\udc5c\ud835\udc56\ud835\udc63\ud835\udc52. We use the default experimental setting with \ud835\udf0e= 0.1 and use CiM Device-1 as the experimental environment. The results are shown on Figure 6. It is evident that our framework outperforms each baseline across five CiM devices. Besides, the performance of each baseline on the same dataset can be largely different given different device, while our framework can produce a more robust performance. 0.000 0.025 0.050 0.075 0.100 0.125 0.150 Device Variation ( ) 0.10 0.15 0.20 0.25 0.30 ROUGE-1 SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI Figure 7: Performance comparison between our framework and four baselines on CiM device-1 with different device variation \ud835\udf0e, given dataset DBLP. By default, we use \ud835\udf0e= 0.1 to calculate the device variation of the five CiM devices. We also conduct an additional study to evaluate our framework given different \ud835\udf0evalues. Since we have already use dataset Citation and dataset Movie to study the performance of our frameworks seen in Figure 6, we choose a different dataset DBLP, using ROUGE-1 as the metric. For the LLM in RAG, we choose Mistral-7B. We examine the \ud835\udf0evalues higher and lower than 0.1, including 0, 0.025, 0.05, 0.075, 0.125, and 0.15. The case of \ud835\udf0e = 0 reflects the ideal performance. For the CiM device, we use CiM device-1. As shown in Figure 7, our framework outperforms baselines across different device variation values. Finally, RoCR is a training method that generates more robust weights for the sentence embedding model. It does not change the model structure. Thus, there is no hardware (e.g., energy and latency) overhead during inference. 5", + "additional_graph_info": { + "graph": [ + [ + "Ruiyang Qin", + "Zheyu Yan" + ], + [ + "Ruiyang Qin", + "Zhenge Jia" + ], + [ + "Ruiyang Qin", + "Ahmed Abbasi" + ], + [ + "Zheyu Yan", + "Weiwen Jiang" + ], + [ + "Zhenge Jia", + "Dawei Li" + ], + [ + "Zhenge Jia", + "Cong Liu" + ], + [ + "Ahmed Abbasi", + "Abiy Tasissa" + ], + [ + "Ahmed Abbasi", + "Shuchin Aeron" + ] + ], + "node_feat": { + "Ruiyang Qin": [ + { + "url": "http://arxiv.org/abs/2405.04700v1", + "title": "Robust Implementation of Retrieval-Augmented Generation on Edge-based Computing-in-Memory Architectures", + "abstract": "Large Language Models (LLMs) deployed on edge devices learn through\nfine-tuning and updating a certain portion of their parameters. Although such\nlearning methods can be optimized to reduce resource utilization, the overall\nrequired resources remain a heavy burden on edge devices. Instead,\nRetrieval-Augmented Generation (RAG), a resource-efficient LLM learning method,\ncan improve the quality of the LLM-generated content without updating model\nparameters. However, the RAG-based LLM may involve repetitive searches on the\nprofile data in every user-LLM interaction. This search can lead to significant\nlatency along with the accumulation of user data. Conventional efforts to\ndecrease latency result in restricting the size of saved user data, thus\nreducing the scalability of RAG as user data continuously grows. It remains an\nopen question: how to free RAG from the constraints of latency and scalability\non edge devices? In this paper, we propose a novel framework to accelerate RAG\nvia Computing-in-Memory (CiM) architectures. It accelerates matrix\nmultiplications by performing in-situ computation inside the memory while\navoiding the expensive data transfer between the computing unit and memory. Our\nframework, Robust CiM-backed RAG (RoCR), utilizing a novel contrastive\nlearning-based training method and noise-aware training, can enable RAG to\nefficiently search profile data with CiM. To the best of our knowledge, this is\nthe first work utilizing CiM to accelerate RAG.", + "authors": "Ruiyang Qin, Zheyu Yan, Dewen Zeng, Zhenge Jia, Dancheng Liu, Jianbo Liu, Zhi Zheng, Ningyuan Cao, Kai Ni, Jinjun Xiong, Yiyu Shi", + "published": "2024-05-07", + "updated": "2024-05-07", + "primary_cat": "cs.LG", + "cats": [ + "cs.LG", + "cs.AI", + "cs.DC", + "cs.IR" + ], + "main_content": "INTRODUCTION The emerging Large Language Models (LLMs) are deployed primarily on centralized cloud platforms [1, 2] (Cloud LLMs), raising concerns about user privacy and trustworthy issues [3]. These issues become even more prominent in areas such as healthcare [4], companionship [5], and personal assistance [6], where the user privacy and trustworthiness of LLMs are crucial. To address these issues, the cloud LLMs will eventually transform into personalized LLMs, capable of generating personalized responses, deployed on edge devices (Edge LLMs), where users can keep all their private data and the model learns from those data locally. To better suit the needs of individual users, Edge LLMs must learn from user interactions. However, their capability of learning is constrained by their limited RAM and computational power. Similar to Cloud LLMs, the Edge LLMs primarily learn by finetuning their model parameters. Yet, given that these models often contain over 3 billion parameters, updates can be challenging, even with numerous efforts to accelerate them [7\u20139]. For example, using the experimental high-performance embedded system like NVIDIAAGX, the pockengine method [9] can still take 90 hours to learn from a middle-sized dataset Alpaca with only 52k documents, making this option impractical for normal users. E x : \u201cI am sick?\u201d Sentence Embedding Model E(x) User Query Profile Data Embedding Space S \u2026 P(x, d83) P(x, d29) P(x, d37) Top k (k = 1) DAC ADC \u2026 CiM E(d83) Data: d83, d29, d37 User Query LLM Output NVM Digital Logic \ud835\udc6c(\ud835\udc99) \u2219\ud835\udc6c(\ud835\udc85\ud835\udc8a) = \ud835\udc0f(\ud835\udc31, \ud835\udc85\ud835\udc8a) E(d1) E(d2) E(d3) E(d4) E(dn) Document 2 Document 1 Document n \u2026 Figure 1: The workflow of RAG on edge-based CiM. CiM performs max inner product search (MIPS) to retrieve the top-ranked documents, concatenating them with user query to allow the LLM to generate personalized responses. Retrieval-augmented generation (RAG), on the other hand, is a more resource-efficient choice [10], and hence becoming the de facto learning method for Edge LLMs. In a typical RAG system, it consists of a retriever and a generator. The retriever is commonly backed by max inner product search (MIPS). When the retriever receives a user query, it will retrieve the most relevant document from profile data, as shown in Figure 1. The profile data has many documents, and each document \ud835\udc51\ud835\udc56contains specific information that may be relevant to user queries. The generator can be seen as a LLM, which takes the user query \ud835\udc65and retriever-obtained documents as a prompt and generates a corresponding response. For every document\ud835\udc51\ud835\udc56and the user query \ud835\udc65, RAG utilizes a sentence embedding model shown in Figure 1 to convert them into vectors (i.e., \ud835\udc38(\ud835\udc51\ud835\udc56) and \ud835\udc38(\ud835\udc65), respectively). The vectors for documents can be named as document embeddings and stored as a matrix as shown in Figure 1. The vector for user query, named query embedding \ud835\udc38(\ud835\udc65), will be used in MIPS to perform inner product with every document embedding. The larger the product \ud835\udc43(\ud835\udc65,\ud835\udc51\ud835\udc56), the more semantic similar it will be between the user query and the document. Using RAG, Edge LLMs can provide user-preferred responses by retrieving relevant documents from profile data, and the profile data can be incrementally updated with new documents. This is an efficient learning process without costly updating the model parameters via fine-tuning [11]. Other than the inevitable LLM inference cost, the primary computational cost of RAG is about retrieval, which is more than ten times less than the cost of updating model parameters. While the computational cost of RAG is more edge-friendly, there still exist two issues impeding RAG from being deployed for real-time user interaction on Edge LLMs. Firstly, the growing profile data as stored cannot be unlimited without affecting the access time. If the size of the profile data exceeds the RAM capacity, arXiv:2405.04700v1 [cs.LG] 7 May 2024 \fRuiyang Qin1, Zheyu Yan1, Dewen Zeng1, Zhenge Jia1, Dancheng Liu2, Jianbo Liu1, Ahmed Abbasi1,Zhi Zheng1, Ningyuan Cao1, Kai Ni1, Jinjun Xiong2, Yiyu Shi1 it will need to be offloaded into the storage, such as a hard disk drive (HDD) or solid-state drive (SSD). Accessing data from HDD or SSD will significantly increase the data transfer latency [12], rendering real-time user interaction impractical. Secondly, the core retrieval method of RAG, MIPS, may experience decreased efficiency as profile data grows, and it can become potentially prohibitive when dealing with overwhelmingly large datasets. For example, on Raspberry Pi 4B, MIPS can take 5 minutes to find one appropriate profile data among 21M documents [10], which is even longer than the 2-minute inference time of an Edge LLM. Unfortunately, few efforts have been made to optimize RAG towards Edge LLMs. Thus, we propose to utilize the Computing-in-Memory (CiM) architecture to address this issue. As shown in Figure 1, CiM architectures using memory arrays have shown substantial promise in accelerating matrix-vector multiplication [13], which is the key operation of MIPS. The CiM architectures often utilize massive parallel processing to perform computations directly within the memory array where the data is stored, such that they can minimize the data movement through in-situ data access and significantly increase the throughput [14]. Given the same amount of documents, CiM can finish computation within 50ms [15], which is negligible compared to the computation latency on normal edge devices. Furthermore, by incorporating non-volatile memory (NVM) devices, such as phase-change memories (PCMs), resistive random-access memories (RRAMs), and ferroelectric field-effect transistors (FeFETs), CiM can outperform conventional MOSFET-based designs in terms of energy efficiency [16]. 0.00 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 Level of noise ( ) 0.0 0.2 0.4 0.6 0.8 1.0 Accuracy Citation Movie Rating News DBLP Figure 2: The impact on MIPS accuracy when the RAG\u2019s document embedding is perturbed by various levels of Gaussian noise caused by the device variations. An accurate retrieval means the document retrieved under the impact of the noise is the same as that retrieved without noise. Unfortunately, simply changing the underlying hardware is not enough, as the non-idealities of the NVM devices in CiM array could greatly deteriorate the RAG performance. First, the operations performed in CiM architectures are susceptible to various sources of noise, including electronic noise (thermal, shot, and flicker), deviceto-device variability, and line noise from the supporting circuitry [17]. These noise sources can corrupt the computations, especially when the signal levels are close to the noise floor, which is a common scenario in high-precision tasks. Such noise issues are critical in RAG applications where the accuracy and quality of the generated content heavily rely on the precision of the underlying computations. Additionally, the CiM architecture is primarily designed and optimized for low-resolution computation [18]. Moreover, CiM arrays are typically sized at a fixed dimension, such as 64x64 [19], which is different from the documents\u2019 embedding dimension (e.g., 128). Therefore, both RAG\u2019s data precision (typically FP32) and its embedding dimension need to be reduced to fit in the size of CiM\u2019s crossbar arrays. To illustrate the impact of these on RAG, as an example, we present a preliminary study on MIPS performance in Figure 2, where we use a simple yet representative Gaussian noise to simulate the noise from the device variations in CiM. As shown in Figure 2, as the noise level increases, MIPS accuracy (specified in section 4.1.3) drops dramatically, approaching random guessing. To address these issues, we further propose a novel optimization framework for CiM-backed RAG, called Robust CiM-backed RAG (RoCR). The framework consists of three parts. The first part is a contrastive learning method. We use it to optimize the document embedding model. The second part is a novel data construction method to generate both positively and negatively labeled data pairs for contrastive learning. For the profile data, they can be either labeled to indicate the explicit user-preferred response to certain input, or simply statements without explicit labels that only implicitly indicate user preferences. Our data construction method is capable of dealing with both types of profile data. The third part is a noise-aware training method. It goes in tandem with contrastive learning to obtain a sentence embedding model that can generate document and user query embeddings with high noise-resilient capability, while such embeddings can fit into CiM architectures under different designs and configurations. Our major contributions can be summarized as: \u2022 We propose the first work to harvest CiM advantages for RAG acceleration on the edge. We provide a pathway to utilize emerging CiM devices to expand the Edge LLMs\u2019 capability in terms of storing a high volume of profile data with fast MIPS computing. \u2022 We introduce noise-aware training to enhance the noiseresilient capabilities of RAG\u2019s document embedding. The resulting noise-resilient embeddings can be reused robustly, saving resources needed to calibrate and regenerate embeddings. \u2022 Our experiments on various datasets show that our proposed framework can improve the RAG performance on multiple CiM devices up to 35%, approaching to the theoretical RAG performance. Across a wide device variation (noise) range on a single CiM device, our proposed framework can still improve the RAG performance. 2 RELATED WORK 2.1 CiM Architectures and their NVMs As shown in the middle part of Figure 1, memory arrays are the key component for vector-matrix multiplication. In this array, matrix values are stored at NVM cells, such as emerging NVM technologies like PCMs, RRAMs, and FeFETs, at the cross-points of vertical and horizontal lines. Simultaneously, vector values flow along the horizontal lines of the array. Operations within the memory array take place in the analog domain by exploiting law of physics directly. However, for other essential functions like shift-and-add for multiple bits and sorting to find the top-k ranked values would be done in the digital domain. Thus, digital-to-analog and analog-to-digital \fRobust Implementation of Retrieval-Augmented Generation on Edge-based Computing-in-Memory Architectures profile data Data Construction Module positive examples anchor examples \u2026 Reshape Module embeddings Contrastive Learning close far Device Variation NVMs Sentence Embedding Model negative examples Flexible Noise-aware Training Module optimize constraints Figure 3: Overview of the proposed Robust CiM-backed RAG framework (RoCR). It optimizes the sentence embedding model to adapt different types of NVMs utilized by CiM. converters (DACs and ADCs) are used to connect these different components. CiM arrays suffer from various sources of variations and noises. Two major ones include spatial variations and temporal variations. Spatial variations result from fabrication defects and have both local and global correlations. FeFET devices also suffer from temporal variations due to the stochasticity in memory switching and also aging, which causes fluctuations in conductance when programmed at different times. Temporal variations are typically independent from device to device and are irrelevant to the value to be programmed [20]. In this work, as a proof of concept, we focus on the impact of temporal variations in the programming process on DNN performance. Temporal variation makes the programmed resistance of a device deviate from what is expected. The proposed framework can also be extended to other sources of variations with modification. Measurement results [21, 22] show that the noise on DNN weights caused by device variations can be safely modeled as a Gaussian noise with zero mean, each with a standard deviation associated with the weight value. A detailed representation is given by: v = v0 + \u0394v, \u0394v \u223cN (0, \ud835\udf0e\ud835\udc63) (1) where v is the actual embedding deployed on the accelerators, v0 is the target embedding value, and \ud835\udf0e\ud835\udc63is a value measured by the experiments. We collect the measurement results from RRAM and FeFET devices and the specific value will be discussed in Section 4.1. 2.2 Past Noise Mitigation Methods Several strategies have been introduced to tackle the challenge of device variations in CiM accelerators. These methods can be separated into software and hardware-based techniques. The software-based techniques are generally developed to obtain more robust DNN models [19, 22\u201324] or recommendation systems [25], and are thus not suitable for generating more robust MIPS solutions. For the hardware techniques, the write-verify procedure [26, 27] is one of the most commonly used approach during programming. Initially, a NVM device is programmed to a set state via a designated pulse pattern. Subsequent to this, the device\u2019s value is verified to ascertain if its conductance aligns with a stipulated range of the desired value, essentially assessing its accuracy. If discrepancies arise, a supplemental update pulse is initiated to reset the device conductance nearer to the target. This loop persists until the disparity between the programmed device value and the target value diminishes to a satisfactory margin, typically taking a handful of cycles. Cutting-edge research suggests that by selectively applying write-verify to a subset of pivotal devices, one can uphold the average accuracy of a DNN [21]. Additionally, a variety of circuit design initiatives [18, 28] have been put forth to counteract device variations. 3 PROPOSED WORK 3.1 Framework Overview As shown in Figure 3, our proposed framework, Robust CiM-backed RAG (RoCR), consists of three stages. First, we apply contrastive learning to utilize the training data to optimize the training module. To do that, in the second stage, we take the profile data and construct via a data construction module to obtain contrastive training data pairs, which are then used in the flexible noise-aware training module. In the third stage, we obtain the constraints of NVMs in CiM via profiling. These constraints will be encoded into the flexible noise-aware training module and used to train the sentence embedding model so that it can generate embedding that are robust against device variation of the target NVMs. After training, the training module can be turned into a new sentence embedding model and generate CiM-friendly embeddings. 3.2 Contrastive Learning: Triplet Loss Function When we apply RAG using CiM, we first need to store embeddings into NVMs as shown in Figure 1. Such embeddings are generated by the sentence embedding model, and they are the numerical representations of profile data. Each single document in the profile data can have its unique embedding, which is a vector. The embeddings stored on NVMs can consist of a matrix as the orange blocks shown in Figure 1. Given a user query, which will also be converted into an embedding, CiM can operate MIPS between this user query embedding and all profile embeddings simultaneously via vector-matrix multiplication. The top-ranked values in the product will be used as the index to retrieve the corresponding document data, as the pink block shown in Figure 1. This retrieved user-relevant document is the output of MIPS. However, as we have explained in Section 2.1, writing the document embeddings into NVMs can cause them to suffer from temporal variations (device variations). Then, the NVM-stored embeddings will be different from the original sentence embedding model generated embeddings. As shown in Figure 4, the vanilla embedding model generates desired embedding, which will deviate to the noise embedding under device variation, such that the irrelevant embedding is ranked higher than desired embedding due to its larger inner product. Contrastive learning can learn the representations via push away dissimilar examples and pull close similar examples [29]. In particular, the contrastive loss function can be used to increase the distance between dissimilar examples. In our work, we propose to improve the noise-resilient capability by contrastive learning. By increasing the distance between \fRuiyang Qin1, Zheyu Yan1, Dewen Zeng1, Zhenge Jia1, Dancheng Liu2, Jianbo Liu1, Ahmed Abbasi1,Zhi Zheng1, Ningyuan Cao1, Kai Ni1, Jinjun Xiong2, Yiyu Shi1 noise embedding irrelevant embedding query retrieve the wrong data irrelevant embedding query NVMs Device Variation lead to Vanilla CiM-backed RAG Robust CiM-backed RAG Our embedding model noise-resilient embeddings user profile data NVMs Device Variation desired embedding vanilla embedding model user profile data retrieve the desired data embeddings Figure 4: Improvement by our Robust CiM-backed RAG. Our framework generates noise-resilient embeddings, as shown the orange and blue point in right subfigure dissimilar examples, as shown the right subfigure in Figure 4, deviated desired embedding will still have a larger inner product with the query compared to the irrelevant embedding. Our contrastive learning loss function is based on Weinberger et al. [30]. For each example \ud835\udc65\ud835\udc56in a mini-batch of N anchor examples, our data construction method will construct \ud835\udc3epositive and \ud835\udc3enegative examples corresponding to \ud835\udc65\ud835\udc56. We can have {{(\ud835\udc65\ud835\udc56,\ud835\udc65\u2212 \ud835\udc56,\ud835\udc65+ \ud835\udc56)\ud835\udc58}\ud835\udc56=1,...,\ud835\udc41}\ud835\udc58=1,...,\ud835\udc3e, in which \ud835\udc65\u2212and \ud835\udc65+ are negative and positive examples corresponding to \ud835\udc65\ud835\udc56, where \ud835\udc65\ud835\udc56is closer to \ud835\udc65+ \ud835\udc56compared to \ud835\udc65\u2212 \ud835\udc56. Also, \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56) represents the learned embedding of \ud835\udc65\ud835\udc56. Then the loss function L can be defined as: L = \ud835\udc41 \u2211\ufe01 \ud835\udc56=1 1 \ud835\udc3e \ud835\udc3e \u2211\ufe01 \ud835\udc58=1 max \u0010 0, d(\ud835\udc65\ud835\udc56,\ud835\udc65\u2212 \ud835\udc56(\ud835\udc58)) \u2212d(\ud835\udc65\ud835\udc56,\ud835\udc65+ \ud835\udc56(\ud835\udc58)) + \ud835\udc5a \u0011 , d(\ud835\udc65\ud835\udc4e,\ud835\udc65\ud835\udc4f) = sim(emb(\ud835\udc65\ud835\udc4e), emb(\ud835\udc65\ud835\udc4f)) (2) The distance \ud835\udc51(\ud835\udc65\ud835\udc4e,\ud835\udc65\ud835\udc4f) is calculated by the Euclidean distance between embeddings of two data \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc4e) and \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc4f). The function \ud835\udc60\ud835\udc56\ud835\udc5a() calculate the semantic similarity. 3.3 Data Construction To train the sentence embedding model via contrastive learning, it is critical to construct pairs of examples where the positive examples and negative examples need to be distinct from each other [31]. In our work, since we use triplet contrastive loss, instead of pairs of examples, we will construct trios of examples where each triplet contains an anchor, positive, and negative example. We use profile data to construct triplets of examples. For the profile data, it is generated by the user during the user-LLM interaction and contains the user preference information. There exists two situations for such data. First, the profile data can contain explicit labels indicating the user preferred response to the corresponding content. Second, the profile data also can be statements containing the user-related information but without explicit user preferences As shown in Figure 5, to deal with the two situations, we come up with two data construction methods: Construction Data with Explicit labels (CDE) and Construction Data with Implicit labels (CDI). \u201cJake Blues, just released from prison, puts his old band back together to save the Catholic home where he and his brother Elwood were raised.\u201d is \u201cdystopia\u201d negative r = 0.1 r = 0 r = 0 \u201cFresh out of prison, Jake Blues rallies his old band to save their childhood Catholic home\u201d is \u201cclassic\u201d positive example (embedding) \u201cJake Blues, just released\u2026\u201d is \u201cclassic\u201d anchor example (embedding) \u201cJake Blues, just released \u2026\u201d is \u201cdystopia\u201d negative example (embedding) r = 0.1 \u201cVictims of traumatized \u2026\u201d r = 0 r = 0.9 CDE CDI E anchor/positive example negative example \u201cTwo victims of traumatized childhoods become lovers and serial murderers irresponsibly glorified by the mass media.\u201d anchor/positive/negative example \u201cTwo people with traumatic pasts turn into a couple on a crime spree, mistakenly idolized by the media.\u201d \u201cIndividuals, mired in traumas, unite *() crime-ridden bond, enthrall\u2606\u2609\u00a7ing the media's distorted spotlight.\" \u201cJake Blues, just released from prison, puts his old band back together to save the Catholic home where he and his brother Elwood were raised.\u201d is \u201cclassic\u201d explicit label Statement/implicit label Figure 5: Examples of the two data construction methods. For data with explicit labels, CDE is used to construct the training data. For data without explicit labels (implicit labeled data), CDI is used to construct the training data. 3.3.1 Construction Trios via Data with Explicit Labels (CDE). For the data with explicit labels, each of the data consists of a textual content c and its corresponding label l which indicates the user preferred response regarding to the content c. As shown in the CDE part in Figure 5, there exists explicit label circled by dashed line. Using the profile data, we will construct triplet examples in the format of (\ud835\udc65\ud835\udc56,\ud835\udc65\u2212 \ud835\udc56,\ud835\udc65+ \ud835\udc56). Given a dataset D with size of \ud835\udc5bprofile documents, each piece of data consists of a content \ud835\udc50\ud835\udc56and the corresponding label \ud835\udc59\ud835\udc56where \ud835\udc56\u2208{1, 2, ...,\ud835\udc5b}. The anchor example \ud835\udc65\ud835\udc56can be constructed as: \ud835\udc65\ud835\udc56= \ud835\udc50\ud835\udc56\u2295\ud835\udc59\ud835\udc56, for \ud835\udc56= 1, 2, . . . ,\ud835\udc5b (3) where \u2295denotes a concatenation operation, specifically used here to combine label and content. Negative examples \ud835\udc65\u2212 \ud835\udc56can be constructed by concatenating \ud835\udc50\ud835\udc56with a random label \ud835\udc59\ud835\udc57that is different from \ud835\udc59\ud835\udc56as follows: \ud835\udc65\u2212 \ud835\udc56= \ud835\udc50\ud835\udc56\u2295\ud835\udc59\ud835\udc57, where \ud835\udc59\ud835\udc56\u2260\ud835\udc59\ud835\udc57. (4) Randomly assigning a different label ensures diversity in the negative examples while maintaining the same content from the anchor. Different from constructing anchor and its negative examples, it is challenging to construct positive examples corresponding to the anchor examples since it is more difficult to formalize semantically similar data than to formalize semantically dissimilar data. To construct positive examples, we follow the SimCSE method [32] to add a dropout rate \ud835\udc5finto the sentence embedding model M. The process for constructing positive examples involves two main steps. First, the textual positive example is formalized as: \ud835\udc65+ \ud835\udc56= \ud835\udc65\ud835\udc56, for \ud835\udc56= 1, 2, ...,\ud835\udc5b (5) where we align each anchor with the corresponding positive example. This step effectively duplicates the anchor data as a starting point for generating the embeddings. \fRobust Implementation of Retrieval-Augmented Generation on Edge-based Computing-in-Memory Architectures Second, the embedding generation process varies based on the dropout rate applied within the model M. When model M is utilized to generate embeddings for anchor and negative examples, the dropout rate is set to 0. In contrast, for generating embeddings for positive examples, a non-zero dropout rate \ud835\udc5fis used. The anchor, negative, positive examples, as shown in Figure 5, can be constructed as: \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56) = M(\ud835\udc65\ud835\udc56,\ud835\udc51\ud835\udc5f\ud835\udc5c\ud835\udc5d\ud835\udc5c\ud835\udc62\ud835\udc61= 0) \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\u2212 \ud835\udc56) = M(\ud835\udc65\u2212 \ud835\udc56,\ud835\udc51\ud835\udc5f\ud835\udc5c\ud835\udc5d\ud835\udc5c\ud835\udc62\ud835\udc61= 0) \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65+ \ud835\udc56) = M(\ud835\udc65+ \ud835\udc56,\ud835\udc51\ud835\udc5f\ud835\udc5c\ud835\udc5d\ud835\udc5c\ud835\udc62\ud835\udc61= \ud835\udc5f) (6) The condition of \ud835\udc5f\u22600 can induce variation in the embeddings, enhancing the model\u2019s ability to recognize semantically similar yet variably expressed content. Given the construction factor \ud835\udc3e, we can construct the triplet data examples as: D\ud835\udc61\ud835\udc5f\ud835\udc56\ud835\udc5d\ud835\udc59\ud835\udc52\ud835\udc61= \ud835\udc41 \u00d8 \ud835\udc56=1 n (\ud835\udc65\ud835\udc56(\ud835\udc58),\ud835\udc65\u2212 \ud835\udc56(\ud835\udc58),\ud835\udc65+ \ud835\udc56(\ud835\udc58)) : \ud835\udc58= 1, 2, . . . , \ud835\udc3e o (7) For the triplet data examples D\ud835\udc61\ud835\udc5f\ud835\udc56\ud835\udc5d\ud835\udc59\ud835\udc52\ud835\udc61, their embeddings for each augmentation \ud835\udc58are given by: E = \ud835\udc41 \u00d8 \ud835\udc56=1 n (\ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56(\ud835\udc58)),\ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\u2212 \ud835\udc56(\ud835\udc58)),\ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65+ \ud835\udc56(\ud835\udc58)) : \ud835\udc58= 1, 2, . . . , \ud835\udc3e o (8) As shown in Figure 5, for data with explicit labels, a content\ud835\udc50can concatenate with its corresponding label \ud835\udc59to formalize the positive and anchor example. That content \ud835\udc50can also concatenate with other labels \ud835\udc59\u2032 to formalize the negative example. The positive example can be finally obtained from the sentence embedding model with dropout rate \ud835\udc5f. The anchor and negative example can be finally obtained from the sentnece embedding model with \ud835\udc5f= 0. 3.3.2 Construction Trios via Data with Implicit Labels (CDI). For data with implicit labels, each of the data consists of solely textual content c. As shown of the CDI part in Figure 5, there is no explicit label to indicate user preferences. Instead, the data can be seen as a statement containing some user-related information. To construct the anchor examples and positive examples, we can use the exact same method in EDC. Given a dataset D with size of n profile data, each piece of data consits of a content \ud835\udc50\ud835\udc56. The anchor data \ud835\udc65\ud835\udc56can be constructed as: \ud835\udc65\ud835\udc56= \ud835\udc50\ud835\udc56, for \ud835\udc56= 1, 2, . . . ,\ud835\udc5b (9) For each anchor data \ud835\udc65\ud835\udc56, constructing its corresponding negative example is not as simple as merely concatenating the content\ud835\udc50\ud835\udc56with a non-corresponding label \ud835\udc59\ud835\udc58. To construct negative examples, we employ a reciprocal approach with the positive examples, applying a similar method to both. We first initialize the negative example and positive example following the equation 5: \ud835\udc65\u2212 \ud835\udc56= \ud835\udc65+ \ud835\udc56= \ud835\udc65\ud835\udc56, for \ud835\udc56= 1, 2, . . . ,\ud835\udc5b (10) For the positive example \ud835\udc65+ \ud835\udc56, it can be finalized by incorporating a dropout rate \ud835\udc5finto the sentence embedding model M, where a rate of 0 < \ud835\udc5f\u22640.2 can generate a sentence embedding with a semantic representation similar to \ud835\udc65\ud835\udc56and ensure good model training performance [32]. Increasing the dropout rate to a higher value, such as 0.5, can distort the semantic representation of \ud835\udc65+ \ud835\udc56, making it dissimilar to that of \ud835\udc65\ud835\udc56. Training the model with such positive examples can result in poorer performance. For positive examples in training the sentence embedding model, the higher dropout rate performs more like a noise rather than a data augmentation method. In our work, we train the sentence embedding model to generate embeddings that maintain their integrity under noisy conditions, such as during writing into Compute-in-Memory (CiM). The noise can alter or fragment the original semantic representations. For instance, as illustrated in Figure 5, using a high dropout rate \ud835\udc5f= 0.9 can lead to a negative example with a corrupted representation. Although it may lack certain informative content, this negative example becomes semantically distinct from both the anchor and positive examples, effectively simulating the effect of CiM corruption. This approach not only differentiates the negative examples semantically but also aligns them with the corrupted data scenarios for noise-aware training. Given the triple examples (\ud835\udc65\ud835\udc56,\ud835\udc65\u2212 \ud835\udc56,\ud835\udc65+ \ud835\udc56), for \ud835\udc56= 1, 2, ...,\ud835\udc5bas shown in equation 10, we have the dropout rate \ud835\udc5ffor formalizing the positive examples where 0 < \ud835\udc5f\u22640.2. Correspondingly, the dropout rate for formailzing the negative examples can be 1 \u2212\ud835\udc5f. Given the sentence embedding model M, the anchor example, positive example, and negative example can be constructed as: emb(\ud835\udc65\ud835\udc56) = M(\ud835\udc65\ud835\udc56, dropout = 0) emb(\ud835\udc65\u2212 \ud835\udc56) = M(\ud835\udc65\u2212 \ud835\udc56, dropout = 1 \u2212\ud835\udc5f) emb(\ud835\udc65+ \ud835\udc56) = M(\ud835\udc65+ \ud835\udc56, dropout = \ud835\udc5f) (11) 3.4 Flexible Noise-aware Training In the previous two stages, we construct the data to train the sentence embedding model based on contrastive learning. Meanwhile, the training can be more effective when injecting the simulated device variation [33] so that the model can be optimized with consideration of the device variation. Additionally, the sentence embedding model needs to produce embeddings that can fit with the different CiMs, which might have various NVM designs. To do that, we need the sentence embedding model reshapes its output embeddings into certain dimensions and precision. Hence, we propose a flexible noise-aware training method, which can generate the noise-resilient embedding, fitting to various CiMs. As shown in Figure 3, in the flexible noise-aware training module, the embedding generated by sentence embedding model will be shaped based on the CiM\u2019s NVMs constraints where required dimension is \ud835\udc51and required precision is \ud835\udc5d, and being injected device variation to formalize the embeddings. The reshape module, shown in Figure 3, seen as an autoencoder to reconstruct its input embedding [34], can be expressed as \ud835\udc60\u210e\ud835\udc5d(), initialized by \ud835\udc51 and \ud835\udc5d, takes the anchor embedding \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56) as input. We can have \ud835\udc60\u210e\ud835\udc5d(\ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)) = \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)\ud835\udc51\u2217\ud835\udc5d. Based on the device variation shown as Table 2, we can have: \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)\ud835\udc51\u2217\ud835\udc5d \ud835\udf0e = (\ud835\udc52\u2032 \u2217\ud835\udc3f0 + \ud835\udc52\u2032 \u2217\ud835\udc3f1 + \ud835\udc52\u2032 \u2217\ud835\udc3f2 + \ud835\udc52\u2032 \u2217\ud835\udc3f3) \u2217\ud835\udf0e, (12) \fRuiyang Qin1, Zheyu Yan1, Dewen Zeng1, Zhenge Jia1, Dancheng Liu2, Jianbo Liu1, Ahmed Abbasi1,Zhi Zheng1, Ningyuan Cao1, Kai Ni1, Jinjun Xiong2, Yiyu Shi1 Table 1: Performance comparison between our framework and four baselines on five CiM devices with device variation specified in Table 2 across five datasets. Evaluate the performance of our framework using EDC (RoCR-EDC) and using IDC (RoCR-IDC) to optimize the performance of RAG, which utilizes Gemma-2 as its LLM. Dataset Citation Movie Rating News DBLP CiM Method Acc \u2191 F1 \u2191 Acc \u2191 F1 \u2191 MAE \u2193 RMSE \u2193 ROUGE-1 \u2191 ROUGE-L \u2191 ROUGE-1 \u2191 ROUGE-L \u2191 Device-1 SWV 0.4208 0.3339 0.1305 0.1974 0.3850 0.8093 0.0754 0.0731 0.1709 0.1590 CxDNN 0.4223 0.3576 0.1516 0.1762 0.4404 0.9135 0.0640 0.0632 0.1646 0.1449 CorrectNet 0.4155 0.3791 0.0996 0.1305 0.3609 0.7071 0.0512 0.0764 0.1603 0.1538 Vanilla RAG 0.4401 0.3476 0.1017 0.0838 0.3903 0.8944 0.0754 0.0731 0.1731 0.1473 RoCR-CDE 0.5536 0.3956 0.2242 0.2303 0.3108 0.6856 0.1041 0.0987 0.2066 0.1924 RoCR-CDI 0.5409 0.5117 0.2273 0.2487 0.2767 0.6083 0.0831 0.0808 0.2317 0.2176 Device-2 SWV 0.1831 0.1552 0.1992 0.1957 0.4205 0.8775 0.0296 0.0289 0.1968 0.1874 CxDNN 0.4013 0.3557 0.2167 0.2019 0.4423 0.8367 0.0604 0.0791 0.1517 0.1401 CorrectNet 0.3827 0.3209 0.1625 0.1909 0.3762 0.8062 0.0513 0.0505 0.2042 0.1945 Vanilla RAG 0.4801 0.3462 0.1576 0.2079 0.4153 0.9354 0.0296 0.0289 0.1618 0.1353 RoCR-CDE 0.5407 0.4396 0.2924 0.2509 0.2553 0.5385 0.1209 0.0946 0.2025 0.1906 RoCR-CDI 0.5299 0.4591 0.2971 0.2386 0.2124 0.5763 0.0884 0.0853 0.2240 0.2098 Device-3 SWV 0.2450 0.2564 0.1695 0.1641 0.3460 0.7416 0.0725 0.069 0.1018 0.0954 CxDNN 0.4811 0.4006 0.2367 0.2113 0.2851 0.6928 0.0761 0.0707 0.1425 0.1111 CorrectNet 0.4510 0.3918 0.0792 0.1029 0.3704 0.7937 0.0585 0.0555 0.1715 0.1346 Vanilla RAG 0.4852 0.3618 0.1614 0.1636 0.3255 0.7649 0.0725 0.0690 0.1647 0.1437 RoCR-CDE 0.5139 0.4116 0.2242 0.2215 0.3208 0.6481 0.0825 0.0805 0.1893 0.1754 RoCR-CDI 0.5515 0.4984 0.2152 0.2131 0.2916 0.6245 0.1099 0.1049 0.2294 0.2140 Device-4 SWV 0.5135 0.4260 0.1271 0.1178 0.3610 0.8196 0.0259 0.0256 0.1871 0.1786 CxDNN 0.4733 0.3964 0.1267 0.2158 0.3468 0.7616 0.0646 0.0634 0.1603 0.1538 CorrectNet 0.4628 0.4019 0.1592 0.1847 0.4013 0.9274 0.0705 0.0750 0.1628 0.1292 Vanilla RAG 0.2101 0.2401 0.1219 0.2019 0.4015 0.8544 0.0505 0.0489 0.1929 0.1814 RoCR-CDE 0.5836 0.5555 0.1706 0.2817 0.3139 0.6856 0.0873 0.0851 0.1984 0.1882 RoCR-CDI 0.5352 0.4289 0.1642 0.2445 0.2706 0.5916 0.1154 0.1128 0.2148 0.1978 Device-5 SWV 0.4320 0.3541 0.1250 0.1076 0.3652 0.7616 0.0434 0.0427 0.0985 0.0923 CxDNN 0.4301 0.0538 0.0751 0.0458 0.3503 0.8185 0.0707 0.0682 0.2042 0.1945 CorrectNet 0.4145 0.3926 0.1083 0.1395 0.5526 0.8185 0.0735 0.0776 0.2096 0.1879 Vanilla RAG 0.4256 0.3522 0.0847 0.0863 0.3951 0.8515 0.0676 0.0653 0.2018 0.1846 RoCR-CDE 0.5698 0.5223 0.2152 0.1669 0.2959 0.6245 0.0936 0.0891 0.1946 0.1844 RoCR-CDI 0.5254 0.4504 0.2394 0.2458 0.2624 0.6325 0.0799 0.0764 0.2238 0.2095 where \ud835\udc52\u2032 = \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)\ud835\udc51\u2217\ud835\udc5d. The device variation, as noise, is injected into embeddings to formalize \ud835\udc52\ud835\udc5a\ud835\udc4f(\ud835\udc65\ud835\udc56)\ud835\udc51\u2217\ud835\udc5d \ud835\udf0e , which will be used in contrastive learning to train the sentence embedding model, as shown in Figure 3. 4 EXPERIMENTAL EVALUATION 4.1 Experimental Setup 4.1.1 Datasets. To demonstrate our robust CiM-backed RAG, we employ five datasets with different tasks and domains, including Citation Identification [35] (Citation), Movie Tagging [36] (Movie), Product Rating [37] (Rationg), News Headline Generation [38] (News), and DBLP-Citation-network V14 [39] (DBLP) to evaluate the proposed framework. The data in each dataset consists of query data and profile data. In our evaluation, the profile data will be used to formalize user history, and the profile corresponding query data will be used as the user input. The first three datasets contain binary, five-class, and fifteen-class classification tasks respectively. The last two datasets contain text generation tasks. In the Citation Identification dataset, every piece of query data consists of a paper title and two references, and the correct reference is provided. RAG uses the profile data corresponding to the paper titles with their detailed contents to choose the appropriate reference. In the Movie Tagging dataset, each query data contains a description of a movie, and RAG uses a similar description and its corresponding tag in the profile data to tag the query data. The Product Rating dataset has a similar structure as the Movie Tagging dataset. In News Headline Generation and DBLP datasets, each query data contains an abstract, which can be summarized into a title. RAG uses a similar abstract and its corresponding title in profile data to generate the title for query data. All five datasets have labels in their query data. 4.1.2 Default Experimental Setting. Our framework chooses all-MiniLM-L6-v2 [40] as the sentence embedding model. For each dataset, we randomly select 2000 documents from profile data as the anchor examples. To examine the data construction method of CDE, we set the augmentation factor \ud835\udc58= 5 to obtain 10000 negative and positive examples. We set dropout rate as 0.1 to obtain the positive examples while maintain it as 0 when process anchor and negative examples. To examine the data construction method CDI, we set dropout rate for positive examples as 0.1 and dropout rate for negative examples as 0.9. To align with experiments for CDE, we also set \ud835\udc58= 5 in the experiments for CDI. For the experimental results, we run five times and get the average. In experiments, we set the device variation \ud835\udf0e= 0.1 and shape embeddings into dimension of 64 with precision of \ud835\udc56\ud835\udc5b\ud835\udc618. The learning rate is 2\ud835\udc52\u22125. In all experiments, we adhere to the device variation model previously described. The specific parameters are abstracted and then simplified from three representative NVM devices, two of them \fRobust Implementation of Retrieval-Augmented Generation on Edge-based Computing-in-Memory Architectures D-1 D-2 D-3 D-4 D-5 0.2 0.4 0.6 0.8 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (a) Citation on Gemma-2B D-1 D-2 D-3 D-4 D-5 0.2 0.4 0.6 0.8 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (b) Citation on Phi-2 D-1 D-2 D-3 D-4 D-5 0.2 0.4 0.6 0.8 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (c) Citation on Mistral-7B D-1 D-2 D-3 D-4 D-5 0.2 0.4 0.6 0.8 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (d) Citation on Llama-2-3B D-1 D-2 D-3 D-4 D-5 0.0 0.1 0.2 0.3 0.4 0.5 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (e) Movie on Gemma-2B D-1 D-2 D-3 D-4 D-5 0.0 0.1 0.2 0.3 0.4 0.5 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (f) Movie on Phi-2 D-1 D-2 D-3 D-4 D-5 0.0 0.1 0.2 0.3 0.4 0.5 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (g) Movie on Mistral-7B D-1 D-2 D-3 D-4 D-5 0.0 0.1 0.2 0.3 0.4 0.5 Accuracy SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI (h) Movie on Llama-2-3B Figure 6: Performance comparison between our framework and four baselines on RAG utilizing the LLMs including Gemma-2B, Phi-2, Mistral-7B, and Llama-2-3B with device variation specified in Table 2, given dataset \ud835\udc36\ud835\udc56\ud835\udc61\ud835\udc4e\ud835\udc61\ud835\udc56\ud835\udc5c\ud835\udc5band \ud835\udc40\ud835\udc5c\ud835\udc63\ud835\udc56\ud835\udc52. Table 2: Device non-ideality modeling for different real and synthesized devices. For devices with more than two levels, the device variation for each level is depicted as \ud835\udc3f\ud835\udc65. Name # of Levels Device Variations \ud835\udf0e\ud835\udc63 \ud835\udc3f0 \ud835\udc3f1 \ud835\udc3f2 \ud835\udc3f3 \ud835\udc45\ud835\udc45\ud835\udc34\ud835\udc401 (Device-1) 1 0.0100 0.0100 0.0100 0.0100 \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc472 (Device-2) 4 0.0067 0.0135 0.0135 0.0067 \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc473 (Device-3) 4 0.0049 0.0146 0.0146 0.0049 \ud835\udc45\ud835\udc45\ud835\udc34\ud835\udc404 (Device-4) 4 0.0038 0.0151 0.0151 0.0038 \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc476 (Device-5) 4 0.0026 0.0155 0.0155 0.0026 are resistive random-access memory (RRAM) devices extracted from [27, 41] and the other is a ferroelectric field effect transistor (FeFET) device extracted from [42]. We name them \ud835\udc45\ud835\udc45\ud835\udc34\ud835\udc401, \ud835\udc45\ud835\udc45\ud835\udc34\ud835\udc404 and \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc472, respectively. We also extrapolate the modeling data to obtain two synthesized \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc473 and \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc476 devices. Detailed device modeling results are demonstrated in Table 2. A \ud835\udc65-level device means this device can represent \ud835\udc65distinct values and \ud835\udf0e\ud835\udc3f2 = 0.01 means the variation of this device is 0.01 when it is representing the level value 2. Using the device variations obtained from real CiM devices, we perform our experiments on a single Nvidia A10 GPU. Document embeddings are shaped based on different CiM devices and stored as parallel arrays, similar to how they would be mapped to multiple NVM devices in practical scenarios. For example, if an embedding is shaped to contain all uint8 values, when it is mapped to 4-level (2-bit) devices such as \ud835\udc39\ud835\udc52\ud835\udc39\ud835\udc38\ud835\udc472, each element of the vector is represented by four devices. 4.1.3 Evaluation Methods. Our first three datasets examine the model classification capability, and the rest of two datasets examine the text generation capability. In particular, dataset \ud835\udc36\ud835\udc56\ud835\udc61\ud835\udc4e\ud835\udc61\ud835\udc56\ud835\udc5c\ud835\udc5band \ud835\udc40\ud835\udc5c\ud835\udc63\ud835\udc56\ud835\udc52has two and fifteen labels respectively. We can examine the binary and multiclass classification capabilities of the LLMs enhanced by our framework. In this way, we use accuracy to examine the ability of the models to correctly classify instances across different classes, and we use F1 score to examine the balance between precision and recall in classification tasks. For dataset \ud835\udc45\ud835\udc4e\ud835\udc61\ud835\udc56\ud835\udc5b\ud835\udc54, while it has five labels and also examine the multiclass classification, we use mean absolute error (MAE) and root mean square error (RMSE) to evaluate from from a regression perspective [43]. For MAE, it measures the average magnitude of errors in the predictions, providing a straightforward assessment of the model\u2019s overall accuracy in predicting the rating values. For RMSE, it captures the square root of the average squared differences between predicted and actual ratings, offering a metric sensitive to larger errors, which can highlight significant discrepancies between the model\u2019s predictions and true values. For dataset \ud835\udc41\ud835\udc52\ud835\udc64\ud835\udc60and \ud835\udc37\ud835\udc35\ud835\udc3f\ud835\udc43, their labels are sentences. Such datasets examine the text generation capabilities. We use ROUGE1 and ROUGE-L to evaluate the overlap between generated texts and reference texts [44], capturing both the precision and recall of individual words (ROUGE-1) and the longest matching sequence (ROUGE-L), ensuring a comprehensive evaluation of the text generation quality. For accuracy, F1, ROUGE-1 and ROUGE-L, their higher values reflect the better performance. For MAE and RMSE, their lower value represent the better performance. Additionally, we use accuracy to measure the MIPS performance (MIPS accuracy), representing the ratio of MIPS results under device variation and MIPS results without device variation (references). 4.1.4 Baselines. As this is the first work to improve the RAG robustness on Edge-based CiM, we do not have state-of-the-art for comparison. As such, we construct baselines from the past noise mitigation methods originally designed to boost DNN robustness. The first baseline is selective write verify [21] (SWV). While it originally utilizes the second derivation to evaluate the device variation impact on neural network weights, we use the second derivation to measure the embedding deviation between the ground truth embedding and the embedding under device variation. The second baseline is (CxDNN) [45]. While they use compensation factor to improve the robustness of vector-matrix multiplication, we use the compensation factor the calibrate the embedding impacted by device variation. The third baseline is CorrectNet [46], where it utilizes the cross entropy loss and regularization to improve the robustness of neural networks in CiM. To use it as a baseline, we also use the cross entropy loss the regularization as the loss function to \fRuiyang Qin1, Zheyu Yan1, Dewen Zeng1, Zhenge Jia1, Dancheng Liu2, Jianbo Liu1, Ahmed Abbasi1,Zhi Zheng1, Ningyuan Cao1, Kai Ni1, Jinjun Xiong2, Yiyu Shi1 calibrate the device output embedding. Additionally, we examine the Vanilla RAG, which contains no noise mitigation methods, as our fourth baseline. The baselines use the same experimental setting as our framework does. 4.2 Results For RAG, it can be simplified as the combination of MIPS and LLM, where the MIPS as a retriever searches the appropriate information and the LLM as a generator processes the searched results. Hence, in our experiments, we first evaluate the performance of MIPS under the device variation of device-1. We take the MIPS results obtained without device variation as the references (i.e., ground truth). Using the metric of MIPS accuracy, we examine how many MIPS results under device variation will match the references. Since the quality of retrieved content largely depends on the base sentence embedding model, and we focus on mitigating the device variation impact on the embedding model, we do not assess the quality of references. As shown in Table 3, our framework using the two data construction methods outperforms the four baselines across five datasets. It shows that our framework can mitigate the embedding perturbation due to device variation. These results can also correspond to the preliminary study shown in Figure 2, where the increment of \ud835\udf0e in naive Gaussian noise will jeopardize the MIPS performance. Table 3: Performance (MIPS accuracy) comparison between our framework and baselines. Accuracy is computed based on MIPS-retrieved documents under device variation of device-1 and the these retrieved without device variation. Dataset Citation Movie Rating News DBLP SWV 0.4200 0.1728 0.1050 0.0855 0.2295 CxDNN 0.4401 0.2017 0.0503 0.0754 0.1681 CorrectNet 0.4013 0.0699 0.0509 0.0533 0.1609 Vanilla RAG 0.4547 0.1694 0.0933 0.0649 0.1747 RoCR-CDE 0.9231 0.4639 0.1583 0.1921 0.2750 RoCR-CDI 0.9344 0.4355 0.1266 0.1708 0.2905 After we compare the MIPS performance of our framework and baselines, we further present a comprehensive evaluation to show the RAG performance of them. We use Gemma-2B as the LLM in RAG. Additionally, with Gemma-2B, we run RAG without device variation to obverse its ideal performance, where we get 0.5200 of accuracy for Citation, 0.3728 of accuracy for Movie, 0.3150 of MAE for Rating, 0.0855 of ROUGE-1 for News, and 0.2295 of ROUGE-1 for DBLP. On five CiM devices, whose device variations have been shown in Table 2, we examine RAG with five datasets. As shown in Table 1, given the same datasets, it is clear that each device variation significantly compromises the RAG robustness, whereas our framework can mitigate the different device variation. For example, the RAG performance for Citation dataset on Device-2 can range from 0.18 to 0.48, while our framework can boost the accuracy performance of Citation dataset above 0.5 for all five devices. Compared to the four baselines whose performances are relatively worse than the ideal performance, our framework significantly approaches and sometimes outperforms the ideal performance via generating better sentence embeddings. This is because RoCR also serves as a regularization to improve the model\u2019s generalization. In addition, we evaluate the impact of different LLMs on the performance of our framework. As Figure 1 shown, the LLM takes the concatenation of MIPS searched data and user query as the input and generates the response regarding the user query. Since different LLMs may have different response given the same query, we select four emerging edge-friendly medium-size LLMs in our experiments to examine the performance of our framework. Gemma-2B [47] is a new SOTA open model introduced by Google, with 4.95G model weights. According to Google, Gemma can outperform the same sized Llama-2 in reasoning capabilities. Hence, we also use Llama2-3B [48], one of the earliest open LLMs introduced by Meta, with 6.85G model weights. Similarly, Phi-2 [49] released by Microsoft, is a powerful small LLM with 5G model weights. Additionally, Mistral7B-GPTQ [50] made by Mistral AI, is a well-performed LLM after Llama model. We select dataset \ud835\udc36\ud835\udc56\ud835\udc61\ud835\udc4e\ud835\udc61\ud835\udc56\ud835\udc5c\ud835\udc5band dataset \ud835\udc40\ud835\udc5c\ud835\udc56\ud835\udc63\ud835\udc52. We use the default experimental setting with \ud835\udf0e= 0.1 and use CiM Device-1 as the experimental environment. The results are shown on Figure 6. It is evident that our framework outperforms each baseline across five CiM devices. Besides, the performance of each baseline on the same dataset can be largely different given different device, while our framework can produce a more robust performance. 0.000 0.025 0.050 0.075 0.100 0.125 0.150 Device Variation ( ) 0.10 0.15 0.20 0.25 0.30 ROUGE-1 SWV CxDNN CorrectNet Vanilla RAG RoCR-CDE RoCR-CDI Figure 7: Performance comparison between our framework and four baselines on CiM device-1 with different device variation \ud835\udf0e, given dataset DBLP. By default, we use \ud835\udf0e= 0.1 to calculate the device variation of the five CiM devices. We also conduct an additional study to evaluate our framework given different \ud835\udf0evalues. Since we have already use dataset Citation and dataset Movie to study the performance of our frameworks seen in Figure 6, we choose a different dataset DBLP, using ROUGE-1 as the metric. For the LLM in RAG, we choose Mistral-7B. We examine the \ud835\udf0evalues higher and lower than 0.1, including 0, 0.025, 0.05, 0.075, 0.125, and 0.15. The case of \ud835\udf0e = 0 reflects the ideal performance. For the CiM device, we use CiM device-1. As shown in Figure 7, our framework outperforms baselines across different device variation values. Finally, RoCR is a training method that generates more robust weights for the sentence embedding model. It does not change the model structure. Thus, there is no hardware (e.g., energy and latency) overhead during inference. 5" + }, + { + "url": "http://arxiv.org/abs/2311.12275v4", + "title": "Enabling On-Device Large Language Model Personalization with Self-Supervised Data Selection and Synthesis", + "abstract": "After a large language model (LLM) is deployed on edge devices, it is\ndesirable for these devices to learn from user-generated conversation data to\ngenerate user-specific and personalized responses in real-time. However,\nuser-generated data usually contains sensitive and private information, and\nuploading such data to the cloud for annotation is not preferred if not\nprohibited. While it is possible to obtain annotation locally by directly\nasking users to provide preferred responses, such annotations have to be sparse\nto not affect user experience. In addition, the storage of edge devices is\nusually too limited to enable large-scale fine-tuning with full user-generated\ndata. It remains an open question how to enable on-device LLM personalization,\nconsidering sparse annotation and limited on-device storage. In this paper, we\npropose a novel framework to select and store the most representative data\nonline in a self-supervised way. Such data has a small memory footprint and\nallows infrequent requests of user annotations for further fine-tuning. To\nenhance fine-tuning quality, multiple semantically similar pairs of question\ntexts and expected responses are generated using the LLM. Our experiments show\nthat the proposed framework achieves the best user-specific content-generating\ncapability (accuracy) and fine-tuning speed (performance) compared with vanilla\nbaselines. To the best of our knowledge, this is the very first on-device LLM\npersonalization framework.", + "authors": "Ruiyang Qin, Jun Xia, Zhenge Jia, Meng Jiang, Ahmed Abbasi, Peipei Zhou, Jingtong Hu, Yiyu Shi", + "published": "2023-11-21", + "updated": "2024-04-16", + "primary_cat": "cs.CL", + "cats": [ + "cs.CL" + ], + "main_content": "INTRODUCTION While most Large Language Models (LLMs) are still deployed in cloud servers, more and more LLMs (e.g. Llama-3B with parameter size of 6GB) are being deployed on edge and mobile devices such as prompt-driven robots to assist people in daily life [3] and provide personalized companionship [10] while preserving users\u2019 privacy. Traditionally, most LLMs are pretrained in high-performance servers and then deployed in these devices without further training. However, such a generic model usually falls behind in adapting to each individual user\u2019s unique needs and habits. It is often desirable for the deployed LLMs to further learn from real-world input data (e.g. userand LLM-generated texts in their interaction), so that This work was supported in part by NSF 2324864, NSF 2122320, NSF 2324937, and NIH R01EB033387. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org. DAC \u201924, June 23\u201327, 2024, San Francisco, CA, USA \u00a9 2024 Copyright held by the owner/author(s). Publication rights licensed to ACM. ACM ISBN 979-8-4007-0601-1/24/06. https://doi.org/10.1145/3649329.3655665 the LLMs can be personalized and adapted to the user\u2019s immediate context in real-time. This allows more accurate and context-aware responses, improving overall effectiveness of the LLMs. Although LLMs are pre-trained in a self-supervised way through next-token prediction, existing work has demonstrated that their fine-tuning must be supervised, where human-written outputs for task instructions or annotated outputs in a specific task dataset are given. For on-device personalization, it is usually impractical to send new data to the cloud for annotation due to data privacy and security concerns [19]. As such, any annotation has to be done locally by directly asking users to provide preferred responses during the user-LLM interaction. Such annotations need to be sparse because frequent inquires impede the user experience of LLM. Thus, for on-device LLM personalization, it is desirable to learn from new streaming data in-situ with as few annotations as possible. In addition, for on-device personalization, considering limited hardware resources on the edge, it is necessary to learn from usergenerated data streams without accumulating a large dataset. In other words, a small data buffer should be used to form each minibatch for training. Existing LLM training methods assume that each mini-batch is independent and identically distributed (iid) by sampling uniformly at random from each semantic domain [6]. However, it is challenging to maintain the most representative data in the buffer so that learning from this buffer efficiently derives a model that is as effective as if the entire data is used. This is due to two reasons. First, the streaming data collected on edge devices are usually temporally correlated [14] and result in a correlation within each mini-batch. There can be a few rounds of uncontroversial dialogue sets before switching to those that contain useful information. Second, there is no easy way to select representative data for each domain topic such that the data contain rich information in each domain topic from non-iid streaming data, due to the fact that the streaming data are unlabeled. If annotations were available for all the data, we could easily select representative data based on all the annotations even if the streaming data were non-iid. Without addressing these challenges, directly learning from temporally correlated non-iid mini-batches would result in poor representations and inefficient personalization. To tackle the challenges of sparse local annotations and limited buffer size for on-device LLM personalization, in this paper, we propose to utilize embedding entropy, domain-related information, and embedding similarity to measure data quality from different perspectives in an unsupervised way. For each dialogue set in the data, the scores measured by the three metrics reflect the quality of the data regarding the information it contains as well as the domain it belongs to. Based on the three metrics, we propose a data replacement policy for the buffer, which always replaces the data in the buffer that has the lowest scores in these metrics if the arXiv:2311.12275v4 [cs.CL] 16 Apr 2024 \fDAC \u201924, June 23\u201327, 2024, San Francisco, CA, USA Qin et al. buffer is full and the new data have higher scores. To provide annotation needed in the fine-tuning, we ask users to provide preferred responses as annotations for all the data in the buffer. Finally, multiple semantically similar question-answer pairs can lead to better model fine-tuning [11]. Therefore, for each dialogue set selected to store in the buffer, we utilize the LLM to synthesize semantically similar pairs, also without user supervision. In summary, the main contributions of the paper include: \u2022 On-device LLM personalization framework. We propose a framework to form mini-batches of training data for fine-tuning LLM on the fly from the unlabeled input stream generated from user-LLM interactions. It only uses a small data buffer and eliminates the necessity of storing all the streaming data in the device. \u2022 Quality metrics for data selection. We propose a data replacement policy guided by three quality metrics to maintain the most representative data in the buffer for on-device LLM fine-tuning. Annotation is not needed in the data replacement process. \u2022 Data synthesis for labeled pairs. We propose to use the LLM model to generate additional data that are semantically similar to the selected data to enhance fine-tuning quality. As this is the first work for on-device LLM personalization, no state-of-the-art is available, and we constructed a few vanilla baselines for comparison. Experimental results on multiple datasets of varying temporal correlation including ALPACA [16], DOLLY [5], MedDialog [4], Prosocial-Dialog [12], OPENORCA [18], and Empathetic-Dialog [9] show that the proposed framework achieves up to 38% higher ROUGE-1 than the baselines and at the same time greatly improves the learning speed. Table 1: Three example domains and their lexicons. Domain Example Lexicons medical Admin dose vial inhale inject ml pills ingredient Anatomy Pelvis arm sinus breast chest lymph tonsil Drug ACOVA ACTONEL CARTIA EMGEL emotion Fear bunker cartridge cautionary chasm cleave Surprise amazingly hilarious lucky merriment Trust advocate alliance canons cohesion GloVe GloVeTW26 extreme potential activity impact movement GloVeCC41 symptomatic thrombosis fibrillation GloVeTW75 nyquil benadryl midol pepto midol ritalin 2 BACKGROUND AND RELATED WORK 2.1 Background 2.1.1 Text Domain. Text domain usually refers to either the text topic like medical conversation or the embedding lexicon dictionary such as GloVe embedding dictionary. The lexicons related to certain text domains are organized as TABLE 1 shown. The medical, emotion and GloVe are three domains. In each domain, high-level lexicons such as fear and drug are used to index the detailed lexicons shown in Example Lexicons in TABLE 1. 2.1.2 Text Embedding. Text embedding involves converting text data into machine-readable numeric data. The quality of this embedding can influence subsequent text learning tasks and is also intrinsically linked to alignment\u2014a crucial aspect of NLP [20]. A prevalent embedding method assigns unique indices to words based on their position within a comprehensive vocabulary dictionary. Consequently, the same word, regardless of its occurrence in different text data, can be represented consistently using its unique index. In this work, we adopt an embedding technique using a pretrained transformer model. This model not only captures semantic information but also offers superior alignment capabilities. 2.2 Related Work 2.2.1 LLM Personalization. LLM personalization employs fine-tune the model to enhance its capability of text-understanding and textgenerating in specific domains. While existing works concentrate more on scaling up the LLM to enable its comprehensive capabilities, some efforts [15] have been made to fine-tune LLM using relative small dataset with high quality. However, all these works still involve large-scale computation and high-intensive neural network training with the overwhelming dataset size regarding on-device learning, and they assume that each mini-batch can be formed by sampling from the dataset. But when learning from streaming data, data is collected sequentially as it is. Random sampling from the entire input stream to create iid mini-batches is infeasible since it requires to store all the data, which is unavailable for device storage and computationally intractable for device computational resources. Therefore, an approach to form mini-batches on-the-fly while including the most representative data in each mini-batch is needed to enable efficient on-device LLM learning. 2.2.2 Data Selection in Streaming and Continual Learning. There are several supervised streaming and continual learning models that can learn from a stream of data [1]. To overcome the problem of catastrophic forgetting of previously seen data, a data buffer is usually needed to store previous data for rehearsal [17]. However these works cannot handle text input with user-specific semantic domains due to the lack of semantic level data processing and evaluation of these works. Efficiently evaluating input text data and selecting the most representative text which can shape the LLM towards user-specific text generation on devices have not been explored and studied. 3 PROPOSED WORK In this section, we first provide an overview of our framework. We then delve into the details, starting from the three metrics we have found to benefit most for the data selection in LLM personalization, and demonstrate how they collaborate with the data buffer to select data. After that, we demonstrate the data synthesis method we use to augment the selected data and explain the reason to use that. 3.1 Framework Overview In our framework, we assume the atomic unit of data selection is a dialogue set, which contains a pair of question and answer during user-LLM interaction. As shown in Figure 1, the proposed framework has three stages. The first stage selects data to store in the data buffer based on \fEnabling On-Device Large Language Model Personalization with Self-Supervised Data Selection and Synthesis DAC \u201924, June 23\u201327, 2024, San Francisco, CA, USA Figure 1: Overview of the framework. Fine-tune LLMs using data from data selection and following data generating. certain quality metrics, and the selected data will be annotated by the user. The second stage takes the selected (and annotated) data and synthesizes additional data using the LLM. And finally, the selected and synthesized data together will be used for fine-tuning. In the discussion below, we focus on the first two stages where our framework resides. Specifically, with details discussed in Section 3.2, in the first stage, the proposed framework takes each dialogue set in the input streaming data from user-LLM interaction on-the-fly, calculate the quality metrics, and discard the data or update the data buffer based on the metrics. Considering the resource limitation, only a small data buffer is used to maintain the highest quality data. We will inquire user about the expected response as annotation for each selected dialogue set. With details discussed in Section 3.3, in the second stage, each selected dialogue set in the buffer is sent to the LLM for generation of additional dialogue sets that are semantically similar. We use the user annotation to replace the LLM generated response in the selected dialogue set. A pre-stored and fixed prompt is given to instruct the LLM for data generation. For the generated dialogue sets, a sanity check is made to make sure that their semantic similarity with the original dialogue set is above a user-specified threshold. 3.2 Data Selection by Quality Scores Each dialogue set\u2019s quality is captured by scores from three metrics. Each of them measures the quality of data from different perspectives as detailed below. Metric 1: Entropy of Embedding. Entropy of embedding (EOE) comes from the idea of Shannon\u2019s Entropy [22], where higher entropy means more features to learn. For each input \ud835\udc47, EOE aims to qualify and measure the information of embedding vector \u00ae E = \ud835\udc53(\ud835\udc47) generated by an end-to-end embedding function \ud835\udc53(\u00b7). The embedding vector \u00ae E = [\ud835\udc521,\ud835\udc522, . . . ,\ud835\udc52\ud835\udc5e] where \ud835\udc52\ud835\udc56is the embedding of the \ud835\udc56\ud835\udc61\u210etoken in the input and \ud835\udc5eis the length of the embedding. \ud835\udc38\ud835\udc42\ud835\udc38(\u00b7) can then be defined as: EOE(\u00ae E\ud835\udc56) = \u2212\u00cd \ud835\udc52\ud835\udc56\u2208\u00ae E \ud835\udc5d(\ud835\udc52\ud835\udc56) log\ud835\udc5d(\ud835\udc52\ud835\udc56) log(\ud835\udc5b) (1) where \ud835\udc5d(\ud835\udc52\ud835\udc56) represents the probability distribution of \ud835\udc52\ud835\udc56, and \ud835\udc5b is the number of tokens in \ud835\udc47. The term \ud835\udc5d(\ud835\udc52\ud835\udc56) log\ud835\udc5d(\ud835\udc52\ud835\udc56) represents the contribution of each token\u2019s embedding to the overall entropy. The normalization by log(\ud835\udc5b) adjusts for the effect of the sequence length, ensuring that entropy is comparable across sequences of different lengths. Metric 2: Domain Specific Score. While EOE measures the amount of information the input data contains, it cannot provide assessment regarding how much the information can be related to certain domains. As shown in TABLE 1, the domain of medical, emotion, and GloVe embedding can include distinct lexicons. The value of a dialogue set with respect to a particular domain can then be indicated by the token overlapping between the dialogue set and the common lexicons in each domain. Note that this would require a pre-stored dictionary containing common lexicons of domains of interests in the device, which can be easily constructed. Given a dialogue set \ud835\udc47containing \ud835\udc5btokens, and a collection of lexicon set \ud835\udc3f= {\ud835\udc591,\ud835\udc592, . . . ,\ud835\udc59\ud835\udc5a} from \ud835\udc5adifferent domains, the Domain Specific Score (DSS) can be calculated as: DSS(\ud835\udc47, \ud835\udc3f) = 1 \ud835\udc5a \ud835\udc5a \u2211\ufe01 \ud835\udc56=1 |\ud835\udc47\u2229\ud835\udc59\ud835\udc56| \ud835\udc5b (2) where it measures the ratio of tokens in \ud835\udc47belonging to every domain lexicons and output the mean of all ratios across all the domains. As domain can be highly important when adapting LLM to different tasks, the texts in different domains should not be compared to each other purely using EOE, and the text in the same domain should be evaluated together. Metric 3: In-Domain Dissimilarity. While DSS calculates the general overlapping between \ud835\udc47and all domain lexicons, it is important to evaluate how much value \ud835\udc47brings to the domain it overlaps most with, i.e., the dominant domain. The dominant domain can be obtained as: \ud835\udc37\ud835\udc5c\ud835\udc5a\ud835\udc51= arg max \ud835\udc59\ud835\udc56\u2208\ud835\udc3f |\ud835\udc47\u2229\ud835\udc59\ud835\udc56| (3) When a dialogue set is stored in the buffer, we also store its dominant domain and its embedding. When a new dialogue set is considered, we identify all the dialogue sets already in the buffer that have the same dominant domain as the new set, and compute the dissimilarity between them, which will reflect the amount of new information that can be brought by the new set to the dominant domain. Specifically, the In-Domain Dissimilarity (IDD) can be calculated by cosine embedding similarity: IDD(\u00ae E, \ud835\udc35) = 1 \ud835\udc45 \ud835\udc45 \u2211\ufe01 \ud835\udc56=1 (1 \u2212cos(\u00ae E, \u00ae E\ud835\udc56 \ud835\udc37\ud835\udc5c\ud835\udc5a\ud835\udc51)) (4) where E\ud835\udc56 \ud835\udc37\ud835\udc5c\ud835\udc5a\ud835\udc51is the embedding vector of the \ud835\udc56\ud835\udc61\u210edialogue set in the buffer \ud835\udc35that has the same dominant domain as \ud835\udc47, and \ud835\udc45is the total number of such dialogue sets in \ud835\udc35. cos(\u00ae E, \u00ae E\ud835\udc56 \ud835\udc37\ud835\udc5c\ud835\udc5a\ud835\udc51) is the cosine \fDAC \u201924, June 23\u201327, 2024, San Francisco, CA, USA Qin et al. similarity between \u00ae E and \u00ae E\ud835\udc56 \ud835\udc37\ud835\udc5c\ud835\udc5a\ud835\udc51, calculated as: cos(\u00ae E, \u00ae E\ud835\udc56 \ud835\udc37\ud835\udc5c\ud835\udc5a\ud835\udc51) = \u00ae E \u00b7 \u00ae E\ud835\udc56 \ud835\udc37\ud835\udc5c\ud835\udc5a\ud835\udc51 \u2225\u00ae E\u2225\u2225\u00ae E\ud835\udc56 \ud835\udc37\ud835\udc5c\ud835\udc5a\ud835\udc51\u2225 (5) Note that we store the embedding of all the selected dialogue sets in the buffer, so that they do not need to be re-computed each time a new dialogue set is being evaluated. Quality Score Based Data Selection. When a new dialogue set arrives and the buffer is full, we need to decide whether this new set needs to be discarded, or to replace a dialogue set already in the buffer. If the latter, we also need to decide which set in the buffer needs to be replaced. In our framework, for each new input dialogue set\ud835\udc47, its EOE, DSS, and IDD scores will be computed and compared with these scores of all the data in the buffer. If all the three metrics of \ud835\udc47are higher than a dialogue set already in the buffer, then we use \ud835\udc47to replace it. Note that if there are more than one options to replace, we will randomly select one. Users will then be asked to provide annotation to this new dialogue set, for example, by asking \u201cDo you think my response is acceptable and if not what would be an ideal response?\u201d If users provided an alternative response that is preferred, the dialog set will be updated using the user provided content before being placed into the buffer. Finally, from the definition of the three metrics and the replacement policy, it is easy to see that for each new dialogue set, our data selection policy has a linear complexity with respect to the size of the buffer. 3.3 Data Synthesis The selected data in the buffer can capture features unique to the user. However, when such data are used in LLM fine-tuning, the limited size can confine the effectiveness. To address this problem, inspired by the observation that multiple semantically similar question-answer pairs can lead to better model fine-tuning[11], we deploy a self-generated instruction strategy to generate additional data. Specifically, each dialogue set (i.e., \u201coriginal\u201d dialogue set) in the buffer will be sent to the LLM to generate similar ones, by giving the following prompt \u201cPlease refine and generate a text semantically similar to the following text block, no need to answer it, no need to explain, use [ ] to hold your generated response: \u201d followed by the original dialogue set. We run this multiple times to generate several additional sets for each original one. To avoid complicating the data replacement, the data synthesis process will only occur right before the fine-tuning starts each time. However, sometimes we find that the dialogue sets generated by LLM, even though the prompt instructs it to generate semantically similar ones, still differ from the original dialogue set significantly, if measured by ROUGE-1. As such, we add a sanity check for each generated dialogue set, and if ROUGE-1 between it and original set is above a threshold, it will be discarded. 4 EXPERIMENTAL EVALUATION 4.1 Experimental Setup We first explain the datasets used in the experiments, the settings under different experiments, and baselines. Datasets. To show the generalization capability of our framework, we use multiple and diverse datasets, including ALPACA [16], DOLLY [5], MedDialog [4], Prosocial-Dialog [12], OPENORCA [18], and Empathetic-Dialog [9], to evaluate the proposed framework. These datasets reflect different temporal correlation scenarios in the input data stream: ALPACA, DOLLY and OPENORCA contain diversified dialogue sets not bounded to a single domain, and the input data streams formed on them have little temporal correlation. While the other three ones are domain-specific, and thus the data streams are highly temporal correlated. All these datasets are fully annotated. However, our framework only uses annotations for the data selected to finetune the LLM; and the fully annotated dataset is used in the evaluation. Default Experimental Setting. We use a pre-trained Llama-3B [21], one of the most popular on-device LLM, as the model embedded on devices. For each dataset, we randomly choose 10% of the data to simulate input data stream and run our framework on it for model fine-tuning, and the remaining 90% is reserved for evaluation of the fine-tuned mode. For every 800 dialogue sets received in the input stream, we will start the fine-tuning process with 100 epochs using optimizer AdamW. The buffer will not be cleared after the fine-tuning, and the data selection continues after the fine-tuning is done. We obtain input text embedding from Llama-3B last hidden layer during its inference. Unless otherwise mentioned, in data synthesis each dialogue set in the buffer is sent to LLM to generate three additional sets. With the selected and synthesized data, we fine-tune Llama-3B using Low-Rank Adaptation (LoRA) [8], a parameter efficient fine-tune technique. Unless otherwise specified, the batch size is 128 with fixed learning rate of 0.0003. For LoRA settings, the trainable layers are the QKV layers (q_proj, k_proj, v_proj) and attention output layer (o_proj), max sequence length is 512, LoRA rank r is 8, loRA metrics scaling facotr alpha is 16, and LoRA dropout rate is 0.05. For consistency, when we use the fine-tuned model to generate text for evaluation, the temperature \ud835\udf0f is set to 0.5 for all experiments. As for the data selection buffer design, for efficient memory operations, we divide it into bins of equal size and each bin is able to hold the text of one dialog set, its domain as well as its embedding. Considering that the maximum dialogue set is of length 1,024 tokens (512 tokens x2) and the embedding is a floating point vector of length 4,096 for Llama-32B, the bin size is set to 22KB. In the experiments, we will explore the impact of the buffer size. To make sure that our framework can be applied to the various edge devices, we explore buffer sizes from 32 bins (704KB) to 512 bins (11MB). To efficiently evaluate our framework, we use compact, 150 watt, single-slot A10 GPU, which is much smaller than 300 watt double-width A100 GPU. A10 is compatible to fit into robotics applications. ROUGE-1 as Evaluation Metric. After the LLM model is finetuned using our framework, for each dialogue set in the test set, we feed the same user question to the model and collect the response generated. The quality of the data can then be evaluated by measuring the overlapping between the generated responses and the responses in the test dialogue set under the same question, which can be captured by ROUGE-1. ROUGE-1 is commonly used in natural language processing to measure the overlap of unigrams \fEnabling On-Device Large Language Model Personalization with Self-Supervised Data Selection and Synthesis DAC \u201924, June 23\u201327, 2024, San Francisco, CA, USA (a) ALPACA (b) DOLLY (c) Prosocial-Dialog (d) Empathetic-Dialog (e) OPENORCA (f) MedDialog Figure 2: The learning curve of our proposed framework, Random Replace, FIFO Replace, and K-Center with buffer size 281KB on datasets (a) ALPACA (b) DOLLY (c) Prosocial-Dialog (d) Empathetic-Dialog (e) OPENORCA (f) MedDialog. (single words) between the machine-generated summary and a reference summary in terms of F-1 score [13]. A higher ROUGE-1 score suggests that the generated text is more similar to the reference text. Table 2: ROUGE-1 of different methods on six datasets with data buffer 2816KB Random FIFO K-Center Ours ALPACA 0.2457 0.2013 0.2384 0.3736 DOLLY 0.2417 0.1976 0.2403 0.3465 Prosocial 0.2375 0.2190 0.2147 0.3062 Empathetic 0.2352 0.1902 0.2098 0.3260 OPENORCA 0.2286 0.1833 0.2048 0.2813 MedDialog 0.2465 0.2074 0.2204 0.3429 Baselines. As this is the first work on on-device LLM personalization, we do not have state-of-the-art for comparison. As such, we construct a few vanilla baselines. Random Replace is recently used for continual learning [7]. It selects data uniformly at random from new data to replace the ones already in the buffer. FIFO Replace is also recently employed for continual learning [7]. It replaces the oldest data in the buffer with new data. K-Center is a SOTA active learning approach [23] which selects the most representative data by performing k-center clustering in the features space. While not directly used in LLM personalization, these works also do not require labeling information and seemingly simple, and have demonstrated superior performance in maintaining image data for continual learning. In addition, to demonstrate the importance to consider all the three metrics EOE, DSS and IDD, we will perform ablation study on additional three baselines, each only using one of the three for data selection. For fair comparison, for all of these methods we used the same data synthesis based on the selected data as used in our framework. 4.2 Results We start with comparing the ROUGE-1 of Random Replace (Random), FIFO Replace (FIFO), and K-Center on all the datasets using buffer size 128 bins (2816 KB). The results are presented in TABLE 2. From the table we can see that our method outperforms all the baselines by a significant margin, indicating that its superiority in both weak and strong temporal correlation settings. The results also show that the most competitive baseline is the seemingly simple, yet surprisingly effective approach random replace. These results match the results in [2] for image classification tasks, where a random replacement policy outperforms elaborately designed approaches. Table 3: ROUGE-1 based on MedDialog with different buffer sizes. Buffer Size (KB) Ours Random FIFO K-Center 176 0.3040 0.2281 0.2383 0.2160 352 0.3447 0.2455 0.2304 0.2175 704 0.3353 0.2536 0.2389 0.2080 1408 0.3353 0.2791 0.2417 0.2204 2816 0.3940 0.2638 0.2309 0.2073 5632 0.3944 0.2748 0.2381 0.2167 11264 0.4215 0.2834 0.2315 0.2122 Next, as a very important profiling tool for on-device learning, we evaluate the learning curve of the proposed framework and the baselines on these datasets. The learning curve represents how well the LLM can be fine-tuned to generate user-specific text with respect to the number of input dialogue sets seen as the data streams in. The same buffer size is used. The results are depicted in Figure 2 (a)-(f), respectively. From all the figures, we can clearly see that the ROUGE-1 of the proposed framework consistently increases with the increase of seen data, while the ROUGE-1 of the baselines only demonstrate minor improvement. In addition, we evaluate the impact of buffer size on the performance of the proposed framework. The model is trained on the \fDAC \u201924, June 23\u201327, 2024, San Francisco, CA, USA Qin et al. MedDialog dataset. The number of bins in the buffer is in {8, 16, 32, 64, 128, 256, 512} corresponding to a buffer size of {176KB, 353KB, 704KB, 1408KB, 2816KB, 5632KB, 11264KB} respectively. The corresponding learning rate is scaled to {2, 3, 4, 5, 7, 10, 14} X 10\u22125, roughly following a learning rate \u221d \u221a batch size scaling scheme. The proposed framework consistently outperforms the baselines under different buffer sizes. As shown in TABLE 3, under the different buffer sizes, the ROUGE-1 by the proposed framework maintains a clear margin over the baselines. Besides, the margin becomes larger as the buffer size increases. This is because a larger buffer size provides the framework a better opportunity to select more high quality data, and the framework can leverage this opportunity to maintain richer quality data for learning, while the baselines cannot. Also, the proposed framework achieves higher ROUGE-1 when the buffer size becomes larger. This is because a larger buffer size provides a larger batch size, which naturally benefits the LLM fine-tuning. Table 4: ROUGE-1 of our framework and the baselines using only one of the three metrics EOE, DSS or IDD on six datasets with buffer size 2816KB. EOE DSS IDD Ours ALPACA 0.2821 0.2726 0.2950 0.3736 DOLLY 0.2782 0.2633 0.2247 0.3465 Prosocial 0.2617 0.2441 0.2324 0.3062 Empathetic 0.2661 0.2726 0.2707 0.3260 OPENORCA 0.2468 0.2362 0.2468 0.2813 MedDialog 0.2608 0.2726 0.2931 0.3429 Finally, we perform two ablation studies. The first one is to demonstrate the advantage of simultaneously considering all the three quality metrics EOE, DSS and IDD, we modify our framework to use only one of them for data replacement, those only considering one of them. The results on all six datasets are presented in TABLE 4. From the table we can see that simultaneously considering all the metrics always achieves the highest ROUGE-1. Figure 3: ROUGE-1/training time on MedDialog dataset with different number of dialogue sets generated from each original set in the buffer. The second study shows the relationship between the number of additional sets generated during data synthesis for each original dialogue set in the buffer and ROUGE-1/training time per epoch. From Figure 3 we can see that the maximum gain in ROUGE-1 can be attained when six additional sets are generated, while the training time consistently increases. Generating more then six dialogue sets will not further boost the performance, but would cost more time to fine-tune the model. For the sake of balanced efficiency and preference , as mentioned in the experimental setup, in all the experiments we generated three additional dialogue sets. 5" + }, + { + "url": "http://arxiv.org/abs/2112.02994v1", + "title": "IBERT: Idiom Cloze-style reading comprehension with Attention", + "abstract": "Idioms are special fixed phrases usually derived from stories. They are\ncommonly used in casual conversations and literary writings. Their meanings are\nusually highly non-compositional. The idiom cloze task is a challenge problem\nin Natural Language Processing (NLP) research problem. Previous approaches to\nthis task are built on sequence-to-sequence (Seq2Seq) models and achieved\nreasonably well performance on existing datasets. However, they fall short in\nunderstanding the highly non-compositional meaning of idiomatic expressions.\nThey also do not consider both the local and global context at the same time.\nIn this paper, we proposed a BERT-based embedding Seq2Seq model that encodes\nidiomatic expressions and considers them in both global and local context. Our\nmodel uses XLNET as the encoder and RoBERTa for choosing the most probable\nidiom for a given context. Experiments on the EPIE Static Corpus dataset show\nthat our model performs better than existing state-of-the-arts.", + "authors": "Ruiyang Qin, Haozheng Luo, Zheheng Fan, Ziang Ren", + "published": "2021-11-05", + "updated": "2021-11-05", + "primary_cat": "cs.CL", + "cats": [ + "cs.CL", + "cs.AI" + ], + "main_content": "INTRODUCTION The cloze test is a test in which the participant is asked to supply words that have been removed from a passage. Cloze tests are generally used to evaluate a participant\u2019s ability to comprehend the given text. One signi\uffffcant di\ufffference between the cloze task from other Natural Language Processing (NLP) problems is that the former requires a considerably larger long-term memory to make decisions and the ability to comprehend this content. Solving the cloze tests will provide insight into existing NLP tasks in text comprehension. In this paper, we employ a BERT-based sequence-to-sequence (Seq2Seq) model to solve the cloze task. Given a speci\uffffc context in the form of a passage, the solution of a cloze problem based on this context is generated in two steps: understanding the meaning of the idiom and choosing the correct idiom for each \u201cblank\u201d \u2013 where the original word is removed \u2013 in the passage. Previous research approaches NLP problems similar to the cloze task by applying neural network models such as the Knowledgeable Reader [9] and Entity Tracking [5]. These aforementioned approaches treat idioms as regular phrases. However, idiomatic expressions usually have meanings that are highly non-compositional and should not be \u2217All authors contributed equally to this research. understood from a literal standpoint. For example, if we look at the idiom word by word literally, the expression \"it\u2019s raining cats and dogs\" describes cats and dogs falling form the sky. This understanding is apparently incorrect as we generally use this expression to describe a heavy rain. Failure to understand the correct meaning of idiomatic expressions is detrimental to the decision-making process of the models, as even if a model is good enough to comprehend the passage itself, it cannot associate an expression that, from the literal perspective, is completely unrelated to the context. This calls for di\ufffferent approaches to the cloze task as our model is required to not only provide a grammatically sound candidate, but also ensure that the semantical meanings are coherent as well. Previous work on contextual relation understanding has yielded solutions with excellent performance. The BERT [3] performs well at understanding the contextual meaning of a given context. Pretrained BERT and other similar models can be adapted to perform contextual comprehension in other tasks. In this paper, we use pretrained models to solve the context comprehension step of the cloze task. To understand the meaning of idiomatic expressions correctly, we employ another pretrained model XLNET [20] and \uffffne-tune it to solve the cloze task. We train XLNET to learn not only the local context of the removed word (the sentence from which an original word is removed), but also the global context (the entire passage). This knowledge is represented by the last layer output of the hidden layers in XLNET. The contextual embeddings generated by our BERT-based pretrained models are combined with the idiom embeddings from the XLNET model. Softmax [8] is applied to decide on the best word from the combined embeddings. Our models are \uffffne-tuned on the EPIE [14] Static Corpus dataset. The remainder of the paper is organized as follows. Section 2 introduces some related work in cloze-style reading comprehension and modern NLP and Deep Learning technologies. Section 3 describes the method we developed to solve the challenge our problem. Section 4 describes our experiment to examine the performance of the models. Finally, Section 5 and 6 present the result and conclusion of our experiment and research work. 2 RELATED WORK 2.1 Cloze-style reading comprehension Cloze-style reading comprehension uses a passage of word tokens G1:=, with one token G9 masked; the task is to \uffffll in the masked word y, which was originally at position j. There already have a lot of works achieve a great performance in the cloze work [5, 9, 15]. \fRuiyang Qin, Haozheng Luo, Zheheng Fan, and Ziang Ren And Researchers created many large-scale cloze-style reading comprehension datasets yet, such as RACE [6], Children\u2019s Book Test (CBT)[4]. However,these research work only works on the normal words to \uffffnished the Cloze-style reading comprehension, and the idiom phrases are oftentimes non-contextual in the paragraphs. In this research e\uffffort, we want to utilize the most advanced technologies in our tasks to get the state of the art performance in the Idiom Cloze-style reading comprehension. The dataset we use EPIE used in this paper is also a large scale cloze-style dataset but focuses on English idiom prediction. 2.2 Pre-trained Language Models During daily usage, enormous sources of unilateral context can in\uffffuence the model\u2019s accuracy. In practice, it\u2019s highly possible to have the issue that they do not have symbols after sentences and polysemous condition in the sentence. There are previous researches on improving word embedding [10, 12], but it still cannot help us solve the challenge in our tasks. With the milestone of the appearance of transformer [19], there were several pre-trained models proposed in the NLP area like BERT and XLNet. With the various research, Language model pre-training has been proven to be e\uffffective over a list of natural language tasks at both sentence level [2] and token level [18] 2.3 Idiom detection A lot of research work are beginning forces on the idiom clozestyle reading comprehension. The \uffffrst popular neural network reading comprehension models were the Dual Embedding Model with bert [17]. In this previous work from Tan et al. [17], they use the BERT model to encode the contextual sentence as well as candidate phrases. However, the normal BERT model have the shortcoming to handle the long text sequence and lack of con\uffffdence in commonsense pragmatic inference. Also, the BERT model show mediocre performance in negation situation in the sentence. For some Cloze-style reading comprehension, it consist a huge context size and the related keys of cloze choice are far from the masks. Also, we could not ignore the condition of negation and commonsense in the challenge of the Cloze-style reading comprehension. 3 METHOD 3.1 Task De\uffffnition The main idea about our project is the idiom cloze test. We choose idiom as candidate and take o\uffffthe candidate from each sentence. For those candidates, they need to be \ufffflled into each blank spot. The \uffffrst thing is to padding each candidate. Then we need to \uffffnd the most appropriate candidate each time we hit the blank spot. 3.2 Padding Sequence In this part, we begin with processing the candidates. In our project, the \uffffrst step is to grasp idioms or candidates. We will search for the most appropriate candidate in the following steps. To do search, we have to process those candidates. The reason we have to do that is because every candidate has di\ufffferent length and it\u2019s hard to make any operations on those di\ufffferent-length candidates The default padding and probably the most usual padding is zero-padding, in which we add numbers of zeros in the back of each candidate. For the padding length, we will take the value of the longest candidate and use it as our padding length. This task can be achieved by calling speci\uffffc functions. We will need to search for longest candidate \uffffrst. Figure 1: Our Method Diagram about how our Attention Baselines works 3.3 Attention Baselines Previous methods applied to the BERT-based Dual Embedding [17] are only based on the BERT architecture. Because of the shortcoming in BERT and success of XLNET for many NLP task, especially reading comprehension, we proposed to present new methods (shown as Figure 1) based on XLNET and BERT to resolve the Idiom Cloze-style reading comprehension. The \uffffrst one, we treats a English idiom as a sequence of characters and we used the BERT to embedding the passage to analysis the original relationship in each contextual words. We combine the passges with each candidate idiom into a sequence and processes with multiple sequences, one for each candidate. The second baseline we treat the each idiom as a single token which has its own embedding vector and use XLNET to process the passage and then matches the encoded passage with each candidate idiom\u2019s embedding. \fIBERT: Idiom Cloze-style reading comprehension with A\uffffention Attention Baseline with Idioms as Character Sequence Attention baseline with idiom as candidate sequence is work to apply the BERT model for idiom cloze-style reading comprehension. Given a passage P = (?1, ?2, ?3, \u00b7 \u00b7 \u00b7 , [\"\ud434( ], \u00b7 \u00b7 \u00b7 , p=) and a candidate 3: 2 \u21e1, we \uffffrst concatenate them into a single sequence ([CLS], ?1, ?2, ?3, \u00b7 \u00b7 \u00b7 ,d=1,3=2, \u00b7 \u00b7 \u00b7 ,d=: , \u00b7 \u00b7 \u00b7 ,p=,[SEQ]), where3=1 to3=: are the characters and padding of the idiom3=. We can directly use the BERT to process this sequence and obtain the hidden representation for [CLS] in the last hidden layer, denoted by \u2318! :,0 2 R3. In order to detect the candidate idiom 3: among all the candidate, we use the linear layer to process \u2318! :,0 for : = 1, 2, \u00b7 \u00b7 \u00b7 , and use the softmax function with the each probability value of the candidates in D. After that, we will choose the best one candidate as the \uffffnal one for our cloze-style reading comprehension. Attention Baseline with Idiom Embedding Many idiom are non-compositional and therefore their meaning should not be directly derived from the its full individual characters. For example, \"It\u2019s a piece of cake\" literally means it is a number of cake, but it usually used to describe the task is pretty easy. Therefore, if we only embedding with its each characters meaning will cause a lot of confusion and a single embedding vector for the entire idiom can help the model understands the contextual relationship in the reading comprehension. In this baseline, instead of concatenating the passage and a candidate answer into a single sequence of BERT model, we separate them. We used the XLNET to process the passage sequence ([CLS], ?1,?2,?3, \u00b7 \u00b7 \u00b7 , [\"\ud434( ], \u00b7 \u00b7 \u00b7 ,p=,[SEP]). After that, we use the hidden representation of [MASK] at the decode layer, denoted as \u2318! 1, to match each candidate answer with BERT. In this way, no matter how much candidate we are, we only embedding the whole passage once with XLNET model. It can help our work prevent the problem of idiom\u2019s non-composition. We use 3: to denote the embedding vector for candidate 3: 2 \u21e1, the hidden representation \u2318! 1 is work with each candidate idiom via element-wise multiplication. Then the probability of selecting 3: among all the candidate is de\uffffned as equation 1. ?: = 4G?(F \u00b7 (3: \u2326\u2318! 1) + 1) \u00d5\u21e1 30=1 4G?(F \u00b7 (3: \u2326\u2318! 1) + 1) (1) whereF 2 R3 and1 2 R are model parameters, and \u2326is elementwise multiplication. To train the model, we use cross entropy loss as the loss function. 3.4 Context-aware Pooling The attention model baseline have potential problem. We can easily observe the idiom are always non-compositional. As a result, in order the idiom candidate can be \ufffft in the passage well, it not only the grammar should \ufffft with the contextual surrounding, also its meaning should also greatly \ufffft the whole passages. As those reason, how to get the candidate not just reasonable in grammar, such as verbs or noun, is importance for us to solve the cloze-style reading comprehension. That is why we need do some development on our baseline in order to context-aware. As the milestone of the transformer, the more and more pre-train model support the function of the context-aware with the contextual surrounding. Also, some models support the global contextaware, like the BERT work in SQuAD dataset [13]. As a result, we decide to evaluate whether a idiom candidate is suitable in a passage, we need not only understand its neighbour contextual details, also need to know the semantic meaning in the entire passage. That is why we need not only match the idiom candidate to place its context place on, also we must match it meaning with the entire passage. Recall that \ud43b! = (\u2318! 0,\u2318! 1,\u2318! 2, \u00b7 \u00b7 \u00b7 ,\u2318! =) represent the hidden states of the last hidden layer of baseline after it process the sequence. Our model with context-aware pooling can be work as equation 2. ?: = 4G?(3: \u00b7 \u2318! 1 + <0G= 8=0(3: \u00b7 \u2318! 8 )) \u00d5\u21e1 30=1 4G?(3: \u00b7 \u2318! 1 + <0G= 8=0(3: \u00b7 \u2318! 8 )) (2) 3.5 Dual Pretrain Attention Model In our method (Figure 1), we proposed use the linear interpolations [22] to make our solution of idiom detection for the cloze-style reading comprehension become more smooth. We perform linear interpolations in \uffffnal texture hidden space between both training output, one from the output of classi\uffffed with the softmax function in Attention Baseline with Idioms as Character Sequence, and the other is the possibility idiom candidate from the Attention Baseline with Idiom Embedding. We use the _ as a parameter of the weight to make sure both baseline can work smoothly on the \uffffnal output. In our model, The _ is a sample from beta distribution. We ensure the lambda larger than 0.7, ensure the Attention Baseline with Idioms as Character Sequence dominate the combination. With the linear interpolation, we can easily get a new possibility of the candidate and we choose the highest one as our \uffffnal candidate of the cloze-style reading comprehension. 4 DATA We evaluate the accuracy of the classi\uffffcation model with one standard dataset EPIE consisting of 359 kinds of candidate (listed as table 1) , and we make a program to create the classi\uffffcation what idiom should be used in cloze-type reading comprehension sentences. In our program we developed program to use self-attention for the task. After that, We use the training, validation, and test splits as de\uffffned in Lee and Dernoncourt [7] to analyse our loss score of the classi\uffffcation. Table 1 shows the statistics for dataset. There are many number of sentences to classify what kind of the idiom are the most reasonable in the sentence. All of idiom are normally used in the English speaking society and all types of the sentence are the condition of the idioms using. As table 1 shows, we have 21890 candidate as total. For each candidate, we have a corresponding tag (shown as 2). Both O, BIDIOM, and I-IDIOM represent the one position of words or special symbol. Given 1 sentence, we need to take o\uffffthe part which start from the \"B-IDIOM\" and end at the last position of \"I-IDIOM\". We got the 21890 sentences after deleting the candidate from the original sentences. \fRuiyang Qin, Haozheng Luo, Zheheng Fan, and Ziang Ren We use 3 types of labels for our data. For all 21890 candidate, we add a [\u2019CLS\u2019] at the beginning of the candidate and add [\u2019SEP\u2019] at end of the candidate in order to label our data. For all sentences which delete the candidate, we add a [\u2019CLS\u2019] at the beginning add [\u2019SEP\u2019] at end in order to label our deleting sentences, in addition to that, we add a [\u2019UNK\u2019] label at the position of the deleting candidate in the 21890 sentences. By the above labeling, we could encode all 21891 candidate and deleting sentences. The example is showing at table 3. Table 1: Number of Sentences in the Dataset Dataset Train Validation Test T N EPIE 15k 5k 2k 359 21890 |T| represents the number of idiom candidate and |N| represents the sentence data size Table 2: Type of Tags in the Dataset Type1 Type2 Type3 O B-IDIOM I-IDIOM Table 3: Example of Encoding and Labeling Original Sentence:Anyway , thanks MKM and keep up the good work ! Candidate:keep up the good work Label Candidate:\u2019[CLS]\u2019, \u2019keep\u2019, \u2019up\u2019, \u2019the\u2019, \u2019good\u2019, \u2019work\u2019, \u2019[SEP]\u2019 encode:11815, 17, 19, 3466, 414, 536, 692, 21, 435, 76, 18, 195, 154, 17, 136, 4, 3 deleting sentence:\u2019Anyway\u2019, \u2019,\u2019, \u2019thanks\u2019, \u2019MKM\u2019, \u2019and\u2019, \u2019! 5 RESULT We have compared the classi\uffffcation accuracy of our method with several other models (Table 4). We make the Dual BERT Embedding Model and Entity Tracking as the baseline. For methods using attention and deep contextualization word representation in some approaches to classify the idiom candidate of cloze-style reading comprehension, some of them use the self-attention for the task. However, they did not perform as well as our model. All models and their variables were trained eight times, making an average for the performance as a result. From our experiment, as shown as Figure 2, we can get our morel loss reduce with the epochs increase. And we make the cooperation with other two kinds of baselines and our method using the accuracy (Shown as table 4). As we can see, our method have 7.21% higher than the Dual BERT Embedding Model and 14.66% higher than the Entity Tracking in our challenge. That is reasonable that the Dual BERT Embedding Model is designed to solve the challenge of Chinese Idiom Cloze-style Reading comprehension and the Entity Tracking is only designed for the normal Cloze-style Figure 2: Epoch number and the loss Table 4: Accuracy of task in Idiom Cloze-style Reading comprehension Performance with baselines Model EPIE(%) Tan et al. [17] 71.02 Our Method 78.23 Entity Tracking [5] 63.57 Reading comprehension. The Idiom is pretty complex and Idiom always are non-compositional. It is hard to guarantee out methods can work on other kinds of Idiom yet, and from the work of Tan et al, we can see their Dual BERT Embedding Model have a better performance on Chinese Idiom Cloze-style Reading comprehension, they already reach the accuracy of 84.43% in Chinese conditions. 6" + } + ], + "Zheyu Yan": [ + { + "url": "http://arxiv.org/abs/2107.06871v1", + "title": "Uncertainty Modeling of Emerging Device-based Computing-in-Memory Neural Accelerators with Application to Neural Architecture Search", + "abstract": "Emerging device-based Computing-in-memory (CiM) has been proved to be a\npromising candidate for high-energy efficiency deep neural network (DNN)\ncomputations. However, most emerging devices suffer uncertainty issues,\nresulting in a difference between actual data stored and the weight value it is\ndesigned to be. This leads to an accuracy drop from trained models to actually\ndeployed platforms. In this work, we offer a thorough analysis of the effect of\nsuch uncertainties-induced changes in DNN models. To reduce the impact of\ndevice uncertainties, we propose UAE, an uncertainty-aware Neural Architecture\nSearch scheme to identify a DNN model that is both accurate and robust against\ndevice uncertainties.", + "authors": "Zheyu Yan, Da-Cheng Juan, Xiaobo Sharon Hu, Yiyu Shi", + "published": "2021-07-06", + "updated": "2021-07-06", + "primary_cat": "cs.AR", + "cats": [ + "cs.AR", + "cs.LG" + ], + "main_content": "INTRODUCTION Deep Neural Networks (DNNs) have achieved superhuman performance in various perception tasks and have become one of the most popular solutions for these applications. Thus, there is an obvious trend in deploying DNNs on edge devices such as automobiles, smartphones, and smart sensors. However, implementing computational intense DNNs directly on edge devices is a significant challenge due to the limited computation resource and constrained power budget of these devices. Moreover, most of the DNN accelerator designs are confined in a design space where the researchers only consider conventional von-Neumann architectures (e.g., GPUs, mobile CPUs, or FPGAs) as candidate platforms. In von-Neumann architectures, data movement inevitably becomes the bottleneck Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than ACM must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org. ASP-DAC 2021, Tokyo, Japan \u00a9 2021 Association for Computing Machinery. ACM ISBN 978-1-4503-7999-1/21/01...$15.00 https://doi.org/10.1145/3394885.3431635 0 20 40 60 80 100 FC Net LeNet ResNet56 VGG19 Accuracy (%) Model Original Deployed Figure 1: Accuracy differences between models trained in data center and deployed on CiM simulations for different neural architectures. FC Net and LeNet target MNIST, ResNet 56 targets CIFAR-10 and VGG-19 targets ImageNet. An accuracy drop close to 10% can be observed. for system efficiency, due to the well-known memory wall where the computational unit must fetch and store data from the memory hierarchy. Emerging device-based Compute-in-Memory (CiM) neural accelerators [5] offer a great opportunity to break the memory wall with special architectural advantages. CiM architectures offer reduced data movement by in-situ weight data access [17]. Highly efficient emerging devices (e.g. RRAMs, STT-RAMS, and FeFETs) can be devised to offer higher energy efficiency and higher memory density compared with traditional MOSFET [16] based designs. However, such accelerators suffer greatly from design limitations. Non-ideal conditions of emerging devices due to their non-ideal manufacturing process induce uncertainties on emerging devices. These uncertainties, such as device-to-device (D2D) variations, thermal noise, and retrieval limitations, cause value changes that, the weights in the actually deployed accelerators may be different from the desired weight value trained offline in data centers. This weight value change leads to performance degradation in actual accelerator implementations. As an illustration, we train the four models, multilayer perceptron (MLP) and LeNet for MNIST, ResNet 56 for CIFAR-10, and VGG-19 for ImageNet, to state-of-the-art accuracy and deploy them on CiM simulation tools [4]. As shown in Fig. 1, an accuracy degradation of close to 10% is observed in each model implementation. arXiv:2107.06871v1 [cs.AR] 6 Jul 2021 \fASP-DAC 2021, Tokyo, Japan Yan, Juan, Hu and Shi The device uncertainty-induced performance degradation has been studied from different perspectives, including device-level observations [25], architecture level analysis [6], and behavioral level explorations [21]. Finding suitable pairs of DNN models and hardware designs that can together offer both desirable hardware reliability and high inference accuracy requires great effort. Neural Architecture Search (NAS) [24, 26, 27] is one of the most successful efforts to address this issue. NAS liberates human labor from endlessly exploring optimal handcrafted DNN models by automatically identifying neural architectures that can offer desired performances from a pre-determined search space. Co-exploration of neural architecture and hardware design [7\u20139] pushes this concept further by incorporating hardware design specifications into NAS search spaces, so as to offer neural architecture-hardware design pairs that are accurate, efficient, and robust against hardware uncertainties. In this work, we adopt a statistical analysis perspective to study the effect of device uncertainties on the performance of DNNs. We model the emerging device uncertainty as a whole into Gaussian noise on weights and thoroughly investigate the behavior of different DNN models under such uncertainties. We conduct a Monte-Carlo simulation-based analysis on the statistical behavior of the models under the influence of device uncertainties. We then abstract our analysis results to offer supports for NAS applications. The detailed contributions of this work are: \u2022 We propose a Monte-Carlo simulation-based experimental flow to measure the device uncertainty-induced perturbations to DNN models. \u2022 We then thoroughly investigate the behaviors of different DNN models under such perturbations and show that the value changes of their output vectors follow Gaussian distribution. \u2022 To alleviate this effect, we then propose UAE, a device uncertaintyaware NAS framework, to search for architectures that are more robust to device uncertainties. Experimental results show that UAE offers a 2.49% higher accuracy than NACIM [6] with 1.2x of time consumption. By further increasing search complexity, UAE reaches 6.39% higher accuracy than NACIM with 2.5x of search time. 2 BACKGROUND 2.1 CiM DNN Accelerators Researchers have proposed different crossbar-based CiM DNN accelerator architectures [3, 16] for efficient DNN inference. We assume an ISAAC-like architecture [16], and the architecture of the system is organized into multiple tiles, with crossbar arrays as the heart of each tile. The crossbar not only stores the synaptic weights but also performs dot-product computations. One certain crossbar is dedicated to processing a set of neurons in a given DNN layer. The outputs of that layer are fed to other crossbars that are dedicated to processing the next layer. The computation in the crossbar is performed inanalog domain. However, ADC and DAC are used to convert the signal from and to the analog domain dot-product computation and other digital domain operations needed in DNN computation. Crossbar is the key component of CiM DNN accelerators. As shown in Fig. 2, a crossbar can be considered as a processing element for matrix-vector multiplication where matrix value (i.e. weights for NNs) are stored at the cross point of each vertical and horizontal line with resistive emerging devices such as RRAMs and FeFETs, and each vector value is propagated through horizontal data lines. In this work, we assume an RRAM-based design. The calculation in crossbar is performed in analog domain but additional peripheral digital circuits are needed for other key NN operations (e.g., nonlinear activation), so DAC and ADCs are adopted between different components. Device-level limitations confine the application of crossbars. The precision of ADC and DACs limits the precision of DNN activations for each layer and the non-ideal characteristics of emerging devices impose noises on the weights of deployed DNNs. DAC DAC DAC DAC ADC ADC ADC Mux Synapse Figure 2: Illustration on crossbar architecture. 2.2 Device Variation In this work, we assume an RRAM-based crossbar design. RRAM devices suffer various types of faults due to manufacturing and runtime non-idealities. Noise sources that are directly relevant to crossbar-based designs include thermal noise, shot noise, random telegraph noise (RTN), and programming errors [4]. When the circuitry is used for inference, programming errors due to deviceto-device variations could be the dominant error source. Write-and-verify [1, 15, 19] is a simple, accurate, and widely used programming scheme for RRAMs. The key operation is to iteratively apply a series of short pulses and check the difference between current and target resistance, converging progressively on the target resistance. In deploying accelerators for Neural Network inference, this time-consuming progress is tolerable because once programmed, no more modifications to the resistance are needed during the entire life span of the accelerator. Although this scheme pulls down the D2D variation-induced error to less than 1%, a significant error drop can still be observed in conditions shown in Fig. 1. 2.3 Neural Architecture Search Neural Architecture Search (NAS) has achieved state-of-the-art performance in various perceptual tasks, such as image classifications [22, 23], inference security [2] and image segmentation [20]. \fUncertainty Modeling of Emerging Device based Computing-in-Memory Neural Accelerators with Application to Neural Architecture Search ASP-DAC 2021, Tokyo, Japan NAS is becoming increasingly successful mainly because it liberates human designing labors by automatically identifying highperformance neural architectures. Co-exploration of neural architecture and hardware design [7\u20139] push this concept further by incorporating hardware design specifications into NAS search spaces, so as to offer neural architecture-hardware design pairs that are accurate, efficient, and robust against hardware uncertainties. Formally speaking, NAS deals with a problem that, given a perceptual task \ud835\udc47, a human-defined design space S, and a set of figures of merit (FOM) P, what is the best neural architecture in S that can offer optimal performance (in terms of FOM in P) on task \ud835\udc47. A typical reinforcement learning (RL)-based NAS that solves this issue, such as the framework proposed in [26], is composed of three key components, a controller, a trainer and an evaluator. In one iteration (named episode) of RL-based NAS, (1) the controller generates a neural architecture from the design space; (2) the trainer builds the generated neural architecture into a DNN model, named child network, and trains the child network on a held-out training dataset; (3) the evaluator collects the figures of merit (FOM), e.g., test accuracy of the trained child network on test dataset, its latency and/or energy consumption; and (4) the controller use a user-defined reward function to calculate a \ud835\udc5f\ud835\udc52\ud835\udc64\ud835\udc4e\ud835\udc5f\ud835\udc51data from FOM collected by the evaluator and use the \ud835\udc5f\ud835\udc52\ud835\udc64\ud835\udc4e\ud835\udc5f\ud835\udc51to update itself so that it can predict neural architectures with higher FOM. This iterative method terminates under two circumstances: (1) the controller repeatedly predicts the same child network; and (2) the number of predicted architectures exceeds a predefined threshold (episode limit). The child network that offers the highest reward among all the generated neural architectures is presented as the search result. The chosen neural architecture is then re-trained on the training dataset for a longer training time to offer optimal performance. More recently, differentiable NAS [12, 13, 18] has achieved stateof-the-art performance with a much-reduced search time by transforming the search process into training an over-parameterized neural network. However, those approaches suffer from flexibility. More specifically, in the field of research considered in this paper, differentiable NAS struggles in handling large search spaces with multiple different hardware design parameters and complex designs where the number of channels varies for each layer. Thus, in this work, we adopt RL based NAS as our search algorithm. 3 UNCERTAINTY MODELING 3.1 Uncertainty Model In this work, we model device uncertainties as a whole and use a Gaussian distribution to represent them [4, 6]. We set the mean of the uncertainty distribution to be zero, its variation to be 0.04, and for each device, its uncertainty is independently distributed. which is referred from [25], where the uncertainties are measured from actual physical devices. For an easier representation of the latter part of this paper, the uncertainty model is depicted as: \ud835\udc4a\ud835\udc37\ud835\udc52\ud835\udc5d= \ud835\udc4a\ud835\udc38\ud835\udc65\ud835\udc5d+ N(\ud835\udf07, \ud835\udf0e) (1) where N is a Gaussian variable which, on each individual element of the weights, is independent and identically distributed. \ud835\udc4a\ud835\udc38\ud835\udc65\ud835\udc5d and \ud835\udc4a\ud835\udc37\ud835\udc52\ud835\udc5dare the expected weights trained in the data center and the actual weights deployed on the accelerators, respectively. 3.2 Effects on DNN Outputs In this work, we focus on the impact of device uncertainty on classification tasks, and the reasons go as follows: (1) most emerging device-based DNN accelerators target classification tasks, analyzing the effect of device uncertainties on these tasks helps the majority of the researchers to improve their work; (2) DNNs for classification tasks are typically composed of convolution layers and fully connected layers, which are also the basic components of DNNs targeting other application. The effect of device uncertainties on these two components is essential for all types of DNNs. We start by understanding the effect of device uncertainties on the output of a DNN model. Formally speaking, a DNN model \ud835\udc40 can be defined as a combination of its neural architecture and its trained weights. Thus, the inference process of a DNN model with input I that generate an output O can be defined as: O = \ud835\udc39(\ud835\udc4a, I) (2) where \ud835\udc39is the neural architecture of \ud835\udc40, \ud835\udc4ais its weights, I is this input vector and O is the output vector. During training, O is then passed through a loss function, where a version of O after SoftMax is compared with the ground truth classification label \ud835\udc3a\ud835\udc47to generate a loss for the backpropagation process. During inference, the final predicted class of I can be calculated by \ud835\udc4e\ud835\udc5f\ud835\udc54\ud835\udc5a\ud835\udc4e\ud835\udc65(O), which is the index of the item in O that has the maximum value. Although in inference, classification result is the final outcome of a DNN model, the output vector O serves as a better representative of the behavior of this model. The classification result is only an index of the maximum value of O and is thus only a simplified discrete proxy of O. The continuous, multi-dimension vector O contains more information than the classification result. In order to understand how uncertainties in weights may affect the network, it is of crucial importance to understand how it affects O. As defined in 1 and 2, a deployed neural network under the effect of device uncertainties can be depicted as: O\ud835\udc37\ud835\udc52\ud835\udc5d= \ud835\udc39(\ud835\udc4a\ud835\udc37\ud835\udc52\ud835\udc5d, \ud835\udc3c) = \ud835\udc39(\ud835\udc4a\ud835\udc38\ud835\udc65\ud835\udc5d+ \ud835\udc41\ud835\udc57, \ud835\udc3c) (3) where \ud835\udc4a\ud835\udc38\ud835\udc65\ud835\udc5dis the trained value of the neural network to be deployed, \ud835\udc41\ud835\udc57is one sample from the noise distribution, and O\ud835\udc37\ud835\udc52\ud835\udc5dis the affected output. We analyze the distributional behavior of the effect of device uncertainties on the output vector of a DNN model. To conduct this analysis, we first (1) train a DNN model \ud835\udc39to converge and collects its trained weight \ud835\udc4a\ud835\udc38\ud835\udc65\ud835\udc5d. We then (2) fix one input image \ud835\udc3cand collect its output on the trained weight \ud835\udc4a\ud835\udc38\ud835\udc65\ud835\udc5d. We denote this output as the original output O\ud835\udc42\ud835\udc5f\ud835\udc56. After that, we (3) sample \ud835\udc3edifferent instances of noises \ud835\udc411, \ud835\udc412, ...\ud835\udc41\ud835\udc3eand then feed them to Eq. 3, collecting \ud835\udc3edifferent output vectors. Finally, we calculate output change using Eq. 4 O\ud835\udc36\ud835\udc3a= O\ud835\udc37\ud835\udc52\ud835\udc5d\u2212O\ud835\udc42\ud835\udc5f\ud835\udc56 (4) where the output change is the element-wise subtraction of the perturbed and original output. \fASP-DAC 2021, Tokyo, Japan Yan, Juan, Hu and Shi 3.3 Experimental Results In order to get a glance at the statistical behavior of output change, according to the workflow introduced in Sect. 3.2, we train a LeNet model for the MNIST dataset [11] to state-of-the-art accuracy. We then randomly choose one input image in the test dataset and sampled 10k different instances of noise. with this setup, we gathered 10k different output change vectors. The output change is a vector of 10, with each element representing the confidence of classifying the input image into one certain category. Because a high-dimensional vector is not a good choice for analytical study and visualization, we analyze each element of these vectors. We analyze the statistical behavior of each element across different vectors and gathered 10 instances of distribution data. Surprisingly, each element of the output change follows Gaussian distribution. To visualize this finding, we plot the histogram of the distribution of each element of output change vector and the corresponding Gaussian distribution that fits it. The visualization result for the first element of output change is shown in Fig. 3 that the first element of output change vector is a Gaussian variable. Figure 3: Output change distribution of LeNet for MNIST. 10k output change vectors are gathered from one trained LeNet model affected by 10k different instances of noise sampled from N (0, 0.04). This figure shows the distribution of the fist item of the gathered output change vectors. To verify this observation, We tested various networks in various datasets. With the MNIST dataset, we analyze both LeNet and multilayer perceptrons (MLP) using ReLU and Sigmoid activation with 2 layers. With the CIFAR-10 dataset [10], we test a conventional floating-point CNN, a quantized CNN, and two ResNets, ResNet56 and ResNet-110. We also train these models with 3 different initializations to get different trained weights. We evaluate how these output change vectors fit into Gaussian variables by two widely used standards: mean square error (MSE) and Chi-square (\ud835\udf122) test. MSE can be described as: \ud835\udc40\ud835\udc46\ud835\udc38= 1 \ud835\udc41 \ud835\udc41 \u2211\ufe01 \ud835\udc56=1 (\ud835\udc42\ud835\udc56\u2212\ud835\udc38\ud835\udc56)2 (5) and \ud835\udf122 test can be depicted as: \ud835\udf122 = \ud835\udc41 \u2211\ufe01 \ud835\udc56=1 (\ud835\udc42\ud835\udc56\u2212\ud835\udc38\ud835\udc56)2 \ud835\udc38\ud835\udc56 (6) where \ud835\udc42\ud835\udc56and \ud835\udc38\ud835\udc56are the observed (output change) and estimated (Gaussian) value of probability and \ud835\udc41is a user-defined granularity. We define \ud835\udc41= 100 because it is precise enough when we have a total of 10k instances of data. Model Dataset \ud835\udf122 (10\u22122) MSE (10\u22124) MLP-ReLU MNIST 5.22 3.20 MLP-Sigmoid MNIST 5.81 2.20 LeNet MNIST 4.59 2.67 Float-Conv CIFAR-10 7.01 3.03 Fixed-Conv CIFAR-10 6.79 2.74 ResNet-56 CIFAR-10 4.56 1.79 ResNet-110 CIFAR-10 4.81 2.01 Table 1: Gaussian fit for different models. The \ud835\udf122 test result and MSE between the output change and Gaussian distribution is presented. Both tests show that the output change follows Gaussian distribution w.r.t different instances of noise. The evaluation result is shown in Table 1. Note that we have test 3 different initializations for each model and for each model, \ud835\udc5c\ud835\udc62\ud835\udc61\ud835\udc5d\ud835\udc62\ud835\udc61\ud835\udc50\u210e\ud835\udc4e\ud835\udc5b\ud835\udc54\ud835\udc52is a vector of 10. The result shown in Table 1 is an average of them. For each model tested, \ud835\udf122 test results are all below 0.1 and MSE are all below 1 \u00d7 10\u22123, which indicates that they are well fit into Gaussian distributions. Moreover, both errors do not increase when the model is extremely shallow (e.g. 2-layer MLP) and very deep (RestNet-110), so this observation generalizes across different DNN models. The study on each of the models supports the previous observation that their output vectors values follow Gaussian distribution. Based on these studies, we can claim that, with any independent and identically distributed Gaussian noise on weight, the output vector of the same input image follows a multi-dimensional Gaussian distribution1 over different samples of noise. This is a very strong claim but is not counter-intuitive. The output of the first convolution layer is the summation of the multiplication result of deterministic inputs and Gaussianly distributed weights and is thus a summation of Gaussian distributions. The summation of Gaussian variables is also a Gaussian variable, so the output of the first layer is a Gaussian variable. After activation, the input of the second layer is a transformed Gaussian variable and after propagating through this layer, with enough number of operands, the accumulated variable can be approximated by Gaussian variables. Thus, although the final output may not strictly be a Gaussian variable, a Gaussian approximation can be observed. 4 UNCERTAINTY AWARE SEARCH 4.1 Methodology In addition to understanding the effect of device uncertainties, we propose a remedy method to reduce the effect of this issue by adopting NAS. In this work, we propose Uncertainty Aware sEarch (UAE), a more comprehensive uncertainty aware NAS for better exploration of neural architectures in non-ideal emerging devices based CiM NN accelerators. 1Note that each element of the output are deeply co-related, not independent \fUncertainty Modeling of Emerging Device based Computing-in-Memory Neural Accelerators with Application to Neural Architecture Search ASP-DAC 2021, Tokyo, Japan Similar to the state-of-the-art Reinforcement Learning based NAS framework NACIM [6], UAE works iteratively and in each iteration: (1) an LSTM-based controller is used to learn and generate neural architectures; (2) an uncertainty aware trainer is used to train each generated neural architecture to get a model to deploy; (3) an uncertainty aware evaluator is adopted to evaluate the actual performance of the deployed model; (4) the evaluated performance is used as a reward to update the controller so that it can generate neural architectures with higher rewards. The detailed implementation of the uncertainty aware trainer and evaluator are described below. 4.2 Uncertainty-Aware Training & Evaluation We adopt an uncertainty-aware training scheme similar to the one used in NACIM [6]. The training process is organized the same as traditional DNN training that, in each iteration, a subset (batch) of the training data is used to train the model, and after the whole training dataset has been used to train the model, and an epoch of training is finished and another epoch is started. The trainer trains the model for multiple epochs to get a trained model. The uncertainty-aware training augments the training process for each batch to learn a DNN model that is more robust against device variations. In each training batch, before feeding the input into the model, the trainer (1) save the original weight \ud835\udc4a\ud835\udc42\ud835\udc5f\ud835\udc56of the model; (2) sample a noise from the uncertainty distribution and add the noise to the weight of the model to form a \ud835\udc4a\ud835\udc37\ud835\udc52\ud835\udc5d; (3) perform forward inference and back propagation in the perturbed model and collect gradient data for each weight; (4) load the saved \ud835\udc4a\ud835\udc42\ud835\udc5f\ud835\udc56 back to the model and update\ud835\udc4a\ud835\udc42\ud835\udc5f\ud835\udc56with the collected gradient data via stochastic gradient descent. Uncertainty-aware training simulates the process of training DNNs directly on CiM-based accelerators. Experiments in NACIM show that uncertainty-aware training learns DNN models that are robust against device uncertainties. The uncertainty-aware evaluation is performed similarly to the training process. Before evaluation, the evaluator samples an instance of noise from the uncertainty distribution and add the noise to the trained weight \ud835\udc4a\ud835\udc42\ud835\udc5f\ud835\udc56to get a \ud835\udc4a\ud835\udc37\ud835\udc52\ud835\udc5d. The evaluator then evaluates the classification accuracy of the perturbed model on a test dataset. This process is performed for \ud835\udc3etimes and \ud835\udc3edifferent accuracy data are gathered. The evaluator then report one distributional property (e.g., mean, maximum value, 95% minimum value) of the \ud835\udc3eaccuracy data to form a reward. The distributional property to be used is specified by the user. 4.3 Experimental Results We demonstrate the effectiveness of UAE by searching for an optimal quantized CNN for CIFAR-10. The fixed design parameters and hyper-parameters included in the search space are shown in Table 2. For device uncertainty specifications, we assume an ISAAClike [16] neural accelerator architecture and a four-bit RRAM device, whose behavioral model is extracted from [25]. The search process is conducted in a GPU server machine with an Nvidia GTX 1080ti accelerator. As described in Sect. 4.2, there are two major search parameters: the instances (\ud835\udc3e) of noise sampled for each architecture and the Hyper-Parameters Value choices Dataset CIFAR-10 Type Quantized CNN # of Conv Layers 6 # of FC Layers 2 FC Hidden size 1024 # channels (24, 36, 48, 64) Filter Height/Width (1, 3, 5, 7) # of integer bits (0, 1, 2, 3) # of fraction bits (0, 1, 2, 3, 4, 5, 6) Table 2: Quantized CNN for CIFAR-10 search setups. Upperhalf: configurations fixed to be the same among all searched architectures; lower half: hyper-parameters to be searched. distributional properties used to form the accuracy data collected by the evaluator into a reward. We test two different values of \ud835\udc3e, 5, and 100 samples, for the reason that will be explained afterward. We also use two different distributional properties, one is the mean value of all accuracy data (mean) and the other is 95% minimum of the accuracy data (95). The mean value indicates how a model performs under the effect of device uncertainty in average circumstances and the 95% minimum shows the models\u2019 behavior in worst-case scenarios. We offer a comparison for different specifications of UAE and two baseline methods, quantNAS [14], a state-of-the-art NAS framework to search for the optimal quantized CNN and NACIM [6], another uncertainty aware searching framework for CiM-based accelerators. In each experiment, the NAS controller searches for 2000 different architectures (episodes) and the trainer trains each generated architecture for 15 epochs. The DNN models finally presented by each search framework are also evaluated by mean and 95% minimum value with their accuracy data collected by 10k Monte-Carol simulation. The experimental result is shown in Table. 3.2 Method \ud835\udc3e w/o noise mean 95 Time (h) QuantNAS [14] 0 84.92% 08.48% N/A 53 NACIM [6] 1 73.88% 73.45% N/A 98 UAE-M 5 77.48% 75.94% 75.55% 118 UAE-M 100 82.99% 79.84% 77.82% 255 UAE-95 100 80.64% 78.39% 77.98% 255 Table 3: Comparison for different specifications of UAE and two other baselines. Different methods sample different instances of noise (\ud835\udc3e) in uncertainty-aware evaluation. UAEM uses mean value of the accuracy data collected by the evaluator to form a reward and UAE-95 uses the 95% minimum data. Accuracy without noise shows the model accuracy with an ideal device and the mean and 95% minimum (95) value shows the behavior of the searched DNN models under the effect of device uncertainty, evaluated by MonteCarol simulation. 2Because the data for quantNAS and NACIM are collected from published work, we do not have the 95% minimum accuracy result for them. \fASP-DAC 2021, Tokyo, Japan Yan, Juan, Hu and Shi Experimental results show that, without uncertainty-aware training, QuantNAS can identify an optimal DNN model that can offer close to 85% of test accuracy, but struggles in finding proper neural architectures that are robust to device uncertainties, as the test accuracy of the DNN model identified by quantNAS is down to 8.5%, even worse than random guessing (10%). With the help of uncertainty-aware training, NACIM can identify DNN models that are robust against the impact of device uncertainties. However, as NACIM only evaluates the performance of the searched architecture once, the randomness of the device uncertainty hinders the performance of NACIM, resulting in a model with only 73.45% of average accuracy. UAE, on the contrary, is able to find DNN models that are both accurate and robust against the impact of device uncertainties. When collecting only 5 samples in uncertainty-aware evaluation, UAE achieves 2.49% higher accuracy than NACIM with a time overhead of only 20%. When collecting 100 samples in uncertaintyaware evaluation, UAE achieves 6.39% higher accuracy than NACIM a search time overhead of 2.5x. Though further increasing the number of samples is possible, the search time overhead will be too large to endure. The adoption of a 95% minimum value standard is also effective. UAE-95 offers 0.16% higher worst-case accuracy than its UAE-M counterpart with a 1.45% lower average accuracy. 5" + } + ], + "Zhenge Jia": [ + { + "url": "http://arxiv.org/abs/2212.08624v2", + "title": "Development of A Real-time POCUS Image Quality Assessment and Acquisition Guidance System", + "abstract": "Point-of-care ultrasound (POCUS) is one of the most commonly applied tools\nfor cardiac function imaging in the clinical routine of the emergency\ndepartment and pediatric intensive care unit. The prior studies demonstrate\nthat AI-assisted software can guide nurses or novices without prior sonography\nexperience to acquire POCUS by recognizing the interest region, assessing image\nquality, and providing instructions. However, these AI algorithms cannot simply\nreplace the role of skilled sonographers in acquiring diagnostic-quality POCUS.\nUnlike chest X-ray, CT, and MRI, which have standardized imaging protocols,\nPOCUS can be acquired with high inter-observer variability. Though being with\nvariability, they are usually all clinically acceptable and interpretable. In\nchallenging clinical environments, sonographers employ novel heuristics to\nacquire POCUS in complex scenarios. To help novice learners to expedite the\ntraining process while reducing the dependency on experienced sonographers in\nthe curriculum implementation, We will develop a framework to perform real-time\nAI-assisted quality assessment and probe position guidance to provide training\nprocess for novice learners with less manual intervention.", + "authors": "Zhenge Jia, Yiyu Shi, Jingtong Hu, Lei Yang, Benjamin Nti", + "published": "2022-12-16", + "updated": "2022-12-19", + "primary_cat": "eess.IV", + "cats": [ + "eess.IV", + "cs.CV", + "cs.HC", + "cs.LG" + ], + "main_content": "Introduction Automated acquisition guidance can help novice learners to study how to manipulate probes to acquire high-quality POCUS images. However, the di\ufb00erence between human vision and machine vision may confuse novice learners, because the guidance from sonographers and the DNN model may be inconsistent due to the di\ufb00erent interpretations of images between the DNN-based models and humans [6]. For example, DNNs rely more on textures and high-frequency features rather than shapes and low-frequency features. Our previous works show that machine learning based detection methods on medical image can achieve signi\ufb01cantly high accuracy [7\u201315]. This means images considered highquality for humans may not be high-quality for DNN-based machine vision. The discrepancy becomes more signi\ufb01cant due to the large inter-observer variability. As a result, if the acquired images are of high quality for both human and DNN-based segmentation models, the segmentation accuracy can be improved, and accordingly, the human e\ufb00orts needed to correct or identify the bad segmentation can be reduced. As an example in a closely-related area, previous works for medical image compression demonstrated that image compressed with machine vision considered achieved signi\ufb01cantly higher segmentation accuracy than conventional methods that only consider human vision at the same compression rate [16]. Therefore, we will explore methods to optimize the image quality assessment and acquisition guidance to be preferred by both human and machine models. 2 Methods The overall framework proposed is shown in Figure 1. During data acquisition, the scan is checked by sonographers to ensure high visual quality for humans. After that, the segmentation model will 1 \fMulti-Task DNN Image Quality Assessment 6D Distance (feedback together with 6D Distance) Figure 1: Framework of simultaneously optimizing image quality assessment and acquisition guidance by a multi-task DNN. produce segmentation results. Then a multi-task DNN will predict the quality of the input scan image according to the segmentation results, and meanwhile, the model will generate 6D (probe position plus orientation) geometric distances, which can be feedback to novice learners for guidance on how to move from the current probe location and the probe location anticipated to optimize the image. Here, such a DNN model needs to be conducted in a real-time manner, because the learners need immediate feedback from the model to learn how to move the probe. If the predicted quality is lower than the prede\ufb01ned threshold, the novice learner will be prompted to do a re-scan with guidance. The study/exam process is done once the predicted image quality exceeds the threshold (a max number of re-scans can be set to avoid too many trials). Because the prediction model helps learners to select the data that the model can segment well, the quality of the segmentation results and the subsequent medical analysis will be improved. Box 1. Equations C = cc R \u03b1f(\u03b1)d\u03b1; Eq.1 \u22c4C: Original average cost \u22c4cc: Average cost of correcting a failed segmentation \u22c4\u03b1: Probability of segmentation fails \u22c4f(\u03b1): Probability density function of \u03b1 C\u2032 \u03b1 = \u03b1(1 \u2212r)cc + \u03b1r p (cs + C\u2032 \u03b1); Eq.2 \u22c4C\u2032: New average cost \u22c4cs: Average cost of an additional scan \u22c4p: Precision of the quality prediction model \u22c4r: Recall of the quality prediction model C\u2032 \u03b1 = p\u03b1cc\u2212p\u03b1rcc+\u03b1rcs p\u2212\u03b1r ; Eq.3 h(\u03b1) = C\u2032 \u03b1 C\u03b1 = p\u2212pr+r cs cc p\u2212\u03b1r ; Eq.4 \u22c4h(\u03b1): Ratio of new cost to original cost for \u03b1 C\u2032 C = R \u03b1f(\u03b1)h(\u03b1)d\u03b1 R \u03b1f(\u03b1)d\u03b1 ; Eq.5 The key component of the framework is the multi-task DNN model for both image quality prediction and 6D distance generation. We will develop a DNN with a shared encoder (i.e., the front layers of DNN) to extract common features, and then it will be split into two paths for image quality assessment and acquisition guidance tasks, respectively. For the image quality assessment task, we will use a modi\ufb01cation of DNN-based segmentation model as the image quality prediction model. It can take advantage of existing techniques such as model architecture for image segmentation, uncertainty estimation of neural networks, and the attention mechanism. We will compare the quality prediction models that are trained to predict conventional quality metrics and the new quality metric proposed in Aim 1. In this way, we can additionally validate whether the new metric also helps in this framework. On the other hand, for the 6D distance generation task, we will add a tail after the encoder, and each output neuron will correspond to one distance in the 6D distance. We will track the image quality after the learners move the probe according to the predicted 6D distance to evaluate the e\ufb00ectiveness of the model. A threshold applied to the predicted image quality will control the learning loop. A low threshold means a re-scan is suggested only if the predicted image quality is quite low and thus the feedback information to novice learners is minimal. A high threshold means the data is satisfying only if the predicted quality is quite high which leads to higher image quality, and in turn, it indicates a strict requirement for learners. In practice, the threshold can be set based on the progress of the learner. The learning quality of a learner followed the proposed framework can be analyzed via a theoretical cost model. Because the cost for the initial scan and veri\ufb01cation are not a\ufb00ected by the proposed method, we focus on the cost of correcting segmentation and the cost of doing a re-scan in the analysis below. We consider the segmentation on the video obtained fails if correction is needed, and denote \u03b1 as the failure probability. A \ufb01xed \u03b1 for all subjects may be inaccurate because each subject may have a unique condition that makes it easier or more di\ufb03cult to obtain images that can be segmented well. Therefore, we consider each subject has a unique \u03b1 and repetitive scans for the same subject are independent. The original average per-subject cost is given in Eq. 1 (Box 1). The quality prediction model is used to identify failed scans. The new average cost for a certain \u03b1 is given in Eq. 2. The \ufb01rst 2 \fterm is for predicted passed segmentation and the second term is for predicted failed segmentation. Solving Eq. 2 we get Eq. 3. It can be derived that, for a certain \u03b1, the new average cost is lower than the original average cost if and only if p > \u03b1+ cs cc . This indicates a lower bound of precision can reduce the cost. Finally the ratio of the new cost C\u2032 to the original cost C is given in Eq. 4 and Eq. 5. 3 Results Table 1: Estimated cost reduction. \u03b1 is the probability of a segmentation fails. cs cc is the ratio of the scan cost to the correction cost. Cost reduction is 1 \u2212C\u2032 C . \u03b1 0.2 0.3 0.2 0.2 0.2 0.2 cs cc 0.1 0.1 0.2 0.1 0.1 0.1 Precision 0.8 0.8 0.8 0.6 0.9 0.7 Recall 0.8 0.8 0.8 0.6 0.7 0.9 Cost reduction 64% 57% 50% 37% 55% 69% This cost model re\ufb02ects how various factors a\ufb00ect the cost-saving of the proposed framework. f(\u03b1) accounts for the data distribution in the speci\ufb01c applications which can be estimated by examining the segmentation results of interest. Bigger \u03b1 leads to lower cost reduction because it takes more scans to obtain good segmentation. h(\u03b1) is determined by cs cc , p, and r. cs cc is the ratio of the re-scan cost to the correction cost which can be easily estimated by sonographers and radiologists. Smaller cs cc means smaller C\u2032 C and thus more cost reduction. An accurate prediction model is crucial for the cost reduction as re\ufb02ected by p and r. In Table 1, we provide a few numerical examples of the cost reduction when variables are set to typical values. The cost model shows a substantial possible cost reduction. 4" + }, + { + "url": "http://arxiv.org/abs/2008.08060v1", + "title": "Personalized Deep Learning for Ventricular Arrhythmias Detection on Medical IoT Systems", + "abstract": "Life-threatening ventricular arrhythmias (VA) are the leading cause of sudden\ncardiac death (SCD), which is the most significant cause of natural death in\nthe US. The implantable cardioverter defibrillator (ICD) is a small device\nimplanted to patients under high risk of SCD as a preventive treatment. The ICD\ncontinuously monitors the intracardiac rhythm and delivers shock when detecting\nthe life-threatening VA. Traditional methods detect VA by setting criteria on\nthe detected rhythm. However, those methods suffer from a high inappropriate\nshock rate and require a regular follow-up to optimize criteria parameters for\neach ICD recipient. To ameliorate the challenges, we propose the personalized\ncomputing framework for deep learning based VA detection on medical IoT\nsystems. The system consists of intracardiac and surface rhythm monitors, and\nthe cloud platform for data uploading, diagnosis, and CNN model\npersonalization. We equip the system with real-time inference on both\nintracardiac and surface rhythm monitors. To improve the detection accuracy, we\nenable the monitors to detect VA collaboratively by proposing the cooperative\ninference. We also introduce the CNN personalization for each patient based on\nthe computing framework to tackle the unlabeled and limited rhythm data\nproblem. When compared with the traditional detection algorithm, the proposed\nmethod achieves comparable accuracy on VA rhythm detection and 6.6% reduction\nin inappropriate shock rate, while the average inference latency is kept at\n71ms.", + "authors": "Zhenge Jia, Zhepeng Wang, Feng Hong, Lichuan Ping, Yiyu Shi, Jingtong Hu", + "published": "2020-08-18", + "updated": "2020-08-18", + "primary_cat": "cs.LG", + "cats": [ + "cs.LG", + "eess.SP", + "stat.ML" + ], + "main_content": "INTRODUCTION Sudden cardiac death (SCD) is one of the most signi\ufb01cant causes of natural death in the US, which occurs when the heart electrical system malfunctions and leads to 325,000 deaths per year [5]. There are two main causes of SCD, namely, ventricular tachycardia (VT) and ventricular \ufb01brillation (VF), which are the life-threatening ventricular arrhythmias (VA). For people under a great risk of SCD, implantable cardioverter de\ufb01brillator (ICD) is served as a preventive treatment. ICD is a small device implanted under the skin with wires inserted in the heart to detect the intracardiac rhythm [30]. This battery-powered device continuously monitors the intracardiac rhythm and is programmed to deliver a shock when VT or VF is detected, and bring the rhythm back to normal. While ICDs reduce the risk of SCD and increase survival rate, the ICD recipients might experience inappropriate shocks, which are the delivery of shock on the rhythm other than VT or VF. Inappropriate shocks have been associated with proarrhythmias, intolerable pain, and depression [16]. They have been reported to occur in 12% to 23% ICD recipients and constitute 30% to 50% of all shocks [8, 11, 13]. Current VT/VF detection methods count on a wide variety of criteria on intracardiac rhythm, such as heart rate, the number of intervals to detection (NID), and probability counter [3, 28, 31], where there are hundreds of programmable parameters a\ufb00ecting the detection performance. However, it is complicated to obtain the best parameters setting for each patient as it requires massive clinician experience and frequent manual intervention. Moreover, such optimization cannot be conducted in time since the ICD programming update could only be accomplished every 3-6 months [4]. Recently, deep learning technique has been widely applied on electrocardiogram (ECG) arrhythmias classi\ufb01cation using Convolutional Neural Network (CNN) [1, 10, 25]. The CNN-based arrhythmias classi\ufb01cation could eliminate the cumbersome criteria selections and parameters setting in traditional arrhythmia detection methods, while achieves decent detection accuracy. The objective of this paper is to propose a framework for deep learning based VT/VF detection. The framework addresses the following challenges: (1) Existing CNN-based detection models cannot be directly deployed on the implantable devices due to the hardware resources constraints, such as limited memory capacity and computational power; (2) The only intracardiac rhythm sensed by ICDs is the bottleneck for VT/VF detection accuracy improvement. Performing inference on surface and intracardiac rhythm simultaneously could improve the accuracy but the memory and energy overhead would signi\ufb01cantly increase; (3) The personalization of detection model for each patient su\ufb00ers from a long delay and frequent manual intervention on current ICDs platform. To tackle the above challenges, we propose P-VA, a Personalized computing framework and architecture for deep learning based VA detection. The overview of P-VA is demonstrated in Fig. 1. P-VA consists of two parts: the Detection Nodes and the Cloud. The Detection Nodes, which constitute an implantable node and a wearable node, detect VT/VF on intracardiac electrograms (IEGMs) and surface electrocardiograms (ECG) simultaneously. A CNN is designed and deployed on the both nodes to perform a real-time inference. To further improve the detection accuracy, we propose \fthe cooperative inference with a con\ufb01dence score thresholding policy, which enables two nodes to detect VT/VF collaboratively and signi\ufb01cantly reduce the memory and energy overhead by only transmitting the hardly-decidable rhythm segments. On the Cloud, we develop an in-time personalization using deep domain adaptation and a policy network to personalize CNNs for the speci\ufb01c patient. Evaluation results show that our detection nodes could e\ufb00ectively make each inference within 71ms on average. Furthermore, when compared with traditional detection algorithm, our method achieves a comparable VT/VF detection rate and 6.6% reduction in inappropriate shock rate. The main contributions of this paper are summarized as follows: \u2022 We present P-VA, a personalized computing framework for deep learning based VA detection, to improve the accuracy of VA detection. \u2022 To the best of our knowledge, this paper is the \ufb01rst to deploy a CNN on a resources-constrained and ultra-low power processor with real-time VT/VF detection. \u2022 The cooperative inference reduces the inappropriate shock rate by enabling the implantable and the wearable nodes to detect VT/VF collaboratively. \u2022 We develop an in-time personalization to personalize CNNbased detection model for each speci\ufb01c patient. The rest of the paper is organized as follows. In Section 2, background and motivation are introduced. Section 3 \ufb01rst provides an overview of the P-VA framework, followed by the construction of CNN-based detection model, the cooperative inference and the model personalization. Evaluation results of the proposed detection methods and its comparisons with the state-of-the-arts are shown in Section 4. Finally, Section 5 concludes the paper. 2 BACKGROUND AND MOTIVATION In this section, we \ufb01rst introduce the background of ICDs and the impedance of improving VT/VF detection accuracy on ICDs. Next we demonstrate the motivation of proposing deep learning based detection and the challenges in application and deployment. 2.1 VT/VF Detection in ICDs The ICD is implanted to deliver de\ufb01brillation on VT/VF, which are life-threatening VA leading to SCD. Until now, ICDs are still the best preventive treatment for the population under high risk of SCD. As aforementioned, patients with ICDs, however, might receive inappropriate shocks, which severely a\ufb00ect the patients\u2019 quality of life. According to the surveys, 12% to 23% of ICD recipients receive inappropriate shocks in the following 20 months to 11 years after implantation [11, 17, 19, 21]. The study [11] shows that the main cause of inappropriate shock comes from supraventricular arrhythmia misdiagnosed as VT (74.8% of inappropriate shocks). The optimization goal of ICDs is to improve the detection accuracy on VT/VF. However, there are three main obstacles to improve VT/VF detection performance. Complex detection criteria and parameter settings. Current VT/VF detection algorithms count on a combination of various criteria. In the detection programming, there are hundreds of programmable parameters a\ufb00ecting shock delivery decision. The modi\ufb01cation of non-nominal parameter settings (i.e., changing the ICD out-of-the-box factory default settings for the recipient) and innovation of new detection criteria are necessary for the improvement of detection accuracy. However, they require extensive clinician proactivity and engagement. Long delay in personalized detection. The criteria parameters are supposed to be optimized to accommodate the unique rhythm feature of each ICD recipient. After implanting an ICD, the recipient should be followed-up every 3-6 months [4]. During the follow-up, the detection criteria parameters would be \ufb01ne-tuned by a group of doctors based on historical records. However, the detection algorithms could not be updated in time due to the 3-6 months follow-up interval. The in-time personalized detection is unrealistic on the current ICDs platform since it requires massive manual intervention and expertise to \ufb01ne tune criteria parameters, which severely restrict the personalization frequency. Limited rhythm sources. In the current data sources acquisition, there is an intrinsic bottleneck in detection accuracy improvement, that is, ICDs detect VT/VF purely based on the sensed intracardiac rhythm. The involvement of surface rhythm would improve detection accuracy since there would be more rhythm information in the detection. However, due to the constraints in physical size and lifetime, the computational power and memory capacity of ICDs are severely restricted. The processing unit on ICDs must run with few hundreds of kilobyte of on-chip memory and an active power consumption below the 10 mW mark. Those constraints are the impedance to enable ICDs to detect surface rhythm simultaneously. 2.2 Deep Learning in Arrhythmia Detection Recently, deep learning has been applied to classify arrhythmias on ECGs by using convolutional neural networks (CNNs) and achieved outstanding performance in terms of accuracy [1, 7, 10, 12]. Different from existing detection algorithms, the deep learning based methods eliminates the process of criteria design and optimizations. It signi\ufb01cantly reduces the magnitude of cardiological expertise required in the detection parameters \ufb01ne-tuning. CNN could detect the arrhythmias with high accuracy if the training rhythm data is properly and accurately labeled by doctors. However, in ICDs scenarios, existing CNN models cannot be directly deployed. The limited memory capacity and real-time inference requirement are the impedance to deploy CNN models on ICDs. Further e\ufb00ort on the CNN architecture design should be applied to \ufb01t those hardware constraints. Moreover, only one welltrained CNN as a generalized detection model cannot accommodate all patients due to the unique rhythm features of each patient. The in-time personalization of each speci\ufb01c patient\u2019s CNN based detection model remains unsolved. Nevertheless, the improvement of the CNN model detection accuracy is also restricted by the limited rhythm sources. The inference mechanism on both surface and intracardiac rhythm could generate a more accurate prediction. 3 PERSONALIZED DEEP LEARNING FOR VA DETECTION In this section, we \ufb01rst provide an overview of the proposed VT/VF detection framework. Then we introduce the CNN-based detection 2 \fC1 C2 C3 C4 C5 F6 F7 C1 C2 C3 C4 C5 F6 F7 VT/VF Non VT/VF IEGM Segments CONV FC Implantable Node Detection Nodes C1' C2' C3' C4' C5' F6' F7' C1 C2 C3 C4 C5 F6 F7 C1 C2 C3 C4 C5 F6 F7 1. Unsupervised Domain Adaptation IEGM Domain ECG Domain 2. Policy Network Training Policy Network C1 C2 C3 C4 C5 F6 F7 Reward IEGM Segments Policy Prediction Gradient Domain Adaptation Policy Freeze Or Fine-Tuning Cloud All ECG Segments Hardly-decidable IEGM Segments Policy Network Detection Networks \u0102\u0102 All ECG Segments Hardly-decidable IEGM Segments Policy Network Detection Networks \u0102\u0102 C1' C2' C3' C4' C5' F6' F7' ECG Segments VT/VF Non VT/VF CONV FC C1' C2' C3' C4' C5' F6' F7' ECG Segments VT/VF Non VT/VF CONV FC Wearable Node Cooperative Inference Figure 1: An Overview of P-VA Framework. model. After that, we illustrate the cooperative inference mechanism. Finally, we present the in-time CNN model personalization to accommodate each patient\u2019s unique rhythm. 3.1 An Overview of P-VA Framework. In this subsection, we present an overview of the personalized deep learning based VT/VF detection framework. Fig. 1 illustrates our P-VA framework, which consists of the Detection Nodes and the Cloud. There are two main functions provided by the framework, the VT/VF detection on Detection Nodes and the detection model personalization on the Cloud. Detection Nodes. The detection nodes consist of the implantable node and the wearable node, and both nodes perform arrhythmias detection on the sensed rhythm. As shown in the Detection Nodes of Fig. 1, the implantable node continuously monitors intracardiac rhythm while the wearable node continuously monitors surface rhythm. Due to the constraints caused by implantation, the implantable node is equipped with an ultra-low power processing unit with few hundreds of KB on-chip memory and an active power consumption below 10 mW. The wearable node is equipped with a more powerful processing unit due to the relatively loose physicalsize restrictions and easy access to power supply. As illustrated in Fig. 1, both nodes conduct VT/VF detection on intracardiac and surface rhythm simultaneously using CNN with the same architecture. The CNN model is designed to satisfy the hardware constraints and perform real-time inference. To further improve the detection accuracy, the cooperative inference is proposed to enable both nodes to detect VT/VF rhythm collaboratively. However, due to the energy constraints, not all IEGMs could be uploaded from the implantable node to the wearable node. Hence a con\ufb01dence thresholding policy is implemented on the implantable \u0102\u0102 Input 250x1 10 10 16 16 7 5 3 Conv1 BN, ReLU Conv2 BN, ReLU Conv3 BN, ReLU Conv4 BN, ReLU Conv5 BN, ReLU FC1 ReLU FC2 Softmax 3 5 10 10 10 VT/VF Non-VT/VF Stride 2 Stride 2 Stride 1 Stride 1 Stride 1 10 Figure 2: CNN Architecture and Detection Process. node to identify the limited number of hardly-decidable IEGM segments and trigger the cooperative inference. Moreover, the wearable node would upload the received hardly-decidable IEGMs along with its fully-recorded ECGs to the Cloud for further personalization. Cloud. Once the fully-recorded ECGs and the hardly-decidable IEGMs are uploaded to the Cloud, the fully-recorded ECGs would \ufb01rst be labeled by doctors. However, the uploaded IEGMs could not be accurately labeled due to its non-continuity, and only the CNN on ECG domain could be correctly personalized by retraining. To tackle the challenge, as illustrated in Fig. 1, we \ufb01rst apply Maximum Mean Discrepancy (MMD) distance to perform unsupervised domain adaptation on the ECG-domain speci\ufb01c CNN to accommodate the IEGM domain [15]. Here, all possible IEGM-domain speci\ufb01c CNNs with di\ufb00erent CONV layers being frozen or \ufb01netuned would be generated as candidate CNNs. In the step 2 on the Cloud in Fig. 1, the policy network is utilized to determine the best-\ufb01t CNN from the candidate pool for incoming IEGM segment. Once the domain adaptation and the policy network training completes, the personalized CNNs on ECG and IEGM domains along with the policy network would be propagated back to the wearable and the implantable nodes. Moreover, our framework provides the feasibility that the model could be personalized once the uploaded rhythm is manually labeled by the doctors. Di\ufb00erent from traditional upgrading process, our personalization could be completed in a more \ufb02exible and timely way, where the patients do not need to wait for 3-6 months to upgrade the detection model. 3.2 CNN Detection Model In this subsection, we introduce the CNN-based VT/VF detection model. Then, we will introduce the mechanism to determine the shockable rhythm on the implantable node. Since CNN model detects VT/VF on resources-constrained platforms, the network is designed to be relatively small when compared with the existing CNN-based detection models [1, 7, 10, 12]. Fig. 2 illustrates the CNN architecture and the detection process. It consists of \ufb01ve 1D-convolutions (CONV) followed by ReLU function and two fully connected (FC) layers. This CNN-based model requires 26.5 KB to store and the intermediate results during layerby-layer calculation require at most 4.54 KB. As demonstrated in Fig. 2, the input of CNN are 2-second (2s) ECG or IEGM segments (i.e., sampling points within the 2s segment) in a time series and the output would be a series of inference 3 \fC1 C2 C3 C4 C5 F6 F7 C1 C2 C3 C4 C5 F6 F7 Predictions IEGM Segment CONV FC Implantable Node C1' C2' C3' C4' C5' F6' F7' ECG Segment Predictions CONV FC CSIN < T Policy Network Chosen CNN CSIN > T Evaluator Wearable Node Hardly-decidable IEGM Segment Hardly-decidable IEGM Segment CS Comparator Figure 3: Cooperative Inference with Con\ufb01dence Thresholding Policy. results (i.e. VT/VF or non-VT/VF) on each input segment. Based on the series of inference results, on the implantable node, an evaluator would determine the shockable rhythm through a simple but e\ufb00ective decision criteria. This criteria is that the rhythm would be determined as shockable if there are four consecutive VT/VF segments. The detection period on VT/VF is 8 seconds since the detection delay of traditional VT/VF detection algorithm is about 5 to 9 seconds [16]. In other words, if there are four consecutive VT/VF segments in the rhythm, the shock therapy would be triggered. 3.3 Cooperative Inference The CNN-based VT/VF detection performed purely on the implantable node is e\ufb03cient but it does not achieve the perfect detection due to the limited data sources. A way to improve accuracy is to conduct the inference on intracardiac and surface rhythm through the implantable and the wearable node simultaneously, and to choose the inference result with higher con\ufb01dence. However, if such detection is performed, both nodes would frequently communicate with each other to send inference results. The transmission overhead and the corresponding energy consumption would greatly reduce the lifetime of the implantable node and increase the response time to the shockable rhythm. Hence, there is a trade-o\ufb00 between accuracy and lifetime on the device. To address the problem, we propose the cooperative inference along with an inference con\ufb01dence thresholding policy. The cooperative inference is designed to be simple but e\ufb03cient to \ufb01t the resources constraints. It is based on the concept Con\ufb01dence Score (CS), which indicates the con\ufb01dence of the inference on each possible class. As shown in Fig. 3, on the implantable node, its CNN would perform inference on the input IEGM segment. The CS for both classes (i.e., VT/VF and non-VT/VF) on the segment would be calculated and fed into the CS comparator. The CS on the implantable node is de\ufb01ned as follows: \ud436\ud446\ud43c\ud441= |\ud443\ud43c\ud441(\ud466\ud463\ud461\ud463\ud453|\ud465) \u2212\ud443\ud43c\ud441(\ud466\ud45b\ud45c\ud45b\u2212\ud463\ud461\ud463\ud453|\ud465)|, (1) where \ud443\ud43c\ud441(\ud466|\ud465) is the probability of being classi\ufb01ed as VT/VF segment (\ud466\ud463\ud461\ud463\ud453) or not (\ud466\ud45b\ud45c\ud45b\u2212\ud463\ud461\ud463\ud453) given the input IEGM segment \ud465. This probability is obtained by utilizing \ud446\ud45c\ud453\ud461\ud45a\ud44e\ud465on the outputs of the last FC layer. Here, a higher \ud436\ud446\ud43c\ud441represents a more reliable inference result on the input IEGM segment. When \ud436\ud446\ud43c\ud441is low, it reveals the fact that there is a certain level of uncertainty of the inference result, which indicates that the CNN on the implantable could not clearly discriminate the segment. In this case, the CNN on the wearable node should be involved in the VT/VF detection. A con\ufb01dence thresholding policy is proposed to utilize a threshold \ud447on CS to determine the participation of the wearable node in VT/VF detection. As shown in Fig. 3, when \ud436\ud446\ud43c\ud441< \ud447, the corresponding input IEGM segment is de\ufb01ned as the hardly-decidable segment and would be transmitted to the wearable node. On the wearable node, the ECG segment on the same timestamp of the IEGM segment would be the \ufb01rst to feed into CNN and generate the inference result along with the con\ufb01dence score \ud436\ud446\ud44a\ud441, and the \ud436\ud446\ud44a\ud441on the wearable node is de\ufb01ned as follows: \ud436\ud446\ud44a\ud441= |\ud443\ud44a\ud441(\ud466\ud463\ud461\ud463\ud453|\ud465) \u2212\ud443\ud44a\ud441(\ud466\ud45b\ud45c\ud45b\u2212\ud463\ud461\ud463\ud453|\ud465)|, (2) where \ud443\ud44a\ud441(\ud466|\ud465) is the probability of being classi\ufb01ed as VT/VF segment (\ud466\ud463\ud461\ud463\ud453) or not (\ud466\ud45b\ud45c\ud45b\u2212\ud463\ud461\ud463\ud453) given the input ECG segment \ud465. Moreover, the uploaded hardly-decidable IEGM segment is fed into the policy network (which would be introduced in Section 3.4). Here, the policy network would choose one CNN to make inference on the given IEGM segment and the corresponding CS is de\ufb01ned as \ud436\ud446\ud443\ud43f. As shown in Fig. 3, by comparing the value of \ud436\ud446\ud443\ud43fwith \ud436\ud446\ud44a\ud441, the \ufb01nal inference result (i.e., VT/VF or non-VT/VF) with higher CS value would be transmitted back to the implantable node and fed into the decision evaluator on the implantable node. On the other hand, if \ud436\ud446\ud43c\ud441\u2265\ud447, the inference result generated by CNN on the implantable node would be fed into the evaluator directly without the cooperative inference. In the cooperative inference, the threshold\ud447a\ufb00ects the chance of data transmission between the implantable node and the wearable node. The determination of the value of \ud447is based on the tradeo\ufb00among the corresponding performance of accuracy, inference latency and energy consumption. The detailed experimental results and the determination of \ud447will be demonstrated in Section 4.2 3.4 In-time CNN Personalization To cater for the unique features of each patient\u2019s rhythm, the CNNbased detection model needs to be personalized with the sensed rhythm. In the P-VA framework, once the data uploaded to the Cloud is accurately labeled, the CNN model personalization would be automatically conducted by \ufb01ne-tuning CNN with the newly labeled data. This process signi\ufb01cantly reduces the degree of manual intervention and the personalization period. However, in our scenarios, only the arrhythmias on the fullyrecorded ECGs could be accurately labeled by doctors since the hardly-decidable IEGM segments are non-continuous and the ventricular arrhythmias on IEGMs could not be correctly diagnosed. Thus, only the ECG-domain speci\ufb01c CNN could be personalized by \ufb01ne-tuning the CNN on the fully-recorded ECGs. To obtain the personalized CNN model on IEGM domain, we invoke Deep Adaptation Networks (DAN) proposed in [15] and conduct further optimizations by utilizing the policy network. The core of DAN is to integrate the Maximum Mean Discrepancy (MMD) in the loss function [15]. The invocation of MMD explicitly reduces the domain discrepancy on the FC layers. By minimizing the MMD between the source and the target domain, the mean embedding of distributions across domains can be explicitly matched. In this work, the source domain is set as labeled ECGs and the target domain is set as unlabeled IEGMs. For the generalized CNN trained on the rhythm from databases, DAN is applied to \ufb01netune some CONV layers and all FC layers on the ECG domain (i.e., 4 \fReward IEGM Segment Inference Gradient Policy Freeze Freeze Fine-tune Fine-tune Fine-tune C1 C2 C3 C4 C5 F6 F7 C1 C2 C3 C4 C5 F6 F7 C1 C2 C3 C4 C5 F6 F7 C1 C2 C3 C4 C5 F6 F7 \u0102\u0102 C1 C2 C3 C4 C5 F6 F7 C1 C2 C3 C4 C5 F6 F7 \u0102\u0102 Policy Network Candidate CNNs Conv, 5x1 BN, LeakyRelu Conv, 5x1 BN FC3 LeakyReLu FC2 LeakyReLu Policy Network Conv, 5x1 BN, Relu FC1 LeakyReLu LeakyRelu, Dropout max pool x 3 Conv, 5x1 BN, LeakyRelu Conv, 5x1 BN FC3 LeakyReLu FC2 LeakyReLu Policy Network Conv, 5x1 BN, Relu FC1 LeakyReLu LeakyRelu, Dropout max pool x 3 Policy Figure 4: The Illustration of Policy Generation and Training on Policy Network. personalize the CNN on ECG domain for the speci\ufb01c patient), and use MMD to tailor the FC layers to \ufb01t the un-labelled IEGMs domain (i.e., personalize the CNN on IEGM domain for the speci\ufb01c patient). In this way, the model could be personalized once the uploaded ECG is manually labeled by the doctors. The personalization could be completed with less manual intervention. DAN employs a global \ufb01ne-tuning strategy, which \ufb01xes the CONV layers to freeze or \ufb01ne-tune for all input. That is, DAN freezes the low-level CONV layers and \ufb01ne-tunes the high-level CONV layers on the source domain. It assumes that the low-level CONV layers can learn generic features, while high-level CONV layers are slightly domain-biased. However, the assumption are not met when the target training data is not su\ufb03cient or unbalanced. For example, the speci\ufb01c person\u2019s IEGM segments might have higher similarity with the ECG segments from rhythm databases, and routing those segments through some the generalized CNN\u2019s CONV layers could generate more inference results. Inspired by the idea from BlockDrop [29], which uses a policy network to dynamically select which layer of a Residual Network to execute during an inference, we utilize the policy network to route each IEGM segment to a speci\ufb01c CNN. As shown in Fig. 4, we \ufb01rst obtain IEGM-domain speci\ufb01c CNNs under all possible freezing or \ufb01ne-tuning strategy with DAN as the candidate CNNs. Then, the policy network is used to route each incoming IEGM segment for its best-\ufb01t IEGM-domain speci\ufb01c CNN. Fig. 4 demonstrates the architecture of the policy network. It consists of one CONV layer, four dense blocks and three FC layers. Inside each dense block, there are two CONV layers with skip connection. As shown in Fig. 4, there are 32 IEGM-domain speci\ufb01c CNNs (i.e., freeze or \ufb01ne-tune on each CONV layer out of 5) with the application of DAN. Given an IEGM segment s, the policy of deciding which candidate CNN to choose is de\ufb01ned as a 5-dimensional Bernoulli distribution, which takes the form: \ud70b(a|s) = P[\ud434= a|\ud446= s] = 5 \u00d6 \ud456=1 \ud465\ud44e\ud456 \ud456(1 \u2212\ud465\ud456)1\u2212\ud44e\ud456, (3) where s is the input IEGM segment and a is the policy that chooses a certain CNN, as shown in Fig. 4. Here, \ud465is the output vector of the policy network after the Sigmoid function. The i-th element of the vector \ud465, \ud465\ud456\u2208[0, 1], represents the likelihood of the corresponding CONV layer of the ECG-domain speci\ufb01c CNN being frozen or \ufb01netuned. The policy a is also a vector with binary number, which are selected based on \ud465, where \ud44e\ud456= 0 represents frozen CONV layer \ud456 and \ud44e\ud456= 1 represents \ufb01ne-tuned CONV layer \ud456. To encourage the highest accuracy on all segments, as illustrated in Fig. 4, the reward is set based on its prediction correctness of the input segment. This prediction is generated by the IEGM-domain speci\ufb01c CNN selected by the policy network. The reward function associated with the action is de\ufb01ned as \ud445(a) = \u001a \ud6fd \ud456\ud453\ud450\ud45c\ud45f\ud45f\ud452\ud450\ud461 \u2212\ud6fd \ud45c\ud461\u210e\ud452\ud45f\ud464\ud456\ud460\ud452, (4) where \ud6fdis a positive constant. Here, we treat all candidate CNNs equally and reward the correct prediction on the selected CNN with \ud6fd. Similarly, incorrect prediction is penalized by \u2212\ud6fd. Finally, to obtain the optimal choice of the IEGM-domain speci\ufb01c CNN, we maximize the expected reward associated with the action \ud438\ud445= E\ud70b[\ud445(a)]. To maximize the expected value, we utilize the policy gradient to compute the gradients of \ud43d, which is calculated as follow: \u2207\ud438\ud445= E\ud70b[\ud445(a)\u2207log \ud70b(a|s)] = E[\ud445(a)\u2207log 5 \u00d6 \ud456=1 \ud465\ud44e\ud456 \ud456(1 \u2212\ud465\ud456)1\u2212\ud44e\ud456]. (5) Here, we can further optimize the expected gradient to \u2207\ud438\ud445= E\ud70b[\ud445(a)\u2207 5 \u00d5 \ud456=1 log[\ud465\ud456\ud44e\ud456+ (1 \u2212\ud465\ud456)(1 \u2212\ud44e\ud456)]], (6) where the value of \ud44e\ud456is either 0 or 1. Based on the calculated expected gradient on the policy network, we could generate the choice of which IEGM-domain speci\ufb01c CNNs to be applied to the incoming IEGM segment. After that, the \ufb01ne-tuned ECG-domain speci\ufb01c CNN, the policy network, and all candidate IEGM-domain speci\ufb01c CNNs would be propagated back from the Cloud to the wearable node. Due to the hardware constraints, the policy network and all candidate CNNs could only be deployed on the wearable node. One IEGM-domain CNN which achieves the highest accuracy during policy network training would be transmitted from the wearable node and deployed on the implantable node. 4 EVALUATIONS We evaluate the performance of the proposed CNN-based VT/VF detection method with a series of experiments. In this section, 5 \fTable 1: Database Summary. Database # of Recordings Rhythm Source Sampling Rate (Hz) Recording Duration (min) MITDB 48 Lead I 360 30 VFDB 22 Lead I 250 30 CUDB 35 Lead I 250 8 AAEL 304 Lead I, RVA-Bi 1,000 0.5-5 Table 2: Training and Testing Dataset for Generalized CNN Training and Personalization. Dataset # of VT/VF Segments # of Non-VT/VF Segments Data Source Generalization-TrainSet 6,093 25,524 MITDB, CUDB, VFDB Personalization-G1 780 2,274 AAEL Personalization-G2 781 2,275 AAEL Personalization-G3 781 2,275 AAEL we \ufb01rst illustrate the experiments setup and then introduce the evaluation results. 4.1 Experiments Setup 4.1.1 Implementations. In our experiments, the board Apollo3 Blue [27] serves as the implantable node and a Raspberry Pi 3B+ [26] serves as the wearable node. The size of our CNN model is 26.2 KB and requires at most 4.54 KB for intermediate data storage. Such storage requirements could be met by the Apollo3 Blue. Moreover, the total size of the 32 candidate CNN models is 838.4 KB, which is not a large memory overhead for the wearable node. We adopt PyTorch for the generalized CNN model and the policy network training. For the generalized CNN, we set learning rate to 1\ud452\u22124 and use a batch size of 64 during training. We use stochastic gradient descent (SGD) with 0.9 momentum and the loss function is cross-entropy loss function. The total number of epochs is 100. For the policy network, we set learning rate to 1\ud452\u22124 and use a batch size of 4 during training. We use SGD with 0.9 momentum and the loss function is cross-entropy loss function. The total number of epochs is 50. All those training experiments run on the PC as the Cloud with 8 core of Intel Xeon E5-2620 v5 CPU, 512 GB memory, and an NVIDIA GeForce GTX 2080Ti GPU. 4.1.2 Data Preprocessing. The data used in the experiments is obtained from four databases, namely the MIT-BIH arrhythmia database (MITDB) [18] [23], the MIT-BIH malignant ventricular arrhythmia database (VFDB) [9] [22], the Creighton Univeristy ventricular tachyarrhythmia database (CUDB) [20] [24], and the Ann Arbor Electrogram Libraries (AAEL) [2]. The attributes of the recordings acquired from the four databases are summarized in Table 1. As demonstrated in Table 1, the databases MITDB, CUDB and VFDB only contain the ECG recordings (from Lead I) whereas the recordings in the AAEL are recorded as ECG (from lead I) and IEGM (i.e., from the lead placed in right ventricle, named RVA-Bi) simultaneously. Moreover, the sampling rate of the four databases is di\ufb00erent. To ensure the standardization across the databases and reduce inference time, all recordings are downsampled to 125Hz. The ECG recordings in the MITDB, CUDB and VFDB are utilized to train the CNN on ECG domain as the generalized CNN model. The recordings from those three databases are segmented into 2s non-overlapping segments and each segment is labeled as VT/VF or non-VT/VF using ground truth annotations provided in those three databases. The 2s segments from those three databases constitute the training set for the generalized CNN model. As shown in Table 2, there are 6,093 VT/VF segments and 25,524 non-VT/VF segments in the training set, denoted as Generalization-TrainSet. The ECG and IEGM recordings in the AAEL are utilized to perform personalization on generalized CNN model and to evaluate detection performance. The data preprocessing procedure for the AAEL is recording level \u2212 \u2192event level \u2212 \u2192segment level. On the recording level, there are 304 recordings as demonstrated in Table 1. Each recording consists of two channels of data from lead I and RVA-Bi. Then, the recording periods diagnosed as VT and VF in the AAEL are labeled as VT/VF events while other are labeled as non-VT/VF events. The reason for the existence of an event level is that the shock therapy is supposed to be delivered during a VT/VF event and the detection accuracy should be calculated based on the correct detection on the events. After labeling and participating in 304 recordings, there are 198 VT/VF and 273 non-VT/VF events in total. Each event is then segmented into non-overlapping 2s segments labeled with VT/VF or non-VT/VF. There are 2,342 VT/VF segments and 6,824 non-VT/VF segments. For the segments in a time series from the same event, we participate those segments into three equally partitioned set and place those set into three groups, denoted as Personalization-G1, G2, and G3. The detailed statistics of each group are demonstrated in Table 2. The rationale behind such grouping is that the segments (i.e., the patient\u2019s rhythm from G1 and G2) would be utilized to personalize the model \ufb01rst. The data from the same patient (i.e., the same patient\u2019s rhythm from G3) should be applied to evaluate the performance of the personalized CNN model. 4.1.3 Our Methods and Baseline Methods. We \ufb01rst obtain the generalized CNN trained on the ECG segments from GeneralizationTrainSet. Next, we utilize Personalization-G1 and G2 to personalize the generalized CNN model and utilize Personalization-G3 to evaluate performance. We denote the detection model which is personalized with Personalization-G1 and G2 as CNN-2G. The detection model which is personalized with only PersonalizationG1 is denoted as CNN-1G. The generalized CNN which is directly deployed on both nodes are de\ufb01ned as CNN-0G. The cooperative inference and the policy network are activated during the inference. We further implement the CNN-2G without policy network involved. This detection model is used to evaluate the e\ufb00ect of the policy network to detection accuracy. This detection method is denoted as CNN-NoPolicy. 6 \fTable 3: Performance metrics for baseline methods and CNN with cooperative inference and policy network. Methods F1 Score Se/Sp BAC/Acc PPV/NPV Classic .925 .970/.908 .939/.934 .885/.976 SVM-ML .883 .874/.923 .898/.902 .892/.910 CNN-DL .901 .944/.890 .917/.913 .862/.957 CNN-NoPolicy .953 .970/.952 .961/.960 .937/.977 CNN-0G .831 .909/.799 .854/.845 .766/.924 CNN-1G .950 .960/.956 .958/.958 .941/.970 CNN-2G .975 .984/.974 .980/.979 .965/.989 80% 90% 100% 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Detection Accuracy Confidence Score Threshold (T) CNN-2G CNN-1G CNN-0G CNN-NoPolicy Figure 5: Detection Accuracy vs Con\ufb01dence Score Threshold. For the baseline methods, we \ufb01rst simulate a VT/VF discrimination method used in single-chamber ICDs [30], denoted as Classic. In the Classic, the VT zone is set to be 160-200 bpm. The VF zone is set to be the heart rate faster than 200 bpm. The detection window is set as 10 most recent ventricular R-R intervals. The event is determined as the shockable event if the Classic methods decides to deliver the shock. The heart rate boundary of VT/VF zone is also \ufb01ne-tuned for each testing patient to simulate the intervention such that the best discrimination performance could be achieved. We then implement an existing machine learning based detection method using support vector machine (SVM) [14], denoted as SVM-ML. The features extracted in SVM-ML are Count2 and Leakage. The training set is Personalization-G1 and G2, and testing set is Personalization-G3. We do not implement SVM-ML on the implantable node due to its complex feature extraction process, which consumes extensive computational resources and cannot be completed within 1 second for 2s segment input. Existing machine learning based detection methods are not designed to \ufb01t real-time requirements. We also implement a conventional deep learning detection method using CNN. We utilize the IEGM segments from Personalization-G1 and G2 to train the generalized CNN model. The detection performance is evaluated by Personalization-G3 on the implantable node. This detection is denoted as CNN-DL. 4.2 Performance Assessment In this section, we evaluate the performance of CNN-based detection on the P-VA framework with the performance metrics in terms of detection accuracy, latency and energy consumption. 4.2.1 Detection Accuracy. The detection accuracy performance is \ufb01rst reported in terms of sensitivity (Se), speci\ufb01city (Sp), positive and negative predictive accuracy (PPV and NPV), total accuracy (Acc), balanced accuracy (BAC), and F1 score. Those statistics are calculated based on the resulted event detections. We conduct performance evaluations using the aforementioned detection methods. As shown in Table 3, when compared with the classic VT/VF discrimination algorithm, CNN-DL achieves a slight decrease on performance in terms of VA detection (Se) and inappropriate shock rate (Sp). When compared with SVM-ML, CNNDL achieves a 1.1% increment from a baseline of 90.2% in Acc and a 6.9% increment on VT/VF event detection rate represented by Se. In other words, the performance of a single CNN on IEGM domain shows that the deep learning based VT/VF detection could achieve decent detection accuracy. With the assistance of the P-VA framework, the cooperative inference enables CNN model to achieve higher detection accuracy. In the experiment, the con\ufb01dence score threshold \ud447is set to be 0.5 due to the fact that the accuracy becomes relatively stable when \ud447> 0.4. We will demonstrate the accuracy trend along with \ud447in Fig. 5. Here, CNN-2G could achieve the accurate detection, speci\ufb01cally 97.9% accuracy on all events. When compared with the classic detection algorithm, CNN-2G improves by 1.4% on VT/VF event detection accuracy represented by Se and 6.6% on non-VT/VF event detection accuracy represented by Sp. CNN-2G also achieves the best performance in terms of F1 score among all methods. In addition, the personalization process is shown to be necessary for the CNN-based model. As shown in Table 3, CNN-1G experiences a slight degradation in F1 score when compared with CNN-2G. CNN-0G has the worst detection performance among all methods, which we believe is due to the fact that it has no personalization done on the CNN models, so that both node could only make the inference based on the learned features from other patients in rhythm database (i.e., Generalization-TrainSet). Moreover, when compared with CNN-2G, the performance of CNN-NoPolicy illustrates that the policy network could further improve detection accuracy by selecting the best-\ufb01t IEGM-domain CNN. We further investigate the e\ufb00ect of the con\ufb01dence score threshold\ud447on the detection accuracy. The line plot in Fig. 5 demonstrates the accuracy achieved by CNN-0G, CNN-1G, CNN-2G, and CNNNoPolicy. These four CNN-based detection methods show to follow the same trend: the accuracy become relatively stable when\ud447> 0.4 and the cooperative inference could be more accurate for a larger T. It indicates that the appropriate setting of threshold\ud447could achieve the higher detection accuracy through cooperative inference between the wearable and the implantable node. 4.2.2 Detection Delay. The experiments aim at assessing the inference latency on the implantable node. On the implantable node, 7 \f30 50 70 90 110 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Average Inference Latency (ms) Confidence Score Threshold (T) CNN-2G CNN-NoPolicy Figure 6: Detection Latency vs Con\ufb01dence Score Threshold. 0.00 0.10 0.20 0.30 0.40 0.50 0.60 CNN-DL CNN-2G Average Energy Consumption (mJ) Methods Figure 7: Average Energy Consumption of Inference over One Segment for CNN-DL and CNN-2G. inference on a 2s IEGM segment could be completed within 31ms without cooperative inference. Here, we do not consider the latency caused by data collection on the implantable node. Data collection is the process of sensing heart rhythm and sending the sensed data to processing unit. Since our focus is on the calculation in inference, we do not consider the latency caused by data collection for all methods. With cooperative inference involved, the actual inference latency on the implantable node should include the transmission delay and the inference latency caused by the wearable node. Here, we investigate the e\ufb00ect of the con\ufb01dence score threshold \ud447to the inference latency on the implantable node. The line plot in Fig. 6 illustrates the changes of average inference latency on one IEGM segment with an increasing \ud447. The performance of two methods, CNN-2G and CNN-NoPolicy, is evaluated in this experiment. Here, both methods show the same trend: the inference latency would increase as the\ud447increases. It is straightforward since the implantable node would be more likely to upload its IEGM segment for cooperative inference as \ud447increases to 1. Moreover, the average inference time of CNN-2G is longer than that of CNN-NoPolicy because the policy network also takes time to execute on the wearable node. One interesting observation is that there is a plateau in the inference latency for both methods, where the \ud447ranges from 0.5 to 0.7. Therefore, \ud447\u2286[0.5, 0.7] is a suitable value in terms of accuracy and latency. 4.2.3 Energy Consumption. In this subsection, we compare average energy consumption of detection for various methods on the 0.00 0.10 0.20 0.30 0.40 0.50 0.60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Average Energy Consumption (mJ) Confidence Score Threshold (T) CNN-2G CNN-NoPolicy Figure 8: Average Energy Consumption of Inference vs Con\ufb01dence Score Threshold. implantable node. We also evaluate the e\ufb00ect of the con\ufb01dence score threshold \ud447on the energy consumption for the CNN-based methods. The energy consumption of the implantable node comes from several operations, including inference and data transmission. Fig. 7 demonstrates the average energy consumption of inference on a 2s segment for methods CNN-DL and CNN-2G (where \ud447= 0.5) deployed on the implantable node. The performance indicates that the deep learning based methods could achieve a high energy e\ufb03ciency. As shown in Fig. 7, the energy consumption of CNN-DL is less than that of CNN-2G since the data transmission between the implantable and the wearable node consumes extra energy. Fig. 8 illustrates the changes of the average energy consumption of inference over a 2s segment along with the con\ufb01dence score threshold \ud447on the implantable node. The performances of two methods, CNN-2G and CNN-NoPolicy, are evaluated in the experiments. As shown in Fig. 8, both methods would consume more energy with an increasing \ud447since there is a higher probability for the implantable node to transmit data to the wearable node. And CNN-2G would consume more energy because the implantable node should wait for a longer time to receive the results from the wearable node during the cooperative inference. 5" + } + ], + "Ahmed Abbasi": [ + { + "url": "http://arxiv.org/abs/2211.07621v1", + "title": "Alternating minimization algorithm with initialization analysis for r-local and k-sparse unlabeled sensing", + "abstract": "The unlabeled sensing problem is to recover an unknown signal from permuted\nlinear measurements. We propose an alternating minimization algorithm with a\nsuitable initialization for the widely considered k-sparse permutation model.\nAssuming either a Gaussian measurement matrix or a sub-Gaussian signal, we\nupper bound the initialization error for the r-local and k-sparse permutation\nmodels in terms of the block size $r$ and the number of shuffles k,\nrespectively. Our algorithm is computationally scalable and, compared to\nbaseline methods, achieves superior performance on real and synthetic datasets.", + "authors": "Ahmed Abbasi, Abiy Tasissa, Shuchin Aeron", + "published": "2022-11-14", + "updated": "2022-11-14", + "primary_cat": "eess.SP", + "cats": [ + "eess.SP", + "cs.IT", + "cs.LG", + "math.IT", + "math.PR" + ], + "main_content": "Introduction For the linear inverse problem, Y = BX\u2217+ W, where B is the measurement matrix and Y \u2208Rn\u00d7m are linear measurements of unknown X\u2217\u2208Rd\u00d7m. In the unlabeled sensing problem, the measurements are scrambled by an unknown permutation P\u2217: Y = P\u2217BX\u2217+ W, (1) where P\u2217is the unknown permutation matrix and W is additive Gaussian noise with Wij = N(0, \u03c32). Given scrambled measurements Y and the measurement matrix B, the unlabeled sensing problem is to estimate the signal X\u2217. This problem is called the single-view (multi-view) unlabeled sensing problem for m = 1(m > 1). The work in [1] introduced the unlabeled sensing problem and establish that n = 2d measurements are necessary and su\ufb03cient for recovery of x\u2217. Subsequent works [2, 3] have generalized this result and developed information theoretic inachievability analysis. Because estimating the unknown permutation matrix P\u2217is a challenging problem, several works [4, 5, 6, 7, 8, 9] assume a k-sparse, or partially shu\ufb04ed, permutation model. [10, 11] consider an r-local, or block diagonal, permutation model. A permutation matrix P\u2217 k is k-sparse if it has k o\ufb00-diagonal elements, i.e., \u27e8I, P\u2217 k\u27e9= n \u2212k. A permutation matrix P\u2217 r is r-local with s blocks if P\u2217 r = blkidag (P1, \u00b7 \u00b7 \u00b7 , Ps). Fig. 1 illustrates the two models. The two models are compared by information-theoretic inachiveability in [11]. For single-view unlabeled sensing, algorithms based on branch and bound and expectation maximization are proposed in [12, 13, 14]. These algorithms are applicable to small problem sizes. A stochastic alternating minimization approach is proposed in [15]. For multi-view unlabeled sensing, the Levsort subspace matching algorithm was proposed in [16]. A subspace clustering approach was proposed in [7]. The works [4, 5] propose methods based on bi-convex optimization and robust regression, respectively. A spectral initialization based method was proposed recently in [17]. 1.1 Contributions We extend our alternating minimization algorithm for the r-local unlabeled sensing model [10], [11] to the widely considered k-sparse model, Section II. We propose and analyze the initialization to our algorithm, 1 arXiv:2211.07621v1 [eess.SP] 14 Nov 2022 \f0 10 20 30 40 0 10 20 30 40 0 10 20 30 40 0 10 20 30 40 Figure 1: Left. Sparse (or partially shu\ufb04ed) permutation considered in [4, 5, 6, 7], with number of shu\ufb04es k = 10. Right. The r-local permutation structure considered in [10], [11], with block size r = 10. In this paper, we propose and analyze a general algorithm that is applicable to both permutation models. Section III. Speci\ufb01cally, assuming random B or X\u2217, we derive upper bounds on the initialization error for both r-local and k-sparse models. Numerical results and comparisons to baseline methods showing superior performance are given in Section IV. A theoretical contribution is upper-bounding the error in the minimum norm solution to an underdetermined linear inverse problem. Under-determined systems have also been studied as the sketching problem [18], but the results, derived assuming a random sub-sampling strategy and \ufb01xed x\u2217, are not applicable as our sub-sampling strategy is deterministic because of the unknown permutation P\u2217in (1) and random x\u2217. 1.2 Applications of unlabeled sensing The linked linear regression problem [19, 20, 21], or linear regression under blocking, is to \ufb01t a linear model by minimizing over x and P the objective \u2225y \u2212PBx\u22252 2, where P is an unknown r-local permutation. For example, consider a simple statistical model where the weight of an individual depends linearly on age and height. The vector y \u2208Rn contains the weight of n = 10 individuals, the matrix B \u2208Rn\u00d7d, d = 2 contains the values of the age, height of the individuals. The 10 individuals comprise 5 males, 5 females and each record (weight, age, height) is known to belong to a male or a female individual. Letting the \ufb01rst (second) block of 5 rows of y, B contain the records of male (female) individuals, the unknown r-local permutation, r = 5, assigns each weight value (row of y) to its corresponding age, height (row of B). Experimental results and comparisons with baseline methods for the linked linear regression problem are given in Section 4. For the pose and correspondence problem [22], the rows of B \u2208Rn\u00d7d contain the d-dimensional coordinates of the landmark points of an object. The object is transformed by an unknown linear transformation X\u2217and the rows of Y = P\u2217BX\u2217contain the coordinates of the points of the transformed object. Given coordinates B, Y, the problem is to assign a point in B to the corresponding point in Y and estimate the transformation X\u2217. Another application of unlabeled sensing is signal amplitude estimation from binary quantized unlabeled samples [23]. The unknown scalar quantity x is the signal amplitude and the sensing matrix B is replaced by a threshold function that models bit quantization. The image correspondence problem [24] and the 1-d unassigned distance geometry problem (uDGP) were recently formulated as unlabeled sensing problems in [11]. 1.3 Notation and de\ufb01nitions P\u2217\u2208\u03a0n denotes a permutation matrix, where \u03a0n = {Z: Z \u2208{0, 1}n\u00d7n, Z1n = 1n, Z\u22ba1n = 1n} is the set of n \u00d7 n permutation matrices and 1n \u2208Rn is the vector of all ones. P\u2217 r denotes r-local permutations with block size r. P\u2217 k denotes k-sparse permutations with k o\ufb00-diagonal elements. The Hamming distortion dH = \u03a3i1(b P(i) \u0338= P(i)) is the number of mismatches in permutation matrices b P, P\u2217. A\u2020 denotes the Moore-penrose pseudoinverse of matrix A. [A; B] denotes the vertical concatenation of matrices A and B. \u27e8A, B\u27e9= trace(A\u22baB) denotes the matrix inner product. \u2225\u00b7\u2225p denotes the vector p-norm and \u2225\u00b7\u2225F denotes the matrix Frobenius norm. \u2225X\u2225\u03d51(\u2225X\u2225\u03d52) denotes the sub-exponential (sub-Gaussian) norm of the sub-exponential (sub-Gaussian) random variable X. c\u2032 \u2208R denotes an absolute constant. 2 \f2 Algorithm We propose to estimate the permutation P\u2217and the signal X\u2217by minimizing the forward error in (1), (b P, b X) = argmin P\u2208\u03a0n,X F(X, P) = \u2225Y \u2212PBX\u22252 F . (2) Alternating minimization (alt-min) updates for (2) are P(t) = argmin P\u2208\u03a0n \u27e8\u2212YX(t)\u22baB\u22ba, P\u27e9, (3) X(t+1) = argmin X F(X, P(t)) = (P(t)B) \u2020Y. (4) When the unknown permutation P\u2217is r-local, the P update in (3) decouples along the blocks of P\u2217and reduces to the simpler updates in line 9 of Algorithm 1. (2) is a non-convex optimization problem because the set of permutations is a discrete (non-convex) set. Therefore, the initialization to the updates (3), (4) has to be chosen carefully. We propose and analyze initializations for both r-local and k-sparse models in the following sections. A key contribution of our algorithm is that the model assumption is incorporated in the initialization. We note that Algorithm 1 for r-local P\u2217 r without initilization analysis was \ufb01rst proposed in our earlier work [11]. 2.1 Initialization for the r-local model When the unknown permutation P\u2217 r is r-local, we propose to initialize b X by the collapsed initialization (7). Let Pi denote each r \u00d7 r block of P\u2217 r = diag(P1, \u00b7 \u00b7 \u00b7 , Ps). Let Bi \u2208Rr\u00d7d denote blocks of the measurement matrix B = [B1; \u00b7 \u00b7 \u00b7 ; Bs]. Since the permutation P\u2217 r is block-diagonal, the r permuted measurements in each block [Yi : PiBi] are summed to extract one labelled measurement on X\u2217\u2208Rd\u00d7m j=r X j=1 [PiBi(j)]\u22baX\u2217= j=r X j=1 Yi(j) \u2200i \u2208[s], (5) where PiBi(j) \u2208Rd\u00d71 denotes row j of PiBi. Assuming all blocks have the same size r, the number of blocks is s = n/r. The s labelled measurements in (5) are represented in the s \u00d7 d collapsed linear system of equations e Y = e BX\u2217, (6) where the rows of the collapsed measurement matrix e B \u2208Rs\u00d7d and measurements e Y \u2208Rs\u00d7m are e B(i) = j=r X j=1 Bi(j), e Y(i) = j=r X j=1 Yi(j) \u2200i \u2208[s]. Note that e B(i) = Pj=r j=1 PiBi(j) = Pj=r j=1 Bi(j). The proposed initialization b X is the minimum-norm solution to (6), b X = e B\u2020 e Y. (7) Substituting the singular value decomposition form of e B\u2020 = e VS\u22121 e U\u22ba, where e B = e US e V\u22ba, shows that b X is the projection of X\u2217onto the the row space of e B. Formally, \u2225X\u2217\u2212b X\u22252 = \u2225(I \u2212e V e V\u22ba)X\u2217\u22252. (8) For s \u2265d, b X = X\u2217. In section 3.1, we upper bound the error in initialization b X for the under-determined s < d case. 2.2 Initialization for the k-sparse model When the unknown permutation P\u2217 k is k-sparse , we propose to initialize b P(0) = I, which sets b Y(0) = Y = P\u2217 kBX\u2217. Since the permutation matrix P\u2217 k has k o\ufb00-diagonal elements, the initialization b P(0) = I is close to the true solution P\u2217 k as dH(b P(0), P\u2217 k) = k. The initialization error is upper bounded in section 3.2. 3 \fAlgorithm 1 alt-min Input: mode \u2208{r-local, k-sparse}, convergence threshold \u03f5 1: if mode is r-local then 2: b X \u2190collapsed initialization in (7) 3: b Y \u2190B b X 4: else 5: b Y \u2190Y 6: while relative change > \u03f5 do 7: if mode is r-local then 8: for i \u22081 \u00b7 \u00b7 \u00b7 s do //s is the number of blocks 9: b Pi \u2190argmin Pi\u2208\u03a0r \u2212\u27e8Yi b Y\u22ba i , Pi\u27e9 10: b P \u2190diag(b P1, \u00b7 \u00b7 \u00b7 , b Ps) 11: else 12: b P = argmin P\u2208\u03a0n \u2212\u27e8Y b Y\u22ba, P\u27e9 13: b X \u2190B\u2020 b P\u22baY 14: b Y \u2190B b X 15: Return b P, b X 3 Initialization analysis 3.1 r-local model Assuming random models on either B or X\u2217, the results in this section upper bound the error in the proposed initialization (7). Without any assumptions, the worst case error \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2264\u2225y\u22252 2 \u2212\u03c32 min(B)\u2225\u02c6 x\u22252 2 \u03c32 min(B) (9) is achieved for x\u2217aligned with the direction of the singular vector corresponding to the smallest singular value \u03c3min(B). For x\u2217with zero-mean, independent sub-Gaussian random coordinates, Theorem 2.1 in [25] shows that the error \u2225x\u2217\u2212\u02c6 x\u22252 is sub-Gaussian. In contrast, Theorem 1 in this work shows a sub-Gaussian error distribution for \ufb01xed x\u2217and Gaussian B. Theorem 2 shows that the error is sub-Gaussian assuming \ufb01xed B and sub-Gaussian x\u2217. Particularly, our result in Theorem 2 does not assume that the entries of x\u2217are independent. Lemma 1. Let \u02c6 x be as de\ufb01ned in (7). Let x\u2217\u2208Rd be the \ufb01xed unknown vector and let B be a Gaussian measurement matrix. For t > 0, Pr B h\u2225x\u2217\u2212\u02c6 x\u22252 \u2225x\u2217\u22252 \u2265(1 + t) r d \u2212s d i \u22642 exp(\u2212c\u2032t2(d \u2212s)). (10) The result in (10) con\ufb01rms that the relative error decreases with increasing number of measurements s in the under-determined system. For example, let s = 3d/4, the probability that the relative error exceeds 1/2 decays with a sub-Gaussian tail. The bound in (10) is also sharp because it is the upper tail of the following two-sided inequality Pr B h (1 \u2212t) r d \u2212s d \u2264\u2225x\u2217\u2212\u02c6 x\u22252 \u2225x\u2217\u22252 \u2264(1 + t) r d \u2212s d i \u22651 \u22122 exp(\u2212c\u2032t2(d \u2212s)). Proof of Lemma 1. Since B \u2208Rn\u00d7d is assumed Gaussian, the scaled collapsed matrix e B/ \u221a \u2018r (6) is also a Gaussian matrix. The singular vectors of a rectangular Gaussian matrix M \u2208Rp\u00d7q, p > q, span a qdimensional uniformly random subspace of Rp, see Section 5.2.6 in [26]. Therefore, \u02c6 x = (I \u2212e V e V\u22ba)x\u2217is the projection of x\u2217\u2208Rd onto a uniformly random (d\u2212s)-dimensional subspace. The result in (10) follows from invoking the Johonson-Lindenstrauss (JL) Lemma (66) with p = d and q = d \u2212s. 4 \fTheorem 1. Let b X be as de\ufb01ned in (7). Let X\u2217\u2208Rd\u00d7m be the \ufb01xed unknown matrix and let B be a Gaussian measurement matrix. For log m \u2264c\u2032t2(d \u2212s)/2, Pr B h\u2225X\u2217\u2212b X\u2225F \u2225X\u2217\u2225F \u2265(1 + t) r d \u2212s d i \u22642 exp(\u2212c\u2032t2(d \u2212s)/2). (11) Proof of Theorem 1. Let event E = Si=m i=1 Ei be de\ufb01ned as the union of events Ei, where Ei = {x\u2217| \u2225x\u2217 i \u2212\u02c6 xi\u22252 2 \u2265(1 + t)2(d \u2212s) d \u2225x\u2217 i \u22252 2}. (12) Then, Pr h i=m X i=1 \u2225x\u2217 i \u2212\u02c6 xi\u22252 2 \u2264(1 + t)2(d \u2212s) d i=m X i=1 \u2225x\u2217 i \u22252 2 i (13) \u22651 \u2212 i=m X i=1 Pr[Ei] (14) \u22651 \u22122 exp(\u2212c\u2032t2(d \u2212s)/2). (15) (14) follows from noting that Pr[Ec] = 1 \u2212Pr[E] and applying the union bound to E. (15) is by substituting (10) and bounding m exp(\u2212c\u2032t2(d \u2212s)/2) \u22641 for log m \u2264c\u2032t2(d \u2212s)/2. Lemma 2. Let \u02c6 x be as de\ufb01ned in (7). Let B be a \ufb01xed measurement matrix and let x\u2217be a zero-mean sub-Gaussian random vector (31). For t \u22650, Pr x\u2217 \u0002 \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2265c1 + 2K2( \u221a d \u2212s + 1)t] \u2264exp(\u2212t), (16) where c1 = K2(d \u2212s + 1 2 \u221a d \u2212s) and K is as given in (31). Proof of Lemma 2. The result in (16) follows from applying the Hanson-Wright inequality (65) to (8). To derive the result in Theorem 2, it is necessary to show that \u2225x\u2217\u2212\u02c6 x\u22252 2 is a sub-exponential random variable. A random variable X is sub-exponential if for t \u22650, K1 > 0 X \u223csubExp \u21d0 \u21d2Pr[|X| \u2265t] \u2264c\u2032 exp(\u2212t/K1), (17) where c\u2032 \u22651. It cannot be concluded that the shifted random variable \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 is sub-exponential because the lower tail probability Pr[\u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 \u2264\u2212t], t > 0 is not upper bounded in (16). However, our goal is to upper bound the probability that the error exceeds a certain value. We therefore de\ufb01ne the non-negative random variable \u02dc e \u2212c1, which upper bounds the lower tail as {\u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 \u2264\u2212t, t > 0} \u22640, see (18). The de\ufb01nition of \u02dc e \u2212c1 is given in (18), (19). Fig. 2 is a visual description of the de\ufb01nition. We show that \u02dc e \u2212c1 is a sub-exponential random variable in Lemma 3. Lemma 3. The random variable \u02dc e \u2212c1, de\ufb01ned in (18), (19), is a sub-exponential random variable with sub-exponential norm \u2225\u02dc e \u2212c1\u2225\u03d51 = c\u2032K1, where \u02dc e \u2212c1 | E1 = 0, (18) \u02dc e \u2212c1 | E2 = \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c, (19) c = K2(d \u2212s + 1 2 \u221a d \u2212s), K1 = 2K2( \u221a d \u2212s + 1), c\u2032 is an absolute constant and events E1, E2 are E1 = {x\u2217| \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 \u22640}, (20) E2 = Ec 1 = {x\u2217| \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 > 0}. (21) 5 \f!c1 0 jjx$ ! ^ xjj2 2 ! c1 0 ~ e ! c1 ~ e ! c1 against jjx$ ! ^ xjj2 2 ! c1 -1 0 1 X ! c1 9 Unif[!1; 1] 0 0.5 1 Example of de-nition. c1 = 1 FX FY Figure 2: Left. The derived random variable (rv) \u02dc e \u2212c1 is plotted against the error rv \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1. Note that i) \u02dc e \u2212c1 \u22650, ii) \u02dc e \u2212c1 \u2265\u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1, iii) \u02dc e \u2212c1 | E1 = 0 and iv) \u02dc e \u2212c1 | E2 = \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1. Right. Example. The cdfs of Y (\u02dc e \u2212c1) and X(\u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1) \u223cUnif[\u22121, 1] are plotted. Proof of Lemma 3. Pr[\u02dc e \u2212c1 \u2265t] = Pr[\u02dc e \u2212c1 \u2265t | E1] \u00b7 Pr[E1] + Pr[\u02dc e \u2212c1 \u2265t | E2] \u00b7 Pr[E2] = Pr[\u02dc e \u2212c1 \u2265t | E2] \u00b7 Pr[E2] (22) = Pr[\u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 \u2265t | E2] \u00b7 Pr[E2] (23) = Pr[\u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 \u2265t], (24) where (22) follows from (18); speci\ufb01cally, Pr[\u02dc e\u2212c1 \u2265t | E1] = 0\u2200t > 0. (23) follows from (19) and (24) is by Pr[\u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 \u2265t | E2] Pr[E2] = Pr[\u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 \u2265t \u2229E2] and that the event {x\u2217| \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 \u2265t, t > 0} is a subset of E2. From (16), for t \u22650 Pr h \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 2K2( \u221a d \u2212s + 1) \u2265t i \u2264exp(\u2212t). (25) From (24), for t > 0 Pr h \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 2K2( \u221a d \u2212s + 1) \u2265t i = Pr h \u02dc e \u2212c1 2K2( \u221a d \u2212s + 1) \u2265t i , (26) where \u221a d \u2212s + 1 > 0 is a positive number since s < d, see (8). From (18) and (19), \u02dc e \u2212c1 is non-negative so that \u02dc e \u2212c1 = |\u02dc e \u2212c1| and Pr h \u02dc e \u2212c1 2K2( \u221a d \u2212s + 1) \u2265t i = Pr h |\u02dc e \u2212c1| 2K2( \u221a d \u2212s + 1) \u2265t i . (27) Combining (26) and (27), for t > 0 Pr h |\u02dc e \u2212c1| 2K2( \u221a d \u2212s + 1) \u2265t i = Pr h \u2225x\u2217\u2212\u02c6 x\u22252 2 \u2212c1 2K2( \u221a d \u2212s + 1) \u2265t i . (28) Substituting (25) in (28), for t > 0, Pr h |\u02dc e \u2212c1| 2K2( \u221a d \u2212s + 1) \u2265t i \u2264exp(\u2212t). (29) Since exp(0) = 1, (29) also holds at t = 0 Pr h |\u02dc e \u2212c1| 2K2( \u221a d \u2212s + 1) \u2265t i \u2264exp(\u2212t) \u2200t \u22650. (30) In (30), we have veri\ufb01ed the de\ufb01nition in (17) for \u02dc e \u2212c1 with K1 = 2K2( \u221a d \u2212s + 1). By proposition 2.7.1 (a), (d) de\ufb01nition 2.7.5 in [26], and (30), the sub-exponential norm is \u2225\u02dc e \u2212c1\u2225\u03d51 = c\u2032K1. 6 \fTheorem 2. Let X\u2217\u2208Rd\u00d7m be the unknown matrix such that the columns x\u2217 i are identical, independent, zero-mean sub-Gaussian random vectors, i.e., for \u03b1 \u2208Rd, K \u22650 E[exp(\u03b1\u22bax\u2217 i )] \u2264exp(\u2225\u03b1\u22252 2K2/2). (31) Let b X be as de\ufb01ned in (7). Let B be a \ufb01xed measurement matrix. For t \u22650, Pr \u0002 i=m X i=1 \u2225x\u2217 i \u2212\u02c6 xi\u22252 \u2212mc2 \u2265t \u0003 \u22642 exp \u0000\u2212c\u2032t2 mK1 \u0001 , (32) where c2 = K(d \u2212s + 5 2 \u221a d \u2212s + 2) 1 2 , K1 = 2K2( \u221a d \u2212s + 1) and c\u2032 is an absolute constant. Proof of Theorem 2. Note that Pr[|\u02dc e \u2212E[\u02dc e]| \u2265t] = Pr[|\u02dc e \u2212c1 \u2212E[\u02dc e \u2212c1]| \u2265t] \u22642 exp(\u2212c\u2032t/\u2225\u02dc e \u2212c1 \u2212E[\u02dc e \u2212c1]\u2225\u03d51). (33) Since \u2225\u02dc e \u2212c1 \u2212E[\u02dc e \u2212c1]\u2225\u03d51 = c\u2032\u2225\u02dc e \u2212c1\u2225\u03d51 (by 2.7.10 in [26]) and \u2225\u02dc e \u2212c1\u2225\u03d51 = c\u2032K1 (Lemma 3), Pr[|\u02dc e \u2212E[\u02dc e]| \u2265t] \u22642 exp(\u2212c\u2032t/K1), (34) where K1 is as in (30). For z \u22650, |z \u22121| \u2265\u03b4 = \u21d2|z2 \u22121| \u2265max(\u03b4, \u03b42). Therefore, Pr h\f \f \f \u221a \u02dc e \u2212 p E[\u02dc e] p E[\u02dc e] \f \f \f \u2265\u03b4 i \u2264Pr h\f \f \f\u02dc e \u2212E[\u02dc e] E[\u02dc e] \f \f \f \u2265max(\u03b4, \u03b42) i \u2264Pr h\f \f \f\u02dc e \u2212E[\u02dc e] E[\u02dc e] \f \f \f \u2265\u03b42i (35) \u22642 exp(\u2212c\u2032E[\u02dc e]\u03b42/K1), (36) where (36) follows by substituting t = \u03b42 in (34). Changing variables t = \u03b4 p E[\u02dc e] in (36), Pr \u0002\f \f\u221a \u02dc e \u2212 p E[\u02dc e] \f \f \u2265t \u0003 \u22642 exp(\u2212c\u2032t2/K1). (37) From (37) and proposition 2.5.2 (i), (iv) and de\ufb01nition 2.5.6 in [26], the sub-Gaussian norm squared is bounded as \u2225 \u221a \u02dc e \u2212 p E[\u02dc e]\u22252 \u03d52 = c\u2032K1. (38) Applying Hoe\ufb00ding\u2019s inequality (67) to \u221a \u02dc e \u2212 p E[\u02dc e], Pr \u0002 i=m X i=1 \u0000p \u02dc ei \u2212 p E[\u02dc ei] \u2212E[ p \u02dc ei \u2212 p E[\u02dc ei]] \u0001 \u2265t \u0003 \u22642 exp \u0000\u2212c\u2032t2 mK1 \u0001 . (39) Substituting E[ \u221a \u02dc e] \u2212 p E[\u02dc e] \u22640 (Jensen\u2019s inequality) in (39), Pr \u0002 i=m X i=1 p \u02dc ei \u2212m p E[\u02dc e] \u2265t \u0003 \u22642 exp \u0000\u2212c\u2032t2 mK1 \u0001 . (40) For non-negative random variable X, E[X] = R \u221e 0 Pr[X > t]dt. Applied to \u02dc e \u2212c1/2K2( \u221a d \u2212s + 1), E h \u02dc e \u2212c1 2K2( \u221a d \u2212s + 1) i \u2264 Z \u221e 0 exp(\u2212t)dt = 1 (41) In (41), we have substituted the tail probability upper bounds from (30). Substituting c1 from (16) in (41), E[\u02dc e] \u2264K2(d \u2212s + 5 2 \u221a d \u2212s + 2). (42) 7 \fBy de\ufb01nition in (18), (19) (also see Fig. 2), \u2225x\u2217 i \u2212\u02c6 xi\u22252 \u2264\u221a\u02dc ei \u2200i \u2208[m]. Substituting (42) and using \u2225x\u2217\u2212\u02c6 x\u22252 \u2264 \u221a \u02dc e in (40) completes the proof. Remark. Assuming Gaussian B, Theorem 1 shows that the probability that the relative error in (7) exceeds p (d \u2212s)/d decays at a sub-Gaussian rate. Assuming sub-Gaussian x\u2217instead, Theorem 2 shows that the probability that the error exceeds mc2, where c2 as in (32), also decays at a sub-Gaussian rate. Both results agree that the estimate (7) improves as the number of measurements s in the under-determined system (6) increases. The quantity K in (32) depends linearly on the sub-Gaussian norm of x\u2217and can be estimated in practice. For x\u2217\u223cN(0, I), K = 1. For x\u2217uniformly distributed on the Euclidean ball, K = c\u2032, where c\u2032 is an absolute constant. 3.2 k-sparse model For the standard (un-permuted) linear inverse problem y = Bx\u2217+ w, the error in the solution \u2225x\u2217\u2212\u02c6 x\u22252 is upper bounded in terms of the noise \u2225w\u22252 and \u03c3min(B), the smallest singular value of B. In this section, we bound the error in the proposed initialization for the k-sparse permutation model in terms of the value of the objective function F, \u03c3min(B) and the number of shu\ufb04es k. Lemma 4. Let P\u2217 k be the \ufb01xed unknown k-sparse permutation matrix with \u27e8I, P\u2217 k\u27e9= n \u2212k. Let x\u2217be the \ufb01xed unknown vector. Assuming Gaussian B, let y\u2217= Bx\u2217, \u02c6 y(0) = P\u2217 kBx\u2217. For k = 1, \u00b7 \u00b7 \u00b7 , n \u22121 and t \u22650, Pr \u0002 \u2225y\u2217\u2212\u02c6 y(0)\u22252 2 \u22652\u2225y\u2217\u22252 2 \u22122\u2225x\u2217\u22252 2 \u0000n \u2212k \u2212c3 \u221a t \u22123t \u0001\u0003 \u22647 exp(\u2212t), (43) where c3 = 2 \u221a n \u2212k + 2 \u221a 3k. Proof of Lemma 4. Under the k-sparse assumption on P\u2217, the known vector y has k shu\ufb04ed entries. For b P(0) = I, i.e., \u02c6 y(0) = y, the forward error is \u2225y\u2217\u2212\u02c6 y(0)\u22252 2 = 2\u2225y\u2217\u22252 2 \u22122\u27e8y\u2217, \u02c6 y(0)\u27e9, (44) where y\u2217= Bx\u2217is the unknown vector of unshu\ufb04ed measurements. Since \u2225y\u2217\u22252 = \u2225\u02c6 y(0)\u22252 and initialization \u02c6 y(0) = P\u2217 kBx\u2217is known, the only unknown term in (44) is the inner product \u27e8y\u2217, \u02c6 y(0)\u27e9. The scaled inner product \u27e8y\u2217, \u02c6 y(0)\u27e9/\u2225x\u2217\u22252 2 is expanded as \u27e8y\u2217, \u02c6 y(0)\u27e9 \u2225x\u2217\u22252 2 = 1 \u2225x\u2217\u22252 2 i=n X i=1 b\u22ba i x\u2217b\u22ba P\u2217(i)x\u2217 (45) = 1 \u2225x\u2217\u22252 2 i=n\u2212k X i=1 (b\u22ba i x\u2217)2 | {z } \u225cT1 + 1 \u2225x\u2217\u22252 2 n X i=n\u2212k+1 b\u22ba i x\u2217b\u22ba P\u2217(i)x\u2217 | {z } \u225cT2 . We have assumed in (45), wlog, that the last k rows of P\u2217 k are shu\ufb04ed. Assuming Gaussian B, (b\u22ba i x\u2217/\u2225x\u2217\u22252)2 \u223c \u03c72 is Chi-squared distributed with 1 degree of freedom. T1, de\ufb01ned in (45), is the sum of n \u2212k independent Chi-square random variables and is bounded, using (69), as Pr \u0002 T1 \u2264n \u2212k \u22122 p (n \u2212k)t \u0003 \u2264exp(\u2212t). (46) The product random variables in T2 are distributed as the di\ufb00erence of two independent \u03c72 random variables. To see this, let X = b\u22ba i x\u2217/\u2225x\u2217\u22252 , Y = b\u22ba P(i)x\u2217/\u2225x\u2217\u22252. (47) The random variables X and Y in (47) are independent normal random variables. The product random variable XY is expressed as XY = 1 2 \u0000X + Y \u221a 2 \u00012 \u22121 2 \u0000X \u2212Y \u221a 2 \u00012. (48) 8 \fThe random variables (X + Y )/ \u221a 2 \u223cN(0, 1) and (X \u2212Y )/ \u221a 2 \u223cN(0, 1) are jointly Gaussian and uncorrelated. Therefore, (X + Y )/ \u221a 2 is independent of (X \u2212Y )/ \u221a 2 and the product XY is distributed as the di\ufb00erence of two independent \u03c72 distributed random variables Z1 i , Z2 i b\u22ba i x\u2217b\u22ba P(i)x\u2217 \u2225x\u2217\u22252 2 \u223c1 2Z1 i \u22121 2Z2 i \u2200i \u2208n \u2212k + 1, \u00b7 \u00b7 \u00b7 , n. (49) The random variables (rv) in (49) are not mutually independent, but each rv depends on, at most, two other rvs. To see this, let permutation P such that P(i) 7\u2192j, then b\u22ba i x\u2217b\u22ba j x\u2217is not independent of b\u22ba j x\u2217b\u22ba P(j)x\u2217, b\u22ba P\u22ba(i)x\u2217b\u22ba i x\u2217. (50) The k rvs in (49) can therefore be partitioned into three sets P, Q, R such that the rvs within each set are independent. Let k1 be the number of rvs in set P. The sum TP , where TP \u225c 1 \u2225x\u2217\u22252 2 X i\u2208P b\u22ba i x\u2217b\u22ba P(i)x\u2217= 1 2 X i\u2208P Z1 i \u22121 2 X i\u2208P Z2 i , (51) is upper bounded in probability as Pr[TP \u2264\u22122 p k1t \u2212t] \u22642 exp(\u2212t). (52) (52) follows from applying the union bound to probabilities p1, p2 p1 = Pr \u0002 X i\u2208P Z1 i \u2264k1 \u22122 p k1t \u0003 \u2264exp(\u2212t), (53) p2 = Pr \u0002 X i\u2208P Z2 i \u2265k1 + 2 p k1t + 2t \u0003 \u2264exp(\u2212t), (54) and bounding p1, p2 using tail inequalities (69), (68), respectively. De\ufb01ning TQ, TR similarly to (51), with cardinalities k2, k3 and applying the union bound as in (53), (54) gives Pr \u0002 T2 \u2264\u22122( p k1t + p k2t + p k3t) \u22123t \u0003 \u22646 exp(\u2212t), (55) where T2 = TP + TQ + TR. Since \u2225[\u221ak1 \u221ak2 \u221ak3]\u22ba\u22252 1 \u22643\u2225\u00b7\u22252 2 = 3k, \u221ak1 + \u221ak2 + \u221ak3 \u2264 \u221a 3k. Substituting in (55), Pr \u0002 T2 \u2264\u22122 \u221a 3kt \u22123t \u0003 \u22646 exp(\u2212t). (56) Applying the union bound to (46), (56) gives the result in (43). Lemma 5. For the same assumptions as in Lemma 4, k = 1, \u00b7 \u00b7 \u00b7 , n \u22121 and t \u22650, Pr \u0002 \u03c32 min(B)\u2225x\u2217\u2212\u02c6 x(1)\u22252 2 \u22652\u2225y\u2217\u22252 2 \u22122\u2225x\u2217\u22252 2 \u0000n \u2212k \u2212c3 \u221a t \u22123t \u0001 \u2212F (1)\u0003 \u22647 exp(\u2212t), (57) where \u02c6 x(1) = B\u2020\u02c6 y(0), F (1) = \u2225y \u2212B\u02c6 x(1)\u22252 2 and c3 = 2 \u221a n \u2212k + 2 \u221a 3k. Proof of Lemma 5. Let e denote the error term such that \u02c6 y(0) = B\u02c6 x(1) + e, (58) where \u02c6 x(1) = B\u2020\u02c6 y(0), \u02c6 y(0) = P\u2217 kBx\u2217and e \u22a5R(B) is orthogonal to the range space of B because \u02c6 x(1) = argmin x\u2225\u02c6 y(0) \u2212Bx\u22252. Substituting y\u2217= Bx\u2217and (58) below, \u2225y\u2217\u2212\u02c6 y(0)\u22252 2 = \u2225B(x\u2217\u2212\u02c6 x(1)) \u2212e\u22252 2. (59) Using Pythogras\u2019 theorem, \u2225B(x\u2217\u2212\u02c6 x(1)) \u2212e\u22252 2 = \u2225B(x\u2217\u2212\u02c6 x(1))\u22252 2 + \u2225e\u22252 2. (60) Substituting the lower bound \u03c32 min(B)\u2225x\u2217\u2212\u02c6 x(1)\u22252 2 \u2264\u2225B(x\u2217\u2212\u02c6 x(1))\u22252 2 in (60), \u03c32 min(B)\u2225x\u2217\u2212\u02c6 x(1)\u22252 2 \u2264\u2225y\u2217\u2212\u02c6 y(0)\u22252 2 \u2212\u2225e\u22252 2. (61) (62) follows by substituting the probability upper bound for \u2225y\u2217\u2212\u02c6 y(0)\u22252 2 from (43) into (61) and noting that \u2225e\u22252 2 = F (1) = F(b P(0), \u02c6 x(1)). 9 \f10 20 50 100 125 200 250 block size r 0 0.2 0.4 0.6 0.8 1 dH=n P$ r n = 1000 m = 50 d = 100 B 9 N(0; 1) Spectral Biconvex RLUS `2-regularized Proposed (a) 600 650 700 750 800 850 900 number of shu0es k 0 0.2 0.4 0.6 0.8 1 P$ k n = 1000 m = 50 d = 100B 9 N(0; 1) Spectral RLUS `2-regularized Proposed (b) 600 650 700 750 800 825 850 875 900 number of shu0es k 0 0.2 0.4 0.6 0.8 1 P$ k n = 1000 m = 50 d = 100 B 9 Unif Spectral RLUS `2-regularized Proposed (c) 100 105 110 115 120 125 130 135 140 145 150 number of shu0es k 0 0.2 0.4 0.6 0.8 1 P$ k n = 200 m = 10 d = 20B 9 N(0; 1) Spectral RLUS `2-regularized ds+ Proposed (d) 200 250 300 350 400 500 550 600 650 700 750 800 number of shu0es k 2 4 6 8 10 12 14 16 estimation error jjx$ ! ^ xjj2 P$ k n = 1000 m = 1 d = 100B 9 N(0; 1) Alt-min mulitple init Stochastic Alt-min Proposed (e) Figure 3: Synthetic simulations. Y = P\u2217Bn\u00d7dX\u2217 d\u00d7m + W. The entries of X\u2217are drawn from the normal distribution. The permutation matrix P\u2217 r(P\u2217 k) is sampled uniformly from the set of r-local (k-sparse) permutations. The results are averaged over 15 Monte-Carlo runs. (a). Figure plots the fractional Hamming distortion dH/n against block size r. (b), (c), (d). Figure plots dH/n against number of shu\ufb04es k. (e). Figure plots the estimation error against k. Theorem 3. Let P\u2217 k be the \ufb01xed unknown permutation matrix with \u27e8I, P\u2217 k\u27e9= n \u2212k. Let X\u2217be the \ufb01xed unknown matrix. Assuming Gaussian B, let Y\u2217= BX\u2217and b Y(0) = P\u2217 kBX\u2217. For k = 1, \u00b7 \u00b7 \u00b7 , n \u22121 and t \u2265log m2, Pr \u0002 \u03c32 min(B)\u2225X\u2217\u2212b X(1)\u22252 F \u22652\u2225Y\u2217\u22252 F \u22122\u2225X\u2217\u22252 F \u0000n \u2212k \u2212c3 \u221a t \u22123t \u0001 \u2212F (1)\u0003 \u22647 exp(\u2212t), (62) where b X(1) = B\u2020 b Y(0), F (1) = \u2225Y \u2212B b X(1)\u22252 F and c3 = 2 \u221a n \u2212k + 2 \u221a 3k. Proof of Theorem 3. The proof follows by applying the union bound to (57). An immediate upper bound that does not depend on the number of diagonal entries of P\u2217 k is \u03c32 min(B)\u2225X\u2217\u2212b X(1)\u22252 F \u22644\u2225Y\u2217\u22252 F \u2212F (1). (63) (62) shows that the probability that the error exceeds \u2225Y\u2217\u22252 F \u2212c, c = \u2126(n \u2212k) and n \u2212k is the number of diagonal entries in P\u2217 k, decays exponentially. Furthermore, the term \u2225Y\u2217\u22252 F is known and \u2225X\u2217\u2225F can be lower bounded in terms of known quantities as \u2225X\u2217\u22252 F \u2264\u2225Y\u2217\u22252 F /\u03c32 max(B). 4 Results MATLAB code and datasets are at the \ufb01rst author\u2019s GitHub 1. Baselines. We compare against six baseline methods. We refer to these methods as \u2018\u21132-regularized\u2019 [5],\u2018ds+\u2019 [5], \u2018Spectral\u2019 [17], \u2018Biconvex\u2019 [4], \u2018RLUS\u2019 [10], and \u2018Stochastic alt-min\u2019 [15]. The \u2018\u21132-regularized\u2019 1https://github.com/aabbas02/ksparse-and-rlocal 10 \fDataset n d m rmax s Oracle Naive RLUS \u21132-reg alt-min-k alt-min-r ftp 335 30 6 43 46 (0.88, 0) (0.44, 0.70) (0.62, 0.01) (0.57, 0.59) (0.73, 0.41) (0.85, 0.17) scm 8966 35 16 424 1137 (0.58, 0) (0.21, 0.79) (0.52, 0.29) (0.46, 0.49) (0.54, 0.22) (0.55, 0.22) scs 44484 10 6 3553 356 (0.81, 0) (0.01, 0.99) (0.74, 0.24) (0.02, 0.98) (0.73, 0.33) (0.77, 0.21) air-qty 27605 27 16 95 366 (0.69, 0) (0.29, 0.78) (0.65, 0.20) (0.64, 0.21) (0.66, 0.17) (0.65, 0.19) air-qty 27605 27 16 46 744 (0.69, 0) (0.10, 0.94) (0.60, 0.34) (0.26, 0.79) (0.57, 0.42) (0.62, 0.32) Table 1: rmax denotes the largest block size of P\u2217 r and s denotes the number of blocks. The methods are compared based on the coe\ufb03cient of determination R2 and relative error (R2, relative error). The relative error is \u2225X\u2217\u2212 b X\u2225F /\u2225X\u2217\u2225F , where X\u2217= B\u2020Y\u2217is the \u2018oracle\u2019 regression matrix given unpermuted data Y\u2217. The \u2018naive\u2019 estimate from permuted data Y is b X = B\u2020Y. The coe\ufb03cient R2( b X) = 1 \u2212(\u2225Y\u2217\u2212B b X\u2225F /\u2225Y\u2217\u2225F ) measures the goodness of \ufb01t for the unpermuted data. method considers the k-sparse permutation model and incorporates the model assumption by imposing a row-wise group sparse penalty on \u2225b Yi,:\u22252, where b Y = B b X. Other methods are discussed in the following paragraphs. We set \u03f5 = 0.01 in Algorithm 1. Figs. 3a, 3b. We compare our algorithm for the r-local and k-sparse permutation models to baselines. To adapt the \u2018Spectral\u2019, \u2018\u21132-regularized\u2019 and \u2018Biconvex\u2019 methods to the r-local model, we add a constraint enforcing the permutation estimates to be block-diagonal. The results show that our algorithm recovers P\u2217 with decreasing block size r and number of shu\ufb04es k. This observation con\ufb01rms the conclusions of Theorems 1,2,3 as the initialization to our algorithm improves with lower values of r and k. The results also show that our algorithm is applicable to both models, unlike baselines. Our algorithm is also computationally scalable. For r = 125 in Fig. 3a and k = 850 in Fig. 3b, the MATLAB run-times, with 16 Gb RAM, are less than one second. Fig. 3c. The entries of the measurement matrix B are sampled i.i.d. from the uniform [0, 1] distribution. Compared to the case for Gaussian B (Fig. 3b), the performance of the \u2018Spectral\u2019 and \u2018RLUS\u2019 methods deteriorates signi\ufb01cantly. This is because both algorithms consider quadratic measurements YY\u22ba. Speci\ufb01cally, the \u2018Spectral\u2019 method is based on the spectral initialization technique [27], which assumes that the measurement matrix is Gaussian. In contrast, the performance of the proposed algorithm and the \u2018\u21132-regularized\u2019 method does not deteriorate. Fig. 3d. The \u2018ds+\u2019 algorithm [5] considers the convex relaxation of (2) by minimizing the objective over the set of doubly stochastic matrices. Assuming an upper bound on the number of shu\ufb04es k is known, \u2018ds+\u2019 also constrains \u27e8I, P\u27e9\u2265n \u2212k. Each iteration of \u2018ds+\u2019 minimizes a linear program, greatly increasing the run-time of the algorithm. The results show that the proposed algorithm outperforms \u2018ds+\u2019, possibly because, for our algorithm, the objective is optimized directly over the set of permutations. Fig. 3e. We compare to the method in [15] which considers the m = 1 single-view setup and proposes stochastic alternating minimization (S.alt-min) to optimize (2). The run-time for S.alt-min is 50 times the run-time of the proposed algorithm because S.alt-min updates P multiple times in each iteration and retains the best update. [15] also proposes alt-min with multiple initializations for b P(0). The results in Fig. 3e show that our algorithm (alt-min with b P(0) = I initialization) outperforms both S.alt-min and alt-min with multiple initializations. Real data. For the linked linear regression problem introduced in Section 1.2, we report results in Table 1 on the four datasets from [5]. The measurement matrix and the regression model are also de\ufb01ned as in [5]. For \u2018ftp\u2019,\u2018scm\u2019 and \u2018scs\u2019, the values of a feature (or column of the measurement matrix) are rounded and data points with the same feature value are assigned to the same block and permuted. The \u2018air-qty\u2019 dataset comprises time-stamped readings with year, month, day and hour information. In row 4 (5) of Table 1, readings with the same month and day (day and hour) are assigned to the same block and permuted, as also done in [5]. The results show that the proposed alt-min algorithm outperforms the competing baselines. \u2018alt-min-k\u2019, i.e. alt-min initialized to b P(0) = I, is also competitive, possibly because permuting correlated rows may not greatly corrupt the measurement matrix B. 11 \f5" + } + ], + "Weiwen Jiang": [ + { + "url": "http://arxiv.org/abs/2311.12333v1", + "title": "QuGeo: An End-to-end Quantum Learning Framework for Geoscience -- A Case Study on Full-Waveform Inversion", + "abstract": "The rapid advancement of quantum computing has generated considerable\nanticipation for its transformative potential. However, harnessing its full\npotential relies on identifying \"killer applications\". In this regard, QuGeo\nemerges as a groundbreaking quantum learning framework, poised to become a key\napplication in geoscience, particularly for Full-Waveform Inversion (FWI). This\nframework integrates variational quantum circuits with geoscience, representing\na novel fusion of quantum computing and geophysical analysis. This synergy\nunlocks quantum computing's potential within geoscience. It addresses the\ncritical need for physics-guided data scaling, ensuring high-performance\ngeoscientific analyses aligned with core physical principles. Furthermore,\nQuGeo's introduction of a quantum circuit custom-designed for FWI highlights\nthe critical importance of application-specific circuit design for quantum\ncomputing. In the OpenFWI's FlatVelA dataset experiments, the variational\nquantum circuit from QuGeo, with only 576 parameters, achieved significant\nimprovement in performance. It reached a Structural Similarity Image Metric\n(SSIM) score of 0.905 between the ground truth and the output velocity map.\nThis is a notable enhancement from the baseline design's SSIM score of 0.800,\nwhich was achieved without the incorporation of physics knowledge.", + "authors": "Weiwen Jiang, Youzuo Lin", + "published": "2023-11-21", + "updated": "2023-11-21", + "primary_cat": "quant-ph", + "cats": [ + "quant-ph" + ], + "main_content": "INTRODUCTION Quantum computing\u2019s integration with machine learning is a rapidly expanding \ufb01eld, though it is still in search of groundbreaking applications to fully showcase its capabilities. In geophysical inversion, critical for areas like civil infrastructure and energy exploration, recent advancements have applied quantum annealing to seismic inversion problems. These e\ufb00orts, however, primarily tackle linearized versions of the problem. For instance, Souza\u2019s approach reformulates seismic inversion into linear equations and QUBO formulations [1], and Greer develops a QUBO-compatible linearized inversion for dual velocity values, bothbased on traditional seismic techniques [2]. In contrast, our work introduces the \ufb01rst learningbased seismic inversion technique on general-purpose quantum computing platforms, marking a novel direction in this domain. Characterizing subsurface geology is essential for a range of applications, from earthquake research and civil infrastructure to new energy exploration and environmental studies. Seismic inversion, which reconstructs subsurface images from seismic waves, uses full-waveform inversion (FWI) to consider complete waveform data, including amplitude and phase. FWI, addressing nonlinear challenges, o\ufb00ers enhanced accuracy and resolution compared to linear methods. Currently, FWI is approached through physics-based and machine learning-based methods. While physicsbased methods are precise, they face computational challenges and issues like ill-posedness and cycle skipping. Conversely, machine learning-based methods, designed to address these issues, are promising but heavily dependent on extensive training data, which can result in high computational demands. What\u2019s more, seismic waves continuously received by sensors from di\ufb00erent locations have a high correlation on both spatial and temporal. Our study introduces quantum computing as a novel solution to reduce the computational burden in data-driven FWI and leverage fundamental quantummechanics, particularly the entanglement, to extract highly correlated features, showcasing its potential to enhance both the e\ufb03ciency and e\ufb00ectiveness of machine learning in seismic inversion. Unique characteristics and structures of geophysical problems, however, set challenges in designing quantum learning for FWI. Firstly, there is a scarcity of standard datasets tailored to current quantumcapabilities; careless design could result in data misaligned with physical realities, a\ufb00ecting performance. Secondly, a dedicated quantum design framework is lacking; straightforwardly using the quantum learning algorithm (a.k.a., Variational Quantum Circuit or VQC) can easily be suboptimal or ine\ufb03cient because it cannot exploit the speci\ufb01c properties inherent in geophysics to optimize the design. Finally, the most e\ufb00ective ways to harness the full potential of quantum computing in this context remain unclear, requiring further exploration and innovation in the \ufb01eld. In our work, we introduce QuGeo, an innovative quantum learning framework tailoredto address seismic FWI challenges. To tackle the mentioned hurdles, \ufb01rstly, we have created a physics-informed dataset via a governing wave equation, on top of which we further developed a classical machine learning-based data converter to perform data scaling according to the quantum resource constraints e\ufb03ciently. Secondly, we developed an application-speci\ufb01c VQC, namely QuGeoVQC, to incorporate domain-speci\ufb01c knowledge in optimizing the design. QuGeoVQC explores the designs of a data encoder and VQC computing structure to extract spatial and temporal features; it also exploits characteristics of FWI problem to simplify and optimize the encoder to boost the performance. Furthermore, we present a novel data batching technique adapted for quantum computing, which enables quantum computers to process \ud441batches of data in parallel with only \ud459\ud45c\ud454\ud441additional qubits, further catering to the high computational demands from learningbased FWI and advancing the potential of QuGeo in seismic inversion. The main contributions of this paper are as follows: \fConference\u201917, July 2017, Washington, DC, USA W. Jiang and Y. Lin km/s depth (km) o\ufb00set (m) 0 0 surface surface receivers r1 r1 r2 r2 r3 r3 2 4 6 700 4000 3500 time o\ufb00set (m) 0 0 1024 700 o\ufb00set (m) 0 700 o\ufb00set (m) 0 700 (a) Flat rock layers w/ seismic receivers (c) Subsurface velocity map (b) Received seismic data Figure 1: Illustration of the target geophysics application: (a) the photo of a \ufb02at rock layer; (b) the seismic waveform data obtained from the receivers placed on the surface; and (c) the velocity map used to characterize the subsurface structure. \u2022 To the best of our knowledge, this is the very \ufb01rst pilot work in exploring the capacity of general-purpose quantum computing for seismic inversion problems, showcasing the potential of quantum computing for geoscienti\ufb01c analyses. \u2022 We unveil the essential need for a physics-informed dataset to ensure data is aligned with physical realities while simultaneously satisfying the resource constraint in current quantum computing platforms. \u2022 We develop an application-speci\ufb01c variational quantum circuit to leverage domain-speci\ufb01c knowledge in optimizing the design, which is equipped with a novel data batch engine to underpin the high computational demand to process extensive data for learning-based seismic inversion. To evaluate the e\ufb00ectiveness of ourproposedQuGeo framework, we implemented the proposed quantum learning innovations on TorchQuantum platform [3] and conducted tests using the widely recognized OpenFWI dataset from the geophysics community [4]. These tests aimed to validate the integration of physics knowledge and assess the performance of our custom-designed QuGeoVQC module. Our \ufb01ndings demonstrate that the incorporationof physics knowledge in QuGeo not only leads to high prediction accuracy, as re\ufb02ected in the SSIM values, but also results in a remarkably e\ufb03cient learning model utilizing just 576 parameters. This paper is structured as follows: Section 2 presents the background. In Section 3, we detail the QuGeo Framework. Evaluation results and concluding remarks are presented in Sections 4-5. 2 BACKGROUND AND RELATED WORK Data-driven Quantum Learning. The core component of a typical quantum learning framework is a parameterized quantum circuit (a.k.a., variational quantum circuit or ansatz circuit). Like classical machine learning, there are two steps in quantum learning: forward propagation and backward propagation. The forward propagation only involves quantum computing, where data will be encoded, processed, and measured in the quantum circuit. The backward propagation further involves classical computing to calculate the loss according to the measurement results and label, which will then be used to update the parameters in VQC. The optimization framework is to \ufb01nd the optimal parameters in quantum circuits so that the cost function of a certain task can be minimized. Quantum learning has a wide of applications, such as Quantum Approximate Optimization Algorithm (QAOA) for combinatorial optimization problems [5], Variational Quantum Eigensolver (VQE) for quantum chemistry and quantum simulations [6], and Quantum Neural Networks (QNN) for machine learning tasks [3, 7\u201311]. Compared with classical computing, quantum learning gets bene\ufb01ts from entanglement, which has been proven to be scalable to learn from the exponentially increasing size of data [12]. Geoscience application \u2014 Full-Waveform Inversion (FWI). Subsurface structures are typically layer-structured; an example is the \ufb02at rock layers, as illustrated in Figure 1(a). Understanding subsurface structures is a multidisciplinary e\ufb00ort with broad implications. In the \ufb01eld of new and renewable energy exploration, accurately characterizing subsurface structures is crucial for e\ufb00ectively locating energy sources below the Earth\u2019s surface. Note that it not only contributes to resource exploration and extraction but also plays a vital role in addressing environmental challenges, ensuring infrastructure stability, and advancing our knowledge of Earth\u2019s geological processes. Seismic data and velocity maps are two key elements to describe subsurface structures, discussed below. Seismic data, or seismic waveforms, are composed of waves that travel through the Earth\u2019s subsurface. These waves are often generated by controlled explosions or by striking the ground with heavy weights. Captured by geophones or receivers, these waves re\ufb02ect varying subsurface layers. The collected data is then processed to create detailed waveforms in a shot gather, as illustrated in Figure 1b. From this shot-gather waveform data, a velocity map can be derived, indicating the speed at which seismic waves travel through di\ufb00erent subsurface media, as shown in Figure 1c. Since rock properties a\ufb00ect wave speed, the velocity map is essential in identifying and characterizing subsurface geological structures, such as rock layers, faults, and reservoirs. For instance, the example in Figure 1c displays a subsurface structure with \ufb01ve distinct layers, each representing di\ufb00erent rock properties and depths. Building on those concepts, we introduce Full-Waveform Inversion (FWI), a sophisticated seismic imaging technique widely used in geophysics for creating detailed and accurate subsurface models. FWI aims to minimize the discrepancy between observed and simulated seismic waveforms. Applied extensively in both academic and engineering [13], FWI essentially predicts the subsurface velocity map from seismic waveforms recorded at surface receivers. Traditionally, FWI relies on physics-based simulations that are computationally intensive. The concept of data-driven FWI, introduced in recent years [14], has led to its growing success. In this work, we pilot a data-driven quantum learning for Geoscience FWI, harnessing the power of quantum computing to enhance the FWI. 3 QuGeo FRAMEWORK Figure 2 shows the proposed QuGeo framework, which is composed of three components:\u2460QuGeoDatawill consider the quantum device\u2019s capacity and scale the seismic wave data appropriately; \u2461QuGeoVQC is a computation engine which is key to achieving practical usage of near-term noisy quantum computers; and \u2462QuBatch is a performance booster that provides the ability to process data in parallel to unleash the power of quantum computing. \fQGeo: Qantum Learning for Geoscience Conference\u201917, July 2017, Washington, DC, USA depth (km) time o\ufb00set (m) 0 0 2 4 6 700 350 o\ufb00set (m) num of qubits 0 0 200 400 600 800 700 350 time o\ufb00set (m) 0 0 200 400 600 800 700 350 Training data: seismic wave & velocity map QuGeoData 1 Test seismic data 1000 \u00b4 700 standard phy-guide 32 \u00b4 8 8 \u00b4 8 8 \u00b4 8 QuGeoVQC 2 Encoder Decoder VQC # groups # layers pixel vs. layer # batches 3 QuBatch: Data Batch on Quantum Circuits Figure 2: Illustration of the proposed QuGeo framework. 3.1 QuGeoData: Physics-Guided Data Scaling 3.1.1 Scaling data with velocity map. We have pairs of seismic wave and velocity maps in the training dataset. Instead of directly scaling seismic data, we propose to employ Forward Modeling to generate the seismic wave data from downsampled velocity maps. The governing equation of the acoustic wave propagation in a 2dimension isotropic medium with a constant density is as follows: \u22072\ud45d\u22121 \ud4502 \ud7152\ud45d \ud715\ud4612 = \ud460 (1) where \u22072 = \ud7152 \ud715\ud4652 + \ud7152 \ud715\ud4662 , \ud450is velocity map, \ud45dis pressure \ufb01eld and \ud460is source term. Velocity map \ud450depends on the spatial location (\ud465,\ud466) while the pressure \ufb01eld \ud45dand the source term \ud460depend on the spatial location and time (\ud465,\ud466) and \ud461. We will follow the Forward Modeling algorithm [15]. The seismic data is simulated using \ufb01nite di\ufb00erence methods with the absorbing boundary condition. 3.1.2 Scaling data without velocity map. When the QuGeo is applied to real-world applications, we do not have the subsurface velocity map, which requires the scaling of data without using the velocity map. In addition, it has the requirement of high e\ufb03ciency in performing data scaling. To address these issues, we propose an ML-based data scaling approach to train a convolution neural network (CNN) for data compression. Our hypnosis is that physicsrelated features can be learned from the feature extraction by CNN. The key step is to build the dataset. Here, we have the original seismic wave data (\ud437), which has the dimension of 1000 \u00d7 700 as in the example from Figure 2. We also have the physics-guided scaled data (\ud45d\u210e\ud466\ud437), which has the dimension of 32 in the example. The pair of data \u27e8\ud437, \ud45d\u210e\ud466\ud437\u27e9will be built as the training dataset. On top of the dataset, we designed a LeNet-like CNN to perform data compression, which contains two convolutional layers (including a ReLU function after the convolution operation) and a fully connected (FC) layer. Although simple, it is quite e\ufb00ective to perform the data compression, as will be shown in the experimental results. 3.2 QuGeoVQC: Quantum Circuit Design 3.2.1 Encoderof Multi-source Seismic Data. The encoding of seismic wave data to qubits is based on a state-of-the-art quantum encoder from [16], called spatial-temporal encoder \u201cST-Encoder\u201d. It was originally designed for natural images, encoding a group of data (i.e., spatial-close \ud441data) to amplitudes of \ud459\ud45c\ud4542\ud441qubits. To use ST-Encoder in QuGeoVQC, we need to identify how to map data to the amplitudes of a set of qubits. Seismic data has three dimensions, including (1) sources, which generate waves from the surface at di\ufb00erent locations; (2) receivers, which receive waves on the surface; and (3) elapsed time, which shows the wave pressure received over time. As shown in Eq. 1, one source represents an independent event (say vibration from vibroseis trucks), and each of them can be calculated by the di\ufb00erential of pressure on time and location. Therefore, to better extract features from di\ufb00erent sources, we group and encode data from the same source into qubits. 3.2.2 Variational Qantum Circuit. We will follow ST-VQC [16] to create sub-VQCs to independently process data in each group, and gradually commute between groups by using multi-qubit gates across di\ufb00erent sub-VQCs. There are a couple of design hyperparameters that need to be determined. In each sub-VQC, it is necessary to determine how many layers of VQC are needed, which re\ufb02ects the number of trainable parameters. In addition, the order of entanglement between di\ufb00erent groups needs to be identi\ufb01ed. 3.2.3 Decoder of Velocity Maps. In carrying out the waveform inversion task, we observe the simpli\ufb01cation of the decoding circuit can signi\ufb01cantly improve performance, which takes bene\ufb01ts of the task\u2019s property. The decoder design is related to the de\ufb01nition of the loss function used in training VQC. Let \ud43abe the groundtruth velocity map, and \ud43a\ud456,\ud457the velocity at location \u27e8\ud456, \ud457\u27e9, where \ud456, \ud457\u2208[0, \ud441) represents the coordinate. A straightforward design is to conduct a pixel-wise comparison between ground truth and the forward results. In this case, the decoder needs \ud4412 velocities from the quantum circuit, denoted as \ud437. For example, the mean squared error between ground truth and VQC outputs can be de\ufb01ned as: \ud459\ud45c\ud460\ud460\ud45d\ud456\ud465\ud452\ud459= \u00d5 \ud456\u2208[0,\ud441) \u00d5 \ud457\u2208[0,\ud441) {(\ud43a\ud456,\ud457\u2212\ud437\ud456,\ud457)2} (2) As most subsurface has a \ufb02at structure, we can simplify the regression output data. Speci\ufb01cally, instead of pixel-wise comparison, we can predict one velocity of each row. As a result, we only predict \ud441velocities, denoted as \ud437\u2032, leading to the following MSE: \ud459\ud45c\ud460\ud460\ud459\ud44e\ud466\ud452\ud45f= \u00d5 \ud456\u2208[0,\ud441) \u00d5 \ud457\u2208[0,\ud441) {(\ud43a\ud456,\ud457\u2212\ud437\u2032 \ud457)2} (3) The above method can be generalized for the non-\ufb02at subsurface, such as curve structures. Because the subsurface mediums between curves have the same material, indicating a similar velocity. In this case, we can still use one velocity for each row but need to predict a multi-variable function to describe the curve. The row velocity will be used for all locations between two curves. \fConference\u201917, July 2017, Washington, DC, USA W. Jiang and Y. Lin q\u007f q\u0081 |0\u00f1 s0 (a) (b) (c) s1 s2 |0\u00f1 Ue U(q) I \u00c4 U(q) = |j\u00f1 = I \u00c4 U(q) \u00d7 Ue \u00d7|0\u00f1 = = = \u00c4 U(q) s1\u00aes2 I Figure 3: Illustration of the proposed QuBatch with 2 qubits. G\u007f G\u0081 (d) No batch for 2 groups (a) No batch (b) Batch of 2 (c) Batch of 4 U\u007f(q) U!(q) U\u0081(q) G\u007f G\u0081 q_batch\u007f q_batch\u0081 (e) Batch of 2 for 2 groups U\u007f(q) U\u0081(q) I I U!(q) D D U(q) q_batch\u007f U(q) I D q_batch\u0081 U(q) I q_batch\u007f I Figure 4: Illustration of integrating QuBatch to QuGeoVQC with di\ufb00erent batch sizes and group sizes. 3.3 QuBatch: Data Batch on Quantum Circuits 3.3.1 Fundamentals. Before introducing details, we use an example to illustrate the ability of quantum computing to process data batches in parallel in Figure 3. We have two vectors \ud4371 and \ud4372, each of which contains two features. The weight matrix is \ud448(\ud703). There are two computations to be performed: \ud448(\ud703) \u00b7 \ud4371 and \ud448(\ud703) \u00b7 \ud4372. We construct a quantum circuit with three steps (\ud4460 to \ud4462) to perform these computations. As shown in Figure 3(a), an encoder \ud448\ud452 entangle these qubits from \ud4460 to \ud4461: |\ud713\u27e9= \ud448\ud452\u00b7 |0\u27e9= [\ud4371, \ud4372]\ud447. The subcircuit from step \ud4461 to \ud4462 constructs the computation operator, where \u201cno gate\u201d is placed on qubit \ud45e0, indicated by a virtual \ud43c, and the operator \ud448(\ud703) is placed on qubit \ud45e1. As qubits are entangled at step \ud4461, we need to combine these two operators for computation by tensor product, shown in Figure 3(b). Now, we have two \ud448(\ud703) operators located on the diagonal of the matrix. Kindly note that this indicates that we can duplicate the computation operator without any cost, providing the fundamentals to e\ufb03ciently support SIMD operation. Then, as shown in Figure 3(c), we can obtain the results of \ud448(\ud703) \u00b7 \ud4371 and \ud448(\ud703) \u00b7 \ud4372 on the output amplitudes. 3.3.2 \ud444\ud462\ud435\ud44e\ud461\ud450\u210eintegration. To integrate \ud444\ud462\ud44f\ud44e\ud461\ud450\u210eto \ud444\ud462\ud43a\ud452\ud45c\ud449\ud444\ud436, we extend the approach in Figure 3 from two aspects: (1) a larger number of batches and (2) the circuit with multiple groups. For the \ufb01rst extension, \ud444\ud462\ud44f\ud44e\ud461\ud450\u210ecan process batch size of 2\ud441by adding only \ud441qubits (\ud441\u22650), as shown in Figures 4(a)-(c). The second extension is to support multiple groups. This can be achieved by introducing a swap gate before communicating between two groups, as shown in Figures 4(d)-(e). We omit detailed analysis here to save space. 3.3.3 Complexity analysis. Before detailed analysis, we \ufb01rst discuss the overhead introduced by \ud444\ud462\ud435\ud44e\ud461\ud450\u210e. As multiple operators can be produced by using tensor products between one operator with an identity matrix, we do not need to pay overhead for the computation. Kindly note that we need to pay overhead on the data encoding. First, the amplitude encoding will lead to a longer circuit. Fortunately, as shown in [16], the circuit length grows linearly with the increase of qubits. Second, because the sum of the squared magnitudes of the amplitudes of all possible states of a qubit must equal 1, if more data are encoded to a batch, we need to normalize the data, indicating that the data precision will be decreased. Kindly note although the data precision will be decreased, the relevant relationship between data can be maintained. In addition, we can control the group size and batch size to make a tradeo\ufb00 among circuit depth, number of qubits, and data precision. Now, we discuss the complexity. Let \ud435be the number of batches implemented in QuBatch, \ud43abe the number of groups in the encoder, and \ud442(\ud44b) be the original time-space complexity (i.e., qubits times circuit depth). By introducing \ud435bathes to the system, we will have overhead on both qubits number and depth: (1) the additional number of qubits will be \ud442(\ud43a\u00b7 log\ud435); (2) for each group, the circuit length increased along with the additional number of qubits; therefore, it has an overhead of \ud442(log\ud435). As the encoding of di\ufb00erent groups is conducted in parallel, we \ufb01nally have the time-space complexity of \ud442(\ud43a\u00b7 log2 \ud435\u00b7 \ud44b). Compared to the implementation of \ud435batches independently, it will lead to a complexity of \ud442(\ud435\u00b7\ud44b). If \ud435>> \ud43a, QuBatch can exponentially decrease the complexity. 4 EXPERIMENTS This section reports experimental setups, followed by results. Dataset. Evaluations are performed on the FlatVelA dataset in OpenFWI [4]. QuGeoData is applied to adjust the data scale to \ufb01t the target quantum backends. More speci\ufb01cally, the original data in OpenFWI has the dimension of 350, 000 = 5 \u00d7 1000 \u00d7 70 (#source \u00d7 time steps \u00d7 #receiver) for seismic data and 70 \u00d7 70 (depth \u00d7 width) for velocity maps. We set the constraint on the number of the qubits to be less than 16, which \ufb01ts most of today\u2019s superconducting-based or ion-trap-based quantum computers. To this end, we will scale the dimension of seismic data to 256, and the velocity map to 8 \u00d7 8. For comparison, we employ a standard nearest neighbor resampling algorithm to downsample both waveform and velocity map as the baseline, denoted as \u201cD-Sample\u201d. Two methods in QuGeoData will be used for comparison. We denote \u201cQ-D-FW\u201d to indicate the data (D) scaling using forward modeling (FW), which is proposed in Section 3.1.1, and denote \u201cQ-D-CNN\u201d to indicate the data (D) scaling using CNN-based data compression proposed in Section 3.1.2. VQCs. We will compare two QuGeoVQC designs with di\ufb00erences in the decoder. The \ufb01rst one is designed to use the pixelwise loss in Eq. 2, where 8 \u00d7 8 velocities will be decoded as the magnitude of 64 amplitudes from the quantum system. We denote the design as \u201cQ-M-PX\u201d, indicating the VQC model (M) based on the pixel-wise loss. The second one is application-speci\ufb01c design, which leverages the knowledge that the subsurface has a \ufb02at layerwise (LY) structure, denoted as \u201cQ-M-LY\u201d. It uses the loss function in Eq. 3, and the velocities will be decoded using Z-measurement of independent qubits. Q-M-PX and Q-M-LY use the ansatz with 12 blocks, each of which is a \u2018U3+CU3\u2019 block as proposed in [3]. To compare quantum learning and classical learning, we implemented two classical convolutional neural networks (CNN) with \fQGeo: Qantum Learning for Geoscience Conference\u201917, July 2017, Washington, DC, USA 0.72 0.0 0 0.002 0.004 0.006 0.008 0.010 0 100 200 300 400 500 0 100 200 300 400 500 0.4 0.8 0.75 0.78 0.81 0.84 0.87 0.0004 0.0007 0.001 D-Sample Q-D-FW Q-D-CNN D-Sample Q-D-FW Q-D-CNN D-Sample Q-D-FW Q-D-CNN SSIM SSIM MSE MSE (a) (b) (c) Epoch Figure 5: Performance of Q-M-PX VQC on dataset scaled by di\ufb00erent approaches: (a) SSIM vs. MSE, the best solution is on the most left-top corner; (b) convergence comparison of SSIM in training; (c) comparison of MSE in training. pixel-wise and layer-wise decoding, denoted as \u201cCNN-PX\u201d and \u201cCNNLY\u201d. For a fair comparison, we use the same training and testing data and control the number of parameters of all models at the same level. Environment. We carry out the concept-proof evaluation on quantum learning design based on the Torchquantum [3] framework. To enable the proposed encoder and QuBatch, we added two components in TorchQuantum. For all VQC model training, we employ the Adam optimizer with 500 epochs where the initial learning rate is set to 0.1, followed by a cosine annealing schedule. To support training, we split the FlatVelA dataset with 500 samples into a training set (size of 400) and a test set (size of 100). The classical CNNs used in Q-D-CNN, CNN-PX, and CNN-LY are trained from scratch in Pytorch. We used the same training setting (i.e., 500 epoch, Adam optimizer, and 0.1 initial learning rate, etc.). For Q-D-CNN, we applied 500 other samples from the FlatVelA dataset to train the CNN. Then, the trained CNN model is used to generate data for the test on quantum computing in QD-CNN. 4.1 QuGeoData: Physics Guidance is Needed Figure 5 reports the comparison results of data scaling approaches using Q-M-PX VQC. Each point in Figure 5(a) is a VQC model obtained in training, where the x-axis and y-axis stand for Structural Similarity Image Metric (SSIM) and Mean Squared Error (MSE), respectively. Figures 5(b)-(c) give the convergence of model training. We have a couple of observations from these results. First, we can clearly observe that the model trained based on the physicsguided data scaling (i.e., Q-D-FW) signi\ufb01cantly outperformsD-Sample (i.e., green diamond) in both SSIM and MSE. Second, Q-D-FW and Q-D-CNN have similar performance in two metrics. Speci\ufb01cally, the SSIM of Q-D-CNN is 0.8619, which is even slightly higher than Q-D-FW with 0.8591, while the MSE of Q-FM is 0.000461, slightly outperforming Q-D-CNN with 0.000460. The above results emphasize the importance of the incorporation of physics knowledge in data scaling. Furthermore, it re\ufb02ects that the learning-based approach can e\ufb00ectively scale data to keep physics features, which will be very useful in processing the raw seismic data. Time Steps Reciver Reciver Reciver Reciver Reciver Reciver Time Steps (a) Seismic data obtained by Q-D-FM, D-Sampling, Q-D-CNN Q-D-FM (b) Normalized seismic data by quantum encoder SSIM: 1.0 (baseline) SSIM: 0.0597 SSIM: 0.9255 SSIM: 1.0 (baseline) SSIM: 0.5253 SSIM: 0.9989 D-Sample Q-D-CNN Q-D-FM D-Sample Q-D-CNN Figure 6: Visualization of seismic data by di\ufb00erent methods: (a) scaled classical data; (b) normalized quantum data. depth (km) velocity (km/s) 0 0.2 0.4 0.6 0.05 0 0.10 0.05 0 0.10 0.05 0 0.10 0.7 0.06 0.04 km/s D-Sample (0.9613) Ground truth Q-D-CNN (0.9742) Q-D-FM (0.9772) depth (km) (a) Output visualization of Q-M-PX on different datasets (b) Comparison of vertical velocity profiles of inversion results at x = 400 m 0 0.2 0.4 0.6 0.7 depth (km) 0 0.2 0.4 0.6 0.7 depth (km) 0 0.2 0.4 0.6 0.7 horizon distance (m) 0 200 400 600 0 200 400 600 0 200 400 600 0 200 400 600 D-Sample B Ground truth Ground truth Ground truth Q-D-FW Q-D-CNN C D F G E A C Figure 7: Visualization of the predicted velocity map: (a) outputs from di\ufb00erent data scaling approaches; (b) vertical velocity pro\ufb01ling for physics information analysis. Figure 6 gives the visualization of seismic waveform data to better show the causes of performance gain. First, in comparing Q-DFM and D-Sample, we can see a larger wavelength in Q-D-FM. The adjustment of the sampling rate and source wavelet causes this. By down-scaling the time dimension in seismic waves, the sampling rate is decreased. Consequently, we lower the source wavelet frequency from 15Hz to 8Hz to prevent the loss of information from a physics standpoint, resulting in an increased wavelength. Conversely, D-Sample\u2019s approach of directly downsampling the waveform data leads to the inevitable loss of vital physical information, evident in the waveform measurements\u2019 incoherence, which will eventually degrade the resulting imaging accuracy. Secondly, the waveform data from Q-D-FM and Q-D-CNN, with an initial SSIM of 0.9255, see this value rise to 0.9989 following data normalization within quantum state constraints. These \ufb01ndings underscore the signi\ufb01cance of physics-guided data scaling and the e\ufb03ciency of CNN-based data compression methods. Finally, in Figure 7, we present the visualization of results. From Figure 7(a), we can again see the improvements obtained by QD-FM and Q-D-CNN over D-Sample. More interesting results are shown in Figure 7(b), where we compare the vertical velocity pro\ufb01les at horizon distance \ud465= 400. The brown lines are the velocity changes along depth for the ground truth, where the y-value stands the velocity, and the layer boundary (say point B) indicates an interface between two layers. From these \ufb01gures, we can see that D-Sample leads to a larger di\ufb00erence in velocity values, and it cannot predict the interface. Speci\ufb01cally, for all seven in\ufb02ection points, there are \ufb01ve wrong predictions (points A, B, C, E, and G) and only two correct predictions (points D and F). On the other \fConference\u201917, July 2017, Washington, DC, USA W. Jiang and Y. Lin 0.72 0.78 0.84 0.9 0.96 0.0009 0.0006 0.0003 0 Q-D-FM (a) (b) D-Sample Q-D-CNN Q-D-FM D-Sample Q-D-CNN SSIM MSE Q-M-LY Q-M-PX Q-M-LY Q-M-PX Figure 8: Comparison results of Q-M-PX and Q-M-LY. depth (km) velocity (km/s) 0 0.2 0.4 0.6 0.05 0 0.10 0.05 0 0.10 0.7 0.06 0.04 0.02 km/s Q-M-PX Q-D-FW (0.9492) Ground truth Q-M-LY Q-D-FW (0.9854) Q-M-LY depth (km) (a) Output visualization of differne models on different datasets (b) Comparison of vertical velocity profiles of inversion results at x = 400 m 0 0.2 0.4 0.6 0.7 0 0.2 0.4 0.6 0.7 depth (km) depth (km) 0 0.2 0.4 0.6 0.7 horizon distance (m) 0 200 400 600 0 200 400 600 0 200 400 600 D-Sample (0.9606) 0 200 400 600 Q-D-FW & Q-M-PX Ground truth Ground truth Q-D-FW & Q-M-LY 0.05 0 0.10 D-Sample & Q-M-LY Ground truth A C D E B Figure 9: Visualization of the predicted velocity map for QM-LY: (a) ground truth and prediction results; (b) vertical velocity pro\ufb01ling for physics information analysis. hand, there are three correct interface predictions for both Q-DFW and Q-D-CNN. Clearly, the aforementioned results indicate that creating a dataset in accordance with physical principles can enhance performance. However, to fully leverage quantum computing for FWI problems, further improvements in performance are necessary. 4.2 QuGeoVQC Further Boost Performance Figure 8 reports the comparison results on two di\ufb00erent VQC designs: Q-M-PX and Q-M-LY, using both SSIM and MSE metrics. As shown in the \ufb01gures, for all three data scaling methods, results obtained by Q-M-LY signi\ufb01cantly outperform those by Q-M-PX. Speci\ufb01cally, for SSIM using data from Q-D-CNN data, the SSIM improves from 0.862 to 0.905. These \ufb01gures are from 0.859 to 0.892 for Q-D-FW, and 0.800 to 0.842 for D-Sample. Overall, Q-M-LY achieves a 4.5% improvement over Q-M-PX. For MSE, the average improvement reaches 33.23%. These results show the e\ufb00ectiveness of layer-wise VQC design. We have one more interesting observation from the results. Considering that the Q-M-PX using D-Sample is the straightforward implementation of FWI on quantum computing, the proposedQuGeo design can improve the SSIM from 0.800 to 0.905 and reduce MSE from 0.000855 to 0.000328, achieving 11.6% and 61.69% improvements on SSIM and MSE, respectively. This result shows the huge optimization room for implementing FWI on quantum computing, and the e\ufb00ectiveness of our proposed methods. Figure 9 presents the visualization results for Q-M-PX and QM-LY using Q-D-FW, as well as Q-M-LY using D-Sample. In the Model Dataset Batch Extra Qubits SSIM vs. BL Q-M-LY Q-D-FW 0 0 0.8926 BL 2 1 0.8864 0.69% 4 2 0.8678 2.77% Table 1: Evaluation of QuBatch with di\ufb00erent batch sizes on Q-D-FW dataset using Q-M-LY VQC. Table 2: Comparison between quantum and classical learning Model Par. Q-D-FW Q-D-CNN SSIM vs. MSE vs. SSIM vs. MSE vs. CNN-PX 634 0.870 BL 4.34E-04 BL 0.87 BL 4.38E-04 BL CNN-LY 616 0.871 0.04% 4.36E-04 -0.43% 0.87 0.00% 4.36E-04 0.38% Q-M-PX 576 0.859 -1.28% 4.61E-04 -6.10% 0.86 -0.98% 4.62E-04 -5.45% Q-M-LY 576 0.893 2.50% 3.48E-04 19.84% 0.91 3.87% 3.28E-04 25.17% vertical velocity analysis depicted in Figure 9(b), we observe that Q-M-PX inaccurately predicts two interfaces at Points A and B. Although Q-M-LY using D-Sample accurately predicts all interfaces, it incorrectly interprets the relative positioning between two layers at three interfaces, as highlighted at Points C, D, and E. In contrast, Q-M-LY using Q-D-FW, successfully predicts all interfaces while maintaining the correct relative relationships between the layers. These \ufb01ndings further emphasize the e\ufb00ectiveness of layerwise VQC design and highlight the promising potential of quantum learning in addressing the challenges of FWI. 4.3 QuBatch Achieves Competitive Results Next, Table 1 shows the proposed QuBatch can be successfully used in the model training, where we can perform 2\ud441batches in parallel with only \ud441more qubits. In addition, we observe the SSIM has slight degradation compared with the results obtained without using data batch. The root cause might be the decrease in data precision caused by the normalization, which is required by the constraints of amplitudes. As discussed in Section 3.3.3, such effects can be mitigated by making tradeo\ufb00s among data precision and qubits, which will be the future work. 4.4 QuGeo Outperforms Classical ML Table 2 reports the comparison of our proposed quantum learning for FWI with classical learning. We constrain the number of parameters to the same level. As shown in Table 2, CNN-PX and CNN-LY have 58 and 40 more parameters. Whereas, Q-M-LY outperforms both classical results on a dataset obtained by both Q-DFW and Q-D-CNN. Speci\ufb01cally, using CNN-PX as a baseline, Q-MLY achieves 19.84% and 25.17% MSE improvements on two datasets, respectively. The potential reason that quantum learning can outperform classical learning at the same scale is because of the complicated entanglement in quantum computing, which has the potential to extract high-correlation features among data. Achieving better performance even at the small scale is meaningful since realworld applications commonly have hard real-time requirements, in particular, for monitoring tasks in geoscience. \fQGeo: Qantum Learning for Geoscience Conference\u201917, July 2017, Washington, DC, USA 5" + }, + { + "url": "http://arxiv.org/abs/2012.10360v1", + "title": "When Machine Learning Meets Quantum Computers: A Case Study", + "abstract": "Along with the development of AI democratization, the machine learning\napproach, in particular neural networks, has been applied to wide-range\napplications. In different application scenarios, the neural network will be\naccelerated on the tailored computing platform. The acceleration of neural\nnetworks on classical computing platforms, such as CPU, GPU, FPGA, ASIC, has\nbeen widely studied; however, when the scale of the application consistently\ngrows up, the memory bottleneck becomes obvious, widely known as memory-wall.\nIn response to such a challenge, advanced quantum computing, which can\nrepresent 2^N states with N quantum bits (qubits), is regarded as a promising\nsolution. It is imminent to know how to design the quantum circuit for\naccelerating neural networks. Most recently, there are initial works studying\nhow to map neural networks to actual quantum processors. To better understand\nthe state-of-the-art design and inspire new design methodology, this paper\ncarries out a case study to demonstrate an end-to-end implementation. On the\nneural network side, we employ the multilayer perceptron to complete image\nclassification tasks using the standard and widely used MNIST dataset. On the\nquantum computing side, we target IBM Quantum processors, which can be\nprogrammed and simulated by using IBM Qiskit. This work targets the\nacceleration of the inference phase of a trained neural network on the quantum\nprocessor. Along with the case study, we will demonstrate the typical procedure\nfor mapping neural networks to quantum circuits.", + "authors": "Weiwen Jiang, Jinjun Xiong, Yiyu Shi", + "published": "2020-12-18", + "updated": "2020-12-18", + "primary_cat": "quant-ph", + "cats": [ + "quant-ph", + "cs.LG" + ], + "main_content": "INTRODUCTION In the past few years, we have witnessed many breakthroughs in both machine learning and quantum computing research fields. On machine learning, the automated machine learning (AutoML) [47, 48] significantly reduces the cost of designing neural networks to achieve AI democratization. On quantum computing, the scale of the actual quantum computers has been rapidly evolving (e.g., IBM [13] recently announced to debut quantum computer with 1,121 quantum bits (qubits) in 2023). Such two research fields, however, have met the bottlenecks when applying the theoretical knowledge in practice. With the large-size inputs, the size of machine learning models (i.e., neural networks) significantly exceed the resource provided by the classical computing platform (e.g., GPU and FPGA); on the other hand, the development of quantum applications is far behind the development of quantum hardware, that is, it lacks killer applications to take full advantage of high-parallelism provided by a quantum computer. As a result, it is natural to see the emerging of a new research field, quantum machine learning. Like applying machine learning to the classical hardware accelerators, when machine learning meets quantum computers, there will be tons of opportunities along with the challenges. The development of machine leering on the classical hardware accelerator experienced two phases: (1) the design of neural network tailored hardware [15, 16, 25, 26, 40, 45], and (2) the co-design of neural network and hardware accelerator [3, 5, 7, 11, 12, 14, 17, 21, 34\u2013 37, 39]. To best exploit the power of the quantum computer, it would be essential to conduct the co-design of neural network and quantum circuits design; however, with the different basic logic gates between quantum circuit and classical circuit designs, it is still unclear how to design a quantum accelerator for the neural network. In this work, we aim to fix such a missing link by providing an open-source design framework. In general, the full acceleration system will be divided into three parts, the data pre-processing and data post-processing on a classical computer, and the neural network accelerator on the quantum circuit. In the quantum circuit, it will further include the quantum state preparation and the quantum computing-based neural computation. In the following of this paper, we will introduce all the above components in detail and demonstrate the implementation using IBM Qiskit for quantum circuit design and Pytorch for the machine learning model process. The remainder of the paper is organized as follows. Section 2 presents an overview of the full system. Section 3 presents the case study on the MNIST dataset. Insights are discussed in Section 4. Finally, concluding remarks are given in Section 5. arXiv:2012.10360v1 [quant-ph] 18 Dec 2020 \fASPDAC \u201921, January 18\u201321, 2021, Tokyo, Japan W. Jiang, et al. Classical Data Pre-Pro Compute (Q) UP UN Classical Data Post-Pro Classical Data Post-Pro Classical Data Pre-Pro Classical (a) Classical Comp. Accelerator (b) Quantum Comp. Accelerator (c) Hybrid Quantum-Classical Comp. Accelerator Data Pre-Pro Compute (C) Compute (hybrid Q+C) * + + + + + + * * * * * * * w w w w w w w w I0 O0 ON I1 I2 I3 C C Q Q Q C Classical Data Post-Pro |0\u232a |0\u232a |0\u232a \u2026 Figure 1: Illustration of three different types of computing schemes: (a) classical computing \u201cC\u201d based neural computation, where\ud835\udc4ais weights; (b) quantum computing \u201cQ\u201d based neural computation, where\ud835\udc48\ud835\udc5dis the quantum-state preparation and \ud835\udc48\ud835\udc41is the neural computation; (c) hybrid quantumclassical computing \u201cQ+C\u201d based neural computation. 2 OVERVIEW Figure 1 demonstrates three types of neural network design: (1) the classical hardware accelerator; (2) the pure quantum computing based accelerator; (3) the hybrid quantum and classical accelerator. All of these accelerators follow the same flow that the data will be first pre-processed, then the neural computation is accelerated, and finally, the output data will go through the post-processing to obtain the final results. 2.1 Classical acceleration After the success of deep neural networks (e.g., Alexnet [23] and VGGNet [32]) in achieving high accuracy, designing hardware accelerator became the hot topic in accelerating the execution of deep neural networks. On the application-specific integrated circuit (ASIC), works [6, 8, 41\u201343] studied how to design neural network accelerator using different dataflows, including weight stationery, output stationery, etc. By selecting dataflow for a dedicated neural computation, it can maximize the data reuse to reduce the data movement and accelerate the process, which derived the co-design of neural network and ASICs [38]. On the FPGA, work [40] first proposed the tiling based design to accelerate the neural computation, and works [15, 16, 24, 45] gave different designs and extended the implementation to multiple FPGAs. Driven by the AutoML, work [21] proposed the first co-design framework to involve the FPGA implementation into the search loop, so that both software accuracy and hardware efficiency can be maximized. The co-design philosophy also applied in other designs [11, 12, 20, 44] and in this direction, there exist many research works in further integrating the model compression into consideration [19, 28], accelerating the search process [27, 46], 2.2 Pure quantum computing Most recently, the emerging works in using the quantum circuit to accelerate neural computation. The typical work include [9, 18, 33], among which the work [18] first demonstrates the potential quantum advantage that can be achieved by using a co-design philosophy. These works encode data to either qubits [9] or qubit states [18] and use superconducting-based quantum computers to run neural networks. These methods have the following limitations: Due to the short decoherence times in the superconducting-based quantum computers, the condition logic is not supported in the computing process. This makes it hard to implement a function that is not differentiable at all points, like the commonly used Rectified Linear Unit (ReLU) in machine learning models. However, it also has advantages, such as the design can be directly evaluated on an actual quantum computer, and there is no communication between the quantum-classical interface during the computation. In the quantum circuit design, it includes two components: \ud835\udc48\ud835\udc43 for quantum states preparation and \ud835\udc48\ud835\udc41for neural computation, as shown in Figure 1(b). After the component \ud835\udc48\ud835\udc41, it will measure the quantum qubits to extract the output data, which will be further sent to the data post-processing unit to obtain the final results. 2.3 Hybrid quantum-classical computing To overcome the disadvantage of pure quantum computing and take full use of classical computing, the hybrid quantum-classical computing for machine learning tasks is proposed [4]. It establishes a computing paradigm where different neurons can be implemented on either quantum or classical computers, as demonstrated in Figure 1(c). This brings flexibility in implementing functions (e.g., ReLU). However, at the same time, it will lead to massive data transfer between quantum and classical computers. 2.4 Our Focus in The Case Study This work focus on providing a full workflow, starting from the data pre-processing, going through quantum computing acceleration, and ending with the data post-processing. We will apply the MNIST data set as an example to carry out a case study. Computing architecture and neural operation can affect the design. In this work, for the computing architecture, we focus on the pure quantum computing design, since it can be easily extended to the hybrid quantum-classical design by connecting the inputs and output of the quantum acceleration to the traditional classical accelerator; for the neural network, we focus on the multi-layer perceptron, which is the basic operation for a large number of neural computation, like the convolution. 3 CASE STUDY ON MNIST DATASET In this section, we will demonstrate the detailed implementation of four components in the pure quantum computing based neural computation as shown in Figure 1(b): data pre-processing, quantum state preparation (\ud835\udc48\ud835\udc43), neural computation (\ud835\udc48\ud835\udc41), and data postprocessing. 3.1 Data Pre-Processing The first step of the whole procedure is to prepare the quantum data to be encoded to the quantum states. Kindly note in order \fWhen Machine Learning Meets Quantum Computers: A Case Study ASPDAC \u201921, January 18\u201321, 2021, Tokyo, Japan to utilize \ud835\udc41qubits to represent 2\ud835\udc41data, it has constraints on the numbers; more specifically, if a vector\ud835\udc480 of 2\ud835\udc41data can be arranged in the first column of a unitary matrix \ud835\udc48, then for the initial state of |\ud835\udf13\u27e9= 1 \u00b7 |0\u27e9\u2297\ud835\udc41, we can obtain \ud835\udc480 by conducting \ud835\udc48|\ud835\udf13\u27e9= \ud835\udc480, where |0\u27e9\u2297\ud835\udc41represents the zero state with \ud835\udc41qubits. 1 import torch 2 import numpy as np 3 import torchvision.transforms as transforms 4 # Input: img_size =4 to represent the resolution of 4*4 5 class ToQuantumData(object): 6 def __call__(self , tensor): 7 device = torch.device(\"cuda\" if torch.cuda. is_available () else \"cpu\") 8 data = tensor.to(device) 9 input_vec = data.view(-1) 10 vec_len = input_vec.size()[0] 11 input_matrix = torch.zeros(vec_len , vec_len) 12 input_matrix [0] = input_vec 13 input_matrix = np.float64(input_matrix. transpose (0,1)) 14 u, s, v = np.linalg.svd(input_matrix) 15 output_matrix = torch.tensor(np.dot(u, v)) 16 output_data = output_matrix [:, 0]. view(1, img_size ,img_size) 17 return output_data 18 # Similarly , we have \"class ToQuantumMatrix(object)\" which return the output_matrix 19 transform = transforms.Compose ([ transforms.Resize (( img_size , img_size)), transforms.ToTensor (), ToQuantumData ()]) 20 # transform = transforms.Compose ([ transforms.Resize (( img_size ,img_size)),transforms.ToTensor (), transforms.Normalize ((0.1307 ,), (0.3081 ,)), ToQuantumData ()]) Listing 1: Converting classical data to qautnum data Listing 1 demonstrates the data conversion from the classical data to quantum data. We utilize the transforms in torchvision to complete the data conversation. More specifically, we create the ToQuantumData class in Line 5. It will receive a tensor (the original data) as input (Line 6). We apply Singular Value Decomposition (svd) provided by np.linalg to obtain the unitary matrix output_matrix (Line 14), then we extract the first vector from output_matrix as the output_data (Line 16), where the output_matrix represents \ud835\udc48and the output_data represents \ud835\udc480. After we build the ToQuantumData class, we will integrate it into one \u201ctransform\u201d variable, which can further include the data pre-processing functions, such as image resize (Line 20) and data normalization (Line 21). In creating the data loader, we can apply the \u201ctransform\u201d to the dataset (e.g., we can obtain train data by using \u201ctrain_data=datasets.MNIST(root=datapath, train=True,download=True, transform=transform)\u201d). 3.2 \ud835\udc48\ud835\udc43: Quantum State Preparation Theoretically, with the \ud835\udc5b\u00d7 \ud835\udc5bunitary matrix \ud835\udc48, we can directly operate the oracle on the quantum circuit to change 2\ud835\udc41states from the zero state |0\u27e9\u2297\ud835\udc41to \ud835\udc480. This process is widely known as quantum-state preparation. The efficiency of quantum-state preparation can significantly affect the complexity of the whole circuit, and therefore, it is quite important to improve the efficiency of such a process. In general, there are two typical ways to perform the quantum-state preparation: (1) quantum random access memory (qRAM) [29] based approach [1, 22] and (2) computing based approach [2, 10, 30]. Let\u2019s first see the qRAM-based approach, where the vector in \ud835\udc480 will be stored in a binary-tree based structure in qRAM, which can be queried in quantum superposition and can generate the states efficiently. In IBM Qiskit, it provides the initialization function to perform quantum-state preparation, which is based on the method in [31]. 1 from qiskit import QuantumRegister , QuantumCircuit , ClassicalRegister 2 from qiskit.extensions import XGate , UnitaryGate 3 from qiskit import Aer , execute 4 import qiskit 5 # Input: a 4*4 matrix (data) holding 16 input data 6 inp = QuantumRegister (4,\"in_qbit\") 7 circ = QuantumCircuit(inp) 8 data_matrix = Q_InputMatrix = ToQuantumMatrix ()(data. flatten ()) 9 circ.append(UnitaryGate(data_matrix , label=\"Input\"), inp [0:4]) 10 # Using StatevectorSimulator from the Aer provider 11 simulator = Aer.get_backend('statevector_simulator ') 12 result = execute(circ , simulator).result () 13 statevector = result.get_statevector(circ) 14 print(statevector) Listing 2: Quantum-State Preparation in IBM Qiskit In Listing 2, we give the codes to initialize the quantum states, using the unitary matrix \ud835\udc48which is converted from the original data in Listing 1(see Line 18). In this code snippet, we first create a 4-qubit QuantumRegister \u201cinp\u201d (line 6) and the quantum circuit (line 7). Then, we convert the input data to data_matrix, which is then employed to initialize the circuit using function UnitaryGate from qiskit.extensions. Finally, from line 10 to line 14, we output the states of all qubits to verify the correctness. 3.3 \ud835\udc48\ud835\udc41: Neural Computation Now, we have encoded the image data (16 inputs) onto 4 qubits. The next step is to perform the neural computation, that is, the weighted sum with quadratic function using the given binary weights \ud835\udc4a. Neural computation is the key component in quantum machine learning implementation. To clearly introduce this component, we first consider the computation of the hidden layer, which can be further divided into two stages: (1) multiplying inputs and weights, and (2) applying the quadratic function on the weighted sum. Then, we will present the computation of the output layer to obtain the final results. Computation of one neural in the hidden layer Stage 1: multiplying inputs and weights. Since the weight \ud835\udc4ais given, it is pre-determined. We use the quantum gate to operate the weights with the inputs. The quantum gates applied here include the \ud835\udc4bgate and the 3-controlled-Z gate with 3 trigger qubits. The function of such a 3-controlled-Z is to flip the sign of state |1111\u27e9, and the function of \ud835\udc4bgate is to swap one state to another state. For example, if the weight for state |0011\u27e9is \u22121. We operate it on the input follows three steps. First, we swap the amplitude of state |0011\u27e9to state |1111\u27e9using two \ud835\udc4bgates on the first two qubits. Then, in the second step, we apply controlled-Z gate to flip the sign of the state |1111\u27e9. Finally, in the third step, we swap the amplitude of state |1111\u27e9back to state |0011\u27e9using two \ud835\udc4bgates on the first two qubits. Therefore, we can transverse all weights and apply the above three steps to flip the sign of corresponding states. Kindly note that since the non-linear function is a quadratic function, if \fASPDAC \u201921, January 18\u201321, 2021, Tokyo, Japan W. Jiang, et al. the number of \u22121 is larger than +1, we can flip all signs of weights to minimize the number of gates to be put in the circuit. 1 def cccz(circ , q1, q2, q3, q4, aux1 , aux2): 2 # Apply Z-gate to a state controlled by 4 qubits 3 circ.ccx(q1 , q2, aux1) 4 circ.ccx(q3 , aux1 , aux2) 5 circ.cz(aux2 , q4) 6 # cleaning the aux bits 7 circ.ccx(q3 , aux1 , aux2) 8 circ.ccx(q1 , q2, aux1) 9 return circ 10 def neg_weight_gate(circ ,qubits ,aux ,state): 11 for idx in range(len(state)): 12 if state[idx]=='0': 13 circ.x(qubits[idx]) 14 cccz(circ ,qubits [0], qubits [1], qubits [2], qubits [3], aux[0],aux [1]) 15 for idx in range(len(state)): 16 if state[idx]=='0': 17 circ.x(qubits[idx]) 18 # input: weight vector , weight_1_1 19 aux = QuantumRegister (2,\"aux_qbit\") 20 circ.add_register(aux) 21 if weight_1_1.sum() <0: 22 weight_1_1 = weight_1_1 *-1 23 for idx in range(weight_1_1.flatten ().size()[0]): 24 if weight_1_1[idx]== -1: 25 state = \"{0:b}\".format(idx).zfill (4) 26 neg_weight_gate(circ ,inp ,aux ,state) 27 circ.barrier () 28 print(circ) Listing 3: Multiplying inputs and weights on quantum Listing 3 demonstrates the procedure of multiplying inputs and weights. In the list, the function cccz utilizing the basic quantum logic gates to realize the 3-controlled-Z gate with 3 control qubits. The involved basic gates include Toffoli gate (i.e., CCX) and controlled-Z gate (i.e., CZ). Since such a function needs auxiliary (a.k.a., ancilla) qubits, we include 2 additional qubits (i.e., \ud835\udc4e\ud835\udc62\ud835\udc65) in the quantum circuit (i.e., \ud835\udc50\ud835\udc56\ud835\udc5f\ud835\udc50), as shown in Lines 19-20. The function neg_weights_gate flips the sign of the given state, applying the 3-step process. Lines 11-13 complete the first step to swap the amplitude of the given state to the state of |1\u27e9\u22974. Then, the cccz gate is applied to complete the second step. Finally, from line 15 to line 17, the amplitude is swap back to the given state. With the above two functions, we traverse the weights to assign the sign to each state from Lines 21-27. Kindly note that, after this operation, the states vector changed from the initial state |\ud835\udf13\u27e9= \ud835\udc480 to |\ud835\udf13\u2032\u27e9= \ud835\udc48\u2032 0 where the states have the weights. Stage 2: applying a quadratic function on the weighted sum. In this stage, it also follows 3 steps to complete the function. In the first step, we apply the Hadamard (H) gates on all qubits to accumulates all states to the zero states. Then, the second step swap the amplitude of zero state |0\u27e9\u2297\ud835\udc41and the one-state |1\u27e9\u2297\ud835\udc41. Finally, the last step applies the N-control-X gate to extract the amplitude to one output qubit \ud835\udc42, in which the probability of \ud835\udc42= |1\u27e9is equal to the square of the weighted sum. In the first step, the H gates can be applied to accumulate the amplitude of states, because the first row of \ud835\udc3b\u22974 is 1 4 \u00d7 [1, 1, 1, 1] and the \ud835\udc3b\u22974|\ud835\udf13\u2032\u27e9performs the multiplication between the 4 \u00d7 4 matrix and the state vector \ud835\udc48\u2032 0. As a result, the amplitude of |0\u27e9\u2297\ud835\udc41 will be the weighted sum with the coefficient of 1 \u221a \ud835\udc41. 1 def ccccx(circ , q1, q2, q3, q4, q5, aux1 , aux2): 2 circ.ccx(q1 , q2 , aux1) 3 circ.ccx(q3 , q4 , aux2) 4 circ.ccx(aux2 , aux1 , q5) 5 # cleaning the aux bits 6 circ.ccx(q3 , q4 , aux2) 7 circ.ccx(q1 , q2 , aux1) 8 return circ 9 # input: circ after stage 1 10 hidden_neuron = QuantumRegister (1,\"out_qbit\") 11 circ.add_register(hidden_neuron) 12 circ.h(inp) 13 circ.x(inp) 14 ccccx(circ ,inp[0],inp[1],inp[2],inp[3], hidden_neuron , aux[0],aux [1]) Listing 4: Applying quadratic function on the weighted sum Listing 4 demonstrates the implementation of the quadratic function on the weighted sum on Qiskit. In the list, function ccccx is based on the basic Toffoli gate (i.e., CCX) to implement a 4-controlX gate to swap the amplitude between the zero state |0\u27e9\u22974 and the one-state |1\u27e9\u22974. In Line 14, \u210e\ud835\udc56\ud835\udc51\ud835\udc51\ud835\udc52\ud835\udc5b_\ud835\udc5b\ud835\udc52\ud835\udc62\ud835\udc5f\ud835\udc5c\ud835\udc5bis an additional output qubit in the quantum circuit (i.e., \ud835\udc50\ud835\udc56\ud835\udc5f\ud835\udc50) to hold the result for the neural computation, which is added in Lines 10-11. For a neural network with \ud835\udc41neurons in the hidden layer, it has \ud835\udc41sets of weights. We can apply the above neural computation on \ud835\udc41set of weights to obtain \ud835\udc41output qubits. Computation of one neuron in the output layer With these \ud835\udc41output qubits, we have two choices: (1) go to the classical computer and then encode the output of these \ud835\udc41outputs to log2 \ud835\udc41qubits and then repeat these computations for the hidden layer to obtain the final results; (2) continuously use these qubits to directly compute the outputs, but the fundamental computation needs to be changed to the multiplication between random variables because the data associated with a qubit represents the probability of the qubit to be |0\u27e9state. In the following, we demonstrate the implementation of the second choices (fundamental details please refer to [18, 33]). In this example, we follow the network structure with 2 neurons in the hidden layer. In addition, we consider there is only one parameter for the normalization function using one additional qubit for each output neuron. Let \u210e\ud835\udc56\ud835\udc51\ud835\udc51\ud835\udc52\ud835\udc5b_\ud835\udc5b\ud835\udc52\ud835\udc62\ud835\udc5f\ud835\udc5c\ud835\udc5b\ud835\udc60be the outputs of 2 neurons in the hidden layer; let \ud835\udc64\ud835\udc52\ud835\udc56\ud835\udc54\u210e\ud835\udc61_2_1 be the weights for the 1\ud835\udc60\ud835\udc61output neuron in the 2\ud835\udc5b\ud835\udc51layer; let norm_flag_1 and norm_para_1 be the normalization related parameters for the 1\ud835\udc60\ud835\udc61output neuron. Then, we have the following implementation. 1 # Additional registers 2 inter_q_1 = QuantumRegister (1,\"inter_q_1_qbits\") 3 norm_q_1 = QuantumRegister (1,\"norm_q_1_qbits\") 4 out_q_1 = QuantumRegister (1,\"out_q_1_qbits\") 5 circ.add_register(inter_q_1 ,norm_q_1 ,out_q_1) 6 circ.barrier () 7 # Input and weight multiplication 8 if weight_2_1.sum() <0: 9 weight_2_1 = weight_2_1 *-1 10 idx = 0 11 for idx in range(weight_2_1.flatten ().size()[0]): 12 if weight_2_1[idx ]== -1: 13 circ.x(hidden_neurons[idx]) 14 circ.h(inter_q_1) 15 circ.cz(hidden_neurons [0], inter_q_1) 16 circ.x(inter_q_1) 17 circ.cz(hidden_neurons [1], inter_q_1) 18 circ.x(inter_q_1) 19 # quadratic function on weighted sum 20 circ.h(inter_q_1) \fWhen Machine Learning Meets Quantum Computers: A Case Study ASPDAC \u201921, January 18\u201321, 2021, Tokyo, Japan 21 circ.x(inter_q_1) 22 circ.barrier () 23 # normalization for two cases 24 norm_init_rad = float(norm_para_1.sqrt().arcsin ()*2) 25 circ.ry(norm_init_rad ,norm_q_1) 26 if norm_flag_1: 27 circ.cx(inter_q_1 ,out_q_1) 28 circ.x(inter_q_1) 29 circ.ccx(inter_q_1 ,norm_q_1 ,out_q_1) 30 else: 31 circ.ccx(inter_q_1 ,norm_q_1 ,out_q_1) 32 # Recove the inputs for the next neuron computation 33 for idx in range(weight_2_1.flatten ().size()[0]): 34 if weight_2_1[idx]== -1: 35 circ.x(hidden_neurons[idx]) Listing 5: Implementation of the second layer neural computation without measurement after the first layer In the above list, it follows the 2-stage pattern for the computation in the hidden layer. If we modify all sub-index _1 to _2, then we can obtain the quantum circuit for the second output neuron. 3.4 Data Post-Processing After all outputs are computed and stored in the out_q_1 and out_q_2 qubits, we can then measure the output qubits, run a simulation or execute on the IBM Q processors, and finally obtain the classification as follows. 1 from qiskit.tools.monitor import job_monitor 2 3 def fire_ibmq(circuit ,shots ,Simulation = False , backend_name='ibmq_essex '): 4 count_set = [] 5 if not Simulation: 6 provider = IBMQ.get_provider('ibm -q-academic ') 7 backend = provider.get_backend(backend_name) 8 else: 9 backend = Aer.get_backend('qasm_simulator ') 10 job_ibm_q = execute(circuit , backend , shots=shots) 11 job_monitor(job_ibm_q) 12 result_ibm_q = job_ibm_q.result () 13 counts = result_ibm_q.get_counts () 14 return counts 15 16 def analyze(counts): 17 mycount = {} 18 for i in range (2): 19 mycount[i] = 0 20 for k,v in counts.items(): 21 bits = len(k) 22 for i in range(bits): 23 if k[bits -1-i] == \"1\": 24 if i in mycount.keys(): 25 mycount[i] += v 26 else: 27 mycount[i] = v 28 return mycount ,bits 29 30 qc_shots =8192 31 counts = fire_ibmq(circ ,qc_shots ,True) 32 (mycount ,bits) = analyze(counts) 33 class_prob =[] 34 for b in range(bits): 35 class_prob.append(float(mycount[b])/qc_shots) 36 class_prob.index(max(class_prob)) Listing 6: Extract the classification results Listing 6 demonstrate the above three tasks. The fire_ibmq function can execute the constructed circuit in either simulation or a given IBM Q processor backend. The parameter \u201cshots\u201d defines the number of execution to be executed. Finally, the counts for each state will be returned. On the implementation, the probability of each qubit (instead of each state) gives the probability to choose the corresponding class. Therefore, we create the \u201canalyze\u201d function to get the probability for each qubits. Finally, we obtain the classification results by extracting the index of the max probability in the \u201cclass_prob\u201d set. Kindly note that the Listing 6 can also be applied for the hybrid quantum-classical computing. 4 INSIGHTS From the study of implementing neural networks onto the quantum circuits, there are several insights in terms of achieving quantum advantages, listed as follows. \u2022 Data encoding: this case study encodes 2\ud835\udc41data to \ud835\udc41quantum qubits, which provides the opportunity to achieve quantum advantage for conducting inference for each input. An alternative way is to encode \ud835\udc41data to \ud835\udc41qubits, however, with the consideration that each data needs to be operated in the neural computation, such an encoding approach can hardly achieve the quantum advantage. \u2022 Quantum-state preparation: by encoding 2\ud835\udc41data to \ud835\udc41 quantum qubits, we can achieve quantum advantage only if the quantum-state preparation can be efficiently conducted with complexity at \ud835\udc42(\ud835\udc41). \u2022 Quantum computing-based neural computation: Neural computation can also become the performance bottleneck, using the design in Listing 3 to flip one sign at each time, it requires \ud835\udc42(2\ud835\udc41) gates in the worst case. To overcome this, [18] proposed a co-design approach to reduce the number of gates to \ud835\udc42(\ud835\udc412). 5" + }, + { + "url": "http://arxiv.org/abs/2006.14815v2", + "title": "A Co-Design Framework of Neural Networks and Quantum Circuits Towards Quantum Advantage", + "abstract": "Despite the pursuit of quantum advantages in various applications, the power\nof quantum computers in neural network computations has mostly remained\nunknown, primarily due to a missing link that effectively designs a neural\nnetwork model suitable for quantum circuit implementation. In this article, we\npresent the co-design framework, namely QuantumFlow, to provide such a missing\nlink. QuantumFlow consists of novel quantum-friendly neural networks (QF-Nets),\na mapping tool (QF-Map) to generate the quantum circuit (QF-Circ) for QF-Nets,\nand an execution engine (QF-FB). We discover that, in order to make full use of\nthe strength of quantum representation, it is best to represent data in a\nneural network as either random variables or numbers in unitary matrices, such\nthat they can be directly operated by the basic quantum logical gates. Based on\nthese data representations, we propose two quantum friendly neural networks,\nQF-pNet and QF-hNet in QuantumFlow. QF-pNet using random variables has better\nflexibility, and can seamlessly connect two layers without measurement with\nmore qbits and logical gates than QF-hNet. On the other hand, QF-hNet with\nunitary matrices can encode 2^k data into k qbits, and a novel algorithm can\nguarantee the cost complexity to be O(k^2). Compared to the cost of O(2^k)in\nclassical computing, QF-hNet demonstrates the quantum advantages. Evaluation\nresults show that QF-pNet and QF-hNet can achieve 97.10% and 98.27% accuracy,\nrespectively. Results further show that for input sizes of neural computation\ngrow from 16 to 2,048, the cost reduction of QuantumFlow increased from 2.4x to\n64x. Furthermore, on MNIST dataset, QF-hNet can achieve accuracy of 94.09%,\nwhile the cost reduction against the classical computer reaches 10.85x. To the\nbest of our knowledge, QuantumFlow is the first work to demonstrate the\npotential quantum advantage on neural network computation.", + "authors": "Weiwen Jiang, Jinjun Xiong, Yiyu Shi", + "published": "2020-06-26", + "updated": "2020-09-09", + "primary_cat": "quant-ph", + "cats": [ + "quant-ph", + "cs.LG" + ], + "main_content": "Introduction Although quantum computers are expected to dramatically outperform classical computers, so far quantum advantages have only been shown in a limited number of applications, such as prime factorization1 and sampling the output of random quantum circuits2. In this work, we will demonstrate that quantum computers can achieve potential quantum advantage on neural network computation, a very common task in the prevalence of arti\ufb01cial intelligence (AI)1. In the past decade, neural networks3\u20135 have become the mainstream machine learning models, and have achieved consistent success in numerous Arti\ufb01cial Intelligence (AI) applications, such as image classi\ufb01cation6\u20139, object detection10\u201313, and natural language processing14\u201316. When the neural networks are applied to a speci\ufb01c \ufb01eld (e.g., AI in medical or AI in astronomy), the high-resolution input images bring new challenges. For example, one 3D-MRI image contains 224 \u00d7 224 \u00d7 10 \u22485 \u00d7 106 pixels17 while one Square Kilometre Array (SKA) science data contains 32,768 \u00d7 32,768 \u22481 \u00d7 109 pixels18,19. The large inputs greatly increase the computa1Quirk demos at https://wjiang.nd.edu/categories/qf/ tion in neural network20, which gradually becomes the performance bottleneck. Among all computing platforms, the quantum computer is a most promising one to address such challenges2,21 as a quantum accelerator for neural networks22\u201324. Unlike classical computers with N digit bits to represent 1 Nbit number at one time, quantum computers with K qbits can represent 2K numbers and manipulate them at the same time25. Recently, a quantum machine learning programming framework, TensorFlow Quantum, has been proposed26; however, how to exploit the power of quantum computing for neural networks is still remained unknown. One of the most challenging obstacles to implementing neural network computation on a quantum computer is the missing link between the design of neural networks and that of quantum circuits. The existing works separately design them from two directions. The \ufb01rst direction is to map the existing neural networks designed for classical computers to quantum circuits; for instance, recent works27\u201330 map McCulloch-Pitts (MCP) neurons31 onto quantum circuits. Such an approach has dif\ufb01culties in consistently mapping the trained model to quantum circuits. For example, it needs a large number of 1 \fQuantumFlow Co-Design Machine Leanring Models (QF-pNet, QF-hNet) Classic Computer Quantum Computer Quantum Circuit Design and Optimization (QF-Circ) Efficient Forward/Backward Propagation (QF-FB) Datasets QF-Map QF-FB(C) QF-FB(Q) P-LYR U-LYR N-LYR Figure 1. QuantumFlow, an end-to-end co-design framework, provides a missing link between neural network and quantum circuit designs, which is composed of QF-Nets, QFhNet, QF-FB, QF-Circ, QF-Map that work collaboratively to design neural networks and their quantum implementations. qbits to realize the multiplication of real numbers. To overcome this problem, some existing works27\u201330 assume binary representation (i.e., \u201c-1\u201d and \u201c+1\u201d) of activation, which cannot well represent data as seen in modern machine learning applications. This has also been demonstrated in work32, where data in the interval of (0,2\u03c0] instead of binary representation are mapped onto the Bloch sphere to achieve high accuracy for support vector machines (SVMs). In addition, some typical operations in neural networks cannot be implemented on quantum circuits, leading to inconsistency. For example, to enable deep learning, batch normalization is a key step in a deep neural network to improve the training speed, model performance, and stability; however, directly conducting normalization on the output qbit (say normalizing the qbit with maximum probability to probability of 100%) is equivalent to reset a qbit without measurement, which is simply impossible. In consequence, batch normalization is not applied in the existing multi-layer network implementation28. The other direction is to design neural networks dedicated to quantum computers, like the tree tensor network (TTN)33,34. Such an approach suffers from scalability problems. More speci\ufb01cally, the effectiveness of neural networks is based on a trained model via the forward and backward propagation on large training sets. However, it is too costly to directly train one network by applying thousands of times forward and backward propagation on quantum computers; in particular, there are limited available quantum computers for public access at the current stage. An alternative way is to run a quantum simulator on a classical computer to train models, but the time complexity of quantum simulation is O(2m), where m is the number of qbits. This signi\ufb01cantly restricts the trainable network size for quantum circuits. To address all the above obstacles, it demands to take quantum circuit implementation into consideration when designing neural networks. This paper proposes the \ufb01rst codesign framework, namely QuantumFlow, where \ufb01ve subcomponents (QF-pNet, QF-hNet, QF-FB, QF-Circ, and QFMap) work collaboratively to design neural networks and implement them to quantum computers, as shown in Figure 1. In QuantumFlow, the start point is the co-design of networks and quantum circuits. We \ufb01rst propose QF-pNet, which contains multiple neural computation layer, namely P-LYR. In the design of P-LYR, we take full advantage of the ability of quantum logic gates to operate random variables represented by qbits. Speci\ufb01cally, data in P-LYR are modeled as random variables following a two-point distribution, which is consistent to the expression of a qbit; computations in P-LYR can be easily implemented by the basic quantum logic gates. Kindly note that P-LYR can model both inputs and weights to be random variables. But because binary weights can achieve comparable high accuracy for deep neural network applications35 and signi\ufb01cantly reduce circuit complexity, we employ random variables for inputs only and binary values for weights in P-LYR. Bene\ufb01ting from the quantum-aware data interpretation for inputs, P-LYR can be attached to the output qbits of previous layers without measurement; however, it utilizes 2k qbits to represent 2k input data items, and the computation needs at least one quantum gate for each qbit. Therefore, it has high cost complexity. Towards achieving the quantum advantage, we propose a hybrid network, namely QF-hNet, which is composed of two types of neural computation layers: P-LYR and U-LYR. ULYR is based on the unitary matrix, where 2k input data are converted to a vector in the unitary matrix, such that all data can be represented by the amplitudes of states in a quantum circuit with k qbits. The reduction in input qbits provides the possibility to achieve quantum advantage; however, the stateof-the-art implementation27 using hypergraph state for computation still has the cost complexity of O(2k). In this work, we devise a novel optimization algorithm to guarantee the cost complexity of U-LYR to be O(k2), which takes full use of the properties of neural networks and quantum logic gates. Compared with the complexity of O(2k) on classical computing platforms, U-LYR demonstrates the quantum advantages of executing neural network computations. In addition to neural computation, QF-Nets also integrates a quantum-friendly batch normalization N-LYR, which can be plugged into both QF-pNet and QF-hNet. It includes additional parameters to normalize the output of a neuron, which are tuned during the training phase. To support both the inference and training of QF-Nets, we further develop QF-FB, a forward/backward propagation engine. When QF-FB is integrated into PyTorch to conduct inference and training of QF-Nets on classical computers, we denote it as QF-FB(C). QF-FB can also be executed on a quantum computer or a quantum simulator. Based on Qiskit Aer simulator, we implement QF-FB(Q) for inference with or without error models. For each operation in QF-Nets (e.g., neural computations and batch normalization), a corresponding quantum circuit is designed in QF-Circ. In neural computation, an encoder is involved to encode the inputs and weights. The output will be sent to the batch normalization which involves additional control qbits to adjust the probability of a given qbit to be ranged 2/14 \f MLP(C) w/o BN {1,5} 0.2 0.4 0.6 0.8 1.0 0.0 {3,6} {0,3,6} {0,1,3,6,9} {0,1,2,3,4} {0,3,6,9} {1,3,6} {3,8} {3,9} QF-pNet w/o BN FFNN(Q) w/o BN MLP(C) w/ BN binMLP(C) w/ BN binMLP(C) w/o BN QF-pNet w/ BN QF-hNet w/o BN QF-hNet w/ BN FFNN(Q) w/ BN Figure 2. QF-hNet achieves state-of-the-art accuracy in image classi\ufb01cations on different sub-datasets of MNIST. from 0 to 1. Based on QF-Nets and QF-Circ, QF-Map is an automatic tool to conduct (1) network-to-circuit mapping (from QF-Nets to QF-Circ); (2) virtual-to-physic mapping (from virtual qbits in QF-Circ to physic qbits in quantum processors). Network-to-circuit mapping guarantees the consistency between QF-Nets and QF-Circ with or without internal measurement; while virtual-to-physic mapping is based on Qiskit with the consideration of error rates. As a whole, given a dataset, QuantumFlow can design and train a quantum-friendly neural network and automatically generate the corresponding quantum circuit. The proposed co-design framework is evaluated on the IBM Qikist Aer simulator and IBM Quantum Processors. Results This section presents the evaluation results of all \ufb01ve subcomponents in QuantumFlow. We \ufb01rst evaluate the effectiveness of QF-Nets (i.e., QF-pNet and QF-hNet) on the commonly used MNIST dataset36 for the classi\ufb01cation task. Then, we show the consistency between QF-FB(C) on classical computers and QF-FB(Q) on the Qiskit Aer simulator. Next, we show that QF-Map is a key to achieve quantum advantage. We \ufb01nally conduct an end-to-end case study on a binary classi\ufb01cation test case on IBM quantum processors to test QF-Circ. QF-Nets Achieve High Accuracy on MNIST Figure 2 reports the results of different approaches for the classi\ufb01cation of handwritten digits on the commonly used MNIST dataset36. Results clearly show that with the same network structure (i.e., the same number of layers and the same number of neurons in each layer), the proposed QFhNet can achieve the highest accuracy than the existing models: (i) multi-level perceptron (MLP) with binary weights for the classical computer, denoted as MLP(C); (ii) MLP with binary inputs and weights designed for the classical computer, denoted as binMLP(C); and (iii) a state-of-the-art quantumaware neural network with binary inputs and weights28, denoted as FFNN(Q). Before reporting the detailed results, we \ufb01rst discuss the experimental setting. In this experiment, we extract sub-datasets from MNIST, which originally include 10 classes. For instance, {3,6} indicates the sub-datasets with two classes (i.e., digits 3 and 6), which are commonly used in quantum machine learning (e.g., Tensor\ufb02ow-Quantum37). To evaluate the advantages of the proposed QF-Nets, we further include more complicated sub-datasets, {3,8}, {3,9}, {1,5} for two classes. In addition, we show that QF-Nets can work well on larger datasets, including {0,3,6} and {1,3,6} for three classes, and {0,3,6,9}, {0,1,3,6,9}, {0,1,2,3,4} for four and \ufb01ve classes. For the datasets with two or three classes, the original image is downsampled from the resolution of 28\u00d728 to 4\u00d74, while it is downsampled to 8 \u00d7 8 for datasets with four or \ufb01ve classes. All original images in MNIST and the downsampled images are with grey levels. For all involved datasets, we employ a two-layer neural network, where the \ufb01rst layer contains 4 neurons for two-class datasets, 8 neurons for three-class datasets, and 16 neurons for fourand \ufb01ve-class datasets. The second layer contains the same number of neurons as the number of classes in datasets. Kindly note that theses architectures are manually tuned for higher accuracy, the neural architecture search (NAS) will be our future work. In the experiments, for each network, we have two implementations: one with batch normalization (w/ BN) and one without batch normalization (w/o BN). Kindly note that FFNN28 does not consider batch normalization between layers. To show the bene\ufb01ts and generality of our newly proposed BN for improving the quantum circuits\u2019 accuracy, we add that same functionality to FFNN for comparison. From the results in Figure 2, we can see that the proposed \u201cQFhNet w/ BN\u201d (abbr. QF-hNet_BN) achieves the highest accuracy among all networks (even higher than MLP running on classical computers). Speci\ufb01cally, for the dataset of {3,6}, the accuracy of QF-hNet_BN is 98.27%, achieving 3.01% and 15.27% accuracy gain against MLP(C) and FFNN(Q), respectively. It even achieves a 1.17% accuracy gain compared to QF-pNet_BN. An interesting observation attained from this result is that with the increasing number of classes in the dataset, QF-hNet_BN can maintain the accuracy to be larger than 90%, while other competitors suffer an accuracy loss. Speci\ufb01cally, for dataset {0,3,6} (input resolution of 4 \u00d7 4), {0,3,6,9} (input resolution of 8 \u00d7 8), {0,1,3,6,9} (input resolution of 8 \u00d7 8), the accuracy of QF-hNet_BN are 90.40%, 93.63% and 92.62%; however, for MLP(C), these \ufb01gures are 75.37%, 82.89%, and 70.19%. This is achieved by the hybrid use of two types of neural computation in QF-hNet to better extract features in images. The above results validate that the proposed QF-hNet has a great potential in solving machine learning problems and our co-design framework is effective to design a quantum neural network with high accuracy. Furthermore, we have an observation for our proposed 3/14 \fTable 1. Inference accuracy and ef\ufb01ciency comparison between QF-FB(C) and QF-FB(Q) on both QF-pNet and QF-hNet using MNIST dataset to show the consistency of implementations of QF-Nets on classical computers and quantum computers. QF-pNet QF-hNet Qbits (Neurons) Accuracy Elapsed CPU Time Qbits (Neurons) Accuracy Elapsed CPU Time dataset L1 L2 QF-FB(C) QF-FB(Q) Diff. QF-FB(C) QF-FB(Q) L1 L2 QF-FB(C) QF-FB(Q) Diff. QF-FB(C) QF-FB(Q) {3,6} 28(4) 12(2) 97.10% 95.53% -1.57% 5.13S 2,555H 7(4) 5(2) 98.27% 97.46% -0.81% 4.30S 16.57H {3,8} 28(4) 12(2) 86.84% 83.59% -3.25% 5.59S 2,631H 7(4) 5(2) 87.40% 88.06% +0.54% 4.05S 16.56H {1,3,6} 28(8) 18(3) 87.91% 81.99% -5.92% 15.89S 14,650H 7(8) 8(3) 88.53% 88.14% -0.39% 6.96S 47.98H batch normalization (BN). For almost all test cases, BN helps to improve the accuracy of QF-pNet and QF-hNet, and the most signi\ufb01cant improvement is observed at dataset {1,5}, from less than 70% to 84.56% for QF-pNet and 90.33% to 96.60% for QF-hNet. Interestingly, BN also helps to improve MLP(C) accuracy signi\ufb01cantly for dataset {1,3,6} (from less than 60% to 81.99%), with a slight accuracy improvement for dataset {3,6} and a slight accuracy drop for dataset {3,8}. This shows that the importance of batch normalization in improving model performance and the proposed BN is de\ufb01nitely useful for quantum neural networks. QF-FB(C) and QF-FB(Q) are Consistent Next, we evaluate the results of QF-FB(C) for both QFpNet and QF-hNet on classical computers, and that of QFFB(Q) simulation on classical computers for the quantum circuits QF-Circ built upon QF-Nets. Table 1 reports the comparison results in the usage of qbits in QF-Circ, inference accuracy and elapsed time, where results under Column QF-FB(C) are the golden results. Because of the limitation of Qiskit Aer (whose backend is \u201cibmq_qasm_simulator\u201d) used in QFFB(Q) that can maximally support 32 qbits, we measure the results after each neuron. We select three datasets, including {3,6}, {3,8}, and {1,3,6}, for evaluation. Datasets with more classes (e.g., {0,3,6,9}) are based on larger inputs, which will lead to the usage of qbits in QF-pNet to exceed the limitation (i.e., 32 qbits). Speci\ufb01cally, for 4\u00d74 input image in QF-pNet, in the \ufb01rst hidden layer, it needs 23 qbits (16 input qbits, 4 encoding qbits, and 3 auxiliary qbits) for neural computation and 4 qbits for batch normalization, and 1 output qbit; as a result, it requires 28 qbits in total. On the contrary, since QF-hNet is designed in terms of the quantum circuit implementation, which takes full use of all states of k qbits to represent 2k data. In consequence, the number of required qbits can be signi\ufb01cantly reduced. In detail, for the 4 \u00d7 4 input, it needs 4 qbits to represent the data, 1 output qbit, and 2 auxiliary qbits; as a result, it only needs 7 qbits in total. The number of qbits used for each hidden layer (\u201cL1\u201d and \u201cL2\u201d) is reported in column \u201cQbits\u201d, where numbers in parenthesis indicate the number of neurons in a hidden layer. Column \u201cAccuracy\u201d in Table 1 reports the accuracy comparison. For QF-FB(C), there will be no difference in accuracy among different executions. For QF-FB(Q), we implement the obtained QF-Circ from QF-Nets on Qiskit Aer simulation with 8,192 shots. We have the following two observations from these results: (1) There exist accuracy differences bedeviation [0.0,1.0] [0.1,0.9] [0.2,0.8] [0.3,0.7] [0.4,0.6] [0.6,0.4] [0.7,0.3] [0.8,0.2] [0.9,0.1] [1.0,0.0] [0.5,0.5] inputs -0.08 -0.06 -0.04 -0.02 -0.00 0.02 0.04 ibmq_armonk QF-FB(C) QF-FB(Q)-ideal QF-FB(Q)-noise Figure 3. Output probability comparison on QF-FB(C), QFFB(Q)-ideal assuming perfect qbits, QF-FB(Q)-noise applying noise model for \u201cibm_armonk\u201d backend, and results of circuit design (\u201cdesign 4\u201d) in Figure 5(d) on \u201cibm_armonk\u201d backend on IBM quantum processor. tween QF-FB(C) and QF-FB(Q). This is because Qiskit Aer simulation used in QF-FB(Q) is based on the Monte Carlo method, leading to the variation. In addition, since the output probability of different neurons may quite close in some cases, it will easily result in different classi\ufb01cation results for small variations. (2) Such accuracy differences for QF-hNet is much less than that of QF-pNet, because QF-pNet utilizes much more qbits, which leads to the accumulation of errors. In QF-hNet, we can see that there is a small difference between QF-FB(C) and QF-FB(Q). For the dataset {3,8}, QFFB(Q) can even achieve higher accuracy. The above results demonstrate both QF-pNet and QF-hNet can be consistently implemented on classical and quantum computers. Column \u201cElapsed Time\u201d in Table 1 demonstrates the ef\ufb01ciency of QF-FB. The elapsed time is the inference time (i.e., forward propagation), used for executing all images in the test datasets, including 1968, 1983, and 3102 images for {3,6}, {3,8}, and {1,3,6}, respectively. As we can see from the table, QF-FB(Q) for QF-pNet takes over 2,500 Hours for classifying 2 digits and 14,000 Hours for classifying 3 digits, and these \ufb01gures are 16 Hours and 48 Hours for QF-hNet. On the other hand, QF-FB(C) only takes less than 16 seconds for both QF-Nets on all datasets. The speedup of QF-FB(C) over QFFB(Q) is more than six orders of magnitude larger (i.e., 106\u00d7) for QF-pNet, and more than four orders of magnitude larger (i.e., 104\u00d7) for QF-hNet. This veri\ufb01es that QF-FB(C) can provide an ef\ufb01cient forward propagation procedure to support the lengthy training of QF-pNet. In Figure 3, we further verify the accuracy of QF-FB by conducting a comparison for design 4 in Figure 5(d) on IBM quantum processor with \u201cibm_armonk\u201d backend. Kindly note that the quantum processor backend is selected by QF-Map. In this experiment, the result of QF-FB(C) is taken as a base4/14 \f101 16 32 64 128 256 512 1024 2048 102 103 Cost (# of operators) Input Sizes of Neural Computation 104 U-LYR 50 trails U-LYR Average FC(Q) 50 trails FC(Q) Average FC(C) FC(C) v.s. U-LYR 64\u00b4 32\u00b4 20\u00b4 13\u00b4 7.6\u00b4 4.8\u00b4 3.3\u00b4 2.4\u00b4 Figure 4. Demonstration of Quantum Advantage Achieved by U-LYR in QuantumFlow: comparison is conducted by using 50 random generated weights for each input size. line. In the \ufb01gure, the x-axis and y-axis represent the inputs and deviation, respectively. The deviation indicates the difference between the baseline and the results obtained by Qiskit Aer simulation or that by executing on IBM quantum processor. For comparison, we involve two con\ufb01gurations for QFFB(Q): (1) QF-FB(Q)-ideal assuming perfect qbits; (2) QFFB(Q)-noise with error models derived from \u201cibm_armonk\u201d. We launch either simulation or execution for respective approaches for 10 times, each of which is represented by a dot in Figure 3. We observe that the results of QF-FB(Q)-ideal are distributed around that generated by QF-FB(C) within 1% deviation; while QF-FB(Q)-noise obtains similar results of that on the IBM quantum processor. These results verify that the QF-Nets on the classical computer can achieve consistent results with that of QF-Circ deployed on a quantum computer with perfect qbits. QF-Map is the Key to Achieve Quantum Advantage Two sets of experiments are conducted to demonstrate the quantum advantage achieved by QuantumFlow. First, we conduct an ablation study to compare the operator/gate usage of the core computation component, neural computation layer. Then, the comparison on gate usage is further conducted on the trained neural networks for different subdatasets from MNIST. In these experiments, we compare QuantumFlow to MLP(C) and FFNN(Q)28. For MLP(C), we consider the adder/multiplier as the basic operators, while for FFNN(Q) and QuantumFlow, we take the quantum logic gate (e.g., Pauli-X, Controlled Not, Toffoli) as the operators. The operator usage re\ufb02ects the total cycles for neural computation. Kindly note that the results of QuantumFlow are obtained by using QF-Map on neural computation U-LYR; and that of FFNN(Q) are based on the state-of-the-art hypergraph state approach proposed in27. For a fair comparison, QuantumFlow and FFNN(Q) are based on the same weights. Figure 4 reports the comparison results for the core component in neural network, the neural computation layer. The x-axis represents the input size of the neural computation, and the y-axis stands for the cost, that is, the number of operators used in the corresponding design. For quantum implementation (both FC(Q)27 in FFNN(Q)28 and U-LYR in QuantumTable 2. QuantumFlow demonstrates quantum advantages on neural networks for MNIST datasets with the increasing model sizes: comparison on the number of used gates. Dataset Structure MLP(C) FFNN(Q) QF-hNet(Q) In L1 L2 L1 L2 Tot. L1 L2 Tot. Red. L1 L2 Tot. Red. {1,5} 16 4 2 132 18 150 80 38 118 1.27\u00d7 74 38 112 1.34\u00d7 {3,6} 16 4 2 96 38 134 1.12\u00d7 58 38 96 1.56\u00d7 {3,8} 16 4 2 76 34 110 1.36\u00d7 58 34 92 1.63\u00d7 {3,9} 16 4 2 98 42 140 1.07\u00d7 68 42 110 1.36\u00d7 {0,3,6} 16 8 3 264 51 315 173 175 348 0.91\u00d7 106 175 281 1.12\u00d7 {1,3,6} 16 8 3 209 161 370 0.85\u00d7 139 161 300 1.05\u00d7 {0,3,6,9} 64 16 4 2064 132 2196 1893 572 2465 0.89\u00d7 434 572 1006 2.18\u00d7 {0,1,3,6,9} 64 16 5 2064 165 2229 1809 645 2454 0.91\u00d7 437 645 1082 2.06\u00d7 {0,1,2,3,4} 64 16 5 1677 669 2346 0.95\u00d7 445 669 1114 2.00\u00d7 {0,1,3,6,9}\u2217256 8 5 4104 85 4189 5030 251 5281 0.79\u00d7 135 251 386 10.85\u00d7 \u2217: Model with 16\u00d716 resolution input for dataset {0,1,3,6,9} to test scalability, whose accuracy is 94.09%, which is higher than 8\u00d78 input with accuracy of 92.62%. Flow), the value of weights will affect the gate usage, so we generate 50 sets of weights for each scale of input, and the dots on the lines in this \ufb01gure represent average cost. From this \ufb01gure, it clearly shows that the cost of FC(C) in MLP(C) on classical computing platforms grows exponentially along with the increase of inputs. The state-of-the-art quantum implementation FC(Q) has the similar exponentially growing trend. On the other hand, we can see that the growing trend of U-LYR is much slower. As a result, the cost reduction continuously increases along with the growth of the input size of neural computation. For the input size of 16 and 32, the average cost reductions are 2.4\u00d7 and 3.3\u00d7, compared with the implementations on classical computers. When the input size grows to 2,048, the cost reduction increased to 64\u00d7 on average. The cost reduction trends in this \ufb01gure clearly demonstrate the quantum advantage achieved by U-LYR. In the Methods section, for the neural computation with an input size of 2k, we will show that the complexity for quantum implementation is O(k2), while it is O(2k) for classical computers. Table 2 reports the comparison results for the whole network. The neural network models for MNIST in Figure 2 are deployed to quantum circuits to get the cost. In addition, to demonstrate the scalability, we further include a new model for dataset \u201c{0,1,3,6,9}\u2217\u201d, which takes the larger sized inputs but less neurons in the \ufb01rst layer L1 and having higher accuracy over \u201c{0,1,3,6,9}\u201d. In this table, columns L1, L2, and Tot. under three approaches report the number of gates used in the \ufb01rst and second layers, and in the whole network. Columns \u201cRed.\u201d represent the comparison with baseline MLP(C). From the table, it is clear to see that all cases implemented by QF-hNet can achieve cost reduction over MLP(C), while for datasets with more than 3 classes, FFNN(Q) needs more gates than MLP(C). A further observation made in the results is that QF-hNet can achieve higher cost reduction with the increase of input size. Speci\ufb01cally, for input size is 16, the reduction ranges from 1.05\u00d7 to 1.63\u00d7. The reduction increases 5/14 \fto 2.18\u00d7 for input size is 64, and it continuously increases to 10.85\u00d7 when the input size grows to 256. The above results are consistent with the results shown in Figure 4. It further indicates that even the second layer in QF-hNet uses the PLYR which requires more gates for implementation, the quantum advantage can still be achieved for the whole network because the \ufb01rst layer using U-LYR can signi\ufb01cantly reduce the number of gates. Above all, QuantumFlow demonstrates the quantum advantages on MNIST dataset. QF-Circ on IBM Quantum Processor This subsection further evaluates the ef\ufb01cacy of QuantumFlow on IBM Quantum Processors. We \ufb01rst show the importance of quantum circuit optimization in QF-Circ to minimize the number of required qbits. Based on the optimized circuit design, we then deploy a 2-input binary classi\ufb01er on IBM quantum processors. Figure 5 demonstrates the optimization of a 2-input neuron step by step. All quantum circuits in Figures 5(a)-(d) achieve the same functionality, but with a different number of required qbits. The equivalency of all designs will be demonstrated in the Supplementary Information. Design 1 in Figure 5(a) is directly derived from the design methodology presented in Methods section. To optimize the circuit using fewer qbits, we \ufb01rst convert it to the circuit in Figure 5(b), denoted as design 2. Since there is only one controlled-Z gate from qbit I0 to qbit E/O, we can merge these two qbits, and obtain an optimized design in Figure 5(c) with 2 qbits, denoted as design 3. The circuit can be further optimized to use 1 qbit, as shown in Figure 5(d), denoted as design 4. The function f in design 4 is de\ufb01ned as follows: f(\u03b1,\u03b2) = 2 \u00b7arcsin( p x+ y\u22122 \u00b7x\u00b7y), (1) where x = sin2 \u03b1 2 , y = sin2 \u03b2 2 , representing input probabilities. To compare these designs, we deploy them onto IBM Quantum Processors, where \u201cibm_velencia\u201d backend is selected by QF-Map. In the experiments, we use the results from QFFB(C) as the golden results. Figure 5(e) reports the deviations of design 1 and design 4 against the golden results. The results clearly show that design 4 is more robust because it uses fewer qbits in the circuit. Speci\ufb01cally, the deviation of design 4 against golden results is always less than 5%, while reaching up to 13% for design 1. In the following experiments, design 4 is applied in QF-Circ. Next, we are ready to introduce the case study on an end-toend binary classi\ufb01cation problem as shown in Figure 6. In this case study, we train the QF-pNet based on QF-FB(C). Then, the tuned parameters are applied to generate QF-Circ. Finally, QF-Map optimizes the deployment of QF-Circ to IBM quantum processor, selecting the \u201cibmq_essex\u201d backend. The classi\ufb01cation problem is illustrated in Figure 6(a), which is a binary classi\ufb01cation problem (two classes) with two inputs: x and y. For instance, if x = 0.2 and y = 0.6, it indicates class 0. The QF-pNet, QF-Circ, and QF-Map are demonstrated in Figure 6(b)-(d). First, Figure 6(b) shows that E/O I0 I1 |0\u00f1 |0\u00f1 |0\u00f1 Ry(b) Ry(a) X X H H E/O I0 I1 |0\u00f1 |0\u00f1 |0\u00f1 Ry(b) Ry(a) X X H H \u00c5 I0/E/O I1 |0\u00f1 |0\u00f1 Ry(b) Ry(a) X X \u00c5 I0/I1 E/O |0\u00f1 Ry(f(a,b)) (a) (b) (c) (d) [0.0,1.0] [0.1,0.9] [0.2,0.8] [0.3,0.7] [0.4,0.6] [0.6,0.4] [0.7,0.3] [0.8,0.2] [0.9,0.1] [1.0,0.0] [0.5,0.5] deviation inputs 0.00 0.03 0.06 0.09 0.12 0.15 (e) design 1 design 4 Figure 5. Evaluation of the quantum circuits for a two-input neural computation, where weights are {-1,+1}: (a) design 1: original neural computation design; (b-d) three optimized designs (design 2-4), based on design 1; (e) the deviation of design 1 and design 4 obtained from \u201cibm_velencia\u201d backend IBM quantum processor, using QF-FB(C) as golden results. QF-pNet consists of one hidden layer with one 2-input neuron and batch normalization. The output is the probability p0 of class 0. Speci\ufb01cally, an input is recognized as class 0 if p0 \u22650.5; otherwise it is identi\ufb01ed as class 1. The quantum circuit QF-Circ of the above QF-pNet is shown in Figure 6(c). The circuit is composed of three parts, (1) neural computation, (2) batch_adj in batch normalization, and (3) indiv_adj in batch normalization. The neural computation is based on design 4 as shown in Figure 5(d). The parameter of Ry gate in neural computation at qbit q0 is determined by the inputs x and y. Speci\ufb01cally, f(x,y) = 2 \u00b7 arcsin(\u221ax+ y\u22122 \u00b7x\u00b7y), as shown in Formula 1. Then, batch normalization is implemented in two steps, where qbits q2 and q4 are initialized according to the trained BN parameters. During the process, q1 holds the intermediate results after batch_adj, and q3 holds the \ufb01nal results after indiv_adj. Finally, we measure the output on qbit q32. After building QF-Circ, the next step is to map qbits from the designed circuit to the physic qbits on the quantum processor, and this is achieved through our QF-Map. In this experiment, QF-Map selects \u201cibm_essex\u201d as backend with its physical properties shown in Figure 6(d), where error rates of each qbit and each connection are illustrated by different colors. By following the rules as de\ufb01ned by QF-Map (see Method section), we obtain the physically mapped QF-Circ shown in Figure 6(d). For example, the input q0 is mapped to the physical qbit labeled as 4. After QuantumFlow goes through all the steps from input data to the physic quantum processor, we can perform inference on the quantum computer. In this experiments, we 2A Quirk-based example of inputs 0.2 and 0.6 leading to f(x,y) = 1.6910 can be accessed by https://wjiang.nd.edu/quirk_0_2_0_6.html, which is accessible at 06-19-2020. The output probability of 60.3% is larger than 50%, implying the inputs belong to class 0. 6/14 \f\u0013 \u0014 \u0015 q2 q3 q4 1.0 1.0 1.0 0.8 0.6 0.4 0.2 1.0 0.8 0.6 0.4 0.2 1.0 0.8 0.6 0.4 0.2 1.0 0.8 0.6 0.4 0.2 0.0 0.2 0.4 0.4 0.2 1.0 0.5 0.0 1.0 0.5 0.0 1.0 0.5 1.0 0.8 0.6 0.4 0.2 1.0 0.8 0.6 0.4 0.2 1.0 0.8 0.6 0.4 0.2 0.0 1.0 0.5 1.0 0.8 0.6 0.4 0.2 \u0016 \u0017 7.516e-3 1.788e-2 CNOT error rate 3.474e-4 6.272e-4 single qbit error rate |0\u00f1 |0\u00f1 |0\u00f1 x x y y q1 q0 (a) (b) (d) (e) (f) (g) (h) (c) q2 \u00c5 |0\u00f1 q3 |0\u00f1 q4 Ry(0.765) X \u00c5 \u00c5 q0 q1 x=0.2; y=0.6 input output class 0 class 0 0.8 0.6 0.8 0.6 x=0.8; y=0.8 49.53% 49.44% class 1 Batch Normalization batch_adj (t==0) indiv_adj neural comp. weights input prob of 0 \u22640.5 0.765 +1 -1 2.793 class 1 class 0 class 1 x y p x y p x y p x y p Ry(f(x,y)) Ry(2.793) Figure 6. Results of a binary classi\ufb01cation case study on IBM quantum processor of \u201cibmq_essex\u201d backend: (a) binary classi\ufb01cation with two inputs \u201cx\u201d and \u201cy\u201d; (b) QF-Nets with trained parameters; (c) QF-Circ derived from the trained QF-Nets; (d) the virtual-to-physic mapping obtained by QF-Map upon \u201cibmq_essex\u201d quantum processor; (e) QF-FB(C) achieves 100% accuracy; (f) QF-FB(Q) achieves 98% accuracy where 2 marked error cases having probability deviation within 0.6% ; (g) results on \u201cibmq_essex\u201d using the default mapping, achieving 68% accuracy; (h) results obtained by \u201cibmq_essex\u201d with the mapping in (d), achieving 82% accuracy; shots number in all tests is set as 8,192. test 100 combinations of inputs from \u27e8x,y\u27e9= \u27e80.1,0.1\u27e9to \u27e8x,y\u27e9= \u27e81.0,1.0\u27e9. First, we obtain the results using QF-FB(C) as golden results and QF-FB(Q) as quantum simulation assuming perfect qbits, which are reported in Figure 6(e) and (f), achieving 100% and 98% prediction accuracy. The results verify the correctness of the proposed QF-pNet. Second, the results obtained on quantum processors are shown in Figure 6(h), which achieves 82% accuracy in prediction. For comparison, in Figure 6(g), we also show the results obtained by using the default mapping algorithm in IBM Qiskit, whose accuracy is only 68%. This result demonstrates the value of QF-Map in further improving the physically achievable accuracy on a physical quantum processor with errors. Discussion In summary, we propose a holistic QuantumFlow framework to co-design the neural networks and quantum circuits. Novel quantum-aware QF-Nets are \ufb01rst designed. Then, an accurate and ef\ufb01cient inference engine, QF-FB, is proposed to enable the training of QF-Nets on classical computers. Based on QFNets and the training results, the QF-Map can automatically generate and optimize a corresponding quantum circuit, QFCirc. Finally, QF-Map can further map QF-Circ to a quantum processor in terms of qbits\u2019 error rates. The neural computation layer is one key component in QuantumFlow to achieve state-of-the-art accuracy and quanTable 3. Comparison of the implementation of Neural Computation with m = 2k input neurons. Layers FC(C)38 FC(Q)28 P-LYR U-LYR Complexity # Bits/Qbits O(2k) O(k) O(2k) O(k) # Operators O(2k) O(2k) O(k \u00b72k) O(k2) Data Representation Input Data F32 Bin R.V. F32 Weights Bin (F32) Bin Bin (R.V.) Bin Connect Layers w/o Measurement \u2713 \u2713 \u00d7 Summary Flexibility \u00d7 \u2713 \u00d7 Qu. Adv. \u00d7 \u00d7 \u2713 tum advantage. We have shown in Figure 2 that the existing quantum-aware neural network28 that interprets inputs as the binary form will degrade the network accuracy. To address this problem, in QF-pNet, we \ufb01rst propose a probability-based neural computation layer, denoted as P-LYR, which interprets real number inputs as random variables following a two-point distribution. As shown in Table 3, P-LYR can represent both input and weight data using random variables, and it can directly connect layers without measurement. In summary, PLYR provides better \ufb02exibility to perform neural computation than others; however, it suffers high complexity, i.e., O(2k) for the usage of qbits and O(k\u00d72k) for the usage of operators (basic quantum gates). In order to acquire quantum advantages, we further propose a unitary matrix based neural computation layer, called U7/14 \fLYR. As illustrated in Table 3, U-LYR sacri\ufb01ces some degree of \ufb02exibility on data representation and non-linear function but can signi\ufb01cantly reduce the circuit complexity. Specifically, with the help of QF-Map, the number of basic operators used by U-LYR can be reduced from O(2k) to O(k2), compared to FC(C) and FC(Q). Kindly note that this work does not take the cost of inputs encoding into consideration in demonstrating quantum advantage; instead, we focus on the speedup of the commonly used computation component layer, that is, the neural computation layer. The cost of encoding inputs can be reduced to O(1) by preprocessing data and storing them into quantum memory, or approximating the quantum states by using basic gate (e.g., Ry). For neural computation, we demonstrated that U-LYR can successfully achieve quantum advantage in the next section. Batch normalization is another key technique in improving accuracy, since the backbone of the quantum-friendly neuron computation layers (P-LYR and U-LYR) is similar to that in classical computers, using both linear and non-linear functions. This can be seen from the results in Figure 2. Batch normalization can achieve better model accuracy, mainly because the data passing a nonlinear function y2 will lead to outputs to be signi\ufb01cantly shrunken to a small range around 0 for real number representation and 1/m for a two-point distribution representation, where m is the number of inputs. Unlike straightforwardly doing normalization on classical computers, it is non-trivial to normalize a set of qbits. Innovations are made in QuantumFlow for a quantum-friendly normalization. The philosophy of co-design is demonstrated in the design of P-LYR, U-LYR, and N-LYR. From the neural network design, we take the known operations as the backbones in PLYR, U-LYR, and N-LYR; while from the quantum circuit design, we take full use of its ability in processing probabilistic computation and unitary matrix based computations to make P-LYR, U-LYR, and N-LYR quantum-friendly. In addition, as will be shown in the next section, the key to achieve quantum advantage for U-LYR is that QF-Map fully considers the \ufb02exibility of the neural networks (i.e., the order of inputs can be changed), while the requirement of continuously executing machine learning algorithms on the quantum computer leads to a hybrid neural network, QF-hNet, with both neural computation operations: P-LYR and U-LYR. Without the co-design, the previous works did not exploit quantum advantages in implementing neural networks on quantum computers, which re\ufb02ects the importance of conducting co-design. We have experimentally tested QuantumFlow on a 32-qbit Qiskit Aer simulator and a 5-qbit IBM quantum processor based on superconducting technology. We show that the proposed quantum oriented neural networks QF-Nets can obtain state-of-the-art accuracy on the MNIST dataset. It can even outperform the conventional model on a similar scale for the classical computer. For the experiments on IBM quantum processors, we demonstrate that, even with the high error rates of the current quantum processor, QF-Nets can be applied to classi\ufb01cation tasks with high accuracy. In order to accelerate the QF-FB on classical computers to \u2026 \u2026 \u2026 \u2026 \u2026 m Swixi w0 w1 wm-1 I1 I0 O=E(y2) Im-1 y= y2 (c) R R E C A R R (p0) (x0) (x1) (xm-1) (p1) (pm-1) 28\u00b428 downsample grey level 4\u00b44 (a) (b) \u2026 \u2026 x0 r.v. -1 1.0 0.9 1.0 0.0 0.1 0.0 +1 x1 x15 m Swiui w0 w1 wm-1 I1 I0 O=y2 Im-1 y= y2 U Cu Au (p0) (u0) (u1) (um-1) (p1) (pm-1) 0.0 0.9 1.0 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.5 0.0 0.9 1.0 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.5 (d) U [0, 0.9, 0, 0, 0, 0.1, 0, 0, 1.0, 0.5, 0.5, 0, 0, 0, 0]T [0, 0.59, 0, 0, 0, 0.07, 0, 0, 0.66, 0.33, 0.33, 0, 0, 0, 0]T Figure 7. Neural Computation: (a) prepossessing of inputs by i) down-sampling the original 28 \u00d7 28 image in MNIST to 4 \u00d7 4 image and ii) get the 4 \u00d7 4 matrix with grey level normalized to [0,1]. (b-c) P-LYR: (b) input data are converted from real number to a random variable following a two-point distribution; (c) four operations in P-LYR, i) R: converting a real number ranging from 0 to 1 to a random variable, ii) C: average sum of weighted inputs, iii) A: non-linear activation function, iv) E: converting random variable to a real number. (d-e) U-LYR: (d) m input data are converted to a vector in the \ufb01rst column of a m\u00d7m unitary matrix; (e) three operations in U-LYR, i) U: unitary matrix converter, ii) Cu: average sum of weighted inputs; iii) Au: non-linear activation function. support training, we make the assumptions that the perfect qbits are used. This enables us to apply theoretic formulations to accelerate the simulation process; however, it leads to some error in predicting the outputs of its corresponding deployment on a physical quantum processor with high error rates (such as the current IBM quantum processor with error rates in the range of 10\u22122). However, we do not deem this as a drawback of our approach, rather this is an inherent problem of the current physical implementation of quantum processors. As the error rates get smaller in the future, it will help to narrow the gap between what QF-Nets predicts and what quantum processor delivers. With the innovations on reducing the error rate of physic qbits, QF-Nets will achieve better results. Methods We are going to introduce QuantumFlow in this section. Neural computation and batch normalization are two key components in a neural network, and we will present the design and implementation of these two components in QF-Nets, QF-FB, QF-Circ, and QF-Map, respectively. QF-pNet and QF-hNet Figure 7 demonstrates two different neural computation components in QuantumFlow: P-LYR and U-LYR. As stated in the Discussion section, P-LYR and U-LYR have their different features. Before introducing these two components, we demonstrate the common prepossessing step in Figure 7(a), 8/14 \fz = E(y2) Batch Normalization (a) (b) batch_adj(t, q) if t == 0: z = else: z = indiv_adj(g) batch_adj(t, q) indiv_adj(g) (1-z) \u00b4 (sin ) + z q 2 2 q 2 2 z \u00b4 (sin ) z = ^ ^ ^ ~ g 2 2 z \u00b4 (sin ) z ~ A E C Cu Au Figure 8. Quantum implementation aware batch normalization: (a) connected to P-LYR; (b) connected to U-LYR. which goes through the downsampling and grey level normalization to obtain a matrix with values in the range of 0 to 1. With the prepossessed data, we will discuss the details of each component in the following texts. Neural Computation P-LYR: An m-input neural computation component is illustrated in 7(d), where m input data I0,I1,\u00b7\u00b7\u00b7 ,Im\u22121 and m corresponding weights w0,w1,\u00b7\u00b7\u00b7 ,wm\u22121 are given. Input data Ii is a real number ranging from 0 to 1, while weight wi is a {\u22121,+1} binary number. Neural computation in P-LYR is composed of 4 operations: i) R: this operation converts a real number pk of input Ik to a two-point distributed random variable xk, where P{xk = \u22121} = pk and P{xk = +1} = 1\u2212pk, as shown in 7(b). For example, we treat the input I0\u2019s real value of p0 as the probability of x0 that outcomes \u22121 while q0 = 1 \u2212p0 as the probability that outcomes +1. ii) C: this operation calculates y as the average sum of weighted inputs, where the weighted input is the product of a converted input (say xk) and its corresponding weight (i.e., wk). Since xk is a two-point random variable, whose values are \u22121 and +1 and the weights are binary values of \u22121 and +1, if wk = \u22121, wk \u00b7 xk will lead to the swap of probabilities P{xk = \u22121} and P{xk = +1} in xk. iii) A: we consider the quadratic function as the non-linear activation function in this work, and A operation outputs y2 where y is a random variable. iv) E: this operation converts the random variable y2 to 0-1 real number by taking its expectation. It will be passed to batch normalization to be further used as the input to the next layer. Neural Computation U-LYR: Unlike P-LYR taking advantage of the probabilistic properties of qbits to provide the maximum \ufb02exibility, U-LYR aims to minimize the gates for quantum advantage using the property of the unitary matrix. The 2k input data are \ufb01rst converted to 2k corresponding data that can be the \ufb01rst column of a unitary matrix, as shown in Figure 7(d). Then the linear function Cu and activation quadratic function Au are conducted. U-LYR has the potential to signi\ufb01cantly reduce the quantum gates for computation, since the 2k inputs are the \ufb01rst column in a unitary matrix and can be encoded to k qbits. But the state-of-the-art hypergraph based approach27 needs O(2k) basic quantum gates to encode 2k corresponding weights to k qbits, which is the same with that of classical computer needing O(2k) operators (i.e., adder/multiplier). In the later section of QF-Map, we propose an algorithm to guarantee that the number of used basic quantum gates to be O(k2), achieving quantum advantages. Multiple Layers: P-LYR and U-LYR are the fundamental components in QF-Nets, which may have multiple layers. In terms of how a network is composed using these two components, we present two kinds of neural networks: QF-pNet and QF-hNet. QF-pNet is composed of multiple layers of P-LYR. For its quantum implementation, operations on random variables can be directly operated on qbits. Therefore, R operation is only conducted in the \ufb01rst layer. Then, C and A operations will be repeated without measurement. Finally, at the last layer, we measure the probability for output qbits, which is corresponding to the E operation. On the other hand, QFhNet is composed of both U-LYR and P-LYR, where the \ufb01rst layer applies U-LYR with the converted inputs. The output of U-LYR is directly represented by the probability form on a qbit, and it can seamlessly connect to C in P-LYR used in later layers. Batch Normalization: Figure 8 illustrates the proposed batch normalization (N-LYR) component. It can take the output of either P-LYR or U-LYR as input. N-LYR is composed of two sub-components: batch adjustment (\u201cbatch_adj\u201d) and individual adjustment (\u201cindiv_adj\u201d). Basically, batch_adj is proposed to avoid data to be continuously shrunken to a small range (as stated in Discussion section). This is achieved by normalizing the probability mean of a batch of outputs to 0.5 at the training phase, as shown in Figure 9(c)-(d). In the inference phase, the output \u02c6 z can be computed as follows: \u02c6 z = (1 \u2212z)\u00d7 (sin2\u03b8 2 )+ z, if t = 0 \u02c6 z = z\u00d7 (sin2 \u03b8 2 ), if t = 1 (2) After batch_adj, the outputs of all neurons are normalized around 0.5. In order to increase the variety of different neurons\u2019 output for better classi\ufb01cation, indiv_adj is proposed. It contains a trainable parameter \u03bb and a parameter \u03b3 (see Figure 9(e)). It is performed in two steps: (1) we get a start point of an output pz according to \u03bb, and then moves it back to p=0.5 to obtain parameter \u03b3; (2) we move pz the angle of \u03b3 to obtain the \ufb01nal output. Since different neurons have different values of \u03bb, the variation of outputs can be obtained. In the inference phase, its output \u02dc z can be calculated as follows. \u02dc z = \u02c6 z\u00d7 (sin2 \u03b3 2) (3) The determination of parameters t, \u03b8, and \u03b3 is conducted in the training phase, which will be introduced later in QF-FB. QF-FB QF-FB involves both forward propagation and backward propagation. In forward propagation, all weights and parameters are determined, and we can conduct neural computation and batch normalization layer by layer. For -LYp, the neural computation will compute y = \u2211\u2200i{xi\u00d7wi} m and y2, where xi is a twopoint random variable. The distributions of y and y2 are illustrated in Figure 9(a)-(b). It is straightforward to get the 9/14 \f\u00d5pi + \u00d5qi pm-1...p1q0 pm-1...q1p0 + + qm-1...p1p0 \u2026 + qm-1...q1p0 qm-1...p1q0 + + pm-1...q1q0 \u2026 \u2026 \u2026 \u2026 -1 1 ( ) 0 -m+2 y2 2 y m m-2 m \u00d5pi + \u00d5qi pm-1...p1q0 pm-1...q1p0 + + + qm-1...p1p0 \u2026 + + qm-1...q1p0 qm-1...p1q0 + + pm-1...q1q0 \u2026 \u2026 \u2026 1 0 m-2 m (a) (b) pmean (c) (d) (e) t=0; q=2\u00b4arcsin( ) pmean 1-pmean 0.5-pmean downward p = 0 |0\u00f1 |1\u00f1 p = 1 p = 0.5 p = 0.5 p = 0.5 upward pz pz (pz / n+0.5)\u00b4l g g ^ t=1; q=2 \u00b4 arcsin( ) pmean ^ ^ pmean g=2\u00b4arcsin( ) (pz / n+0.5)\u00b4l \u00d6 \u00d6 pmean 0.5 0.5 \u00d6 Figure 9. QF-FB: (a-b) distribution of random variable y and y2 in neural computation component of QF-pNet; (c-e) determination of parameters, t, \u03b8, and \u03b3, in batch normalization component of QF-Nets. expectation of y2 by using the distribution; however, for m inputs, it involves 2m terms (e.g., \u220fqi is one term), and leads to the time complexity to be O(2m). To reduce the time complexity, QF-FB takes advantage of independence of inputs to calculate the expectation as follows: E([\u2211\u2200i wixi]2) = E(\u2211\u2200i[wixi]2 + 2 \u00d7\u2211\u2200i\u2211\u2200j>i[wixiwjxj]) = m+ 2 \u00d7\u2211\u2200i\u2211\u2200j>i E(wixi)\u00d7 E(wjxj) (4) where E(\u2211\u2200i[wixi]2) = m, since [wixi]2 = 1 and there are m inputs in total. The above formula derives the following algorithm with time complexity of O(m2) to simulate the neural computation P-LYR. Algorithm 1: QF-FB: simulating P-LYR Input: (1) number of inputs m; (2) m probabilities \u27e8p0,\u00b7\u00b7\u00b7 , pm\u22121\u27e9; (3) m weights \u27e8w0,\u00b7\u00b7\u00b7 ,wm\u22121\u27e9. Output: expectation of y2 1. Expectation of random variable xi: ei = E(xi) = 1\u22122\u00d7 pi; 2. Expectation of wi \u00d7xi: E(wi \u00d7xi) = wi \u00d7ei; 3. Sum of pair product sumpp = \u2211\u2200i \u2211\u2200j>i{E(wi \u00d7xi)\u00d7E(wj \u00d7xj)}; 4. Expectation of y2: E(y2) = m+2\u00d7sumpp m2 ; 5. Return E(y2); For -LYu, the neural computation will \ufb01rst convert inputs I = {i0,i1,\u00b7\u00b7\u00b7 ,im\u22121} to a vector U = {u0,u1,\u00b7\u00b7\u00b7 ,um\u22121} who can be the \ufb01rst column of a unitary matrix MATu. By operating MATu on K = log2m qbits with initial state (i.e., |0\u27e9), we can encode U to 2K = m states. The generating of unitary matrix MATu is equivalent to the problem of identifying the nearest orthogonal matrix given a square matrix A. Here, matrix A is created by using I as the \ufb01rst column, and 0 for all other elements. Then, we apply Singular Value Decomposition (SVD) to obtain B\u2211C\u2217= SVD(A), and we can obtain MATu = BC\u2217. Based on the obtained vector U in MATu, -LYu computes y = \u2211\u2200i{ui\u00d7wi} m and y2, as shown in the following algorithm. Algorithm 2: QF-FB: simulating U-LYR Input: (1) number of inputs m; (2) m input values \u27e8p0,\u00b7\u00b7\u00b7 , pm\u22121\u27e9; (3) m weights \u27e8w0,\u00b7\u00b7\u00b7 ,wm\u22121\u27e9. Output: [ \u2211\u2200i{ui\u00d7wi} m ]2 1. Generating square matrix A and compute B\u2211C\u2217= SVD(A) 2. Calculating MATu = BC\u2217and extract vector U from MATu ; 3. Compute y = \u2211\u2200i{ui\u00d7wi} m ; 4. Return y2; The forward propagation for batch normalization can be ef\ufb01ciently implemented based on the output of the neural computation. A code snippet is given as follows. Algorithm 3: QF-FB: simulating N-LYR Input: (1) E(y2) from neural computation; (2) parameters t, \u03b8, \u03b3 determined by training procedure. Output: normalized output \u02dc z 1. Initialize z: z = E(y2); 2. Calculate \u02c6 z according to Formula 2; 3. Calculate \u02dc z according to Formula 3; 4. Return \u02dc z; For the backward propagation, we need to determine weights and parameters (e.g., \u03b8 in N-LYR). The typically used optimization method (e.g., stochastic gradient descent39) is applied to determine weights. In the following, we will discuss the determination of N-LYRparameters t, \u03b8, \u03b3. The batch_adj sub-component involves two parameters, t and \u03b8. During the training phase, a batch of outputs are generated for each neuron. Details are demonstrated in Figure 9(c)-(d) with 6 outputs. In terms of the mean of outputs in a batch pmean, there are two possible cases: (1) pmean \u22640.5 and (2) pmean > 0.5. For the \ufb01rst case, t is set to 0 and \u03b8 = 2 \u00d7 arcsin( q 0.5\u2212pmean 1\u2212pmean ) can be derived from Formula 2 by setting \u02c6 z to 0.5; similarly, for the second case, t is set to 1 and \u03b8 = 2 \u00d7 arcsin( q 0.5 pmean ). Kindly note that the training procedure will be conducted in multiple iterations of batches. As with the method for batch normalization in the conventional neural network, we employ moving average to record parameters. Let xi be the parameter of x (e.g., \u03b8) at the ith iteration, and xcur be the value obtained in the current iteration. For xi, it can be calculated as xi = m \u00d7 xi\u22121 + (1 \u2212m) \u00d7 xcur, where m is the momentum which is set to 0.1 by default in the experiments. In forward propagation, the sub-module indiv_adj is almost the same with batch_adj for t = 0; however, the determination of its parameter \u03b3 is slightly different from \u03b8 for batch_adj. As shown in Figure 9(e), the initial probability of \u02c6 z after batch_adj is pz. The basic idea of indiv_adj is to move \u02c6 z by an angle, \u03b3. It will be conducted in three steps: (1) we move start point at pz to point A with the probability of (pz/n+0.5)\u00d7\u03bb, where n is the batch size and \u03bb is a trainable variable; (2) we obtain \u03b3 by moving point A to p = 0.5; (3) we \ufb01nally move solution at pz by the angle of \u03b3 to obtain the \ufb01nal result. By replacing P mean by (pz/n + 0.5)\u00d7 \u03bb in batch_adj when t = 1, we can calculate \u03b3. For each batch, we calculate the mean of \u03b3, and we also employ the moving average to record \u03b3. 10/14 \fIm-2 I0 Im-1 |0\u00f1 E0 |0\u00f1 E1 H H |0\u00f1 |0\u00f1 Ek-1 |0\u00f1 O Ek-2 H H H H H \u2026 |0\u00f1 |0\u00f1 |0\u00f1 \u2026 \u2026 ... ... ... H \u00c5 (a) R M (c) (b) (e) O I P \u00c5 |j\u00f1 |0\u00f1 |0\u00f1 Ry(q) Ry(q1) Ry(qm-2) Ry(qm-1) X \u00c5 P(O=|1\u00f1)= P(O = |1\u00f1) = |j\u00f1 |0\u00f1 |0\u00f1 Ry(g) \u00c5 g(q,g)=2\u00b4arcsin( \u00b4 ) (1-z)\u00b4(sin )+z q 2 2 ^ g 2 2 z \u00b4 (sin ) q 2 sin g 2 sin W O I P (d) P(O = |1\u00f1) = |j\u00f1 |0\u00f1 |0\u00f1 Ry(q) \u00c5 q 2 2 z \u00b4 (sin ) O I P (f) |j\u00f1 |0\u00f1 |0\u00f1 Ry(g(q,g)) \u00c5 O I P A C |0\u00f1 E0 |0\u00f1 E1 |0\u00f1 |0\u00f1 Ek-1 |0\u00f1 O Ek-2 \u2026 MATu \u00c5 U M Au Cu W QF-Map Figure 10. QF-Circ: (a) quantum circuit designs for QF-pNet; (b) quantum circuit design for QF-hNet; (c-f): batch normalization, quantum circuit designs for different cases; (c) design of \u201cbatch_adj\u201d for the case of t = 0; (d) design of \u201cbatch_adj\u201d for the case of t = 1; (e) design of \u201cindiv_adj\u201d; (f) optimized design for a speci\ufb01c case when t = 1 in \u201cbatch_adj\u201d. QF-Circ We now discuss the corresponding circuit design for components in QF-Nets, including P-LYR, U-LYR, and N-LYR. Figures 10(a)-(b) demonstrate the circuit design for P-LYR (see Figure 7(c)) and U-LYR (see Figure 7(e)), respectively; Figures 10(c)-(f) demonstrate the N-LYR in Figure 8. Implementing P-LYR on quantum circuit: For an minput neural computation, the quantum circuit for P-LYR is composed of m input qbits (I), and k = log2m encoding qbits (E), and 1 output qbit (O). In accordance with the operations in P-LYR, the circuit is composed of four parts. In the \ufb01rst part, the circuit is initialized to perform R operation. For qbits I, we apply m Ry gates with parameter \u03b8 = 2\u00d7arcsin(\u221apk) to initialize the input qbit Ik in terms of the input real value pk, such that the state of Ik is changed from |0\u27e9to \u221aqk|0\u27e9+ \u221apk|1\u27e9. For encoding qbits E and output qbit O, they are initialized as |0\u27e9. The second part completes the average sum function, i.e., C operation. It further includes three steps: (1) dot product of inputs and weights on qibits I, (2) make encoding qbits E into superposition, (3) encode m probabilities in qbits I to 2k = m states in qbits E. The third part implements the quadratic activation function, that is the A operation. It applies the control gate to extract the amplitudes in states |I0I1\u00b7\u00b7\u00b7Im\u22121\u27e9\u2297|00\u00b7\u00b7\u00b70\u27e9to qbit O. As we know that the probability is the square of the amplitude, the quadratic activation function can be naturally implemented. Finally, E operations corresponds to the fourth part that measures qbit O to obtain the output real number E(y2), where the state of O is |O\u27e9= p 1 \u2212E(y2)|0\u27e9+ p E(y2)|1\u27e9. A detailed demonstration of the equivalency between QF-Circ and P-LYR can be found in the Supplementary Information. Kindly note that for a multi-layer network composed of PLYR, namely QF-pNet, there is no need to have a measurement at interfaces, because the converting operation R initializes a qbit to the state exactly the same with |O\u27e9. In addition, the batch normalization can also take |O\u27e9as input. Implementing U-LYR on quantum circuit: For an minput neural computation, the quantum circuit for U-LYR contains k = log2m encoding qbits E and 1 output qbit O. According to U-LYR, the circuit in turn performs U, Cu, Au operations, and \ufb01nally obtains the result by a measurement. In the \ufb01rst operation, unlike the circuit for P-LYR using R gate to initialize circuits using m qbits; for U-LYR, we using the matrix MATu to initialize circuits on k = log2m qbits E. Recalling that the \ufb01rst column of MATu is vector V, after this step, m elements in vector V will be encoded to 2k = m states represented by qbits E. The second operation is to perform the dot product between all states in qbits E and weights W, which is implemented by control Z gates and will be introduced in QF-Map. Finally, like the circuit for P-LYR, the quadratic activation and measurement are implemented. Kindly note that, in addition to quadratic activation, we can also implement higher orders of non-linearity by duplicating the circuit to perform U, Cu, and Au to achieve multiple outputs. Then, we can use control NOT gate on the outputs to achieve higher orders of non-linearity. For example, using a Toffoli gate on two outputs can realize y4. Let the non-linear function be yk and the cost complexity of U-LYR using quadratic activation be O(N), then the cost complexity of U-LYR using yk as the non-linear function will be O(kN). For neural networks with given inputs, we can preprocess the U operation and store the states in quantum memory40. Thus, the key for quantum advantage is to exponentially reduce the number of gates used in neural computation, compared with the number of basic operators used in classical computing. We will present an algorithm in QF-Map for ULYR to achieve this goal. Implementing N-LYR on quantum circuit: Now, we discuss the implementation of N-LYR in quantum circuits. In these circuits, three qbits are involved: (1) qbit I for input, which can be the output of qbit O in circuit without measurement, or initialized using a Ry gate according to the measurement of qbit O in circuit; (2) qbit P conveys the parameter, which is obtained via training procedure, see details in QFFB; (3) output qbits O, which can be directly used for the next layer or be measured to convert to a real number. Figures 10(b)-(c) show the circuit design for two cases in batch_adj. Since parameters in batch_adj are determined in the inference phase, if t = 0, we will adopt the circuit in Figure 10(b), otherwise, we adopt that in Figure 10(c). Then, Figure 10(d) shows the circuit for indiv_adj. We can see that circuits in Figures 10(c) and (d) are the same except the ini11/14 \f(a) (b) |0\u00f1 q3 |0\u00f1 q2 |0\u00f1 |0\u00f1 q0 q1 |0\u00f1 q3 |0\u00f1 q2 |0\u00f1 |0\u00f1 q0 q1 (c) |0\u00f1 q3 |0\u00f1 q2 |0\u00f1 |0\u00f1 q0 q1 Z Figure 11. Illustration of state |6\u27e9= |0110\u27e9and |4\u27e9= |0100\u27e9 in a k = 4 computation system: (a) FG6; (b) PG6; (c) PG4. tialization of parameters, \u03b8 and \u03b3. For circuit optimization, we can merge the above two circuits into one by changing the input parameters to g(\u03b8,\u03b3), as shown in Figure 10(e). In this circuit, \u02dc z\u2032 = z \u00d7 sin2 g(\u03b8,\u03b3) 2 , while for applying circuits in Figures 10(c) and (d), we will have \u02dc z = z\u00d7 sin2 \u03b8 2 \u00d7 sin2 \u03b3 2. To guarantee the consistent function, we can derive that g(\u03b8,\u03b3) = 2 \u00d7 arcsin(sin \u03b8 2 \u00d7 sin \u03b3 2). QF-Map QF-Map is an automatic tool to map QF-Nets to the quantum processor through two steps: network-to-circuit mapping, which maps QF-Nets to QF-Circ; and virtual-to-physic mapping, which maps QF-Circ to physic qbits. Mapping QF-Nets to QF-Circ: The \ufb01rst step of QFMap is to map three kinds of layers (i.e., P-LYR, U-LYR, and N-LYR) to QF-Circ. The mappings of P-LYR and N-LYR are straightforward. Speci\ufb01cally, for P-LYR in Figure 10(a), the circuit for weight W is determined using the following rule: for a qbit Ik, an X gate is placed if and only if Wk = \u22121. Let the probability P(xk = \u22121) = P(Ik = |0\u27e9) = qk, after the X gate, the probability becomes 1 \u2212qk. Since the values of random variable xk are \u22121 and +1, such an operation computes \u2212xk. For N-LYR, let O1 be the output qbit of the \ufb01rst layer. It can be directly connected to the qbit I in Figure 10(c)-(f), according to the type of batch normalization, which is determined by the training phase. The mapping of U-LYR to quantum circuits is the key to achieve quantum advantages. In the following texts, we will \ufb01rst formulate the problem, and then introduce the proposed algorithm to guarantee the cost for a neural computation with 2k inputs to be O(k2). Before formally introducing the problem, we \ufb01rst give some fundamental de\ufb01nitions that will be used. We \ufb01rst de\ufb01ne the quantum state and the relationship between states as follows. Let the computational basis be composed of k qbits, as in Figure 10(b). De\ufb01ne |xi\u27e9= |bi k\u22121,\u00b7\u00b7\u00b7 ,bi j,\u00b7\u00b7\u00b7 ,bi 0\u27e9to be the ith state, where b j is a binary number and xi = \u2211\u2200j{bi j \u00b72 j}. For two states |xp\u27e9and |xq\u27e9, we de\ufb01ne |xp\u27e9\u2286|xq\u27e9if \u2200bp j = 1, we have bq j = 1. We de\ufb01ne sign(xi) to be the sign of xi. Next, we de\ufb01ne the gates to \ufb02ip the sign of states. The controlled Z operation among K qbits (e.g., CKZ) is a quantum gate to \ufb02ip the sign of states25,27. De\ufb01ne FGxi to be a CKZ gate to \ufb02ip the state xi only. It can be implemented as follows: if bi j = 1, the control signal of the jth qbit is enabled by |1\u27e9, otherwise if bi j = 0, it is enabled by |0\u27e9. De\ufb01ne PGxi to be a controlled Z gate to \ufb02ip all states \u2200xm if xm \u2286xi. It can be implemented as follows: if bi j = 1, there is a control signal of the jth qbit, enabled by |1\u27e9, otherwise, it is not a control qbit. Speci\ufb01cally, if there is only bi m = 1 for all bi k \u2208xi, we put a Z gate on the mth qbit. Figure 11 illustrates FG6, PG6 and PG4. We de\ufb01ne cost function C to be the number of basic gates (e.g., Pauli-X, Toffoli) used in a control Z gate. Now, we formally de\ufb01ne the weight mapping problem as follows: Given (1) a vector W = {wm\u22121,\u00b7\u00b7\u00b7 ,w0} with m binary weights (i.e., -1 or +1) and (2) a computational basis of k = log2m qbits that include m states X = {xm\u22121,\u00b7\u00b7\u00b7 ,x0} and \u2200xj \u2208X, sign(xj) is +, the problem is to determine a set of gates G in either FG or PG to be applied, such that the circuit cost is minimized, while the sign of each state is the same with the corresponding weight; i.e., \u2200xj \u2208X, signG(xj) = sign(wj) and min = \u2211g\u2208G(C(g)), where signG(xj) is the sign of state xj under the computing conducted by a sequence of quantum gates in G. A straightforward way to satisfy the sign \ufb02ip requirement without considering cost is to apply FG for all states whose corresponding weights are \u22121. A better solution for cost minimization is to use hypergraph states27, which starts from the states with less |1\u27e9, and apply PG to reduce the cost. However, as shown in the previous work, both methods have the cost complexity of O(2k), which is the same as classical computers and no quantum advantage can be achieved. Toward the quantum advantage, we made the following important observation: the order of weights can be adjusted, since matrix MAT \u2032 u obtained by switching two rows in the unitary matrix MATu will still be a unitary matrix. Based on this property, we can simplify the weight mapping problem to determine a set of gates, such that the cost is minimized while the number of states with sign \ufb02ip is the same as the number of \u22121 in weight W. On top of this, we propose an algorithm to guarantee the cost complexity to be O(k2). Compared to O(2k) needed for classical computers, we can achieve quantum advantages. To demonstrate how to guarantee the cost complexity to be O(k2), we \ufb01rst have the following theorem. Theorem 1. For an integer number R where R > 0 and R \u2264 2k\u22121, the number R can be expressed by a sequence of addition (+) or subtraction (\u2212) of a subset of Sk = {2i|0 \u2264i < k}; when the terms of Sk are sorted in a descending order, the sign of the expression (addition and subtraction) are alternative with the leading sign being addition (+). Proof. The above theorem can be proved by induction. First, for k = 2, the possible values of R are {1,2}, the set S2 = {2,1}. The theorem is obviously true. Second, for k = 3, the possible values of R are {1,2,3,4}, and the set S3 = {4,2,1}. In this case, only R = 3 needs to involve 2 numbers from S3 using the expression 3 = 4\u22121; other numbers can be directly expressed by themselves. So, the theorem is true. Third, assuming the theorem is true for k = n \u22121, we can prove that for k = n the theorem is true for the following three cases. Case 1: For R < 2n\u22122, since the theorem is true for k = n\u22121, based on the assumption, all numbers less than 2n\u22122 can be expressed by using set Sn\u22121 and thus we can also express them by using set Sn because Sn\u22121 \u2286Sn; Case 2: For R = 2n\u22122, 12/14 \fitself is in set Sn; Case 3: For R > 2n\u22122, we can express R = 2n\u22121 \u2212T, where T = 2n\u22121 \u2212R < 2n\u22122. Since the theorem is true for k = n\u22121, we can express T by using set Sn \u22122n\u22121 = {2i|0 \u2264i < n \u22121} = Sn\u22121; hence, R can be expressed using set Sn. Above all, the theorem is correct. We propose to only use PG gate in a set {PGx(j) | x(j) = 2 j \u22121 & j \u2208[1,k]} for any required number R \u2208(0,2k) of sign \ufb02ips on states; for instance, if k = 4, the gate set is {PG0001,PG0011,PG0111,PG1111} and R \u2208(0,16). This can be demonstrated using the above theorem and properties of the problem: (1) the problem has symmetric property due to the quadratic activation function. Therefore, the weight mapping problem can be reduced to \ufb01nd a set of gates leading to the number of \u22121 no larger than 2k\u22121; i.e., R \u2208(0,2k\u22121]. (2) for PGx(j), it will \ufb02ip the sign of 2k\u2212j states; since j \u2208[1,k], the numbers of the \ufb02ipped sign by these gates belong to a set Sk = {2i|0 \u2264i < k}; These two properties make the problem in accordance with that in Theorem 1. The weight mapping problem is also consistent with three rules in the theorem. (1) A gate can be selected or not, indicating the \ufb01nally determined gate set is the subset of Sk; (2) all states at the beginning have the positive sign, and therefore, the \ufb01rst gate will increase sign \ufb02ips, indicating the leading sign is addition (+); (3) \u2200p < q, x(q) \u2286x(p); it indicates that among the 2k\u2212p states whose signs are \ufb02ipped by x(p), there are 2k\u2212q states signs are \ufb02ipped back; this is in accordance to alternatively use + and \u2212in the expression in Theorem 1. Followed by the proof procedure, we devise the following recursive algorithm to decide which gates to be employed. Algorithm 4: QF-Map: weight mapping algorithm Input: (1) An integer R \u2208(0,2k\u22121]; (2) number of qbits k; Output: A set of applied gate G void recursive(G,R,k){ if (R < 2k\u22122){ recursive(G,R,k\u22121); // Case 1 in the third step } else if (R == 2k\u22121){ G.append(PG2k\u22121); // Case 2 in the third step return; }else{ G.append(PG2k\u22121); recursive(G,2k\u22121 \u2212R,k\u22121); // Case 3 in the third step } } // Entry of weight mapping algorithm set main(R,k){ Initialize empty set G; recursive(G,R,k); return G } In the above algorithm, the worst case for the cost is that we apply all gates in {PGx(j) | x(j) = 2 j \u22121 & j \u2208[1,k]}. Let the state x(j) has y |1 > states, if y > 2 the PGx(j) can be implemented using 2y\u22121 basic gates, including y\u22121 Toffoli gates for controlling, 1 control Z gate, and y\u22121 Toffoli gates for resetting; otherwise, it uses 1 basic gates. Based on these understandings, we can calculate the cost complexity in the worst case, which is 1 + 1 + 3 + \u00b7\u00b7\u00b7 + (2 \u00d7 k \u22121) = k2 + 1. Therefore, the cost complexity of linear function computation is O(k2). The quadratic activation function is implemented by a CkZ gate, whose cost is O(k). Thus, the cost complexity for neural computation U-LYR is O(k2). Finally, to make the functional correctness, in generating the inputs unitary matrix, we swap rows in it in terms of the weights, and store the generated results in quantum memory. Mapping QF-Circ to physic qbits: After QF-Circ is generated, the second step is to map QF-Circ to quantum processors, called virtual-to-physic mapping. In this paper, we deploy QF-Circ to various IBM quantum processors. Virtual-tophysic mapping in QF-Map has two tasks: (1) select a suitable quantum processor backend, and (2) map qbits in QF-Nets to physic qbits in the selected backend. For the \ufb01rst task, QFMap will i) check the number of qbits needed; ii) \ufb01nd the backend with the smallest number of qbit to accommodate QF-Circ; iii) for the backends with the same number of qbits, QF-Map will select a backend for the minimum average error rate. The second task in QF-Map is to map qbits in QF-Nets to physic qbits. The mapping follows two rules: (1) the qbit in QF-Nets with more gates is mapped to the physic qbit with a lower error rate; and (2) qbits in QF-Nets with connections are mapped to the physic qbits with the smallest distance. Data availability The authors declare that all data supporting the \ufb01ndings of this study are available within the article and its Supplementary Information \ufb01les. Source data can be accessed via https://wjiang.nd.edu/categories/qf/. Code availability All relevant codes will be open in github upon the acceptance of the manuscript or be available from the corresponding authors upon reasonable request." + }, + { + "url": "http://arxiv.org/abs/1907.08985v2", + "title": "Achieving Super-Linear Speedup across Multi-FPGA for Real-Time DNN Inference", + "abstract": "Real-time Deep Neural Network (DNN) inference with low-latency requirement\nhas become increasingly important for numerous applications in both cloud\ncomputing (e.g., Apple's Siri) and edge computing (e.g., Google/Waymo's\ndriverless car). FPGA-based DNN accelerators have demonstrated both superior\nflexibility and performance; in addition, for real-time inference with low\nbatch size, FPGA is expected to achieve further performance improvement.\nHowever, the performance gain from the single-FPGA design is obstructed by the\nlimited on-chip resource. In this paper, we employ multiple FPGAs to\ncooperatively run DNNs with the objective of achieving super-linear speed-up\nagainst single-FPGA design. In implementing such systems, we found two barriers\nthat hinder us from achieving the design goal: (1) the lack of a clear\npartition scheme for each DNN layer to fully exploit parallelism, and (2) the\ninsufficient bandwidth between the off-chip memory and the accelerator due to\nthe growing size of DNNs. To tackle these issues, we propose a general\nframework, \"Super-LIP\", which can support different kinds of DNNs. In this\npaper, we take Convolutional Neural Network (CNN) as a vehicle to illustrate\nSuper-LIP. We first formulate an accurate system-level model to support the\nexploration of best partition schemes. Then, we develop a novel design\nmethodology to effectively alleviate the heavy loads on memory bandwidth by\nmoving traffic from memory bus to inter-FPGA links. We implement Super-LIP\nbased on ZCU102 FPGA boards. Results demonstrate that Super-LIP with 2 FPGAs\ncan achieve 3.48x speedup, compared to the state-of-the-art single-FPGA design.\nWhat is more, as the number of FPGAs scales up, the system latency can be\nfurther reduced while maintaining high energy efficiency.", + "authors": "Weiwen Jiang, Edwin H. -M. Sha, Xinyi Zhang, Lei Yang, Qingfeng Zhuge, Yiyu Shi, Jingtong Hu", + "published": "2019-07-21", + "updated": "2020-02-08", + "primary_cat": "cs.DC", + "cats": [ + "cs.DC" + ], + "main_content": "INTRODUCTION Deep Neural Networks (DNNs) have been continuously achieving breakthroughs in many challenging AI domains, such as image recognition [1], object detection [2], and natural language processing [3]. More recently, DNNs have been applied to process live data in interactive services. For instance, a trained DNN can be employed to process the live video stream for traffic surveillance and emergency response [4], and to analyze medical scans to help doctors during surgery [5]. Thus, the design of systems for real-time DNN inference becomes an imminent challenge, which attracts increasing studies from both industry [6, 7] and academia [2, 5, 8]. Out of all leading computation platforms for DNNs, FPGAs stand out due to their flexibility and versatility over ASICs and their efficiency over CPUs and GPUs. In addition, FPGAs are expected to be more suitable for real-time DNN inference [6, 7] for the following reasons. First, even though ASICs can achieve better latency and energy efficiency, it is prohibitive to design ASIC for each different application or upgrade the design when needed. Second, the realtime inference has rigorous requirements of guaranteed latency to ensure user experience, reliability, and even safety. To meet the hard deadlines, uncertainties in CPUand GPU-based designs (caused by accessing caches) force them to apply the worst-case analysis with a safety margin [9], which leads to inferior design. In contrast, designers are able to customize FPGAs to make the accelerators process the deterministic timing characteristics, which can avoid the overhead caused by the safety margin. Third, realtime inference commonly needs to process data with low batch size, which renders the batch throughput optimization inefficient. For instance, Google\u2019s TPU [10] requires the batch size of at least 16 for energy efficiency while FPGAs can extract parallelism from individual execution instance to reduce latency for the low or even no batching. While most FPGA-based DNN acceleration has been focusing on single-FPGA platform [11\u201314], the growth of resource requirement in DNNs has far exceeded the growth of the resource integrated into one FPGA. As a result, the limited on-chip resources will hinder the exploitation of model parallelism from further boosting time performance. To overcome this challenge, [15] proposed to employ multiple FPGAs, on which DNN layers can be processed in a pipelined fashion. Pipelining designs can achieve high throughput; however, the latency cannot be reduced. With the objective of minimizing latency for real-time AI applications, we exploit the parallelisms in DNN layers and concurrently process each DNN layer across multiple FPGAs. However, we observe that with the growing size of models and volume of input data, a straightforward partition of DNNs to multiple FPGAs leads the severe performance degradation due to insufficient communication bandwidth. In this paper, we propose a new framework, namely \u201cSuper-LIP\u201d, to address the performance bottlenecks in DNNs. To illustrate the framework, we take Convolutional Neural Networks (CNNs) as a vehicle, since CNNs have large amount of intermediate data and more complicated data reuse patterns than Recurrent Neural Networks (RNNs), which results in the acceleration for CNNs on multi-FPGA more challenging. Given a CNN, we first formulate an accurate performance model to detect performance bottleneck in an early stage for the latter optimization of accelerator design. Compared with the existing model [14], the proposed one is more accurate since we investigate the fine-grained data accesses/communication patterns. Based on the accurate model, we identify that the communication bottleneck is commonly at accessing off-chip memory. We propose a novel design, \u201cXFER\u201d, to take advantages of the high-bandwidth inter-FPGA links by offloading part of the data traffic from the memory bus to these links. As a result, performance bottleneck on memory bandwidth can be significantly alleviated. arXiv:1907.08985v2 [cs.DC] 8 Feb 2020 \fCODES+ISSS, 2019, New York, NY Layer Model 1 Input Application Accelerator Design 2 Performace Model and Bottleneck Analysis 3 Computation Bound Communication Bound Analytic Model design parameters Workload Balance 4 Communication Balance 5 PE PE IFM OFM XFER FPGA1 FPGA2 WEI IFM OFM WEI SW/HW scale-up 6 Output Multi-FPGA design XFER XFER XFER XFER XFER Design Super-LIP Framework one FPGA FPGA Accelerator Design Figure 1: Overview of Super-LIP Framework. The main contributions made in this paper are threefold: \u2022 Super-LIP Framework. We build a framework, Super-LIP, to control the exploration of FPGA-based designs for realtime DNN inference to achieve Super-Linear speedup across multiple FPGAs. Inside Super-LIP, we have further made two contributions listed as follows. \u2022 Accurate Model. First, we formulate an accurate analytic model to quantify the performance-resource trade-off in terms of data access/communication patterns, which can guide designers to better design DNN accelerator and provide insights on how to partition DNNs onto multiple-FPGAs. \u2022 XFER Design. Second, we propose a novel design, XFER, to partition and map DNNs onto multiple FPGAs to exploit high parallelism in DNN layers. XFER can further alleviate the performance bottleneck on memory bandwidth by transferring part of the traffic to inter-FPGA links. Evaluations are conducted on Xilinx ZCU102 FPGA boards connected via optical fiber cables using SFP+ transceiver. Results show that Super-LIP can achieve 2.82\u00d7 and 5.81\u00d7 reduction in latency, while achieving 8.61\u00d7 and 1.81\u00d7 improvement in energy efficiency, compared to GPU and mobile GPU, respectively. Compared with the state-of-the-art single-FPGA design, Super-LIP with 2 FPGAs achieves 3.48\u00d7 speedup and 39.86% improvement in energy efficiency. In addition, when the size of the FPGA cluster scales up to 16, the latency can be consistently reduced. For instance, the latency of YOLO [16] on one FPGA is 126.6ms, which can be reduced to 4.53ms, achieving 27.93\u00d7 reduction. This confirms the applicability and scalability of Super-LIP. The remainder of the paper is organized as follows. Section 2 presents the Super-LIP framework and design challenges. Section 3 and Section 4 present the accurate analytic model and novel XFER design in Super-LIP. Experimental results are shown in Section 5. Section 6 discusses related work. Finally, concluding remarks are given in Section 7. 40 60 80 100 20 0 0 10 20 30 40 50 60 70 80 Computation roof Bandwidth roof (2.23GB/s) Peformance (GFLOPS) Computation to Communication Ratio (FLOP/DRAM byte access) Model Performance Real Performance Model Performance A B Real Performance Figure 2: Model performance vs. real performance. 2 SUPER-LIP FRAMEWORK & CHALLENGES Figure 1 demonstrates the overview of the proposed Super-LIP framework. Super-LIP takes a Deep Neural Network (DNN) as input. And it outputs a multi-FPGA design, onto which the given DNN is partitioned and mapped through a novel technique proposed in this paper. The design objective of Super-LIP is to achieve the minimum latency for real-time AI with ultra-low batch size. Super-LIP, in the middle of Figure 1, sequentially explores two design spaces: (1) accelerator design space on the left-hand side (\u2780-\u2782), which determines the hardware-level parallelism (e.g., how many DSPs to compute multiply-accumulate operations, and how many channels to move data between off-chip and on-chip memory); (2) multi-FPGA design space on the right-hand side (\u278d-\u278f), which determines task-level parallelism (e.g., how to partition each DNN layer and how to communicate between FPGAs). In the exploration of both spaces, there exist several challenges needing to be addressed, which are demonstrated as follows. Challenge 1: Inaccurate performance models hinder designers to optimize accelerators. Figure 2 shows the design space exploration of Layer 5 in AlexNet [1] using the model proposed by [14] which is based on roof-line model. In this figure, each point represents a design. Computation roof is determined by the computation resource in FPGA, while bandwidth roof is the theoretic peak memory bandwidth to access off-chip memory in terms of designs. Design points under these roofs are regarded as attainable. We implement designs A and B in Figure 2 on the ZCU102 FPGA board to capture its real performance of on-board execution. We observe that even though design points A and B are under both roofs, their real performance cannot reach the estimated model performance. This is because the model in [14] assumes the uninterrupted memory access, which is basically impossible due to the synchronization of operations (i.e, the completed operations need to wait for the slower ones, see Figure 6). In addition, design A with the best model performance is inferior to design B in real performance. Therefore, it is imperative to develop an accurate performance model which can explore the optimal designs. Challenge 2: How to alleviate communication bottleneck without costly modifications on hardware? As shown in Figure 1 \u2782, there are potentially two kinds of performance bottlenecks: computation bottleneck bounded by the computation resource and communication bottleneck bounded by \fCODES+ISSS, 2019, New York, NY PE PE IFM OFM XFER WEI IFM OFM WEI FPGA1 FPGA2 Off-chip memory On-chip buffer Accelerator IFM OFM WEI PE Cycles 1412 234 2953 1782 Ops IFM OFM W&X PE Cycles 1412 234 1695 1782 Ops (a) w/o XFER w/ XFER Lat Lat 2953 1782 (b) (c) Figure 3: The XFER design and the performance gain. the off-chip memory bandwidth. For computation bottleneck, we can enlarge the accelerator to involve more computation resource to alleviate it. However, it is hard to alleviate communication bottlenecks without costly modifications on the FPGA hardware (e.g., increase the size of on-chip memory). Thanks to the inter-FPGA links in an FPGA cluster, memory bandwidth bottleneck can be alleviated by offloading traffic from the memory bus to inter-FPGA links, which can be realized from a high-level implementation without any modifications on hardware. This idea is inspired by the observation from the results in comparing data transmission time between accessing off-chip memory and switching between FPGAs. Experimental results on two connected ZCU102 FPGAs via SFP+ cables show that the speed of inter-FPGA communication is competitive with accessing offchip memory. Specifically, inter-FPGA communication is 3 times faster than accessing off-chip memory when the packet size is 1KB. The figure is 1.6 times when the packet size increases to 64KB and 128KB. The obtained speedup is mainly because platforms provide high-speed serial communication, while the speed of memory accesses is bounded by the accelerator designs (details in Section 3 \u2781-1). Motivated by the above results, we propose a novel design methodology in the Super-LIP framework, namely \u201cXFER\u201d, to address two implementation problems in exploring multi-FPGA designs: (1) how to partition computations in DNN layers for higher model parallelism; and (2) what type of data can be off-loaded to inter-FPGA links. Figure 1, from \u278dto \u278f, demonstrates three steps in XFER to optimize the accelerators on multiple FPGAs: first, it determines the partitions of DNN layers to balance computation workloads (\u278d); second, it identifies the traffic to be off-loaded to inter-FPGA links to balance communication (\u278e); last, it scales up the number of FPGAs to further speedup the whole DNN network (\u278f). Figure 3 (a) illustrates an example of XFER employed between two FPGAs. As shown in the figure, FPGA1 and FPGA2 share the same set of weights and have different sets of input/output feature maps (IFMs/OFMs). Traditionally, each FPGA will load the weight and compute by itself. In XFER, each FPGA only loads half of the shared weight from the off-chip memory. Then, they will send the loaded half weight to each other through inter-FPGA links. In this way, each FPGA only loads parts of the weights from off-chip memory, which significantly reduces the traffic loads on the memory bus. As a result, the overall latency regarding to the pipeline cycle time (Lat2 in Figure 6) can be reduced from 2,953 to 1,782, achieving 39.65% improvement, as shown in Figure 3 (b)-(c). Kindly note that the pipeline cycle time is determined by the slowest operation (details can be found in Formulas 12 and 13). In the following sections, we will address the first challenge by formulating an accurate performance analytic model in Section3, which is the base of optimizing DNN accelerators on a multi-FPGA L1 L2 L3 L4 M R C N K K B \u2026 \u2026 IFM OFM L=\u2329B,M,N,R,C,K\u232a Figure 4: Super-LIP \u2780: CNN layer model. platform. Second, in the design of a computing platform with multiple FPGAs where communication channels can be established between two FPGAs, we present the novel XFER design in Section 4 to address the second challenge. 3 ACCURATE ANALYTIC MODELS Figures 4-6 shows the details of accelerator optimization (left-hand side) in Super-LIP. We first formulate the model for one CNN layer in \u2780; then, the accelerator design for both off-chip optimization and on-chip implementations are depicted in \u2781-1 and \u2781-2, respectively. At the end of this section, we present the performance model and bottleneck detection (component \u2782in Figure 1). \u2780Layer Model. Layer model describes the properties of a CNN layer. In Figure 4, we show the details of the second layer L2 in a CNN with 4 layers. A CNN layer is defined as L = \u27e8B, M, N,R,C,K\u27e9, where B is the batch size; M and N represent the number of channels in output/input feature maps (OFM/IFM); R and C represent the number of rows and columns in OFM; K refers to kernel size. For example, L = \u27e82, 128, 192, 13, 13, 3\u27e9describes Layer 5 in AlexNet with the batch size of 2. Based on the proposed layer model, we will introduce how to design CNN accelerators on an FPGA (component \u2781in Figure 1). \u2781Accelerator Design. The core of FPGA-based accelerator design is the on-chip computation engine (as shown in right-hand part of Figure 5(b)), which will conduct a set of multiplicationand-accumulation in parallel. Since the memory and computation requirement of one layer significantly exceeds the on-chip resource, the computation engine cannot process all operations in one CNN layer at once; instead, it will be invoked repeatedly. To match the speed between the data consumed by the computation engine and the data produced by accessing off-chip memory, we use the on-chip memory (i.e., BRAM) to be a cache, which constructs a two-level computing model, as shown in Figure 5(b). In the first level, we move data between off-chip memory and on-chip memory, denoted as \u2781-1 off-chip design. In the second level, we move data between on-chip memory and computation engine, denoted as \u2781-2 on-chip design. \u2781-1 Off-Chip Design. The off-chip design needs to control the sequence of data to be uploaded to the on-chip memory. To ensure the functional correctness, we need to determine the size of data and the order of data to be uploaded, which correspond to loop tiling and loop ordering. A data tile of each data type is the basic unit to be moved between off-chip and on-chip memory. Let \u27e8Tm,Tn,Tr ,Tc\u27e9be tiling parameters on OFM channel, IFM channel, row, column. Then, we can get the size of data tile for IFM (to be Tn \u00b7 Tr \u00b7 Tc), OFM (to be Tm \u00b7Tr \u00b7Tc), and weight (to be Tm \u00b7Tn \u00b7 k \u00b7 k, where k is the kernel \fCODES+ISSS, 2019, New York, NY A A 1 C E D D E Tn Tm Tr Tc Tn Tm k Tr Tc \u2329Tm,Tn,Tr,Tc\u232a -1: off-chip optimization: 2 Off-Chip Memory (DRAM) Tn Tm Ip Wp Op Tn Tm . Tm F \u2026 (a) B B = \u00d7 + + \u00d7 = \u00d7 + + \u00d7 + + \u2026 \u2026 \u2026 Tm Tn On-Chip Memory and Data Flow IFM WEI OFM words On-Chip Computation Engine -2: on-chip design: 2 (b) \u2329Ip,Wp,Op\u232a \u2026 Figure 5: Super-LIP \u2781: (a) \u2781-1 the off-chip optimization; (b) \u2781-2 the on-chip accelerator design. size). In Figure 5(a), the colored data demonstrate the data tiles. Note that these tiling parameters will be constrained by on-chip resource, which will be introduced later in this section. Next, the loop order will determine the sequence of data to be moved between off-chip and on-chip memory. The convolution operation involves 4-level of nested loops (details please refer to Fig. 5 in [14]). These loops traverse along IFM channel, OFM channel, row/column, and batch, which correspond to directions C, D, E, F in Figure 5(a), respectively. Based on the above loop order, we can get the trip count, which will be used in modeling the computation latency. We first introduce the trip count for loops along IFM channel (C). According to the tiling parameters, in the loop each step will involve Tn channels, and there are N IFM channels in total. Therefore, the trip count for direction C is \u2308N Tn \u2309. Similarly, we can obtain the trip count for direction D as \u2308M Tm \u2309. Then, for direction E, it will move along R rows and C columns, and each step along row and column is Tr and Tc, so the trip count is \u2308C Tc \u2309\u00d7 \u2308R Tr \u2309. Finally, for batch size of B, we need to traverse each batch and the trip count for F is B. \u2781-2 On-Chip Design. Based on the loop optimization parameters, we model the on-chip computation and buffer allocation. Then, we model the off-chip/on-chip communication based on the data width related parameters \u27e8Ip,Wp,Op\u27e9. For the on-chip computation model, as shown in Figure 5(b), there areTm\u00d7Tn Multiply-Accumulate (MAC) operations conducted in parallel. In this paper, we consider different data types: For the 16bits fixed point, each MAC utilizes 1 DSP, while for the 32bits floating point, each MAC utilizes 5 DSPs. Let D be the number of DSPs provided by the platform, we have the following constraints for 32bits float-point and 16bits fix-point, respectively: 5 \u00d7Tm \u00d7Tn \u2264D (1) Tm \u00d7Tn \u2264D (2) ... { \uf8eeN/Tn\uf8f9 Lat2 O I W COMP prologue { Lat ... { one load Lat1 ITER epilogue Performance Bottleneck Figure 6: Super-LIP \u2782: Performance model and bottleneck detection. As to the on-chip buffer design, there are three kinds of buffers: IFM, OFM and Weight (WEI) buffers. The size of IFM buffer is determined by the loop tiling on IFM. For each iteration, Tn \u00d7 Tr \u00d7 Tc pixels in IFM are loaded to the on-chip buffer, as shown in Figure 5(a). Hence, the IFM buffer is declared as a 3-dimension array I[Tn][Tr ][Tc]. Similarly, OFM and WEI buffers are declared as O[Tm][Tr ][Tc] and W [Tm][Tn][K][K], respectively. In order to match the speed of computation, these arrays should be partitioned into different on-chip memories (i.e. BRAM) which can be accessed in parallel. As shown in Figure 5(b), each computation involves Tn, Tm, and Tm \u00d7Tn pixels/weights in IFM, OFM, and WEI buffers. Accordingly, we completely partition IFM and OFM along their first dimension, and WEI along its first two dimensions. Then, we calculate the usage of BRAMs for IFM (bI), OFM (bO), WEI (bW ): bI = 2 \u00d7Tn \u00d7 \u2308Tr \u00b7 Tc \u00b7 BITs/18K\u2309 (3) bO = 2 \u00d7Tm \u00d7 \u2308Tr \u00b7 Tc \u00b7 BITs/18K\u2309 (4) bW = 2 \u00d7Tm \u00d7Tn \u00d7 \u2308K \u00b7 K \u00b7 BITs/18K\u2309 (5) where 2 represents the double-buffer technique adopted in the design. For the ease of illustration, we do not put the double buffer in Figure 5(b). Let B be the number of BRAMs in the platform, we have the following constraint. bI + bO + bW \u2264B (6) Finally, we determine the data width parameters \u27e8Ip,Wp,Op\u27e9, which are used to model the off-chip/on-chip communication bandwidth. Ip,Wp,Op represent the number of AXI_STREAMs employed in transmitting IFM, WEI, and OFM, and in turn determine the width of AXI bus. In a given platform, the data width of the memory bus is limited, denoted as W. We have the following constraint. BITs \u00d7 (Ip +Wp + Op) \u2264W (7) where notation BITs is the data bit-width adopted in designs. \u2782Performance Model and Analysis. We first model the offchip/on-chip communication latency for transferring IFM, OFM, and WEI, based on parameters \u27e8Ip,Wp,Op\u27e9. For instance, the size of IFM buffer is Tn \u00b7 Tr \u00b7 Tc, and we employ Ip AXI_STREAMs for data transfer, indicating that Ip pixels can be loaded to IFM buffer within 1 clock cycle in the pipelined fashion. Hence, the latency of loading IFM (tImem) can be formulated. tImem = Tn \u00b7 Tr \u00b7 Tc/Ip (8) Similarly, we model the latency of loading WEI buffer (tWmem) and offloading OFM buffer (tOmem) as follows. tWmem = Tm \u00b7 Tn \u00b7 K \u00b7 K/Wp (9) tOmem = Tm \u00b7 Tr \u00b7 Tc/Op (10) \fCODES+ISSS, 2019, New York, NY Then, after filling up the on-chip buffers, data in them can support K \u00d7 K \u00d7Tr \u00d7Tc \u00d7Tm \u00d7Tn MACs. As stated in \u2781-2 On-Chip Design, the Processing Element (PE) can conduct Tm \u00d7 Tn MAC operations in parallel. Therefore, the latency of one execution of PE (tComp) can be modeled as follows. tComp = K \u00b7 K \u00b7 Tr \u00b7 Tc (11) Next, we are going to model the system latency. Benefiting from the double buffer technique, loading IFM, loading WEI, and executing PE can be conducted in parallel. In addition, loading OFM can be overlapped with \u2308N Tn \u2309executions, as shown in Figure 6. With the known trip counts in \u2781-1, we model the latency as follows. Lat1 = max{tComp,tImem,tWmem} (12) Lat2 = max{\u2308N Tn \u2309\u00b7 Lat1,tOmem} (13) Lat = B \u00d7 \u2308R Tr \u2309\u00d7 \u2308C Tc \u2309\u00d7 \u2308M Tm \u2309\u00d7 Lat2 + (tOmem + Lat1) (14) where Lat1 and Lat2 are the latencies of one trip for loop C and D, respectively, and Lat is the overall system latency. Based on the above performance and resource usage models, we can formulate the optimization problem of minimizing latency as integer non-linear programming problem, which incorporates constraints from Formula 1 to 14. The objective of this problem is to minimize latency, as follows. Objective : min = Lat (15) Performance Bottleneck Detection. The above analytic model can help designer to detect the performance bottleneck. Specifically, we have the following corollary. Corollary 1. Given a CNN layer and the design parameters, we can detect the performance bottlenecks by considering Lat1 and Lat2 as follows: \u2022 if Lat2 is dominated by tOmem, the performance bottleneck is on transmitting OFM data, otherwise, \u2022 if Lat1 is dominated by tImem, the performance bottleneck is on transmitting IFM data, \u2022 if Lat1 is dominated by tWmem, the performance bottleneck is on transmitting weights, \u2022 if Lat1 is dominated by tComp, we have fully utilized the involved computation resource. 4 XFER DESIGN In this section, we will present the XFER design for CNNs on multiple FPGAs, which can effectively alleviate the performance bottleneck on off-chip memory bandwidth and in turn achieve the super-linear performance. 4.1 Design Principles and Objective Here, we present three design principles and our ultimate objective for implementing CNNs on multi-FPGA clusters. P1. Maximizing the utilization of computation resources. The design should fully utilize the computation resources. In order to achieve this goal, the workloads should be balanced so that FPGAs will not be idle. Meanwhile, we need to avoid memory access stalls, hence DSPs don\u2019t have to wait for the data loading from off-chip memory. P2. Balancing the traffic loads across multiple FPGAs. Different from the single-FPGA design where the memory bus is the only communication channel to access off-chip data, in multi-FPGA clusters, inter-FPGA links provide extra communication bandwidth, which can considerably improve the efficiency of data transfer. However, it is essential to balance the traffic on memory buses and inter-FPGA links for performance improvement. P3. Minimizing the exchange of data in off-chip memories. The movements of data stored in off-chip memory are controlled by CPUs, which incurs high latency. Thus, we should avoid such movement as much as possible. Objective. Achieving super-linear speedup. The design objective is to achieve super-linear performance, such that the latency can be minimized without compromising on throughput or energy efficiency, which leads to the ultimate realization of real-time DNN inference. Following the above principles and objective, XFER consists of the following three steps: First, XFER achieves linear speedup through balancing computation workloads. Then, to achieve further speedup, XFER identifies the shared data among different partitions, and distributes these data across FPGAs to reduce the traffic loads on each FPGA\u2019s memory bus. During run time, FPGAs transfer a part of the data stored in their local off-chip memory via inter-FPGA links. 4.2 Layer Partition and Workload Balance A CNN layer can be partitioned into different parts to be computed in parallel. The most common partition is the batch partition, where the IFM and OFM are divided along batching direction, as shown in Figure 7(a). The computation of a batch of OFM only relies on the corresponding batch of IFM and the whole weights. In consequence these batches can be computed in parallel in multiple processing elements (PEs) if weights are duplicated to PEs. Similarly, we can partition CNN layers along rows (R) and columns (C), as shown in Figure 7(b)-(c). In addition, we can partition a CNN layer as follows: dividing the OFM into multiple parts along channel direction, and dividing weights correspondingly, as shown in Figure 7(d). In this case, we use the whole IFM and part of weights to compute part of OFM, and we call such partition as OFM channel partition. Similarly, we can partition IFM along channel direction and weights correspondingly, as shown in Figure 7(e). For each kind of partition, we define a partition factor to indicate the number of parts generated by the partition. We use notations Pb, Pr , Pc, Pm, Pn to represent factors for partitions along with batch (B), rows (R), columns (C), OFM channels (M), and IFM channels (N). For instance, Pr = 2 indicates that we partition IFM/OFM along rows into 2 parts, as shown in Figure 7(b). Kindly note that we use factors of 2 in Figure 7 for the simplicity of illustration; however, these factors can be other positive integers except 2, which will be restricted by the number of available FPGAs in a system. According to the types of shared data, we can classify partitions into 3 categories: first, \u201cweight shared\u201d case, where the computations of different partitions use the same weights, such as row or column partitions in Figure 7(a)-(c); second, \u201cIFM shared\u201d case, where the computations under the OFM channel partition use the same IFM, as shown in Figure 7(d); third, \u201cOFM shared\u201d case, where \fCODES+ISSS, 2019, New York, NY (b) Row Partition (d) OFM Channel Partition (e) IFM Channel Partition (a) Batch Partition PE PE PE PE I W O I W O I W O I W O (f) Weight Shared (g) IFM Shared (c) Column Partition PE PE I W O I W O (h) OFM Shared Summation Processing System (DRAM) Programmable Logic FPGA f1 f2 f1 f2 f1 f2 batch #1 batch #2 Figure 7: Five kinds of partitions and the base-line designs: (a) batch partition Pb = 2; (b) row partition Pr = 2; (c) column partition Pc = 2; (d) OFM channel partition Pm = 2; (e) IFM channel partition Pn = 2; (f) design for batch/row/column partitions; (g) design for OFM channel partition; (h) design for IFM channel partition. PE PE PE PE I W O I O W O W O (a) Pr = 2 (c) Pm = 2 W XFER I I XFER void XFER_load_weight(float bW[SIZE], stream &mem_in, stream &b2b_in, stream &b2b_out){ for(int i=0; i &mem_in, stream &b2b_in, stream &b2b_out){ for(int i=0; i rL (A \u2212b) + L r L L \u2264rL (1) In the above function, there are two cases. First, if L > rL, it indicates that the performance of the resultant system cannot satisfy the timing speci\ufb01cation. In this case, we do not train the child network and directly return a negative reward to the controller. In the second case, we sum up the reward of performance and accuracy, where the performance reward is set as L r L , which indicates a solution has higher performance reward if its latency approaches the required level. Here, b is a baseline function, which is an exponential moving average of the previous architecture accuracies [16]. 3.3 Tiling Parameters: \u2780FNAS-Design weights \u2026 Tm \u2026 layer 1 layer 2 Tm N Tn Tn (a) N/Tn=2 Tr R Tc (b) R/Tr=2, C/Tc=2 (c) M/Tm=3, N/Tn=2, R/Tr=1, C/Tc=2 C 1 2 3 4 1 2 layer 1 layer 2 layer 3 T1,1,1 ifm T1,1,2 ifm T1,2,1 ifm T1,2,2 ifm T2,1,1 ofm T2,1,2 ofm T2,2,1 ofm T2,2,2 ofm ofm T2,3,1 ofm T2,3,2 ofm T2,1,1 ifm T2,1,2 ifm T2,2,1 ifm T2,2,2 ifm T3,1,1 ofm T3,1,2 ofm T3,2,1 ofm T3,2,2 ofm ofm T3,3,1 ofm T3,3,2 ofm (d) Tm!=Tn T1,1,1 ifm T1,1,2 ifm T1,2,1 ifm T1,2,2 ifm T2,1,1 ofm T2,1,2 ofm T2,2,1 ofm T2,2,2 ofm T2,3,1 ofm T2,3,2 ofm v1,1,1,1 v1,1,2,1 v1,1,3,1 v1,1,1,2 v1,1,2,2 v1,1,3,2 v1,2,1,1 v1,2,2,1 v1,2,3,1 v1,2,1,2 v1,2,2,2 v1,2,3,2 T2,1,1 ifm T2,1,2 ifm T2,2,1 ifm T2,2,2 ifm T3,1,1 ofm T3,1,2 ofm T3,2,1 ofm T3,2,2 ofm T3,3,1 ofm T3,3,2 ofm v2,1,1,1 v2,1,2,1 v2,1,3,1 v2,1,1,2 v2,1,2,2 v2,1,3,2 v2,2,1,1 v2,2,2,1 v2,2,3,1 v2,2,1,2 v2,2,2,2 v2,2,3,2 layer 1 layer 2 layer 3 conv 1 conv 2 (e) Tile-based Task Graphs with convolutional tasks derived from (d) inter-layer dependencies intra-layer dependencies inter-layer dependencies Figure 3: FNAS-Design and FNAS-GG: (a) channel tiles; (b) row/col tiles; (c) tile-based convolution; (d) encoding of tiles; (e) tile-based task graph. Due to the limited resource on FPGA, it may be di\ufb03cult to place a whole convolutional layer on FPGA. In consequence, it is common to apply tiling technique to split convolutional operations into multiple small tasks [8, 12\u201315]. FNAS-Design is to determine the tiling parameters for a given NN architecture on target FPGAs. Take one convolutional operation as an example, it involves four parameters \u27e8Tm,Tn,Tr,Tc\u27e9, related to the input/output feature maps (IFM/OFM). Here, the number of IFM channel is N . The size of corresponding tiles isTn (channels). IFM is then partitioned into \u2308N Tn \u2309tiles, as shown in Figure 3(a). Similarly, OFM with M channels is partitioned to \u2308M Tm \u2309tiles. In addition, the numbers of row/column of OFM are R and C, respectively. They are tiled according to Tr and Tc as shown in Figure 3(b). After tiling the IFM/OFM/row/col, one convolutional operation is divided to smaller tasks, as shown in Figure 3(c). Each task corresponds to a pair of IFM/OFM tiles. Tasks in one layer will be continuously loaded to a Processing Element (PE) on FPGA for execution (the load sequence is determined by \u2782FNAS-Sched). For a task, it involves Kh \u00d7Kw \u00d7Tr \u00d7Tc \u00d7Tm \u00d7Tn Multiply-Accumulate (MAC) operations, where Kh and Kw are the height and weight of \ufb01lter determined by the controller. A PE composed ofTm\u00d7Tn DSPs can execute Tm \u00d7 Tn MAC operations (16bit \ufb01x-point) in parallel [13]. Then the latency of a task is Kh \u00d7 Kw \u00d7Tr \u00d7Tc. In FNAS, each layer is allocated to a dedicated PE, and PEs are performed in the pipeline fashion. Such architecture can be implemented on one FPGA as in [8, 15] or multiple FPGAs as in [4, 14]. The resource (e.g., DSP and memory bandwidth) for each layer can be obtained by considering the load balance. And then the best parameters \u27e8Tm,Tn,Tr ,Tc\u27e9can be obtained according to [8, 13]. 3.4 Tile-based task graph generator: \u2781FNAS-GG FNAS-GG is a graph generator that takes the design parameters and NN architecture to generate the dependency graph between \fT1,1,1 ifm T1,1,2 ifm T1,2,1 ifm T1,2,2 ifm T2,1,1 ofm T2,1,2 ofm T2,2,1 ofm T2,2,2 ofm T2,3,1 ofm T2,3,2 ofm v1,1,1,1 v1,1,2,1 v1,1,3,1 v1,1,1,2 v1,1,2,2 v1,1,3,2 v1,2,1,1 v1,2,2,1 v1,2,3,1 v1,2,1,2 v1,2,2,2 v1,2,3,2 T2,1,1 ifm T2,1,2 ifm T2,2,1 ifm T2,2,2 ifm T3,1,1 ofm T3,1,2 ofm T3,2,1 ofm T3,2,2 ofm T3,3,1 ofm T3,3,2 ofm v2,1,1,1 v2,1,2,1 v2,1,3,1 v2,1,1,2 v2,1,2,2 v2,1,3,2 v2,2,1,1 v2,2,2,1 v2,2,3,1 v2,2,1,2 v2,2,2,2 v2,2,3,2 v1,1,1,1 v1,1,2,1 v1,1,3,1 v1,1,1,2 v1,1,2,2 v1,1,3,2 v1,2,1,1 v1,2,2,1 v1,2,3,1 v1,2,1,2 v1,2,2,2 v1,2,3,2 v2,1,1,1 v2,1,2,1 v2,1,3,1 v2,1,1,2 v2,1,2,2 v2,1,3,2 v2,2,1,1 v2,2,2,1 v2,2,3,1 v2,2,1,2 v2,2,2,2 v2,2,3,2 PE1 PE2 start-time time OFM reuse IFM reuse (a) Ordered tile-based task graph (b) Schedule Figure 4: FNAS-Sched: (a) re-ordered graph from 3(e); (b) the generated schedule graph. data tiles and tasks, called tile-based task graph. To generate the graph, the generator \ufb01rst needs to de\ufb01ne each tile for a given design. Then, it can generate the tile-based task graph. According to FNAS-Design, there are two kinds of tiles: channel tile and row/col tile. For channel tile, letCHif m i = {1, 2, \u00b7 \u00b7 \u00b7 , \u2308CHi Tn \u2309} be a set of indices in the ith layer under tiling parameter Tn (considering ith layer\u2019s IFM); similarly CHof m i = {1, 2, \u00b7 \u00b7 \u00b7 , \u2308CHi Tm \u2309} is under tiling parameter Tm (considering ith layer\u2019s OFM). For row/col tile, let RCi = {1, 2, \u00b7 \u00b7 \u00b7 , \u2308Ri Tr \u2309\u00b7 \u2308Ci Tc \u2309} be a set of indices in layer i under tiling parameter Tr and Tc. Based on these parameters, we can de\ufb01ne the tiles as follows. We de\ufb01ne a tile in IFM as T if m i,j,m, indicating the tile is in the ith layer, the jth channel tile in CHif m i and mth row/col tile in RCi. Similarly, the tile in OFM is de\ufb01ned asT of m i,k,m, where k is the index of channel tile in CHof m i . Then, we can build the dependencies among data tiles and tasks. There are two kinds of dependencies. First, inter-layer dependencies describe the dependency between tasks and data tiles in two consecutive layers. We de\ufb01ne a task node to bevi,j,k,m, which process the tile T if m i,j,m and generate the tile T of m i+1,k,m. Next, the intra-layer dependencies describe dependency between two data tiles in one layer. If the tiling parameters Tm and Tn for a layer are di\ufb00erent, as shown in Layer 2 in Figure 3(d), the dependency would not be the simple one-to-one mapping Instead, it can be represented as follows. For the tile T if m i,j,m, its data is depending on tile T of m i,k,m if (j \u22121) \u00b7 Tn Tm + 1 \u2264k \u2264j \u00b7 Tn Tm , where k \u2208N. By following the above rules, the graph can be generated. For the tiles of three layers in Figure 3(d), its corresponding tile-based task graph is shown in Figure 3(e). 3.5 Scheduler design: \u2782FNAS-Sched FNAS-Sched is a scheduler to determine the sequence of tasks to be executed on multiple PEs, such that the schedule length (latency) can be minimized. FNAS-Sched tries to maximally exploit the parallelism among di\ufb00erent convolutional operations based on the tile-based task graph. The design follows three principles: \u2022 P1. Minimizing the start time of each PE to execute tasks as early as possible. for(row=0; row