waterfall 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,316 @@
1
+ import gc
2
+ import logging
3
+ import os
4
+ import time
5
+ from collections import defaultdict
6
+ from functools import partial
7
+ from multiprocessing import Pool
8
+ from typing import List, Tuple, Optional
9
+
10
+ import numpy as np
11
+ import torch
12
+ from scipy.sparse import csr_matrix, vstack
13
+ from tqdm import tqdm
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.tokenization_utils_base import PreTrainedTokenizerBase
16
+ from transformers.generation.logits_process import LogitsProcessor, TopKLogitsWarper, TopPLogitsWarper
17
+
18
+ from waterfall.permute import Permute
19
+ from waterfall.WatermarkingFn import WatermarkingFn
20
+ from waterfall.WatermarkingFnFourier import WatermarkingFnFourier
21
+
22
+ class PerturbationProcessor(LogitsProcessor):
23
+ def __init__(self,
24
+ N : int = 32000, # Vocab size
25
+ id : int = 0, # Watermark ID
26
+ ) -> None:
27
+
28
+ self.id = id
29
+ self.N = N
30
+ self.init_token_count = None
31
+ self.phi = np.ones(N)
32
+ self.n_gram = 2
33
+
34
+ self.skip_watermark = False
35
+
36
+ self.permute = Permute(self.N)
37
+
38
+ def reset(self, n_gram : int = 2) -> None:
39
+ self.n_gram = n_gram
40
+ self.init_token_count = None
41
+ if np.allclose(self.phi,np.median(self.phi)):
42
+ self.skip_watermark = True
43
+ logging.warning(f"Generating without watermark as watermarking function is flat")
44
+ else:
45
+ self.skip_watermark = False
46
+
47
+ def set_phi(self, phi : np.ndarray) -> None:
48
+ self.phi = phi
49
+
50
+ def __call__(self, input_ids: torch.LongTensor,
51
+ scores: torch.FloatTensor) -> torch.FloatTensor:
52
+
53
+ if self.skip_watermark:
54
+ return scores
55
+
56
+ if self.init_token_count is None:
57
+ self.init_token_count = input_ids.shape[1]
58
+
59
+ # Insufficient tokens generated for n-gram
60
+ if self.init_token_count + self.n_gram - 1 > input_ids.shape[1]:
61
+ return scores
62
+
63
+ prev_tokens = input_ids[:,-self.n_gram+1:].cpu().numpy()
64
+ permutations = [self.permute.get_permutation(prev_tokens[i,:], self.id, cache=True) for i in range(prev_tokens.shape[0])]
65
+
66
+ scores[:,:self.N] += torch.tensor(self.phi[permutations],
67
+ device=scores.device,
68
+ dtype=scores.dtype)
69
+ return scores
70
+
71
+ def indices_to_counts(N : int, dtype : np.dtype, indices : np.ndarray) -> csr_matrix:
72
+ counts = csr_matrix([np.bincount(j, minlength=N).astype(dtype) for j in indices])
73
+ return counts
74
+
75
+ class Watermarker:
76
+ def __init__(self,
77
+ tokenizer : PreTrainedTokenizerBase,
78
+ model : Optional[PreTrainedModel] = None,
79
+ id : int = 0,
80
+ kappa : float = 6,
81
+ k_p : int = 1,
82
+ n_gram : int = 2,
83
+ watermarkingFnClass = WatermarkingFnFourier
84
+ ) -> None:
85
+ assert kappa >= 0, f"kappa must be >= 0, value provided is {kappa}"
86
+
87
+ assert (model is None) or isinstance(model, PreTrainedModel), f"model must be a transformers model, value provided is {type(model)}" # argument order for tokenizer and model were swapped since the original code
88
+
89
+ self.tokenizer = tokenizer
90
+ self.model = model
91
+ self.id = id
92
+ self.k_p = k_p
93
+ self.n_gram = n_gram
94
+ self.kappa = kappa
95
+
96
+ self.N = self.tokenizer.vocab_size
97
+ self.logits_processor = PerturbationProcessor(N = self.N, id = id)
98
+
99
+ self.compute_phi(watermarkingFnClass)
100
+
101
+ def compute_phi(self, watermarkingFnClass = WatermarkingFnFourier) -> None:
102
+ self.watermarking_fn: WatermarkingFn = watermarkingFnClass(id = id, k_p = self.k_p, N = self.N, kappa = self.kappa)
103
+ self.phi = self.watermarking_fn.phi
104
+
105
+ self.logits_processor.set_phi(self.phi)
106
+
107
+ def generate(
108
+ self,
109
+ prompt : Optional[str] = None,
110
+ tokd_input : Optional[torch.Tensor] = None,
111
+ n_gram : Optional[int] = None,
112
+ max_new_tokens : int = 1000,
113
+ return_text : bool =True,
114
+ return_tokens : bool =False,
115
+ return_scores : bool =False,
116
+ do_sample : bool =True,
117
+ **kwargs
118
+ ) -> List[str] | dict:
119
+
120
+ assert self.model is not None, "Model is not loaded. Please load the model before generating text."
121
+
122
+ if n_gram is None:
123
+ n_gram = self.n_gram
124
+ if tokd_input is None:
125
+ assert prompt is not None, "Either prompt or tokd_input must be provided."
126
+ tokd_input = self.tokenizer(prompt, return_tensors="pt", add_special_tokens=False)
127
+ tokd_input = tokd_input.to(self.model.device)
128
+ logits_processor = []
129
+ if "top_k" in kwargs and kwargs["top_k"] is not None and kwargs["top_k"] != 0:
130
+ logits_processor.append(TopKLogitsWarper(kwargs.pop("top_k")))
131
+ if "top_p" in kwargs and kwargs["top_p"] is not None and kwargs["top_p"] < 1.0:
132
+ logits_processor.append(TopPLogitsWarper(kwargs.pop("top_p")))
133
+ if self.kappa != 0:
134
+ logits_processor.append(self.logits_processor)
135
+
136
+ with torch.no_grad():
137
+ self.logits_processor.reset(n_gram)
138
+ output = self.model.generate(
139
+ **tokd_input,
140
+ max_new_tokens=max_new_tokens,
141
+ do_sample=do_sample,
142
+ logits_processor=logits_processor,
143
+ pad_token_id=self.tokenizer.eos_token_id,
144
+ **kwargs
145
+ )
146
+ output = output[:,tokd_input["input_ids"].shape[-1]:].cpu()
147
+
148
+ return_dict = {}
149
+
150
+ if return_scores:
151
+ cumulative_token_count = self.get_cumulative_token_count(self.id, output, n_gram = n_gram, return_dense=False)
152
+ cumulative_token_count = vstack([i[0] for i in cumulative_token_count], format="csr")
153
+ q_score, _, _ = self.watermarking_fn.q(cumulative_token_count, k_p = [self.k_p], use_tqdm=False)
154
+ return_dict["q_score"] = q_score[:,0]
155
+
156
+ if return_tokens:
157
+ return_dict["tokens"] = output
158
+
159
+ if return_text:
160
+ decoded_output = self.tokenizer.batch_decode(output, skip_special_tokens=True)
161
+ decoded_output = [i.strip() for i in decoded_output]
162
+ return_dict["text"] = decoded_output
163
+
164
+ if len(output) == 1:
165
+ for k, v in return_dict.items():
166
+ return_dict[k] = v[0]
167
+
168
+ if return_text and len(return_dict) == 0:
169
+ return decoded_output
170
+
171
+ return return_dict
172
+
173
+ def get_cumulative_token_count(
174
+ self,
175
+ ids : List[int] | int,
176
+ all_tokens : List[torch.Tensor] | torch.Tensor | List[np.ndarray] | np.ndarray | List[List[int]] | List[int],
177
+ n_gram : int = 2,
178
+ return_unshuffled_indices : bool = False,
179
+ use_tqdm : bool = False,
180
+ return_dense : bool = True,
181
+ batch_size : int = 2**8,
182
+ ) -> List[csr_matrix] | List[np.ndarray] | Tuple[List[csr_matrix], List[List[np.ndarray]]] | Tuple[List[np.ndarray], List[List[np.ndarray]]]:
183
+ if isinstance(ids, int):
184
+ ids = [ids]
185
+ if isinstance(all_tokens[0], int) or (isinstance(all_tokens, (np.ndarray, torch.Tensor)) and all_tokens.ndim == 1):
186
+ all_tokens = [all_tokens]
187
+ all_tokens = list(map(lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor) else x, all_tokens))
188
+ max_length = max(map(len, all_tokens))
189
+ window = n_gram - 1
190
+
191
+ # Collect all unique seeds for psuedo-random number generation
192
+ key_index_dict = defaultdict(set)
193
+ all_keys = []
194
+ for i, tokens in enumerate(tqdm(all_tokens, desc="Collecting unique n-grams", disable=not use_tqdm)):
195
+ all_keys.append([])
196
+ for j in range(window, len(tokens)):
197
+ prev_token = tuple(tokens[j-window:j])
198
+ t = tokens[j]
199
+ if t >= self.N:
200
+ break
201
+ key_index_dict[prev_token].add(t)
202
+ all_keys[i].append((prev_token, t))
203
+ key_index_dict = {k:tuple(v) for k,v in key_index_dict.items()}
204
+
205
+ use_mp = len(all_tokens) > batch_size * 4
206
+ if use_mp:
207
+ p = Pool(len(os.sched_getaffinity(0))-1)
208
+ pool_map = partial(p.imap, chunksize=batch_size)
209
+ else:
210
+ pool_map = map
211
+
212
+ # Generate permutations for all unique seeds
213
+ permutations = pool_map(
214
+ partial(self.logits_processor.permute.get_unshuffled_indices, ids),
215
+ key_index_dict.items())
216
+ permutations = tqdm(permutations, total=len(key_index_dict), desc="Getting permutations", disable=not use_tqdm)
217
+ for k, value in zip(key_index_dict.keys(), permutations):
218
+ key_index_dict[k] = value
219
+
220
+ # Assign indices to unshuffled_indices
221
+ unshuffled_indices: List[np.ndarray] = [] # [text x id x length]
222
+ for keys in tqdm(all_keys, desc="Assigning indices", disable=not use_tqdm):
223
+ if len(keys) == 0:
224
+ unshuffled_indices.append(np.zeros((len(ids), 0), dtype=np.min_scalar_type(self.N)))
225
+ else:
226
+ unshuffled_indices.append(np.stack([key_index_dict[key][t] for key, t in keys]).T) # [id x length]
227
+
228
+ # Convert indices to counts
229
+ cumulative_token_count = pool_map(
230
+ partial(indices_to_counts, self.N, np.min_scalar_type(max_length)),
231
+ unshuffled_indices
232
+ )
233
+ cumulative_token_count = list(tqdm(cumulative_token_count, total=len(unshuffled_indices), desc="Counting tokens", disable=not use_tqdm))
234
+
235
+ if use_mp:
236
+ p.close()
237
+ p.join()
238
+
239
+ if return_dense:
240
+ cumulative_token_count = list(map(lambda x: x.toarray(), cumulative_token_count))
241
+
242
+ if return_unshuffled_indices:
243
+ return cumulative_token_count, unshuffled_indices
244
+ return cumulative_token_count
245
+
246
+ def verify(
247
+ self,
248
+ text : str | List[str],
249
+ id: Optional[int | List[int]] = None,
250
+ k_p : Optional[int | List[int]] = None,
251
+ return_ranking : bool = False,
252
+ return_extracted_k_p : bool = False,
253
+ return_counts : bool = False,
254
+ return_unshuffled_indices : bool = False,
255
+ use_tqdm : bool = False,
256
+ batch_size : int = 2**8,
257
+ ) -> np.ndarray | dict:
258
+ begin_time = time.time()
259
+
260
+ if id is None:
261
+ id = self.id
262
+
263
+ if isinstance(text, str):
264
+ texts = [text]
265
+ else:
266
+ texts = text
267
+
268
+ tokens = [np.array(self.tokenizer.encode(text, add_special_tokens=False), dtype=np.uint32) for text in tqdm(texts, desc="Tokenizing", disable=not use_tqdm)]
269
+
270
+ if isinstance(id, int):
271
+ ids = [id]
272
+ else:
273
+ ids = id
274
+
275
+ if isinstance(k_p, int):
276
+ k_ps = [k_p]
277
+ else:
278
+ k_ps = k_p
279
+
280
+ # Get cummulative token counts
281
+ start_time = time.time()
282
+ results = self.get_cumulative_token_count(ids, tokens, self.n_gram, return_unshuffled_indices, use_tqdm=use_tqdm, return_dense=False, batch_size=batch_size)
283
+ gc.collect()
284
+ if return_unshuffled_indices:
285
+ results, unshuffled_indices = results
286
+ results = vstack(results, format="csr")
287
+ if use_tqdm:
288
+ tqdm.write(f"Cummulative token counts done in {time.time() - start_time:.2f} seconds")
289
+
290
+ # Calculate Q score via dot product
291
+ start_time = time.time()
292
+ q_score, ranking, k_p_extracted = self.watermarking_fn.q(results, k_p = k_ps, batch = batch_size, use_tqdm = use_tqdm)
293
+ q_score, ranking = [i.reshape(-1, len(ids), i.shape[-1]) for i in (q_score, ranking)] # [text x ids x k_p for i in (score, rank)]
294
+ k_p_extracted = k_p_extracted.reshape(-1, len(ids)) # [text x ids]
295
+ if use_tqdm:
296
+ tqdm.write(f"Q score calculated in {time.time() - start_time:.2f} seconds")
297
+
298
+ res = q_score # [text x ids x k_p]
299
+
300
+ if return_ranking or return_extracted_k_p or return_counts or return_unshuffled_indices:
301
+ res = {
302
+ "q_score": q_score, # [text x ids x k_p]
303
+ }
304
+ if return_ranking:
305
+ res["ranking"] = ranking # [text x ids x k_p]
306
+ if return_extracted_k_p:
307
+ res["k_p_extracted"] = k_p_extracted # [text x ids]
308
+ if return_counts:
309
+ res["counts"] = results # [text x ids x k_p]
310
+ if return_unshuffled_indices:
311
+ res["unshuffled_indices"] = unshuffled_indices # [text x ids x length]
312
+
313
+ if use_tqdm:
314
+ tqdm.write(f"Total time taken for verify: {time.time() - begin_time:.2f} seconds")
315
+
316
+ return res
@@ -0,0 +1,54 @@
1
+ import numpy as np
2
+ from tqdm import tqdm
3
+ from multiprocessing import Pool
4
+ import os
5
+ from functools import partial
6
+ from typing import List, Tuple
7
+ from scipy.sparse import spmatrix
8
+
9
+ class WatermarkingFn:
10
+ def __init__(self, id : int = 0, k_p : int = 1, N : int = 32000, kappa : float = 1.) -> None:
11
+ self.id = id
12
+ self.k_p = k_p
13
+ self.N = N
14
+ self.kappa = kappa
15
+ self.phi = None
16
+ self.dtype = np.min_scalar_type(self.N)
17
+
18
+ def _q(self, bins : np.ndarray | spmatrix, k_p : List[int]) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
19
+ raise NotImplementedError
20
+
21
+ def q(self,
22
+ bins : np.ndarray | spmatrix,
23
+ k_p : List[int], # If set, only return the k_p-th element of the dot product and its ranking
24
+ batch : int = 2**8,
25
+ use_tqdm : bool = False,
26
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
27
+ if bins.ndim == 1:
28
+ bins = bins[None,:]
29
+ res = []
30
+ bins_sum = bins.sum(axis=1).reshape(-1,1)
31
+ bins_sum[bins_sum == 0] = 1
32
+ batch_range = range(0, bins.shape[0], batch)
33
+ batched = (bins[i:i+batch] / bins_sum[i:i+batch] for i in batch_range)
34
+ use_mp = len(batch_range) > 4
35
+ if use_mp:
36
+ p = Pool(len(os.sched_getaffinity(0))-1)
37
+ pool_map = p.imap
38
+ else:
39
+ pool_map = map
40
+ res = pool_map(partial(self._q, k_p=k_p), batched)
41
+ if use_tqdm:
42
+ res_ = []
43
+ with tqdm(total=bins.shape[0], desc="Calculating dot product") as pbar:
44
+ for r in res:
45
+ res_.append(r)
46
+ pbar.update(len(r[0]))
47
+ res = res_
48
+ else:
49
+ res = list(res)
50
+ if use_mp:
51
+ p.close()
52
+ p.join()
53
+ k_p_strength, k_p_ranking, k_p_extracted = list(map(np.concatenate, zip(*res)))
54
+ return k_p_strength, k_p_ranking, k_p_extracted
@@ -0,0 +1,32 @@
1
+ from waterfall.WatermarkingFn import *
2
+ import numpy as np
3
+ from scipy.fft import rfft
4
+ from scipy.sparse import isspmatrix
5
+
6
+ class WatermarkingFnFourier(WatermarkingFn):
7
+ def __init__(self, id : int = 0, k_p : int = 1, N : int = 32000, kappa : float = 1.) -> None:
8
+ super().__init__(id = id, k_p = k_p, N = N, kappa = kappa)
9
+
10
+ freq = self.k_p
11
+ assert (freq > 0) and (freq < self.N), f"k_p must be 0<k_p<{self.N}, value provided is {freq}"
12
+
13
+ half_N = int(self.N/2)
14
+ if freq <= half_N:
15
+ self.phi = np.cos(np.arange(self.N)/self.N*2*np.pi*freq)
16
+ else:
17
+ freq -= half_N
18
+ self.phi = np.sin(np.arange(self.N)/self.N*2*np.pi*freq)
19
+ self.phi *= self.kappa
20
+
21
+ self.scaling_factor = 1
22
+
23
+ def _q(self, bins : np.ndarray | spmatrix, k_p : List[int]) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
24
+ if isspmatrix(bins):
25
+ bins = bins.todense()
26
+ q = rfft(bins, axis=-1)[:,1:-1].astype(np.complex64)
27
+ q = np.concatenate((np.real(q), np.imag(q)), axis=1)
28
+ q *= self.scaling_factor
29
+ k_p_strength = q[:,np.array(k_p)-1]
30
+ k_p_ranking = ((q[...,None,:] > k_p_strength[...,None]).sum(axis=-1)).astype(self.dtype)
31
+ k_p_extracted = (np.argmax(q, axis=-1) + 1).astype(self.dtype)
32
+ return k_p_strength, k_p_ranking, k_p_extracted
@@ -0,0 +1,42 @@
1
+ from waterfall.WatermarkingFn import *
2
+ import numpy as np
3
+
4
+ class WatermarkingFnSquare(WatermarkingFn):
5
+ def __init__(self, id : int = 0, k_p : int = 1, N : int = 32000, kappa : float = 1.) -> None:
6
+ super().__init__(id = id, k_p = k_p, N = N, kappa = kappa)
7
+
8
+ self.k_N = 0
9
+
10
+ if (self.N%2)==1:
11
+ self.k_N = 1
12
+ self.phi = np.ones(self.N) * self.kappa
13
+ self.phi[self.N//2:] *= -1
14
+ self.phis = [self.phi]
15
+ return
16
+
17
+ N = self.N
18
+ while not (N & 0b1):
19
+ N >>= 1
20
+ self.k_N += 1
21
+ assert (k_p > 0) and (k_p < (self.k_N * 2)), f"k_p {k_p} larger than available number of fns {self.k_N*2-1}"
22
+
23
+ self.phis = np.empty((self.k_N*2-1, self.N), dtype=np.float32)
24
+ for i in range(self.k_N*2-1):
25
+ k_p = i+1
26
+ if k_p <= self.k_N:
27
+ self.phis[i] = (-1)**(np.floor(np.arange(self.N)*2**k_p/self.N)) * self.kappa
28
+ else:
29
+ k_p -= self.k_N
30
+ self.phis[i] = (-1)**(np.floor(np.arange(self.N)*2**k_p/self.N+0.5)) * self.kappa
31
+
32
+ self.phi = self.phis[self.k_p-1]
33
+
34
+ self.scaling_factor = 1 / self.kappa
35
+
36
+ def _q(self, bins : np.ndarray | spmatrix, k_p : List[int]) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
37
+ q = bins.dot(self.phis.T)
38
+ q *= self.scaling_factor
39
+ k_p_strength = q[:,np.array(k_p)-1]
40
+ k_p_ranking = ((q[...,None,:] > k_p_strength[...,None]).sum(axis=-1)).astype(self.dtype)
41
+ k_p_extracted = (np.argmax(q, axis=-1) + 1).astype(self.dtype)
42
+ return k_p_strength, k_p_ranking, k_p_extracted
waterfall/__init__.py ADDED
File without changes
waterfall/permute.py ADDED
@@ -0,0 +1,67 @@
1
+ import numpy as np
2
+ import psutil
3
+ from collections import OrderedDict
4
+ import gc
5
+ from typing import TypeVar, Tuple
6
+
7
+ T = TypeVar('T')
8
+
9
+ class LRUCache:
10
+ def __init__(self, capacity: int = 1000) -> None:
11
+ self.cache = OrderedDict()
12
+ self.capacity = capacity
13
+ self.cache_hits : int = 0
14
+ self.cache_misses : int = 0
15
+
16
+ def get(self, key: Tuple) -> T | None:
17
+ if key not in self.cache:
18
+ self.cache_misses += 1
19
+ return None
20
+ else:
21
+ self.cache_hits += 1
22
+ # Move the accessed item to the end of the OrderedDict to mark it as recently used.
23
+ self.cache.move_to_end(key)
24
+ return self.cache[key]
25
+
26
+ def __str__(self) -> str:
27
+ gc.collect()
28
+ return f"Cache hits: {self.cache_hits}, misses: {self.cache_misses}, rate: {self.cache_hits/(max(self.cache_hits+self.cache_misses, 1)):.2f}"
29
+
30
+ def put(self, key: Tuple, value: T) -> None:
31
+ if key in self.cache:
32
+ # Update the value and move it to the end.
33
+ self.cache.move_to_end(key)
34
+ self.cache[key] = value
35
+ if len(self.cache) > self.capacity:
36
+ # Remove the first key-value pair which is the least recently used.
37
+ del self.cache[next(iter(self.cache))]
38
+
39
+ def clear(self) -> None:
40
+ self.cache.clear()
41
+ gc.collect()
42
+
43
+ class Permute:
44
+ permutations = LRUCache()
45
+ def __init__(self, N : int = 128000) -> None:
46
+ self.N = N
47
+ self.dtype = np.min_scalar_type(self.N)
48
+ assert self.dtype.kind == 'u', "N must be a positive integer"
49
+ size_per_permutation_in_bytes = N * self.dtype.itemsize
50
+ cache_size = int(psutil.virtual_memory().total * 0.02 / size_per_permutation_in_bytes) # 2% of total memory
51
+ self.permutations.capacity = cache_size
52
+
53
+ def get_permutation(self, prev_tok, id : int, cache : bool = False) -> np.ndarray:
54
+ key = (id, *prev_tok)
55
+ if cache:
56
+ permutation = self.permutations.get(key)
57
+ if permutation is None:
58
+ permutation = np.random.RandomState(key).permutation(self.N).astype(self.dtype)
59
+ self.permutations.put(key, permutation)
60
+ else:
61
+ permutation = np.random.RandomState(key).permutation(self.N).astype(self.dtype)
62
+ return permutation
63
+
64
+ def get_unshuffled_indices(self, ids, args) -> dict[int, np.ndarray]:
65
+ key, indices = args
66
+ permutation = np.stack([self.get_permutation(key, id) for id in ids])
67
+ return {k: v for k, v in zip(indices, permutation[:,indices].T)}
waterfall/watermark.py ADDED
@@ -0,0 +1,307 @@
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import torch
5
+ from typing import List, Literal, Optional, Tuple
6
+
7
+ from transformers import AutoTokenizer, AutoModelForCausalLM
8
+ from sentence_transformers import SentenceTransformer
9
+ from tqdm.auto import tqdm
10
+
11
+ from waterfall.WatermarkingFnFourier import WatermarkingFnFourier
12
+ from waterfall.WatermarkingFnSquare import WatermarkingFnSquare
13
+ from waterfall.WatermarkerBase import Watermarker
14
+
15
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
16
+
17
+ PROMPT = (
18
+ "Paraphrase the user provided text while preserving semantic similarity. "
19
+ "Do not include any other sentences in the response, such as explanations of the paraphrasing. "
20
+ "Do not summarize."
21
+ )
22
+ PRE_PARAPHRASED = "Here is a paraphrased version of the text while preserving the semantic similarity:\n\n"
23
+
24
+ def detect_gpu() -> str:
25
+ """
26
+ Use torch to detect if MPS, CUDA, or neither (default CPU)
27
+ are available.
28
+
29
+ Returns:
30
+ String for the torch device available.
31
+ """
32
+ if torch.backends.mps.is_available():
33
+ return "mps"
34
+ elif torch.cuda.is_available():
35
+ return 'cuda'
36
+ else:
37
+ return 'cpu'
38
+
39
+ def watermark(
40
+ T_o: str,
41
+ watermarker: Watermarker,
42
+ sts_model: SentenceTransformer,
43
+ num_beam_groups: int = 4,
44
+ beams_per_group: int = 2,
45
+ STS_scale:float = 2.0,
46
+ diversity_penalty: float = 0.5,
47
+ max_new_tokens: Optional[int] = None,
48
+ ) -> str:
49
+ paraphrasing_prompt = watermarker.tokenizer.apply_chat_template(
50
+ [
51
+ {"role":"system", "content":PROMPT},
52
+ {"role":"user", "content":T_o},
53
+ ], tokenize=False, add_generation_prompt = True) + PRE_PARAPHRASED
54
+
55
+ watermarked = watermarker.generate(
56
+ paraphrasing_prompt,
57
+ return_scores = True,
58
+ max_new_tokens = int(len(paraphrasing_prompt) * 1.5) if max_new_tokens is None else max_new_tokens,
59
+ do_sample = False, temperature=None, top_p=None,
60
+ num_beams = num_beam_groups * beams_per_group,
61
+ num_beam_groups = num_beam_groups,
62
+ num_return_sequences = num_beam_groups * beams_per_group,
63
+ diversity_penalty = diversity_penalty,
64
+ )
65
+
66
+ # Select best paraphrasing based on q_score and semantic similarity
67
+ sts_scores = STS_scorer(T_o, watermarked["text"], sts_model)
68
+ selection_score = sts_scores * STS_scale + torch.from_numpy(watermarked["q_score"])
69
+ selection = torch.argmax(selection_score)
70
+
71
+ T_w = watermarked["text"][selection]
72
+
73
+ return T_w
74
+
75
+ def verify_texts(texts: List[str], id: int,
76
+ watermarker: Optional[Watermarker] = None,
77
+ k_p: Optional[int] = None,
78
+ model_path: Optional[str] = "meta-llama/Llama-3.1-8B-Instruct"
79
+ ) -> Tuple[float,float]:
80
+ """Returns the q_score and extracted k_p"""
81
+
82
+ if watermarker is None:
83
+ assert model_path is not None, "model_path must be provided if watermarker is not passed"
84
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
85
+ watermarker = Watermarker(tokenizer=tokenizer)
86
+
87
+ if k_p is None:
88
+ k_p = watermarker.k_p
89
+
90
+ verify_results = watermarker.verify(texts, id=[id], k_p=[k_p], return_extracted_k_p=True) # results are [text x id x k_p]
91
+ q_score = verify_results["q_score"]
92
+ k_p_extracted = verify_results["k_p_extracted"]
93
+
94
+ return q_score[:,0,0], k_p_extracted[:, 0]
95
+
96
+ def STS_scorer_batch(
97
+ original_texts: List[str],
98
+ test_texts: List[List[str]],
99
+ sts_model: SentenceTransformer
100
+ ) -> torch.Tensor:
101
+
102
+ assert len(original_texts) == len(test_texts), "original_texts and test_texts must have the same length"
103
+ assert all(len(test_texts[0]) == len(sublist) for sublist in test_texts[1:]), "All sublists in test_texts must have the same length"
104
+
105
+ all_text = original_texts + [text for sublist in test_texts for text in sublist]
106
+ embeddings = sts_model.encode(all_text, convert_to_tensor=True, normalize_embeddings=True)
107
+ original_embeddings = embeddings[:len(original_texts)]
108
+ test_embeddings = embeddings[len(original_texts):].reshape(len(test_texts), -1, embeddings.shape[1])
109
+ cos_sim = torch.einsum('ik,ijk->ij', original_embeddings, test_embeddings).cpu()
110
+ return cos_sim
111
+
112
+ def STS_scorer(
113
+ original_text: str,
114
+ test_texts: str | List[str],
115
+ sts_model: SentenceTransformer
116
+ ) -> float | torch.Tensor:
117
+ cos_sim = STS_scorer_batch(
118
+ original_texts=[original_text],
119
+ test_texts=[[test_texts] if isinstance(test_texts, str) else test_texts],
120
+ sts_model=sts_model
121
+ )[0]
122
+ if isinstance(test_texts, str):
123
+ cos_sim = cos_sim.item()
124
+ return cos_sim
125
+
126
+ def watermark_texts(
127
+ T_os: List[str],
128
+ id: Optional[int] = None,
129
+ k_p: int = 1,
130
+ kappa: float = 2.0,
131
+ model_path: str = "meta-llama/Llama-3.1-8B-Instruct",
132
+ torch_dtype: torch.dtype = torch.bfloat16,
133
+ sts_model_path: str = "sentence-transformers/all-mpnet-base-v2",
134
+ watermark_fn: Literal["fourier", "square"] = "fourier",
135
+ watermarker: Optional[Watermarker] = None,
136
+ sts_model: Optional[SentenceTransformer] = None,
137
+ device: str = detect_gpu(),
138
+ num_beam_groups: int = 4,
139
+ beams_per_group: int = 2,
140
+ diversity_penalty: float = 0.5,
141
+ STS_scale:float = 2.0,
142
+ use_tqdm: bool = False,
143
+ ) -> List[str]:
144
+ if watermark_fn == 'fourier':
145
+ watermarkingFnClass = WatermarkingFnFourier
146
+ elif watermark_fn == 'square':
147
+ watermarkingFnClass = WatermarkingFnSquare
148
+ else:
149
+ raise ValueError("Invalid watermarking function")
150
+
151
+ if watermarker is None:
152
+ assert model_path is not None, "model_path must be provided if watermarker is not passed"
153
+ model = AutoModelForCausalLM.from_pretrained(
154
+ model_path,
155
+ torch_dtype=torch_dtype,
156
+ device_map=device,
157
+ )
158
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
159
+
160
+ watermarker = Watermarker(tokenizer=tokenizer, model=model, id=id, kappa=kappa, k_p=k_p, watermarkingFnClass=watermarkingFnClass)
161
+ else:
162
+ tokenizer = watermarker.tokenizer
163
+ device = watermarker.model.device
164
+ id = watermarker.id
165
+
166
+ if id is None:
167
+ raise Exception("ID or Watermarker class must be passed to watermark_texts.")
168
+
169
+ if sts_model is None:
170
+ assert sts_model_path is not None, "sts_model_path must be provided if sts_model is not passed"
171
+ sts_model = SentenceTransformer(sts_model_path, device=device)
172
+
173
+ T_ws = []
174
+
175
+ for T_o in tqdm(T_os, desc="Watermarking texts", disable=not use_tqdm):
176
+ T_w = watermark(
177
+ T_o,
178
+ watermarker = watermarker,
179
+ sts_model = sts_model,
180
+ num_beam_groups = num_beam_groups,
181
+ beams_per_group = beams_per_group,
182
+ diversity_penalty = diversity_penalty,
183
+ STS_scale = STS_scale,
184
+ )
185
+ T_ws.append(T_w)
186
+
187
+ return T_ws
188
+
189
+ def pretty_print(
190
+ T_o: str, T_w: str,
191
+ sts_score: float,
192
+ T_o_q_score: float, T_w_q_score: float,
193
+ k_p: int, T_w_k_p: int,
194
+ ) -> None:
195
+ print(f"\nOriginal text T_o:\n\n{T_o}\n")
196
+ print(f"\nWatermarked text T_w:\n\n{T_w}\n")
197
+
198
+ # Original text
199
+ print(f"Verification score of T_o: \033[93m{T_o_q_score:.4f}\033[0m")
200
+
201
+ # Watermarked text
202
+ print(f"Verification score of T_w: \033[92m{T_w_q_score:.4f}\033[0m\n")
203
+
204
+ print(f"STS score of T_w : \033[94m{sts_score:.4f}\033[0m\n")
205
+
206
+ # Extract from watermarked text
207
+ print(f"Watermarking k_p : \033[95m{k_p}\033[0m")
208
+ print(f"Extracted k_p from T_w : \033[96m{T_w_k_p}\033[0m\n")
209
+
210
+ def main():
211
+ parser = argparse.ArgumentParser(description='generate text watermarked with a key')
212
+ parser.add_argument('--id',default=42,type=int,
213
+ help='id: unique ID')
214
+ parser.add_argument('--kappa',default=2.,type=float,
215
+ help='kappa: watermarking strength')
216
+ parser.add_argument('--k_p', default=1, type=int,
217
+ help="k_p: Perturbation key")
218
+ parser.add_argument('--model', default='meta-llama/Llama-3.1-8B-Instruct', type=str,
219
+ help="watermarking model")
220
+ parser.add_argument('--sts_model', default='sentence-transformers/all-mpnet-base-v2', type=str,
221
+ help="STS model")
222
+ parser.add_argument('--T_o', default=None, type=str,
223
+ help="original_text")
224
+ parser.add_argument('--watermark_fn', default='fourier', type=str,
225
+ help="watermarking function, can be 'fourier' or 'square'")
226
+ parser.add_argument('--device', default=detect_gpu(), type=str,
227
+ help="device to use for generation")
228
+ parser.add_argument('--num_beam_groups', default=4, type=int,
229
+ help="number of beam groups for generation")
230
+ parser.add_argument('--beams_per_group', default=2, type=int,
231
+ help="number of beams per group for generation")
232
+ parser.add_argument('--diversity_penalty', default=0.5, type=float,
233
+ help="diversity penalty for group beam search")
234
+ parser.add_argument('--STS_scale', default=2.0, type=float,
235
+ help="scale factor for trade-off between STS and q score. Higher means more emphasis on STS.")
236
+
237
+ args = parser.parse_args()
238
+
239
+ if args.watermark_fn == 'fourier':
240
+ watermarkingFnClass = WatermarkingFnFourier
241
+ elif args.watermark_fn == 'square':
242
+ watermarkingFnClass = WatermarkingFnSquare
243
+ else:
244
+ # Add any other self-defined watermarking functions here
245
+ raise ValueError("Invalid watermarking function")
246
+
247
+ id = args.id
248
+ kappa = args.kappa
249
+ k_p = args.k_p
250
+ model_name_or_path = args.model
251
+ sts_model_name = args.sts_model
252
+ T_o = args.T_o
253
+ device = args.device
254
+ num_beam_groups = args.num_beam_groups
255
+ beams_per_group = args.beams_per_group
256
+ diversity_penalty = args.diversity_penalty
257
+ STS_scale = args.STS_scale
258
+
259
+ if args.T_o is None:
260
+ T_o = "Protecting intellectual property (IP) of text such as articles and code is increasingly important, especially as sophisticated attacks become possible, such as paraphrasing by large language models (LLMs) or even unauthorized training of LLMs on copyrighted text to infringe such IP. However, existing text watermarking methods are not robust enough against such attacks nor scalable to millions of users for practical implementation."
261
+ T_os = [T_o] # Replace with your own list of texts to watermark
262
+
263
+ # Initialize tokenizer and model
264
+ tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
265
+ model = AutoModelForCausalLM.from_pretrained(
266
+ model_name_or_path,
267
+ torch_dtype=torch.bfloat16,
268
+ device_map=device,
269
+ )
270
+
271
+ watermarker = Watermarker(tokenizer=tokenizer, model=model, id=id, kappa=kappa, k_p=k_p, watermarkingFnClass=watermarkingFnClass)
272
+
273
+ sts_model = SentenceTransformer(sts_model_name, device=device)
274
+
275
+ T_ws = watermark_texts(
276
+ T_os, id, k_p, kappa,
277
+ watermarker=watermarker, sts_model=sts_model,
278
+ beams_per_group=beams_per_group,
279
+ num_beam_groups=num_beam_groups,
280
+ diversity_penalty=diversity_penalty,
281
+ STS_scale=STS_scale,
282
+ use_tqdm=True
283
+ )
284
+
285
+ # watermarker = Watermarker(tokenizer=tokenizer, model=None, id=id, k_p=k_p, watermarkingFnClass=watermarkingFnClass) # If only verifying the watermark, do not need to instantiate the model
286
+ q_scores, extracted_k_ps = verify_texts(T_os + T_ws, id, watermarker, k_p=k_p)
287
+
288
+ for i in range(len(T_os)):
289
+ # Handle the case where this is being run
290
+ # in an IDE or something else without terminal size
291
+ try:
292
+ column_size = os.get_terminal_size().columns
293
+ except OSError as ose:
294
+ column_size = 80
295
+
296
+ print("=" * column_size)
297
+
298
+ sts_score = STS_scorer(T_os[i], T_ws[i], sts_model)
299
+ pretty_print(
300
+ T_os[i], T_ws[i],
301
+ sts_score,
302
+ q_scores[i], q_scores[i + len(T_os)],
303
+ k_p, extracted_k_ps[i + len(T_os)],
304
+ )
305
+
306
+ if __name__ == "__main__":
307
+ main()
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: waterfall
3
+ Version: 0.1.0
4
+ Summary: Scalable Framework for Robust Text Watermarking and Provenance for LLMs
5
+ Author-email: Xinyuan Niu <aperture@outlook.sg>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/aoi3142/Waterfall
8
+ Project-URL: Issues, https://github.com/aoi3142/Waterfall/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: accelerate>=0.29.0
15
+ Requires-Dist: numpy>=2.0.0
16
+ Requires-Dist: scipy>=1.13.0
17
+ Requires-Dist: sentence-transformers>=3.0.0
18
+ Requires-Dist: torch>=2.3.0
19
+ Requires-Dist: transformers>=4.43.1
20
+ Dynamic: license-file
21
+
22
+ # Waterfall: Scalable Framework for Robust Text Watermarking and Provenance for LLMs [EMNLP 2024 Main Long]
23
+ Gregory Kang Ruey Lau*, Xinyuan Niu*, Hieu Dao, Jiangwei Chen, Chuan-Sheng Foo, Bryan Kian Hsiang Low
24
+
25
+ [EMNLP](https://aclanthology.org/2024.emnlp-main.1138/) | [ArXiv](https://arxiv.org/abs/2407.04411) | [PDF](https://arxiv.org/pdf/2407.04411)
26
+
27
+ ## TL;DR: Training-free framework for text watermarking that is scalable, robust to LLM attacks, and applicable to original text of multiple types
28
+
29
+ ![Alt text](Images/Problem_formulation.jpg "")
30
+
31
+ 1. Watermark original text $T_o$ with watermark key $\mu$ → watermarked text $T_w$ with same semantic content
32
+
33
+ 2. Adversaries try to claim IP by plagiarizing text (e.g. paraphrasing), or by using text to train their own LLMs without authorization
34
+
35
+ 3. Clients can quickly verify whether a suspected text $T_{sus}$ contains the watermark and originated from $T_o$
36
+
37
+ Note: This code has been slightly modified from the implementation of the experiments in the paper. Refer to Appendix L.6 for details.
38
+
39
+ # Abstract
40
+ Protecting intellectual property (IP) of text such as articles and code is increasingly important, especially as sophisticated attacks become possible, such as paraphrasing by large language models (LLMs) or even unauthorized training of LLMs on copyrighted text to infringe such IP. However, existing text watermarking methods are not robust enough against such attacks nor scalable to millions of users for practical implementation. In this paper, we propose Waterfall, the first training-free framework for robust and scalable text watermarking applicable across multiple text types (e.g., articles, code) and languages supportable by LLMs, for general text and LLM data provenance. Waterfall comprises several key innovations, such as being the first to use LLM as paraphrasers for watermarking along with a novel combination of techniques that are surprisingly effective in achieving robust verifiability and scalability. We empirically demonstrate that Waterfall achieves significantly better scalability, robust verifiability, and computational efficiency compared to SOTA article-text watermarking methods, and also showed how it could be directly applied to the watermarking of code.
41
+
42
+ # Watermark process
43
+
44
+ ![Alt text](Images/Watermarking_process.png "")
45
+
46
+ 1. Original text $T_o$ is fed into LLM paraphraser to produce initial logits $L$.
47
+
48
+ 2. Unique ID $\mu$ and preceding $n-1$ tokens form the permutation key $k_\pi$ which seed a pseudo-random permutation which permutes the initial logits from $V_o$ space into $V_w$ space.
49
+
50
+ 3. Perturbation key $k_p$ selects a perturbation function $\mathcal{F}_1$ out of a family of orthogonal functions. $\mathcal{F}_1$ is added to the permuted logits.
51
+
52
+ 4. The perturbed logits are permuted back from $V_w$ space into $V_o$ space with the inverse of the permutation in step 2.
53
+
54
+ 5. A token is sampled from the perturbed logits $\check{L}$ and is appended to the watermarked text.
55
+
56
+ 6. Append the generated token to the prompt and continue autoregressive generation (steps 1-5) until the eos token.
57
+
58
+ # Verification of un/watermarked text
59
+
60
+ ![Alt text](Images/Illustration.gif "Text watermarked with a sine-watermark shows the watermark signal when verified with the correct key")
61
+
62
+ 1. For each token $\hat{w}$ in the watermarked text $T_w$ (original text is not required), use the unique ID $\mu$ and preceding $n-1$ tokens to permute the token index of $\hat{w}$ from $V_o$ space into $V_w$ space.
63
+
64
+ 2. Count the tokens to get a cumulative token distribution $C$ in $V_w$ space.
65
+
66
+ 3. Calculate the watermark score $q$ by taking the inner product of the cumulative token distribution $C$ with the perturbation function $\mathcal{F}_1$.
67
+
68
+ 4. Watermarked text will have $C$ that resembles $\mathcal{F}_1$, resulting in high $q$. Unwatermarked text or text watermarked with different ID $\mu$ will have a flat $C$, and text watermarked with different $k_p$ will have a $C$ that is orthogonal to $\mathcal{F}_1$, resulting in low watermark score $q$.
69
+
70
+ # Extraction of perturbation key $k_p$
71
+
72
+ 1. Perform steps 1-2 in verification.
73
+
74
+ 2. Calculate the watermark scores $q$ for all perturbation functions $\mathcal{F}_1$ in family of orthogonal functions.
75
+
76
+ 3. Extracted $k_p$ corresponds to the perturbation function $\mathcal{F}_1$ with the highest scoring watermark score in step 2.
77
+
78
+ # Using our code
79
+
80
+ [Optional]
81
+ If using `conda` (or other pkg managers), it is highly advisable to create a new environment
82
+
83
+ ```sh
84
+ conda create -n waterfall python=3.11 --yes `# Compatible with python version higher than 3.10`
85
+ conda activate waterfall
86
+ ```
87
+
88
+ Clone and install our package
89
+ ```sh
90
+ git clone https://github.com/aoi3142/Waterfall.git
91
+ pip install -e Waterfall `# Install in 'editable' mode with '-e', can be omitted`
92
+ ```
93
+
94
+ ## Minimal demonstration for Waterfall watermarking
95
+
96
+ Use the command `waterfall_demo` to watermark a piece of text, and then verify the presence of the watermark in the watermarked text
97
+ ```sh
98
+ waterfall_demo
99
+ ```
100
+
101
+ Additional arguments
102
+ ```sh
103
+ waterfall_demo \
104
+ --T_o "TEXT TO WATERMARK" `# Original text to watermark` \
105
+ --id 42 `# Unique watermarking ID` \
106
+ --k_p 1 `# Additional perturbation key` \
107
+ --kappa 2 `# Watermark strength` \
108
+ --model meta-llama/Llama-3.1-8B-Instruct `# Paraphrasing LLM` \
109
+ --watermark_fn fourier `# fourier/square watermark` \
110
+ --device cuda `# Use cuda/cpu`
111
+ ```
112
+
113
+ ## Using our code to watermark and verify
114
+
115
+ To watermark texts
116
+
117
+ ```python
118
+ from waterfall.watermark import watermark_texts
119
+
120
+ id = 1 # specify your watermarking ID
121
+ texts = ["...", "..."] # Assign texts to be watermarked
122
+
123
+ watermarked_text = watermark_texts(texts, id) # List of strings
124
+ ```
125
+
126
+ To verify watermark strength of texts
127
+
128
+ ```python
129
+ from waterfall.watermark import verify_texts
130
+
131
+ id = 1 # specify your watermarking ID
132
+ test_texts = ["...", "..."] # Suspected texts to verify
133
+
134
+ watermark_strength = verify_texts(test_texts, id)[0] # np array of floats
135
+ ```
136
+
137
+ # Code structure
138
+
139
+ - `watermark.py` : Sample watermarking script used by with `watermark_demo` command, includes beam search and other optimizations
140
+ - `WatermarkerBase.py` : Underlying generation and verification code provided by `Watermarker` class
141
+ - `WatermarkingFn.py` : Abstract class `WatermarkingFn` for watermarking functions, inherit it to create new perturbation functions
142
+ - `WatermarkingFnFourier.py` : Fourier watermarking function `WatermarkingFnFourier` inherited from `WatermarkingFn`
143
+ - `WatermarkingFnSquare.py` : Square watermarking function `WatermarkingFnSquare` inherited from `WatermarkingFn`
144
+
145
+ # BibTeX
146
+ ```
147
+ @inproceedings{lau2024waterfall,
148
+ title={Waterfall: Scalable Framework for Robust Text Watermarking and Provenance for {LLM}s},
149
+ author={Lau, Gregory Kang Ruey and Niu, Xinyuan and Dao, Hieu and Chen, Jiangwei and Foo, Chuan-Sheng and Low, Bryan Kian Hsiang},
150
+ booktitle={Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing},
151
+ year={2024},
152
+ month={nov},
153
+ address={Miami, Florida, USA},
154
+ url={https://aclanthology.org/2024.emnlp-main.1138/},
155
+ doi={10.18653/v1/2024.emnlp-main.1138},
156
+ pages={20432--20466},
157
+ }
158
+ ```
@@ -0,0 +1,13 @@
1
+ waterfall/WatermarkerBase.py,sha256=ou78I1XisalHbJLqyST6ryuLjtkFnY7Y60fUKdIwLy4,12905
2
+ waterfall/WatermarkingFn.py,sha256=-b-kGRdL0a7eKRqJmcHPAR_rCjxQYnsg1Ne6bTwBc1I,1931
3
+ waterfall/WatermarkingFnFourier.py,sha256=QYayAQYwi1dQkDIyqmvhU568VhrVYTVy47HkI8F8SZs,1358
4
+ waterfall/WatermarkingFnSquare.py,sha256=2PAO05DdKT02npo7GDf_82D520nP7kGAWK6H4E4JMt4,1638
5
+ waterfall/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ waterfall/permute.py,sha256=RwxOHFhx_VSOhhFwy5s79YgwTUBkfW2-LCCXYR3VT2o,2582
7
+ waterfall/watermark.py,sha256=whiNhPwWNNIZwXMH6r7QzEE3A7Niq2Ro9elA1iSRoxI,11952
8
+ waterfall-0.1.0.dist-info/licenses/LICENSE,sha256=zAtaO-k41Q-Q4Etl4bzuh7pgNJsPH-dYfzvznRa0OvM,11341
9
+ waterfall-0.1.0.dist-info/METADATA,sha256=ONpoos0Pyx43h4ntb9Fs4l78F3GZNxq__Ox05GMFD8A,8221
10
+ waterfall-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
+ waterfall-0.1.0.dist-info/entry_points.txt,sha256=XXnUzuWXu2nc9j4WAll9tq6HyodN_8WJLjeG0O4Y2Gw,60
12
+ waterfall-0.1.0.dist-info/top_level.txt,sha256=5rTgijeT9V5GRCwIDZmhjeZ4khgH1lmfhS9ZmdUUCKQ,10
13
+ waterfall-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ waterfall_demo = waterfall.watermark:main
@@ -0,0 +1,201 @@
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 2024 Xinyuan Niu
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.
@@ -0,0 +1 @@
1
+ waterfall