File size: 10,984 Bytes
85e172b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360

import os
import copy
import numpy as np

from tqdm import tqdm

import torch 

from . import compute_wb

from util import extraction
from util import utils


def extract_subject_feature(
        request,
        model,
        tok,
        layer, 
        module_template
    ):
    """ Extracts the subject feature from a model for a single request, whole prompt for attacks
    """
    # retrieves the last token representation of `subject` 
    feature_vector = extraction.extract_features_at_tokens(
            model,
            tok,
            prompts = [request["prompt"]],
            subjects = [request["subject"]],
            layer = layer,
            module_template = module_template,
            tok_type = 'subject_final',
            track = 'in',
            batch_size = 1,
            return_logits = False,
            verbose = False
        )[0]
    return feature_vector


def augment_prompt(prompt, aug_mode, num_aug, stopwords=['{}'], size_limit=10):
    """ Use of nlpaug to augment texutal prompts
    """
    import nlpaug.augmenter.char as nac
    import nlpaug.augmenter.word as naw

    if aug_mode == 'KeyboardAug':

        aug = nac.KeyboardAug(stopwords=stopwords, aug_char_max=size_limit)
        augmented_prompts = aug.augment(prompt, n=num_aug)

    elif aug_mode == 'OcrAug':

        aug = nac.OcrAug(stopwords=stopwords, aug_char_max=size_limit)
        augmented_prompts = aug.augment(prompt, n=num_aug)

    elif aug_mode == 'RandomCharInsert':

        aug = nac.RandomCharAug(stopwords=stopwords, action="insert", aug_char_max=size_limit)
        augmented_prompts = aug.augment(prompt, n=num_aug)

    elif aug_mode == 'RandomCharSubstitute':

        aug = nac.RandomCharAug(stopwords=stopwords, action="substitute", aug_char_max=size_limit)
        augmented_prompts = aug.augment(prompt, n=num_aug)

    elif aug_mode == 'SpellingAug':
        
        aug = naw.SpellingAug(stopwords=stopwords, aug_max=size_limit)
        augmented_prompts = aug.augment(prompt, n=num_aug)

    else:
        raise AssertionError('Augmentation mode not supported: {}'.format(aug_mode))

    return augmented_prompts


def iterative_augment_prompt(
        aug_portion, 
        aug_mode='KeyboardAug',
        size_limit = 1,
        same_length = False,
        num_aug = 10000
    ):
    """ Iterative augmentation until size limit reqched
    """
    
    all_augmented_prompts = []
    count = 0

    portion_length = len(aug_portion)

    while True:

        augmented_prompts = augment_prompt(aug_portion, aug_mode, num_aug, size_limit=size_limit)

        if aug_portion.endswith(' '):
            augmented_prompts = [augmented_prompt + ' ' for augmented_prompt in augmented_prompts]

        all_augmented_prompts = all_augmented_prompts + augmented_prompts

        # find unique preprompts
        unique_augmented_prompts = np.unique(all_augmented_prompts)

        # same length
        if same_length:
            lengths = np.array([len(t) for t in unique_augmented_prompts])
            unique_augmented_prompts = unique_augmented_prompts[lengths == portion_length]


        if (len(unique_augmented_prompts) >= num_aug) or (count > 30):
            break

        count += 1

    augmented_prompts = unique_augmented_prompts[:num_aug]
    return augmented_prompts



def extract_augmentations(
        model,
        tok,
        request,
        layers,
        module_template = 'transformer.h.{}.mlp.c_fc',
        tok_type = 'last',
        num_aug = 2000,
        aug_mode = 'KeyboardAug',
        size_limit = 1,
        batch_size = 64,
        aug_portion = 'prompt',
        static_context = None,
        return_logits = True,
        augmented_cache = None,
        return_augs_only = False,
        include_original = True,
        include_comparaitve = False,
        return_features = True,
        verbose = False
    ):
    """ Make text augmentations and extract features
    """
    if type(layers) == int: layers = [layers]

    # find prompt and subject of request
    word = request["subject"]
    prompt = request["prompt"]

    # find portion of text to augment
    if aug_portion == 'context':
        pre_prompt = ''
        to_aug_text  = static_context
        post_prompt = prompt 
        same_length = False

    elif aug_portion == 'wikipedia':
        pre_prompt = ''
        to_aug_text = None
        post_prompt = prompt 
        same_length = False

    elif aug_portion == 'prompt':
        to_aug_text = prompt.format(word)
        same_length = False

    else:
        raise ValueError('invalid option for which portion to augment:', aug_portion)


    # perform text augmentation
    if augmented_cache is not None:

        if type(augmented_cache)==str:
            augmented_cache = utils.loadjson(augmented_cache)['augmented_cache']

        if len(augmented_cache)> num_aug:
            augmented_cache = np.random.choice(augmented_cache, num_aug, replace=False)

        augmented_texts = augmented_cache

    else:
        augmented_texts = iterative_augment_prompt(
            aug_portion=to_aug_text, 
            aug_mode=aug_mode, 
            size_limit=size_limit,
            same_length = same_length,
            num_aug = num_aug
        )

    if return_augs_only:
        return augmented_texts

    # add original as first one
    if (to_aug_text is not None) and (include_original):
        augmented_texts = np.array([to_aug_text] + list(augmented_texts))
    else:
        augmented_texts = np.array(augmented_texts)

    # process back to subject and prompts
    if aug_portion in ['context']:
        
        aug_prompts = [pre_prompt + a + post_prompt for a in augmented_texts]
        aug_subjects = [word for a in augmented_texts]

        if include_comparaitve:
            aug_prompts.append(static_context+'{}')
            aug_subjects.append('')
            aug_prompts.append(prompt)
            aug_subjects.append(word)

    elif aug_portion == 'wikipedia':

        aug_prompts = [pre_prompt + a + post_prompt for a in augmented_texts]
        aug_subjects = [word for a in augmented_texts]

        if include_comparaitve:
            aug_prompts.append(augmented_texts[0]+'{}')
            aug_subjects.append('')
            aug_prompts = [prompt] + aug_prompts
            aug_subjects = [word] + aug_subjects

    elif aug_portion == 'prompt':
        
        # use same subject text indices since we have static length augmentation
        start_idx = len(prompt.split('{}')[0])
        end_idx = len(prompt.split('{}')[0]) + len(word)

        aug_subjects = augmented_texts
        aug_prompts = ['{}' for i in range(len(augmented_texts))]


    if return_features:

        # extract feature cloud
        layer_names = [module_template.format(l) for l in layers]

        extraction_return = extraction.extract_multilayer_at_tokens(
            model,
            tok,
            prompts = aug_prompts,
            subjects = aug_subjects,
            layers = layer_names,
            module_template = None,
            tok_type = tok_type,
            track = 'in',
            return_logits = return_logits,
            batch_size = batch_size,
            verbose = verbose
        )
        feature_cloud = torch.stack([extraction_return[l]['in'] for l in layer_names])

    else:
        feature_cloud = None

    aug_prompts = np.array(aug_prompts)
    aug_subjects = np.array(aug_subjects)

    if return_logits:
        aug_logits = extraction_return['tok_predictions']
    else:
        aug_logits = None

    return aug_prompts, aug_subjects, feature_cloud, aug_logits


def convert_to_prompt_only_request(request):
    new_request = copy.deepcopy(request)
    new_request['prompt'] = '{}'
    new_request['subject'] = request['prompt'].format(request['subject']) 
    return new_request


def extract_target(
        request,
        model,
        tok,
        layer,
        hparams,
        mode = 'prompt'
    ):
    """ Function to extract target features
    """
    target_set = {}

    if mode in ['prompt', 'origin_prompt', 'origin_context', 'origin_wikipedia']:

        if (mode == 'prompt') and (request['prompt'] != '{}'):
            raise ValueError('Mode [prompt] only works for empty request prompt [{}]')

        # find w1 input of target prompt 
        target_set['w1_input'] = extract_subject_feature(
            request,
            model,
            tok,
            layer = layer,
            module_template = hparams['rewrite_module_tmp'],
        )
        target_set['Y_current'] = np.array(
            target_set['w1_input'].cpu().numpy(), dtype=np.float32)

    elif mode in ['context', 'instructions']:

        # find w1 input of just context
        target_set['ctx_request'] = copy.deepcopy(request)
        target_set['ctx_request']['prompt'] = "{}"
        target_set['ctx_request']['subject'] = hparams['static_context']

        target_set['w1_context'] = extract_subject_feature(
            target_set['ctx_request'],
            model,
            tok,
            layer = layer,
            module_template = hparams['rewrite_module_tmp'],
        )
        target_set['Y_context'] = np.array(
            target_set['w1_context'].cpu().numpy(), dtype=np.float32)

        # find w1 input of original request
        target_set['org_request'] = copy.deepcopy(request)
        target_set['org_request']['prompt'] = target_set['org_request']['prompt'].split(hparams['static_context'])[-1]
        
        target_set['org_request'] = convert_to_prompt_only_request(target_set['org_request'])

        # find w1 input of target subject NOTE: need to change load from fcloud to subject pickle file
        target_set['w1_org'] = extract_subject_feature(
            target_set['org_request'],
            model,
            tok,
            layer = layer,
            module_template = hparams['rewrite_module_tmp'],
        )
        target_set['Y_org_current'] = np.array(
            target_set['w1_org'].cpu().numpy(), dtype=np.float32)

        # find w1 input of static context + original request
        target_set['oap_request'] = copy.deepcopy(request)
        if not target_set['oap_request']['prompt'].startswith(hparams['static_context']):
            target_set['oap_request']['prompt'] = hparams['static_context'] + target_set['oap_request']['prompt']

        target_set['oap_request'] = convert_to_prompt_only_request(target_set['oap_request'])

        target_set['w1_oap'] = extract_subject_feature(
            target_set['oap_request'],
            model,
            tok,
            layer = layer,
            module_template = hparams['rewrite_module_tmp'],
        )

        target_set['Y_current'] = 0.5 * (target_set['Y_org_current'] + target_set['Y_context'])
        target_set['w1_input'] = 0.5 * (target_set['w1_org'] + target_set['w1_context'])

    else:
        raise ValueError('mode not supported: {}'.format(mode))

    return target_set