├── .gitignore
├── LICENSE
├── README.md
├── mink_prob.png
├── process_data.py
└── src
├── __pycache__
├── eval.cpython-39.pyc
└── options.cpython-39.pyc
├── eval.py
├── options.py
├── out
├── huggyllama
│ └── llama-13b_huggyllama
│ │ └── llama-7b
│ │ └── input
│ │ ├── auc.png
│ │ ├── auc.txt
│ │ ├── auc_google.txt
│ │ └── low_google.txt
└── text-davinci-003_huggyllama
│ └── llama-7b
│ └── input
│ ├── auc.png
│ └── auc.txt
└── run.py
/.gitignore:
--------------------------------------------------------------------------------
1 | ### AL ###
2 | #Template for AL projects for Dynamics 365 Business Central
3 | #launch.json folder
4 | .vscode/
5 | #Cache folder
6 | .alcache/
7 | #Symbols folder
8 | .alpackages/
9 | #Snapshots folder
10 | .snapshots/
11 | #Testing Output folder
12 | .output/
13 | #Extension App-file
14 | *.app
15 | #Rapid Application Development File
16 | rad.json
17 | #Translation Base-file
18 | *.g.xlf
19 | #License-file
20 | *.flf
21 | #Test results file
22 | TestResults.xml
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # :detective: Detecting Pretraining Data from Large Language Models
2 |
3 | This repository provides an original implementation of [Detecting Pretraining Data from Large Language Models](https://arxiv.org/pdf/2310.16789.pdf) by *Weijia Shi, *Anirudh Ajith, Mengzhou Xia, Yangsibo Huang, Daogao Liu
4 | , Terra Blevins
5 | , Danqi Chen
6 | , Luke Zettlemoyer
7 |
8 | [Website](https://swj0419.github.io/detect-pretrain.github.io/) | [Paper](https://arxiv.org/pdf/2310.16789.pdf) | [WikiMIA Benchmark](https://huggingface.co/datasets/swj0419/WikiMIA) | [BookMIA Benchmark](https://huggingface.co/datasets/swj0419/BookMIA) | [Detection Method Min-K% Prob](#🚀run-our-min-k%-prob-&-other-baselines)(see the following codebase)
9 |
10 | ## Overview
11 | We explore the **pretraining data detection problem**: given a piece of text and black-box access to an LLM without knowing the pretraining data, can we determine if the model was trained on the provided text?
12 | To faciliate the study, we built a dynamic benchmark **WikiMIA** to systematically evaluate detecting methods and proposed **Min-K% Prob** 🕵️, a method for detecting undisclosed pretraining data from large language models.
13 |
14 |
15 |
16 |
17 |
18 | :star: If you find our implementation and paper helpful, please consider citing our work :star: :
19 |
20 | ```bibtex
21 | @misc{shi2023detecting,
22 | title={Detecting Pretraining Data from Large Language Models},
23 | author={Weijia Shi and Anirudh Ajith and Mengzhou Xia and Yangsibo Huang and Daogao Liu and Terra Blevins and Danqi Chen and Luke Zettlemoyer},
24 | year={2023},
25 | eprint={2310.16789},
26 | archivePrefix={arXiv},
27 | primaryClass={cs.CL}
28 | }
29 | ```
30 |
31 | ## 📘 WikiMIA Datasets
32 |
33 | The **WikiMIA datasets** serve as a benchmark designed to evaluate membership inference attack (MIA) methods, specifically in detecting pretraining data from extensive large language models. Access our **WikiMIA datasets** directly on [Hugging Face](https://huggingface.co/datasets/swj0419/WikiMIA).
34 |
35 | #### Loading the Datasets:
36 |
37 | ```python
38 | from datasets import load_dataset
39 | LENGTH = 64
40 | dataset = load_dataset("swj0419/WikiMIA", split=f"WikiMIA_length{LENGTH}")
41 | ```
42 | * Available Text Lengths: `32, 64, 128, 256`.
43 | * *Label 0*: Refers to the unseen data during pretraining. *Label 1*: Refers to the seen data.
44 | * WikiMIA is applicable to all models released between 2017 to 2023 such as `LLaMA1/2, GPT-Neo, OPT, Pythia, text-davinci-001, text-davinci-002 ...`
45 |
46 | ## 📘 BookMIA Datasets for evaluating MIA on OpenAI models
47 |
48 | The BookMIA datasets serve as a benchmark designed to evaluate membership inference attack (MIA) methods, specifically in detecting pretraining data from OpenAI models that are released before 2023 (such as text-davinci-003). Access our **BookMIA datasets** directly on [Hugging Face](https://huggingface.co/datasets/swj0419/BookMIA).
49 |
50 | The dataset contains non-member and member data:
51 | - non-member data consists of text excerpts from books first published in 2023
52 | - member data includes text excerpts from older books, as categorized by Chang et al. in 2023.
53 |
54 |
55 | #### Loading the Datasets:
56 |
57 | ```python
58 | from datasets import load_dataset
59 | dataset = load_dataset("swj0419/BookMIA")
60 | ```
61 | * Available Text Lengths: `512`.
62 | * *Label 0*: Refers to the unseen data during pretraining. *Label 1*: Refers to the seen data.
63 | * WikiMIA is applicable to OpenAI models that are released before 2023 `text-davinci-003, text-davinci-002 ...`
64 |
65 |
66 |
67 | ## 🚀 Run our Min-K% Prob & Other Baselines
68 |
69 | Our codebase supports many models: Whether you're using **OpenAI models** that offer logits or models from **Huggingface**, we've got you covered:
70 |
71 | - **OpenAI Models**:
72 | - `text-davinci-003`
73 | - `text-davinci-002`
74 | - ...
75 |
76 | - **Huggingface Models**:
77 | - `meta-llama/Llama-2-70b`
78 | - `huggyllama/llama-70b`
79 | - `EleutherAI/gpt-neox-20b`
80 | - ...
81 |
82 | 🔐 **Important**: When using OpenAI models, ensure to add your API key at `Line 38` in `run.py`:
83 | ```python
84 | openai.api_key = "YOUR_API_KEY"
85 | ```
86 | Use the following command to run the model:
87 | ```bash
88 | python src/run.py --target_model text-davinci-003 --ref_model huggyllama/llama-7b --data swj0419/WikiMIA --length 64
89 | ```
90 | 🔍 Parameters Explained:
91 | * Target Model: Set using --target_model. For instance, --target_model huggyllama/llama-70b.
92 |
93 | * Reference Model: Defined using --ref_model. Example: --ref_model huggyllama/llama-7b.
94 |
95 | * Data Length: Define the length for the WikiMIA benchmark with --length. Available options: 32, 54, 128, 256.
96 |
97 | 📌 Note: ***For optimal results, use fixed-length inputs with our Min-K% Prob method*** (When you evalaute Min-K% Prob method on your own dataset, make sure the input length of each example is the same.)
98 |
99 | 📊 Baselines: Our script comes with the following baselines: PPL, Calibration Method, PPL/zlib_compression, PPL/lowercase_ppl
100 |
101 |
--------------------------------------------------------------------------------
/mink_prob.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/swj0419/detect-pretrain-code/a5048f93c4fa6491aab0638bb3e6fd5a662d7698/mink_prob.png
--------------------------------------------------------------------------------
/process_data.py:
--------------------------------------------------------------------------------
1 | from datasets import load_dataset
2 | from datasets import Dataset
3 | from ipdb import set_trace as bp
4 | # from options import Options
5 | from src.eval import *
6 |
7 |
8 | # data: different length:
9 | def process_each_dict_length_data(data, length=32):
10 | new_data = []
11 | for ex in data:
12 | ex_copy = ex.copy()
13 | if len(ex_copy["input"].split()) < length:
14 | continue
15 | else:
16 | ex_copy["input"] = " ".join(ex_copy["input"].split()[:length])
17 | new_data.append(ex_copy)
18 | return new_data
19 |
20 | def change_type(data):
21 | new_data = {"input": [], "label": []}
22 | for ex in data:
23 | ex["label"] = int(ex["label"])
24 | new_data["input"].append(ex["input"])
25 | new_data["label"].append(ex["label"])
26 | return new_data
27 |
28 | if __name__ == "__main__":
29 | dataset = load_jsonl("/fsx-onellm/swj0419/attack/detect-pretrain-code/data/wikimia.jsonl")
30 | # bp()
31 | data = convert_huggingface_data_to_list_dic(dataset)
32 | for length in [128, 256]:
33 | new_data = process_each_dict_length_data(data, length=length)
34 | print(f"length {length} data size: {len(new_data)}")
35 | dump_jsonl(new_data, f"data/WikiMIA_length{length}.jsonl")
36 | huggingface_dataset = Dataset.from_dict(change_type(new_data))
37 | huggingface_dataset.push_to_hub("swj0419/WikiMIA", f"WikiMIA_length{length}")
38 |
39 |
40 |
--------------------------------------------------------------------------------
/src/__pycache__/eval.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/swj0419/detect-pretrain-code/a5048f93c4fa6491aab0638bb3e6fd5a662d7698/src/__pycache__/eval.cpython-39.pyc
--------------------------------------------------------------------------------
/src/__pycache__/options.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/swj0419/detect-pretrain-code/a5048f93c4fa6491aab0638bb3e6fd5a662d7698/src/__pycache__/options.cpython-39.pyc
--------------------------------------------------------------------------------
/src/eval.py:
--------------------------------------------------------------------------------
1 | import logging
2 | logging.basicConfig(level='ERROR')
3 | import numpy as np
4 | from tqdm import tqdm
5 | import json
6 | from collections import defaultdict
7 | import matplotlib.pyplot as plt
8 | from sklearn.metrics import auc, roc_curve
9 | import matplotlib
10 | import random
11 |
12 |
13 | matplotlib.rcParams['pdf.fonttype'] = 42
14 | matplotlib.rcParams['ps.fonttype'] = 42
15 |
16 |
17 | matplotlib.rcParams['pdf.fonttype'] = 42
18 | matplotlib.rcParams['ps.fonttype'] = 42
19 |
20 | # plot data
21 | def sweep(score, x):
22 | """
23 | Compute a ROC curve and then return the FPR, TPR, AUC, and ACC.
24 | """
25 | fpr, tpr, _ = roc_curve(x, -score)
26 | acc = np.max(1-(fpr+(1-tpr))/2)
27 | return fpr, tpr, auc(fpr, tpr), acc
28 |
29 |
30 | def do_plot(prediction, answers, sweep_fn=sweep, metric='auc', legend="", output_dir=None):
31 | """
32 | Generate the ROC curves by using ntest models as test models and the rest to train.
33 | """
34 | fpr, tpr, auc, acc = sweep_fn(np.array(prediction), np.array(answers, dtype=bool))
35 |
36 | low = tpr[np.where(fpr<.05)[0][-1]]
37 | # bp()
38 | print('Attack %s AUC %.4f, Accuracy %.4f, TPR@5%%FPR of %.4f\n'%(legend, auc,acc, low))
39 |
40 | metric_text = ''
41 | if metric == 'auc':
42 | metric_text = 'auc=%.3f'%auc
43 | elif metric == 'acc':
44 | metric_text = 'acc=%.3f'%acc
45 |
46 | plt.plot(fpr, tpr, label=legend+metric_text)
47 | return legend, auc,acc, low
48 |
49 |
50 | def fig_fpr_tpr(all_output, output_dir):
51 | print("output_dir", output_dir)
52 | answers = []
53 | metric2predictions = defaultdict(list)
54 | for ex in all_output:
55 | answers.append(ex["label"])
56 | for metric in ex["pred"].keys():
57 | if ("raw" in metric) and ("clf" not in metric):
58 | continue
59 | metric2predictions[metric].append(ex["pred"][metric])
60 |
61 | plt.figure(figsize=(4,3))
62 | with open(f"{output_dir}/auc.txt", "w") as f:
63 | for metric, predictions in metric2predictions.items():
64 | legend, auc, acc, low = do_plot(predictions, answers, legend=metric, metric='auc', output_dir=output_dir)
65 | f.write('%s AUC %.4f, Accuracy %.4f, TPR@0.1%%FPR of %.4f\n'%(legend, auc, acc, low))
66 |
67 | plt.semilogx()
68 | plt.semilogy()
69 | plt.xlim(1e-5,1)
70 | plt.ylim(1e-5,1)
71 | plt.xlabel("False Positive Rate")
72 | plt.ylabel("True Positive Rate")
73 | plt.plot([0, 1], [0, 1], ls='--', color='gray')
74 | plt.subplots_adjust(bottom=.18, left=.18, top=.96, right=.96)
75 | plt.legend(fontsize=8)
76 | plt.savefig(f"{output_dir}/auc.png")
77 |
78 |
79 | def load_jsonl(input_path):
80 | with open(input_path, 'r') as f:
81 | data = [json.loads(line) for line in tqdm(f)]
82 | random.seed(0)
83 | random.shuffle(data)
84 | return data
85 |
86 | def dump_jsonl(data, path):
87 | with open(path, 'w') as f:
88 | for line in tqdm(data):
89 | f.write(json.dumps(line) + "\n")
90 |
91 | def read_jsonl(path):
92 | with open(path, 'r') as f:
93 | return [json.loads(line) for line in tqdm(f)]
94 |
95 | def convert_huggingface_data_to_list_dic(dataset):
96 | all_data = []
97 | for i in range(len(dataset)):
98 | ex = dataset[i]
99 | all_data.append(ex)
100 | return all_data
--------------------------------------------------------------------------------
/src/options.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import os
3 | from pathlib import Path
4 | import logging
5 |
6 | logger = logging.getLogger(__name__)
7 |
8 | class Options():
9 | def __init__(self):
10 | self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
11 | self.initialize_parser()
12 |
13 | def initialize_parser(self):
14 | self.parser.add_argument('--target_model', type=str, default="text-davinci-003", help="the model to attack: huggyllama/llama-65b, text-davinci-003")
15 | self.parser.add_argument('--ref_model', type=str, default="huggyllama/llama-7b")
16 | self.parser.add_argument('--output_dir', type=str, default="out")
17 | self.parser.add_argument('--data', type=str, default="swj0419/WikiMIA", help="the dataset to evaluate: default is WikiMIA")
18 | self.parser.add_argument('--length', type=int, default=64, help="the length of the input text to evaluate. Choose from 32, 64, 128, 256")
19 | self.parser.add_argument('--key_name', type=str, default="input", help="the key name corresponding to the input text. Selecting from: input, parapgrase")
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/src/out/huggyllama/llama-13b_huggyllama/llama-7b/input/auc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/swj0419/detect-pretrain-code/a5048f93c4fa6491aab0638bb3e6fd5a662d7698/src/out/huggyllama/llama-13b_huggyllama/llama-7b/input/auc.png
--------------------------------------------------------------------------------
/src/out/huggyllama/llama-13b_huggyllama/llama-7b/input/auc.txt:
--------------------------------------------------------------------------------
1 | ppl AUC 0.5865, Accuracy 0.6090, TPR@0.1%FPR of 0.2308
2 | ppl/Ref_ppl (calibrate PPL to the reference model) AUC 0.7019, Accuracy 0.7163, TPR@0.1%FPR of 0.4231
3 | ppl/lowercase_ppl AUC 0.5753, Accuracy 0.5994, TPR@0.1%FPR of 0.1538
4 | ppl/zlib AUC 0.7179, Accuracy 0.7179, TPR@0.1%FPR of 0.3077
5 | Min_20.0% Prob AUC 0.6186, Accuracy 0.6474, TPR@0.1%FPR of 0.1538
6 | Min_30.0% Prob AUC 0.6106, Accuracy 0.6250, TPR@0.1%FPR of 0.1538
7 | Min_40.0% Prob AUC 0.5913, Accuracy 0.5929, TPR@0.1%FPR of 0.1923
8 | Min_50.0% Prob AUC 0.5833, Accuracy 0.6106, TPR@0.1%FPR of 0.2308
9 | Min_60.0% Prob AUC 0.5849, Accuracy 0.6106, TPR@0.1%FPR of 0.2308
10 |
--------------------------------------------------------------------------------
/src/out/huggyllama/llama-13b_huggyllama/llama-7b/input/auc_google.txt:
--------------------------------------------------------------------------------
1 | ppl 0.663
2 | ppl/Ref_ppl (calibrate PPL to the reference model) 0.626
3 | ppl/lowercase_ppl 0.58
4 | ppl/zlib 0.619
5 | mean 0.663
6 | Min_0.2% Prob 0.677
7 | Min_0.3% Prob 0.678
8 | Min_0.4% Prob 0.675
9 | Min_0.5% Prob 0.67
10 | Min_0.6% Prob 0.666
11 |
--------------------------------------------------------------------------------
/src/out/huggyllama/llama-13b_huggyllama/llama-7b/input/low_google.txt:
--------------------------------------------------------------------------------
1 | ppl 0.086
2 | ppl/Ref_ppl (calibrate PPL to the reference model) 0.074
3 | ppl/lowercase_ppl 0.069
4 | ppl/zlib 0.137
5 | mean 0.086
6 | Min_0.2% Prob 0.127
7 | Min_0.3% Prob 0.104
8 | Min_0.4% Prob 0.096
9 | Min_0.5% Prob 0.089
10 | Min_0.6% Prob 0.089
11 |
--------------------------------------------------------------------------------
/src/out/text-davinci-003_huggyllama/llama-7b/input/auc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/swj0419/detect-pretrain-code/a5048f93c4fa6491aab0638bb3e6fd5a662d7698/src/out/text-davinci-003_huggyllama/llama-7b/input/auc.png
--------------------------------------------------------------------------------
/src/out/text-davinci-003_huggyllama/llama-7b/input/auc.txt:
--------------------------------------------------------------------------------
1 | ppl AUC 0.7420, Accuracy 0.7452, TPR@0.1%FPR of 0.3846
2 | ppl/Ref_ppl (calibrate PPL to the reference model) AUC 0.2949, Accuracy 0.5176, TPR@0.1%FPR of 0.0769
3 | ppl/lowercase_ppl AUC 0.6747, Accuracy 0.6747, TPR@0.1%FPR of 0.3077
4 | ppl/zlib AUC 0.7564, Accuracy 0.7356, TPR@0.1%FPR of 0.4231
5 | Min_20.0% Prob AUC 0.7724, Accuracy 0.8237, TPR@0.1%FPR of 0.4231
6 | Min_30.0% Prob AUC 0.7660, Accuracy 0.8237, TPR@0.1%FPR of 0.3846
7 | Min_40.0% Prob AUC 0.7660, Accuracy 0.8029, TPR@0.1%FPR of 0.4231
8 | Min_50.0% Prob AUC 0.7468, Accuracy 0.7644, TPR@0.1%FPR of 0.3846
9 | Min_60.0% Prob AUC 0.7420, Accuracy 0.7452, TPR@0.1%FPR of 0.3846
10 |
--------------------------------------------------------------------------------
/src/run.py:
--------------------------------------------------------------------------------
1 | import logging
2 | logging.basicConfig(level='ERROR')
3 | import numpy as np
4 | from pathlib import Path
5 | import openai
6 | import torch
7 | import zlib
8 | from transformers import AutoTokenizer, AutoModelForCausalLM
9 | from tqdm import tqdm
10 | import numpy as np
11 | from datasets import load_dataset
12 | from options import Options
13 | from eval import *
14 |
15 |
16 | def load_model(name1, name2):
17 | if "davinci" in name1:
18 | model1 = None
19 | tokenizer1 = None
20 | else:
21 | model1 = AutoModelForCausalLM.from_pretrained(name1, return_dict=True, device_map='auto')
22 | model1.eval()
23 | tokenizer1 = AutoTokenizer.from_pretrained(name1)
24 |
25 | if "davinci" in name2:
26 | model2 = None
27 | tokenizer2 = None
28 | else:
29 | model2 = AutoModelForCausalLM.from_pretrained(name2, return_dict=True, device_map='auto')
30 | model2.eval()
31 | tokenizer2 = AutoTokenizer.from_pretrained(name2)
32 | return model1, model2, tokenizer1, tokenizer2
33 |
34 | def calculatePerplexity_gpt3(prompt, modelname):
35 | prompt = prompt.replace('\x00','')
36 | responses = None
37 | # Put your API key here
38 | openai.api_key = "YOUR_API_KEY" # YOUR_API_KEY
39 | while responses is None:
40 | try:
41 | responses = openai.Completion.create(
42 | engine=modelname,
43 | prompt=prompt,
44 | max_tokens=0,
45 | temperature=1.0,
46 | logprobs=5,
47 | echo=True)
48 | except openai.error.InvalidRequestError:
49 | print("too long for openai API")
50 | data = responses["choices"][0]["logprobs"]
51 | all_prob = [d for d in data["token_logprobs"] if d is not None]
52 | p1 = np.exp(-np.mean(all_prob))
53 | return p1, all_prob, np.mean(all_prob)
54 |
55 |
56 | def calculatePerplexity(sentence, model, tokenizer, gpu):
57 | """
58 | exp(loss)
59 | """
60 | input_ids = torch.tensor(tokenizer.encode(sentence)).unsqueeze(0)
61 | input_ids = input_ids.to(gpu)
62 | with torch.no_grad():
63 | outputs = model(input_ids, labels=input_ids)
64 | loss, logits = outputs[:2]
65 |
66 | '''
67 | extract logits:
68 | '''
69 | # Apply softmax to the logits to get probabilities
70 | probabilities = torch.nn.functional.log_softmax(logits, dim=-1)
71 | # probabilities = torch.nn.functional.softmax(logits, dim=-1)
72 | all_prob = []
73 | input_ids_processed = input_ids[0][1:]
74 | for i, token_id in enumerate(input_ids_processed):
75 | probability = probabilities[0, i, token_id].item()
76 | all_prob.append(probability)
77 | return torch.exp(loss).item(), all_prob, loss.item()
78 |
79 |
80 | def inference(model1, model2, tokenizer1, tokenizer2, text, ex, modelname1, modelname2):
81 | pred = {}
82 |
83 | if "davinci" in modelname1:
84 | p1, all_prob, p1_likelihood = calculatePerplexity_gpt3(text, modelname1)
85 | p_lower, _, p_lower_likelihood = calculatePerplexity_gpt3(text.lower(), modelname1)
86 | else:
87 | p1, all_prob, p1_likelihood = calculatePerplexity(text, model1, tokenizer1, gpu=model1.device)
88 | p_lower, _, p_lower_likelihood = calculatePerplexity(text.lower(), model1, tokenizer1, gpu=model1.device)
89 |
90 | if "davinci" in modelname2:
91 | p_ref, all_prob_ref, p_ref_likelihood = calculatePerplexity_gpt3(text, modelname2)
92 | else:
93 | p_ref, all_prob_ref, p_ref_likelihood = calculatePerplexity(text, model2, tokenizer2, gpu=model2.device)
94 |
95 | # ppl
96 | pred["ppl"] = p1
97 | # Ratio of log ppl of large and small models
98 | pred["ppl/Ref_ppl (calibrate PPL to the reference model)"] = p1_likelihood-p_ref_likelihood
99 |
100 |
101 | # Ratio of log ppl of lower-case and normal-case
102 | pred["ppl/lowercase_ppl"] = -(np.log(p_lower) / np.log(p1)).item()
103 | # Ratio of log ppl of large and zlib
104 | zlib_entropy = len(zlib.compress(bytes(text, 'utf-8')))
105 | pred["ppl/zlib"] = np.log(p1)/zlib_entropy
106 | # min-k prob
107 | for ratio in [0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]:
108 | k_length = int(len(all_prob)*ratio)
109 | topk_prob = np.sort(all_prob)[:k_length]
110 | pred[f"Min_{ratio*100}% Prob"] = -np.mean(topk_prob).item()
111 |
112 | ex["pred"] = pred
113 | return ex
114 |
115 | def evaluate_data(test_data, model1, model2, tokenizer1, tokenizer2, col_name, modelname1, modelname2):
116 | print(f"all data size: {len(test_data)}")
117 | all_output = []
118 | test_data = test_data
119 | for ex in tqdm(test_data):
120 | text = ex[col_name]
121 | new_ex = inference(model1, model2, tokenizer1, tokenizer2, text, ex, modelname1, modelname2)
122 | all_output.append(new_ex)
123 | return all_output
124 |
125 |
126 | if __name__ == '__main__':
127 | args = Options()
128 | args = args.parser.parse_args()
129 | args.output_dir = f"{args.output_dir}/{args.target_model}_{args.ref_model}/{args.key_name}"
130 | Path(args.output_dir).mkdir(parents=True, exist_ok=True)
131 |
132 | # load model and data
133 | model1, model2, tokenizer1, tokenizer2 = load_model(args.target_model, args.ref_model)
134 | if "jsonl" in args.data:
135 | data = load_jsonl(f"{args.data}")
136 | else: # load data from huggingface
137 | dataset = load_dataset(args.data, split=f"WikiMIA_length{args.length}")
138 | data = convert_huggingface_data_to_list_dic(dataset)
139 |
140 | all_output = evaluate_data(data, model1, model2, tokenizer1, tokenizer2, args.key_name, args.target_model, args.ref_model)
141 | fig_fpr_tpr(all_output, args.output_dir)
142 |
143 |
--------------------------------------------------------------------------------