Protecting Privacy in Classifiers by Token Manipulation (2024)

Abstract: Using language models as a remote service entails sending private information to an untrusted provider. In addition, potential eavesdroppers can intercept the messages, thereby exposing the information. In this work, we explore the prospects of avoiding such data exposure at the level of text manipulation. We focus on text classification models, examining various token mapping and contextualized manipulation functions in order to see whether classifier accuracy may be maintained while keeping the original text unrecoverable. We find that although some token mapping functions are easy and straightforward to implement, they heavily influence performance on the downstream task, and via a sophisticated attacker can be reconstructed. In comparison, contextualized manipulation provides an improvement in performance.

heading: 1 Introduction
text: Large language models (LLMs) have greatly advanced the field of NLP in recent years, exhibiting exceptional proficiency across a wide spectrum of tasks, including dependency parsing (Duong et al., 2015), natural language understanding (Dong et al., 2019), automatic question-answering (OpenAI, 2021; Ouyang et al., 2022), machine translation (Dabre et al., 2020), text classification (Minaee et al., 2021), and many more (Li et al., 2022). However, this success comes with potential privacy risks, as the models process vast amounts of data that might contain personal or sensitive information and may abuse or leak it. For instance, information can be leaked by model inversion (Li et al., 2017), re-identification techniques (Lison et al., 2021; Ben Cheikh Larbi et al., 2023), exploitation of feature memorization within the LLM (Carlini et al., 2021), and more. Offering LLMs as cloud services, such as ChatGPT (Ouyang et al., 2022), might also impose potential threats to privacy if the server exhibits a semi-honest stance, actively
seeking to glean more insights from the input than is appropriate or by a possible eavesdropper intercepting the input sent to the server.
In order to safeguard privacy, many privacypreserving techniques have been proposed, based on the local differential privacy framework (LDP; Arachchige et al., 2019). In this framework, the user applies a differential privacy mechanism, which can be hosted on a local server, and then sends the privatized data to the remote server. This approach doesn’t require trust from the remote server, and protects the data against potential eavesdroppers. In general, any privacy mechanism can be applied at one or several components of the LLM pipeline. Figure 1 depicts these components: at the text level (text privatization), after the tokenization process (token privatization), after the initial embedding lookup (token embedding privatization), or after applying several layers of the encoder (sequence embedding privatization).
Currently, most privacy-preserving strategies focus on incorporating noise into sequence embedding vectors. The rationale behind this strategy is to minimize the privacy-preserving technique’s impact on the downstream task. Specifically, most systems first obtain a sequence embedding repre-
29
sentation, either by assuming partial access to the remote model (Zhou et al., 2022; Lyu et al., 2020; Qu et al., 2021) or by using a dedicated model to create these embeddings (Li et al., 2018; Coavoux et al., 2018; Mosallanezhad et al., 2019; Plant et al., 2021; Zhou et al., 2023). Afterwards, random noise is incorporated into the embeddings, thus concealing the original input. However, this approach relies on partial access to the remote model, on the ability to provide input to the remote model in vector form, or on sufficient computational and memory resources on the user’s end. These are often not the case. In addition, Kugler et al. (2021) showed that publishing a model’s encoder along with the contextualized embeddings allows an adversary to generate data to train a decoder with a high level of reconstruction accuracy, making these approaches highly susceptible to violation of privacy.
We propose a secure way to use LLMs without assuming access to their parameters. In our framework, both input and output for the privacyproviding mechanism must be given in a token sequence format, eliminating the need to intervene with the LLM’s pre-training procedure or text processing. We focus on applying privacy preservation techniques at the token level, corresponding to layer (B) in Figure 1.
Specifically, we propose two privacy-preserving techniques based on manipulating the input token sequence. The first set of techniques relies on naïve rules of token substitution. The second is based on leveraging contextual information to strategically replace tokens, aiming to retain as much actionable information as possible for the classifier to minimize the impact on the performance of the downstream task.
We test these techniques both for their impact on the downstream task accuracy and for their resilience against reconstruction attacks. We find that replacing tokens based on simple rules is easy for a knowledgeable attacker to reverse, while manipulating tokens based on contextual information can enhance privacy without sacrificing much of the performance.1

heading: 2 Lossy Mapping
text: In order to protect against potential eavesdropping by a middle party, under the assumption that the
1Our code is available at: https://github.com/MeLeLBGU/ Privacy-Preserving-Token-Manipulation.
layers of LLMs are inaccessible to the local device, we start by employing several mapping functions on the tokens of the input text available at the local device. Our initial, naïve mapping functions introduce a random noise component that follows a specific rule: the vocabulary is partitioned into pairs of tokens (u, v), or triplets (u, v, z), and when encountered in an input text to be manipulated, all tokens are mapped to a single representative token of their tuple, without loss of generality u. This strategy produces outputs that are inherently ambiguous, blocking any potential eavesdroppers from recovering the original input text deterministically, given that a many-to-one mapping is not invertible. The only available recourse for an attacker is a statistical strategy, which imposes assumptions on the properties of the input, for example that it was grammatical English text written by a speaker with high proficiency. Indeed, even if an eavesdropper obtains full information of the privacy system, i.e. the partition into token tuples and each tuple’s representative token, each mapped sequence of length m still generates a candidate set of 2m or 3m possible permutations (depending on tuple size) through which the attacker must search. We will examine the practical implications of this large search space later in the section.
For our stated use case of manipulating text being input into a sequence classifier operating atop an LLM, there are two distinct scenarios depending on when we may apply our manipulation. The first scenario involves applying the manipulation process only during the inference phase of a model trained on regular, unmanipulated text, which we will refer to as the TEST case. This operation mode simulates a query sent by a user to an alreadytrained model, such as a user interacting with ChatGPT or another model allowing only inference text interaction via user interface or an API. In the second scenario, which we call ALL, we also apply the manipulation during the training phase, protecting sensitive information in the training data, hoping that the inference phase will now leverage the model’s ability to handle manipulated input as expected and produce better results. In this scenario the model does not inadvertently learn or memorize the sensitive data during the training process, nor does it spend learning resources on tokens never to be seen during inference, but since it is not always possible to assume its availability, we perform our experiments in both settings.
When protecting the original input data, it is essential for the mapper to have minimal impact on the performance of the downstream task, defining the fundamental trade-off in our study. Therefore, the selection process for grouping tokens and selecting each tuple’s representative token is crucial, as it aims to both minimize the mapping’s effect on the downstream task and hinder the attacker’s ability to uncover the original text. We consider the following mapping functions:
Purely random mapping the selection of the token pairs tuples from the vocabulary and of each tuple’s representative is uniformly random.
High-frequency mapping token pairs are selected based on their frequency of occurrence in a tokenized corpus, such as Wikipedia (Foundation, 2023). This involves pairing a higher-frequency token with a lower-frequency token, with the higherfrequency token being designated as the representative. In our mapper, given a vocabulary of even size V , sorted by descending frequency, each token with rank 1 ≤ k ≤ V2 is paired with the token of rank k + V2 . While selecting the high-frequency token as the representative may have a lesser impact on the downstream task, it could potentially weaken the privacy-preserving characteristics, depending on the knowledge possessed by the attacker.
Low-frequency mapping the process is similar to that of the higher-frequency mapper, except that the lower-frequency token is chosen as the representative. Opting for less-frequent tokens as representatives can aid in preserving privacy, but it will likely harm the downstream task.
Due to the simplicity of these mapping strategies, we consider them baselines for further research
and developing better, potentially language-aware strategies. In addition, these mapping functions can easily be generalized to larger tuples, expanding the search space even further, but greatly harming downstream task performance as a result of a much more restricted active vocabulary.

heading: 2.1 Task Performance
text: To assess the impact of the baseline models on downstream task performance, we use two datasets for sequence classification: SST2 (Socher et al., 2013) and IMDb (Maas et al., 2011). The base model chosen was RoBERTa (Liu et al., 2019), a state-of-the-art encoder language model known for its strong performance in sequence classification tasks. In Table 1, we present the results of four baselines on the two datasets, compared with the null mapping results labeled “Plain text”. Perhaps unsurprisingly, the high-frequency baseline achieved the highest accuracy, most likely due to the fact that retaining high-frequency tokens while removing low-frequency ones results in a relatively small number of tokens altered in the datasets. In both datasets this number is roughly 6%, compared with low-frequency mapping’s complement of 94% and with the randomly-selected sets’ 50% and 67%, giving a correlative relationship between this number and the performance level: the fewer tokens are altered, the better the model performs. This effect is much more pronounced when only the test set is affected, and the model is dealing not only with loss of information but also with out-of-distribution behavior. In absolute terms, we find it remarkable that this alteration of a non-negligible portion of tokens causes only a 1–2 percentage point reduction in performance for the IMDb dataset and still under 5 points for SST2.
In Table 2, we present an example of the outcome of applying the 2-Random and the Highfreq privatization techniques on a random phrase (“no apparent joy”) from the SST2 dataset. As ex-
Input: what a nice day what what nice unicorn
pected, the 2-random baseline produces a random sequence of words, whereas the high-frequency mapper leaves the phrase unchanged as the tokens in the original sequence are frequent.

heading: 2.2 Brute-force Attacker
text: Although the many-to-one mapping function introduces some form of protection against data leakage, in practice, reconstructing the original text might be relatively straightforward under certain circumstances. In particular, if an “oracle” attacker has access to the token pairings, it can theoretically determine the original text from the pool of 2m possible permutations by applying a generative LLM such as GPT (Radford et al., 2019) and picking the most probable sequence. However, generating and evaluating all 2m permutations is impractical even for small values of m due to the computational complexity involved. To mitigate this challenge, alternative approaches, such as employing heuristics or utilizing statistical methods, can be explored to narrow down the potential candidates for the original text.
To cope with this task, we describe a heuristic approach to reducing the search space based on beam search (Eisenstein, 2019, §11.3.1) and nucleus sampling (Holtzman et al., 2019). In each step of the process, candidates are generated based on the prefixes of tokens that were produced in the previous steps. In the case of token pairs, each prefix sequence is followed by one of two candidate tokens for the next step based on the known (oracle) token pair that the observed representa-
tive token belongs to. Unlike conventional beam search, where a fixed number of candidates is retained following each step, we opt for a dynamic approach inspired by nucleus sampling, made possible since the scores for each of the two tokens reflect a generative probabilistic process where the relative probability of each interim token sequence on the beam can be estimated and used for dropping highly unlikely sequence prefixes. This means that the number of candidates remaining on the beam varies at each step, adapting to their likelihood and ensuring flexibility in the selection process. We estimate the likelihood of each candidate prefix using a language model.2 After all prefixes on the beam have been scored, we remove the least probable candidates such that the total probability of the remaining candidates exceeds a certain threshold π set by computational constraints but maintaining discoverability. Since the probability of a sequence cannot exceed that of its prefix, the process guarantees that complete sequences that are likely are not being discarded before getting the chance to be fully generated. Overall, this process effectively eliminates highly unlikely candidates, dramatically reducing the search space during its application and streamlining the computational efforts.
This process is illustrated in Figure 2. The “oracle” attacker gains access to the remapped words: (what,a)→ a, (nice, is)→ nice, (day, unicorn)→ unicorn. In the first step, two initial candidates (what and a) are generated based
2https://github.com/simonepri/ lm-scorer
on the first observed token (what). Following the described process, each prefix is evaluated via an LLM to determine its probability, for instance, the probability of what being the first word is 80% when considering the possible set {[s] what, [s] a}. This process is repeated, and the candidates with low probability are removed, such that the total probability of the remaining candidates is above 85%, as indicated by the red boxes. Finally, the probability of the sequence what a beautiful day is the highest, thus the “oracle” attacker returns it as the inferred original text. We note that the low-frequency and high-frequency mappers, despite their differences in representative token selection, will demonstrate equivalent safeguarding mechanisms against this attacker since the attacker does not factor in the choice of the representative token and examines all potential candidates in its effort to uncover the original text.

heading: 2.3 Resilience Against Reconstruction Attacks
text: In Table 3, we present the outcomes of the attacker’s endeavors to reveal the original text from the three techniques: 2-Random, 3-Random, and High-freq (equivalent to Low-freq for a knowledgeable attacker). We report the mean reciprocal rank (MRR) of the correct sequences, the rate of the actual input sequence ranking among the top 5 predictions (Pr@5), and the token-level edit distance between the produced top prediction and the original sequence. The relative success of the mappers in thwarting the oracle attacks on the IMDb dataset compared to SST2 can be attributed to the average token sequence length (m̄), which is 65 and 12, respectively. As sequence length increases, the attacker’s task of uncovering the original text becomes more challenging.
Our results indicate that the naïve baselines are overly simplistic and allow an easy and straight-
forward reconstruction, even within a vast search space (although attacker knowledge of the mapping specifications is required). In cases where performance on the task remains close to that of unmapped text, the recovery price is too high to neglect. Having said that, the computational complexity of applying the naïve baselines is relatively low, and the greatly reduced active vocabulary brings great savings in parameter budgets, which embedding tables often dominate. In a less powerful attack environment, this would make them an efficient choice for preserving privacy on low-resource devices. We expect future work on more principled many-to-one static mappings would be able to improve both task performance and resilience to attackers, while work on attack strategies can present challenges hitherto unseen.

heading: 3 STENCIL Privacy Preservation
text: In the context of protecting privacy within NLP practices, a widely adopted approach for implementing local differential privacy involves introducing a controlled level of noise into different components of the model, effectively concealing the original input. These components may include sequence embeddings, token embeddings, or the tokens themselves (Mosallanezhad et al., 2019; Feyisetan et al., 2020; Lyu et al., 2020; Qu et al., 2021; Zhou et al., 2022). However, in essence, the success of models in most NLP tasks is primarily attributed to their effective utilization of contextual information. Moreover, our study focuses on token-level privacy preservation, i.e., we assume that the parameters of the LLMs are inaccessible, making the importance of contextual information more pronounced. Therefore, a fundamental limitation associated with incorporating noise is the exclusion of contextual information when defining the noise. This omission may hinder the potential benefits contextual details can offer for maintaining the performance of the downstream tasks.
Given this limitation, we propose a new privacy preservation technique, which we call STENCIL.3 With this technique, a mapped token in a sequence “absorbs” information from adjacent tokens to form a new context-aware token, effectively concealing the original token while retaining information beneficial for maintaining task performance.
3This term hails from numerical analysis (Spotz, 1995), where it denotes a computation that involves the surrounding values.
In order to generate the new contextualized token tk → t′k, we first retrieve an embedding vector representation of the neighborhood, of size n+1, containing the tokens ti, ∀i ∈ {k − n/2 . . . k + n/2} using some embedding lookup table E ∈ RV×d, which can be trained independently in a preliminary step or obtained from an available model such as the target model itself. We then subject the n+1 embedding vector representations to a weighted transformation and incorporate them to form a new “quasi-embedding” vector ∑k+n/2 i=k−n/2 fi ·E[ti]. Finally, we return the token t′k that is closest to the quasi-embedding vector in the embedding space, based on cosine-similarity or euclidean distance computation, as an output. To further enhance privacy, we ensure that the new token is different from the original one. Formally, the process can be defined as follows:
t′k = argmin tj∈V ∥∥∥∥∥∥ E[tj ]− k+n 2∑
i=k−n 2
fi ·E[ti] ∥∥∥∥∥∥ , (1)
where V is the vocabulary and fi is the weighted transformation function of the tokens such that∑k+n
2 i=k−n 2 fi = 1.
The level of privacy enhancement and its impact on the downstream task by employing the STENCIL method can be managed by adjusting the window size and the properties of the weighted function f . In our study, we use the gaussian smoothing function as the weighted function. Consequently, the standard deviation, σ, plays a crucial role in the performance and amount of privacy achieved.
As a baseline for our proposed technique, we adopt Qu et al. (2021)’s proposed privacypreserving technique. In contrast to our proposed technique, this approach does not consider context but rather incorporates random noise into token embeddings to enhance privacy. The random noise is obtained by multiplying a sample from a Gamma distribution Γ(d, 1/η) and a uniform sample from a unit hypersphere, where η corresponds to the amount of noise introduced to the original token and d is the dimension of the embedding space.
We note that the most time-intensive operation in both STENCIL and noise-based techniques involves searching for the closest token to the perturbed quasi-embedding vector, while all other operations are negligible in comparison. Overall, the average computational cost per token is 0.005 seconds on two 16-core 3.2 GHz AMD EPYC 7343 Milan processors.

heading: 3.1 Downstream Task Performance
text: To evaluate the impact of the STENCIL method and of the noise-based technique on model performance, we repeat the methodology outlined in §2: we use RoBERTa as the base model and for the word embedding lookup table; SST2 and IMDb as the datasets; and the two distinct application cases: manipulating tokens on inference data only (TEST), and applying the technique during the training phase as well (ALL). However, as these privacy techniques exhibit a realistic case, we also test it on an encoder-decoder model T5-small (Raffel et al., 2020) on the QNLI task from the GLUE dataset (Wang et al., 2019). As in Raffel et al. (2020), we concatenate the question and its corresponding sentence to form a single sequence that serves as the input, while the target prediction is either “entailment” or “not_entailment”, thus forming a classification task.
We report two distinct manipulations based on STENCIL. The first approach follows the process described in (1), where the weighting function fi is derived from a gaussian smoothing with a standard deviation of σ = 0.8 and the number of adjacent tokens considered is set to nine (four from each side, as well as the target token). To preserve model performance, the tokenizer and embedding lookup table used to derive the new tokens were sourced directly from the model being trained. In the second approach, which we call punctuated STENCIL,
denoted STENCILp, we exclude the target token from the computation of the quasi-embedding vector in (1) by setting fk to zero. This exclusion significantly diminishes the attacker’s ability to reconstruct the original token at the expense of performance. The standard deviation we consider for this approach is σ = 1.0, with a window width of nine. For the baseline approach, we report the two best η values: η = 100, 150.
The results are presented in Table 4. The best accuracy is obtained with Noise (η = 150) in the ALL case, where higher values of η yield smaller noise. This comes at great cost in discoverability, to be presented in §3.2.
Compared to the sentiment analysis tasks (SST2 and IMDb), the QNLI task presents greater challenges, primarily due to the complex logical connections required for the model to discern entailment between the given sentence and question. Therefore, despite its instance sizes being very similar to those of IMDb (62 vs. 65), the fact that noise-based perturbations disrupt contextual and semantic information leads to a significant decrease in the model’s ability to discern the logical connections between the parts of the input. This results in a more pronounced performance degradation compared to the long-sequenced IMDb on the TEST case. In contrast, training the model on the noisy data (the ALL setup) proves effective in overcoming this effect, leading to improved results for T5-small.
In Table 2, we present an example of the outcome of applying STENCIL, STENCILp, and the noise mapper on a random phrase from the SST2 dataset. The noise mapper with a value of η = 150 introduces negligible noise, thus producing a similar sequence to the original one. The STENCILbased techniques also produce a similar sequence, although STENCILp swaps the positions of some tokens as a direct result of excluding the target token from the obfuscation process.

heading: 3.2 Nearest-neighbor Reconstruction
text: An attacker can potentially exploit the fact that these techniques utilize contextualized tokens and the selection of the nearest token as the quasiembedding vector (Qu et al., 2021). Specifically, given the new, perturbed token t′, the attacker can obtain the embedding vector representation E[t′]. Afterward, the attacker can calculate the cosine similarity between E[t′] and the other embedding
vector representations (E[t] where t ∈ V\{t′}) and statistically determine the original token. Hence, to test the resilience of these techniques against token inversion attacks, we implement the described attacker and report whether the original token was found to be one of the nearest five (Pr@5).
The success rate of the attacker for the four techniques is presented in Table 4. While the minor alterations in the original tokens contributed to performance improvement in the noise mapper, it is found to be highly vulnerable to simple reconstruction attacks. Taking into account both accuracy and resilience against reconstruction attacks, the STENCIL method demonstrates better results, with a marginal trade-off in performance.

heading: 3.3 Impact of Window Size and σ
text: To better understand the impact of the window size and the value of σ on the accuracy and resilience against reconstruction attack, we conduct tuning experiments for these values. In Table 5, we present the accuracy results of the STENCIL method ap-
plied to the SST2, IMDb, and QNLI datasets, with varying values of σ while keeping the window size constant at 9. Low values of σ imply prioritizing the central token. Hence, the new token will likely be similar to the original token, yielding the highest accuracy results but rendering it more susceptible to reconstruction attacks. In contrast, opting for a higher value of σ will reduce the accuracy results while providing better resilience against the nearest-neighbor reconstruction attacks.
In Table 6, we present the accuracy results of STENCIL on the datasets, examining the impact of different window sizes while maintaining a constant value of σ = 0.2. Given that the average number of tokens in the SST2 dataset is below 10, incorporating 11 neighbors is likely not advantageous, making a window size of 9 yield optimal results. Similarly, for the IMDb and QNLI datasets, optimal results are achieved when considering 11 neighbors. Nevertheless, in comparison to the variable values of σ, the window size exerts a lesser influence on the accuracy of the downstream task
and demonstrates no impact on privacy. This limited effect of the window size, in contrast to the influence of σ, stems from the primary influence of the original token on the downstream task. Consequently, considering more neighbors has a diminished impact.

heading: 4 Conclusion
text: In this paper, we propose several token manipulation methods to preserve privacy under the assumption that the model parameters are inaccessible. We first introduce four mappers that offer advantages compared to existing privacy-preserving techniques. These mappers operate independently of the LLM and the specific downstream task, resulting in a high degree of versatility. Additionally, their computational complexity is relatively low, making them efficient choices for privacy preservation on local, low-resource devices. However, these mappers harm the performance of the downstream tasks and can be easily reconstructed by a knowledgeable attacker.
The second mapper class we propose is based on utilizing contextualized information to maintain performance while obfuscating the original input text. This technique achieves higher privacy measures and has less impact on the downstream task, which makes it more applicable for cases where the downstream task is important. Nevertheless, opting for different weighted functions, such as ones based on a trained model, can further help improve both accuracy and privacy.
An inherent problem with existing privacypreserving techniques is their inability to maintain linguistic properties such as grammar and readability (as seen in Table 2) that are crucial for the performance of the model. Therefore, an additional avenue we plan to explore is application of these and similar rules in differential privacy techniques. For instance, following the application of random perturbations to an embedding vector, instead of simply returning the nearest token to the perturbed vector, one could consider returning a token with similar syntactic attributes, such as part of speech, or verbs with similar causative meanings or stable subcategorization frames.
Lastly, our experiments were limited to classification tasks in the English language. In future research, we intend to explore the effectiveness of these methods in generative tasks, across languages, and in multilingual settings.
Limitations
We demonstrated the privacy achieved by our methods empirically under one attacking scenario. Further comprehensive testing or mathematical proofs would enhance our understanding of the extent of privacy achieved.
An additional limitation of our proposed mechanism is the unchanged sentence length. This imposes a privacy breach in which an author who prefers writing longer or shorter sentences can be re-identified even when introducing random perturbations. Hence, another avenue in this research is reducing the amount of tokens by introducing, for example, a stride parameter to the STENCIL family of mappers. This parameter will determine how often tokens will be output, thus reducing the amount of tokens.

heading: Acknowledgments
text: We thank Niv Gilboa and Michael Elhadad for discussions on the fundamentals of this work. We thank the anonymous reviewers for their comments. This research was funded by the Israeli Ministry of Science and Technology (Grant 22/5451). Re’em Harel was supported by the Lynn and William Frankel Center for Computer Science.

heading: Future Work
text: In future research, we intend to explore the effectiveness of these methods in generative tasks, across languages, and in multilingual settings. Limitations
We demonstrated the privacy achieved by our methods empirically under one attacking scenario. Further comprehensive testing or mathematical proofs would enhance our understanding of the extent of privacy achieved. An additional limitation of our proposed mechanism is the unchanged sentence length. This imposes a privacy breach in which an author who prefers writing longer or shorter sentences can be re-identified even when introducing random perturbations. Hence, another avenue in this research is reducing the amount of tokens by introducing, for example, a stride parameter to the STENCIL family of mappers. This parameter will determine how often tokens will be output, thus reducing the amount of tokens