weijunl commited on
Commit
d75b840
·
verified ·
1 Parent(s): f4e60e1

Upload DPST.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. DPST.py +292 -292
DPST.py CHANGED
@@ -1,293 +1,293 @@
1
-
2
- # This file is taken from the original DPST implementation by Meisenbacher et al.
3
- # Paper: https://aclanthology.org/2025.emnlp-main.455/
4
- # Source: https://github.com/sjmeis/DPST
5
-
6
- import os
7
- import weaviate
8
- from weaviate.classes.query import MetadataQuery, Filter
9
-
10
- from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLM, pipeline
11
- from sentence_transformers import util
12
-
13
- os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
14
- from openie import StanfordOpenIE
15
- from collections import defaultdict
16
- from tqdm.auto import tqdm
17
- import multiprocessing as mp
18
- import numpy as np
19
- from functools import partial
20
- import nltk
21
- import json
22
- import importlib_resources as impresources
23
-
24
- import spacy
25
- spacy.prefer_gpu()
26
-
27
- import torch
28
- from torch.nn import CrossEntropyLoss
29
-
30
- from datasketch import MinHash, MinHashLSH
31
- from nltk import ngrams
32
-
33
- # globals
34
- properties = {
35
- "openie.affinity_probability_cap": 2 / 3,
36
- "openie.triple.strict": False,
37
- }
38
- IEclient = StanfordOpenIE(properties=properties)
39
-
40
- class DPST():
41
- def __init__(self, mode, hf_token=None, model_checkpoint="meta-llama/Llama-3.2-3B-Instruct"):
42
- print("Initializing...", flush=True)
43
-
44
- mode_map = {
45
- "50k": "fiftyk",
46
- "100k": "hundredk",
47
- "200k": "twohundredk"
48
- }
49
-
50
- if mode not in mode_map:
51
- print("Error: [MODE] must be one of [50k, 100k, 200k].")
52
- return
53
- else:
54
- self.mode = mode_map[mode]
55
-
56
- # db connection
57
- self.client = weaviate.connect_to_local()
58
- self.collection = self.client.collections.get("Triples")
59
-
60
- if torch.cuda.is_available() == True:
61
- self.device = "cuda"
62
- else:
63
- self.device = "cpu"
64
-
65
- with open(impresources.files("data") / "clusters" / "{}.json".format(mode), 'r') as f:
66
- self.centroids = torch.tensor(json.load(f)).to(self.device)
67
-
68
- with open(impresources.files("data") / "clusters" / "{}_counts.json".format(mode), 'r') as f:
69
- self.cluster_counts = json.load(f)
70
-
71
- self.model_checkpoint = model_checkpoint
72
-
73
- #self.pool = mp.Pool(mp.cpu_count(), initargs=(nlp,))
74
- self.model = AutoModel.from_pretrained("jinaai/jina-embeddings-v3", trust_remote_code=True).to(self.device)
75
-
76
- self.gen_model = AutoModelForCausalLM.from_pretrained(self.model_checkpoint, token=hf_token, device_map=self.device)
77
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_checkpoint, token=hf_token)
78
-
79
- self.pipe = pipeline(
80
- "text-generation",
81
- model=self.gen_model,
82
- tokenizer=self.tokenizer,
83
- torch_dtype=torch.bfloat16,
84
- device_map="auto",
85
- )
86
-
87
- self.ppl_model = AutoModelForCausalLM.from_pretrained("gpt2").to(self.device)
88
- self.ppl_tokenizer = AutoTokenizer.from_pretrained("gpt2")
89
-
90
- print("Finished.", flush=True)
91
-
92
- def cleanup(self):
93
- self.client.close()
94
- #IEclient.client.stop()
95
-
96
- def exponential(self, candidates, epsilon, sensitivity=1):
97
- probabilities = [np.exp(epsilon * x[1] / (2 * sensitivity)) for x in candidates]
98
- probabilities = probabilities / np.linalg.norm(probabilities, ord=1)
99
- return np.random.choice([x[0] for x in candidates], 1, p=probabilities)[0]
100
-
101
- def query_db(self, vector, cluster):
102
- # Convert numpy array to list if needed
103
- vector_list = vector.tolist() if isinstance(vector, np.ndarray) else vector
104
- response = self.collection.query.near_vector(near_vector=vector_list, limit=self.cluster_counts[cluster], filters=Filter.by_property(self.mode).equal(cluster), return_metadata=MetadataQuery(distance=True))
105
- candidates = [(x.properties["text"], max(1 - x.metadata.distance, 0)) for x in response.objects]
106
- return candidates
107
-
108
- def get_prompt(self, triples, messages=True):
109
- PROMPT = [
110
- {"role": "system", "content": "Generate a concise text for the given set of triples. Ensure that the generated output only includes the provided information from the triples, but feel free to fill in the gaps where sensible. If necessary, ignore triples that do not fit into the larger context. It is very important that the output is grammatically correct, natural, and logical. Provide a text that captures the semantic meaning of the triples, without being too verbose or lengthy. Do not provide any further explanation, only provide the output text."},
111
- {"role": "user", "content": "Input triples: [{’object’: ’Mike_Mularkey’,’property’: ’coach’,’subject’: ’Tennessee_Titans’}]"},
112
- {"role": "assistant", "content": "Output text: Mike Mularkey is the coach of the Tennessee Titans."},
113
- {"role": "user", "content": "Input triples: [{’object’: ’Albert_E._Austin’, ’property’: ’successor’, ’subject’: ’Alfred_N._Phillips’}, {’object’: ’Connecticut’, ’property’: ’birthPlace’, ’subject’: ’Alfred_N._Phillips’}, {’object’: ’United_States_House_of_Representatives’, ’property’: ’office’, ’subject’: ’Alfred_N._Phillips’}]"},
114
- {"role": "assistant", "content": "Output text: Albert E. Austin succeeded Alfred N. Phillips who was born in Connecticut and worked at the United States House of Representatives."},
115
- {"role": "user", "content": "Input triples: [{’object’: ’College_of_William_&_Mary’, ’property’: ’owner’, ’subject’: ’Alan_B._Miller_Hall’}, {’object’: ’2009-06-01’, ’property’: ’completionDate’, ’subject’: ’Alan_B._Miller_Hall’}, {’object’: ’101 Ukrop Way’, ’property’: ’address’, ’subject’: ’Alan_B._Miller_Hall’}, {’object’: ’Williamsburg,_Virginia’, ’property’: ’location’, ’subject’: ’Alan_B._Miller_Hall’}, {’object’: ’Robert_A._M._Stern’, ’property’: ’architect’, ’subject’: ’Alan_B._Miller_Hall’}]"},
116
- {"role": "assistant", "content": "Output text: The Alan B Miller Hall’s location is 101 Ukrop Way, Williamsburg, Virginia. It was designed by Robert A.M. Stern and was completed on 1 June 2009. Its owner is the College of William and Mary."},
117
- {"role": "user", "content": "Input Triples: {}".format(str(triples))}
118
- ]
119
- return PROMPT
120
-
121
- def compute_ppl(self, predictions, batch_size: int = 16, add_start_token: bool = True, max_length=32):
122
- # if batch_size > 1 (which generally leads to padding being required), and
123
- # if there is not an already assigned pad_token, assign an existing
124
- # special token to also be the padding token
125
- if self.ppl_tokenizer.pad_token is None and batch_size > 1:
126
- existing_special_tokens = list(self.ppl_tokenizer.special_tokens_map_extended.values())
127
- # check that the model already has at least one special token defined
128
- assert (
129
- len(existing_special_tokens) > 0
130
- ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
131
- # assign one of the special tokens to also be the pad token
132
- self.ppl_tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]})
133
-
134
- if add_start_token and max_length:
135
- # leave room for <BOS> token to be added:
136
- assert (
137
- self.ppl_tokenizer.bos_token is not None
138
- ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
139
- max_tokenized_len = max_length - 1
140
- else:
141
- max_tokenized_len = max_length
142
-
143
- encodings = self.ppl_tokenizer(
144
- predictions,
145
- add_special_tokens=False,
146
- padding=True,
147
- truncation=True if max_tokenized_len else False,
148
- max_length=max_tokenized_len,
149
- return_tensors="pt",
150
- return_attention_mask=True,
151
- ).to(self.device)
152
-
153
- encoded_texts = encodings["input_ids"]
154
- attn_masks = encodings["attention_mask"]
155
-
156
- # check that each input is long enough:
157
- if add_start_token:
158
- assert torch.all(torch.ge(attn_masks.sum(1), 1)), "Each input text must be at least one token long."
159
- else:
160
- assert torch.all(
161
- torch.ge(attn_masks.sum(1), 2)
162
- ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."
163
-
164
- ppls = []
165
- loss_fct = CrossEntropyLoss(reduction="none")
166
-
167
- for start_index in range(0, len(encoded_texts), batch_size):
168
- end_index = min(start_index + batch_size, len(encoded_texts))
169
- encoded_batch = encoded_texts[start_index:end_index]
170
- attn_mask = attn_masks[start_index:end_index]
171
-
172
- if add_start_token:
173
- bos_tokens_tensor = torch.tensor([[self.ppl_tokenizer.bos_token_id]] * encoded_batch.size(dim=0)).to(self.device)
174
- encoded_batch = torch.cat([bos_tokens_tensor, encoded_batch], dim=1)
175
- attn_mask = torch.cat(
176
- [torch.ones(bos_tokens_tensor.size(), dtype=torch.int64).to(self.device), attn_mask], dim=1
177
- )
178
-
179
- labels = encoded_batch
180
-
181
- with torch.no_grad():
182
- out_logits = self.ppl_model(encoded_batch, attention_mask=attn_mask).logits
183
-
184
- shift_logits = out_logits[..., :-1, :].contiguous()
185
- shift_labels = labels[..., 1:].contiguous()
186
- shift_attention_mask_batch = attn_mask[..., 1:].contiguous()
187
-
188
- perplexity_batch = torch.exp(
189
- (loss_fct(shift_logits.transpose(1, 2), shift_labels) * shift_attention_mask_batch).sum(1)
190
- / shift_attention_mask_batch.sum(1)
191
- )
192
-
193
- ppls += perplexity_batch.tolist()
194
-
195
- return {"perplexities": ppls, "mean_perplexity": np.mean(ppls)}
196
-
197
- def get_triples_ie(self, text):
198
- res = [x for x in IEclient.annotate(text)]
199
- temp = [tuple(x.values()) for x in res]
200
-
201
- current = defaultdict(list)
202
- for t in temp:
203
- current[(t[0], t[1])].append(t)
204
-
205
- final = []
206
- for t in temp:
207
- s = "{} | {} | {}".format(t[0], t[1], t[2])
208
- if s not in final:
209
- final.append(s.replace("_", " "))
210
-
211
- lsh = MinHashLSH(threshold=0.4, num_perm=128)
212
- minhashes = {}
213
- for i, f in enumerate(final):
214
- minhash = MinHash(num_perm=128)
215
- for d in ngrams(f, 3):
216
- minhash.update("".join(d).encode('utf-8'))
217
- lsh.insert(i, minhash)
218
- minhashes[i] = minhash
219
-
220
- matches = {}
221
- for x, y in zip(final, minhashes):
222
- matches[x] = [final[z] for z in lsh.query(minhashes[y]) if z != y]
223
-
224
- clusters = []
225
- covered = []
226
- for m in sorted(matches, key=lambda x: len(matches[x]), reverse=True):
227
- if m not in covered and len(matches[m]) > 0:
228
- clusters.append(matches[m])
229
- covered.extend(matches[m])
230
-
231
- clean = [x.replace(" | ", " ") for x in covered]
232
- if len(clean) == 0:
233
- return []
234
- ppls = dict(zip(covered, self.compute_ppl(predictions=clean, batch_size=64)["perplexities"]))
235
-
236
- best = []
237
- for c in clusters:
238
- scores = [ppls[x] for x in c]
239
- imin = np.argmin(scores)
240
- best.append(c[imin])
241
-
242
- ordered = []
243
- for f in final:
244
- if f in best:
245
- ordered.append(f)
246
- return ordered
247
-
248
- def privatize(self, texts, epsilon=10, DP=True):
249
- results = []
250
- for i, t in tqdm(enumerate(texts), total=len(texts)):
251
- triples = self.get_triples_ie(t)
252
- if len(triples) == 0:
253
- results.append(t)
254
- continue
255
-
256
- if DP == True:
257
- eps = epsilon / len(triples)
258
- query_vectors = self.model.encode(triples, task="text-matching", truncate_dim=32, max_length=64)
259
-
260
- res = util.semantic_search(query_embeddings=torch.tensor(query_vectors).to(self.device), corpus_embeddings=self.centroids, top_k=1)
261
- clusters = [r[0]["corpus_id"] for r in res]
262
-
263
- candidates = []
264
- for q, c in zip(query_vectors, clusters):
265
- near = self.query_db(q, c)
266
- if len(near) > 0:
267
- candidates.append(near)
268
- private_triples = [self.exponential(c, eps) for c in candidates]
269
-
270
- final = []
271
- for p in private_triples:
272
- m = p.split(" | ")
273
- final.append({"object": m[0], "property": m[1], "subject": m[2]})
274
- prompt = self.get_prompt(final)
275
- else:
276
- final = []
277
- for x in triples:
278
- m = x.split(" | ")
279
- final.append({"object": m[0], "property": m[1], "subject": m[2]})
280
- prompt = self.get_prompt(final)
281
-
282
- outputs = self.pipe(
283
- prompt,
284
- pad_token_id=self.tokenizer.eos_token_id,
285
- max_new_tokens=int(len(self.tokenizer.encode(texts[i], return_tensors="pt")[0]))
286
- )
287
- generated = outputs[0]["generated_text"][-1]["content"]
288
-
289
- generated = generated.split("Output text: ")[-1].strip().replace("\n", "")
290
- generated = generated.split("USER:")[0].strip().replace("\n", "")
291
- generated = generated.split("\t")[0].split("ASSISTANT")[0].split("USER")[0].split("###")[0].split("Note:")[0].split("Explanation:")[0].split("```")[0].split("EXPECTED_OUTPUT")[0]
292
- results.append(generated.strip())
293
  return results
 
1
+
2
+ # This file is taken from the original DPST implementation by Meisenbacher et al.
3
+ # Paper: https://aclanthology.org/2025.emnlp-main.455/
4
+ # Source: https://github.com/sjmeis/DPST
5
+
6
+ import os
7
+ import weaviate
8
+ from weaviate.classes.query import MetadataQuery, Filter
9
+
10
+ from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLM, pipeline
11
+ from sentence_transformers import util
12
+
13
+ os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
14
+ from openie import StanfordOpenIE
15
+ from collections import defaultdict
16
+ from tqdm.auto import tqdm
17
+ import multiprocessing as mp
18
+ import numpy as np
19
+ from functools import partial
20
+ import nltk
21
+ import json
22
+ import importlib_resources as impresources
23
+
24
+ import spacy
25
+ spacy.prefer_gpu()
26
+
27
+ import torch
28
+ from torch.nn import CrossEntropyLoss
29
+
30
+ from datasketch import MinHash, MinHashLSH
31
+ from nltk import ngrams
32
+
33
+ # globals
34
+ properties = {
35
+ "openie.affinity_probability_cap": 2 / 3,
36
+ "openie.triple.strict": False,
37
+ }
38
+ IEclient = StanfordOpenIE(properties=properties)
39
+
40
+ class DPST():
41
+ def __init__(self, mode, hf_token=None, model_checkpoint="meta-llama/Llama-3.2-3B-Instruct"):
42
+ print("Initializing...", flush=True)
43
+
44
+ mode_map = {
45
+ "50k": "fiftyk",
46
+ "100k": "hundredk",
47
+ "200k": "twohundredk"
48
+ }
49
+
50
+ if mode not in mode_map:
51
+ print("Error: [MODE] must be one of [50k, 100k, 200k].")
52
+ return
53
+ else:
54
+ self.mode = mode_map[mode]
55
+
56
+ # db connection
57
+ self.client = weaviate.connect_to_local()
58
+ self.collection = self.client.collections.get("Triples")
59
+
60
+ if torch.cuda.is_available() == True:
61
+ self.device = "cuda"
62
+ else:
63
+ self.device = "cpu"
64
+
65
+ with open(impresources.files("data") / "clusters" / "{}.json".format(mode), 'r') as f:
66
+ self.centroids = torch.tensor(json.load(f)).to(self.device)
67
+
68
+ with open(impresources.files("data") / "clusters" / "{}_counts.json".format(mode), 'r') as f:
69
+ self.cluster_counts = json.load(f)
70
+
71
+ self.model_checkpoint = model_checkpoint
72
+
73
+ #self.pool = mp.Pool(mp.cpu_count(), initargs=(nlp,))
74
+ self.model = AutoModel.from_pretrained("jinaai/jina-embeddings-v3", trust_remote_code=True).to(self.device)
75
+
76
+ self.gen_model = AutoModelForCausalLM.from_pretrained(self.model_checkpoint, token=hf_token, device_map=self.device)
77
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_checkpoint, token=hf_token)
78
+
79
+ self.pipe = pipeline(
80
+ "text-generation",
81
+ model=self.gen_model,
82
+ tokenizer=self.tokenizer,
83
+ torch_dtype=torch.bfloat16,
84
+ device_map="auto",
85
+ )
86
+
87
+ self.ppl_model = AutoModelForCausalLM.from_pretrained("gpt2").to(self.device)
88
+ self.ppl_tokenizer = AutoTokenizer.from_pretrained("gpt2")
89
+
90
+ print("Finished.", flush=True)
91
+
92
+ def cleanup(self):
93
+ self.client.close()
94
+ #IEclient.client.stop()
95
+
96
+ def exponential(self, candidates, epsilon, sensitivity=1):
97
+ probabilities = [np.exp(epsilon * x[1] / (2 * sensitivity)) for x in candidates]
98
+ probabilities = probabilities / np.linalg.norm(probabilities, ord=1)
99
+ return np.random.choice([x[0] for x in candidates], 1, p=probabilities)[0]
100
+
101
+ def query_db(self, vector, cluster):
102
+ # Convert numpy array to list if needed
103
+ vector_list = vector.tolist() if isinstance(vector, np.ndarray) else vector
104
+ response = self.collection.query.near_vector(near_vector=vector_list, limit=self.cluster_counts[cluster], filters=Filter.by_property(self.mode).equal(cluster), return_metadata=MetadataQuery(distance=True))
105
+ candidates = [(x.properties["text"], max(1 - x.metadata.distance, 0)) for x in response.objects]
106
+ return candidates
107
+
108
+ def get_prompt(self, triples, messages=True):
109
+ PROMPT = [
110
+ {"role": "system", "content": "Generate a concise text for the given set of triples. Ensure that the generated output only includes the provided information from the triples, but feel free to fill in the gaps where sensible. If necessary, ignore triples that do not fit into the larger context. It is very important that the output is grammatically correct, natural, and logical. Provide a text that captures the semantic meaning of the triples, without being too verbose or lengthy. Do not provide any further explanation, only provide the output text."},
111
+ {"role": "user", "content": "Input triples: [{’object’: ’Mike_Mularkey’,’property’: ’coach’,’subject’: ’Tennessee_Titans’}]"},
112
+ {"role": "assistant", "content": "Output text: Mike Mularkey is the coach of the Tennessee Titans."},
113
+ {"role": "user", "content": "Input triples: [{’object’: ’Albert_E._Austin’, ’property’: ’successor’, ’subject’: ’Alfred_N._Phillips’}, {’object’: ’Connecticut’, ’property’: ’birthPlace’, ’subject’: ’Alfred_N._Phillips’}, {’object’: ’United_States_House_of_Representatives’, ’property’: ’office’, ’subject’: ’Alfred_N._Phillips’}]"},
114
+ {"role": "assistant", "content": "Output text: Albert E. Austin succeeded Alfred N. Phillips who was born in Connecticut and worked at the United States House of Representatives."},
115
+ {"role": "user", "content": "Input triples: [{’object’: ’College_of_William_&_Mary’, ’property’: ’owner’, ’subject’: ’Alan_B._Miller_Hall’}, {’object’: ’2009-06-01’, ’property’: ’completionDate’, ’subject’: ’Alan_B._Miller_Hall’}, {’object’: ’101 Ukrop Way’, ’property’: ’address’, ’subject’: ’Alan_B._Miller_Hall’}, {’object’: ’Williamsburg,_Virginia’, ’property’: ’location’, ’subject’: ’Alan_B._Miller_Hall’}, {’object’: ’Robert_A._M._Stern’, ’property’: ’architect’, ’subject’: ’Alan_B._Miller_Hall’}]"},
116
+ {"role": "assistant", "content": "Output text: The Alan B Miller Hall’s location is 101 Ukrop Way, Williamsburg, Virginia. It was designed by Robert A.M. Stern and was completed on 1 June 2009. Its owner is the College of William and Mary."},
117
+ {"role": "user", "content": "Input Triples: {}".format(str(triples))}
118
+ ]
119
+ return PROMPT
120
+
121
+ def compute_ppl(self, predictions, batch_size: int = 16, add_start_token: bool = True, max_length=32):
122
+ # if batch_size > 1 (which generally leads to padding being required), and
123
+ # if there is not an already assigned pad_token, assign an existing
124
+ # special token to also be the padding token
125
+ if self.ppl_tokenizer.pad_token is None and batch_size > 1:
126
+ existing_special_tokens = list(self.ppl_tokenizer.special_tokens_map_extended.values())
127
+ # check that the model already has at least one special token defined
128
+ assert (
129
+ len(existing_special_tokens) > 0
130
+ ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
131
+ # assign one of the special tokens to also be the pad token
132
+ self.ppl_tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]})
133
+
134
+ if add_start_token and max_length:
135
+ # leave room for <BOS> token to be added:
136
+ assert (
137
+ self.ppl_tokenizer.bos_token is not None
138
+ ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
139
+ max_tokenized_len = max_length - 1
140
+ else:
141
+ max_tokenized_len = max_length
142
+
143
+ encodings = self.ppl_tokenizer(
144
+ predictions,
145
+ add_special_tokens=False,
146
+ padding=True,
147
+ truncation=True if max_tokenized_len else False,
148
+ max_length=max_tokenized_len,
149
+ return_tensors="pt",
150
+ return_attention_mask=True,
151
+ ).to(self.device)
152
+
153
+ encoded_texts = encodings["input_ids"]
154
+ attn_masks = encodings["attention_mask"]
155
+
156
+ # check that each input is long enough:
157
+ if add_start_token:
158
+ assert torch.all(torch.ge(attn_masks.sum(1), 1)), "Each input text must be at least one token long."
159
+ else:
160
+ assert torch.all(
161
+ torch.ge(attn_masks.sum(1), 2)
162
+ ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."
163
+
164
+ ppls = []
165
+ loss_fct = CrossEntropyLoss(reduction="none")
166
+
167
+ for start_index in range(0, len(encoded_texts), batch_size):
168
+ end_index = min(start_index + batch_size, len(encoded_texts))
169
+ encoded_batch = encoded_texts[start_index:end_index]
170
+ attn_mask = attn_masks[start_index:end_index]
171
+
172
+ if add_start_token:
173
+ bos_tokens_tensor = torch.tensor([[self.ppl_tokenizer.bos_token_id]] * encoded_batch.size(dim=0)).to(self.device)
174
+ encoded_batch = torch.cat([bos_tokens_tensor, encoded_batch], dim=1)
175
+ attn_mask = torch.cat(
176
+ [torch.ones(bos_tokens_tensor.size(), dtype=torch.int64).to(self.device), attn_mask], dim=1
177
+ )
178
+
179
+ labels = encoded_batch
180
+
181
+ with torch.no_grad():
182
+ out_logits = self.ppl_model(encoded_batch, attention_mask=attn_mask).logits
183
+
184
+ shift_logits = out_logits[..., :-1, :].contiguous()
185
+ shift_labels = labels[..., 1:].contiguous()
186
+ shift_attention_mask_batch = attn_mask[..., 1:].contiguous()
187
+
188
+ perplexity_batch = torch.exp(
189
+ (loss_fct(shift_logits.transpose(1, 2), shift_labels) * shift_attention_mask_batch).sum(1)
190
+ / shift_attention_mask_batch.sum(1)
191
+ )
192
+
193
+ ppls += perplexity_batch.tolist()
194
+
195
+ return {"perplexities": ppls, "mean_perplexity": np.mean(ppls)}
196
+
197
+ def get_triples_ie(self, text):
198
+ res = [x for x in IEclient.annotate(text)]
199
+ temp = [tuple(x.values()) for x in res]
200
+
201
+ current = defaultdict(list)
202
+ for t in temp:
203
+ current[(t[0], t[1])].append(t)
204
+
205
+ final = []
206
+ for t in temp:
207
+ s = "{} | {} | {}".format(t[0], t[1], t[2])
208
+ if s not in final:
209
+ final.append(s.replace("_", " "))
210
+
211
+ lsh = MinHashLSH(threshold=0.4, num_perm=128)
212
+ minhashes = {}
213
+ for i, f in enumerate(final):
214
+ minhash = MinHash(num_perm=128)
215
+ for d in ngrams(f, 3):
216
+ minhash.update("".join(d).encode('utf-8'))
217
+ lsh.insert(i, minhash)
218
+ minhashes[i] = minhash
219
+
220
+ matches = {}
221
+ for x, y in zip(final, minhashes):
222
+ matches[x] = [final[z] for z in lsh.query(minhashes[y]) if z != y]
223
+
224
+ clusters = []
225
+ covered = []
226
+ for m in sorted(matches, key=lambda x: len(matches[x]), reverse=True):
227
+ if m not in covered and len(matches[m]) > 0:
228
+ clusters.append(matches[m])
229
+ covered.extend(matches[m])
230
+
231
+ clean = [x.replace(" | ", " ") for x in covered]
232
+ if len(clean) == 0:
233
+ return []
234
+ ppls = dict(zip(covered, self.compute_ppl(predictions=clean, batch_size=64)["perplexities"]))
235
+
236
+ best = []
237
+ for c in clusters:
238
+ scores = [ppls[x] for x in c]
239
+ imin = np.argmin(scores)
240
+ best.append(c[imin])
241
+
242
+ ordered = []
243
+ for f in final:
244
+ if f in best:
245
+ ordered.append(f)
246
+ return ordered
247
+
248
+ def privatize(self, texts, epsilon=10, DP=True):
249
+ results = []
250
+ for i, t in tqdm(enumerate(texts), total=len(texts)):
251
+ triples = self.get_triples_ie(t)
252
+ if len(triples) == 0:
253
+ results.append(t)
254
+ continue
255
+
256
+ if DP == True:
257
+ eps = epsilon / len(triples)
258
+ query_vectors = self.model.encode(triples, task="text-matching", truncate_dim=32, max_length=64)
259
+
260
+ res = util.semantic_search(query_embeddings=torch.tensor(query_vectors).to(self.device), corpus_embeddings=self.centroids, top_k=1)
261
+ clusters = [r[0]["corpus_id"] for r in res]
262
+
263
+ candidates = []
264
+ for q, c in zip(query_vectors, clusters):
265
+ near = self.query_db(q, c)
266
+ if len(near) > 0:
267
+ candidates.append(near)
268
+ private_triples = [self.exponential(c, eps) for c in candidates]
269
+
270
+ final = []
271
+ for p in private_triples:
272
+ m = p.split(" | ")
273
+ final.append({"object": m[0], "property": m[1], "subject": m[2]})
274
+ prompt = self.get_prompt(final)
275
+ else:
276
+ final = []
277
+ for x in triples:
278
+ m = x.split(" | ")
279
+ final.append({"object": m[0], "property": m[1], "subject": m[2]})
280
+ prompt = self.get_prompt(final)
281
+
282
+ outputs = self.pipe(
283
+ prompt,
284
+ pad_token_id=self.tokenizer.eos_token_id,
285
+ max_new_tokens=int(len(self.tokenizer.encode(texts[i], return_tensors="pt")[0]))
286
+ )
287
+ generated = outputs[0]["generated_text"][-1]["content"]
288
+
289
+ generated = generated.split("Output text: ")[-1].strip().replace("\n", "")
290
+ generated = generated.split("USER:")[0].strip().replace("\n", "")
291
+ generated = generated.split("\t")[0].split("ASSISTANT")[0].split("USER")[0].split("###")[0].split("Note:")[0].split("Explanation:")[0].split("```")[0].split("EXPECTED_OUTPUT")[0]
292
+ results.append(generated.strip())
293
  return results