Repository navigation
Expand file tree
/
Copy pathgenerate.py
More file actions
719 lines (612 loc) · 31.4 KB
/
Copy pathgenerate.py
File metadata and controls
719 lines (612 loc) · 31.4 KB
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
import torch
import numpy as np
import torch.nn.functional as F
import os, sys
current_script_path = os.path.abspath(__file__)
scripts_dir = os.path.dirname(current_script_path)
project_root = os.path.dirname(scripts_dir)
if project_root not in sys.path:
sys.path.insert(0, project_root)
BASE_LINE= None
def entropy_function(probabilities):
if probabilities.dim() != 3:
raise ValueError("Input tensor 'probabilities' must be a 3D tensor with shape [batch_size, sequence_len, vocab_size]")
epsilon = 1e-12
probs_safe = probabilities.clone() + epsilon
entropy = torch.sum(probabilities.clone() * torch.log(probs_safe), dim=-1)
return entropy
def margin_function(probabilities):
if probabilities.dim() != 3:
raise ValueError("Input tensor 'probabilities' must be a 3D tensor with shape [batch_size, sequence_len, vocab_size]")
sorted_probs, _ = torch.sort(probabilities, dim=-1, descending=True)
top1_probs = sorted_probs[:, :, 0]
top2_probs = sorted_probs[:, :, 1]
confidence = top1_probs - top2_probs
return confidence
def pc_sampler_function(
probabilities: torch.Tensor,
token_ids: torch.Tensor,
lambda_val: float,
alpha: float,
bg_freq_tensor: torch.Tensor
) -> torch.Tensor:
if probabilities.shape != token_ids.shape:
raise f"probabilities.shape: {probabilities.shape}, token_ids.shape: {token_ids.shape} must be equal"
device = probabilities.device
sequence_len = probabilities.shape[1]
f_bg_tensor = bg_freq_tensor[token_ids]
epsilon = 1e-9
cross_entropy_scores = -probabilities * torch.log(f_bg_tensor + epsilon)
cross_entropy_scores = torch.clamp(cross_entropy_scores, max=alpha)
positions = torch.arange(sequence_len, device=device, dtype=torch.float32)
positional_bias = torch.exp(-lambda_val * positions)
final_scores = positional_bias * cross_entropy_scores
return final_scores
def linear_position(
probabilities: torch.Tensor,
token_ids: torch.Tensor,
lambda_val: float,
alpha: float,
bg_freq_tensor: torch.Tensor
) -> torch.Tensor:
if probabilities.shape != token_ids.shape:
raise f"probabilities.shape: {probabilities.shape}, token_ids.shape: {token_ids.shape} must be equal"
device = probabilities.device
batch_size, sequence_len = probabilities.shape
f_bg_tensor = bg_freq_tensor[token_ids]
epsilon = 1e-9
cross_entropy_scores = -probabilities * torch.log(f_bg_tensor + epsilon)
confidence = torch.clamp(cross_entropy_scores, max=alpha)
conf_max = confidence.view(batch_size, -1).max(dim=1, keepdim=True)[0].unsqueeze(1)
conf_min = confidence.view(batch_size, -1).min(dim=1, keepdim=True)[0].unsqueeze(1)
denom = conf_max - conf_min
denom[denom < 1e-9] = 1e-9
confidence_normalized = (confidence - conf_min) / denom
positions = torch.arange(sequence_len, device=device, dtype=torch.float32)
positional_bias = (sequence_len - positions) / sequence_len
final_scores = (1 - lambda_val) * confidence_normalized + lambda_val * positional_bias
return final_scores
def load_baseline(model, baseline_name):
global BASE_LINE
if BASE_LINE is None:
from utils.load_json_or_jsonl import load_json_or_jsonl
p_baseline_dict = load_json_or_jsonl(baseline_name)
token_num_ = p_baseline_dict['num_token']
p_baseline_dict = p_baseline_dict['p_baseline_dict']
del_keys = []
for key in p_baseline_dict.keys():
del_keys.append(key)
for key in del_keys:
p_baseline_dict[int(key)] = p_baseline_dict[key]
for key in del_keys:
del p_baseline_dict[key]
for key in p_baseline_dict.keys():
p_baseline_dict[key] = p_baseline_dict[key] / token_num_
BASE_LINE = torch.full((126464,), 1/token_num_, device=model.device, dtype=torch.float32)
keys = torch.tensor(list(p_baseline_dict.keys()), device=model.device, dtype=torch.long)
values = torch.tensor(list(p_baseline_dict.values()), device=model.device, dtype=torch.float32)
BASE_LINE.scatter_(0, keys, values)
else:
BASE_LINE = BASE_LINE.to(model.device)
def add_gumbel_noise(logits, temperature):
'''
The Gumbel max is a method for sampling categorical distributions.
According to arXiv:2409.02908, for MDM, low-precision Gumbel Max improves perplexity score but reduces generation quality.
Thus, we use float64.
'''
if temperature == 0:
return logits
logits = logits.to(torch.float64)
noise = torch.rand_like(logits, dtype=torch.float64)
gumbel_noise = (- torch.log(noise)) ** temperature
return logits.exp() / gumbel_noise
def get_num_transfer_tokens(mask_index, steps):
'''
In the reverse process, the interval [0, 1] is uniformly discretized into steps intervals.
Furthermore, because LLaDA employs a linear noise schedule (as defined in Eq. (8)),
the expected number of tokens transitioned at each step should be consistent.
This function is designed to precompute the number of tokens that need to be transitioned at each step.
'''
mask_num = mask_index.sum(dim=1, keepdim=True)
base = mask_num // steps
remainder = mask_num % steps
num_transfer_tokens = torch.zeros(mask_num.size(0), steps, device=mask_index.device, dtype=torch.int64) + base
for i in range(mask_num.size(0)):
num_transfer_tokens[i, :remainder[i]] += 1
return num_transfer_tokens
def get_transfer_index(logits, temperature, remasking, mask_index, x, num_transfer_tokens, threshold=None):
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
if remasking == 'low_confidence':
p = F.softmax(logits.to(torch.float64), dim=-1)
x0_p = torch.squeeze(
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
elif remasking == 'random':
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
else:
raise NotImplementedError(remasking)
x0 = torch.where(mask_index, x0, x)
confidence = torch.where(mask_index, x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
if threshold is not None:
num_transfer_tokens = mask_index.sum(dim=1, keepdim=True)
for j in range(confidence.shape[0]):
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j])
transfer_index[j, select_index] = True
if threshold is not None:
for k in range(1, num_transfer_tokens[j]):
if confidence[j, select_index[k]] < threshold:
transfer_index[j, select_index[k]] = False
return x0, transfer_index
def get_transfer_index_dynamic(logits, temperature, remasking, mask_index, x, num_transfer_tokens, factor=1):
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
if remasking == 'low_confidence':
p = F.softmax(logits.to(torch.float64), dim=-1)
x0_p = torch.squeeze(
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
elif remasking == 'random':
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
else:
raise NotImplementedError(remasking)
x0 = torch.where(mask_index, x0, x)
confidence = torch.where(mask_index, x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
num_transfer_tokens = mask_index.sum(dim=1, keepdim=True)
for j in range(confidence.shape[0]):
ns=list(range(1,num_transfer_tokens[j]+1))
es=[factor/(n+1) for n in ns]
threshs=[1-e for e in es]
# at least one token is transferred
threshs[0]=-1
sorted_confidence=torch.sort(confidence[j][mask_index[j]],dim=-1,descending=True)[0]
assert len(sorted_confidence)==len(threshs)
for top_i in range(len(threshs)):
if sorted_confidence[top_i]<threshs[top_i]:
break
if top_i == 0 or top_i == len(threshs)-1:
top_i+=1
_, select_index = torch.topk(confidence[j], k=top_i)
transfer_index[j, select_index] = True
return x0, transfer_index
@torch.no_grad()
def generate(model, prompt, steps=128, gen_length=128, block_length=128, temperature=0.,
cfg_scale=0., remasking='low_confidence', mask_id=126336, return_order=False):
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
x[:, :prompt.shape[1]] = prompt.clone()
prompt_index = (x != mask_id)
if return_order:
orders = {}
assert gen_length % block_length == 0
num_blocks = gen_length // block_length
assert steps % num_blocks == 0
steps = steps // num_blocks
for num_block in range(num_blocks):
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length:prompt.shape[1] + (num_block + 1) * block_length] == mask_id)
num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
for i in range(steps):
mask_index = (x == mask_id)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1)
if remasking == 'low_confidence':
p = F.softmax(logits, dim=-1)
x0_p = torch.squeeze(
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1)
elif remasking == 'random':
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
else:
raise NotImplementedError(remasking)
x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
x0 = torch.where(mask_index, x0, x)
confidence = torch.where(mask_index, x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
for j in range(confidence.shape[0]):
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
transfer_index[j, select_index] = True
if return_order:
if num_block+1 not in orders:
orders[num_block+1] = []
orders[num_block+1].append((select_index-prompt.shape[1]).tolist())
x[transfer_index] = x0[transfer_index]
if return_order:
return x, orders
return x
@torch.no_grad()
def generate_with_pc_sampler(model, prompt, steps=128, gen_length=128, block_length=128, lambd=1, alpha=1, baseline_name='P_baseline.json', temperature=0.,
cfg_scale=0., remasking='low_confidence', mask_id=126336, return_order=False):
global BASE_LINE
if BASE_LINE is None:
load_baseline(model, baseline_name)
if return_order:
orders = {}
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
x[:, :prompt.shape[1]] = prompt.clone()
prompt_index = (x != mask_id)
assert gen_length % block_length == 0
num_blocks = gen_length // block_length
assert steps % num_blocks == 0
steps = steps // num_blocks
for num_block in range(num_blocks):
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length:] == mask_id)
num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
for i in range(steps):
mask_index = (x == mask_id)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
if remasking == 'low_confidence':
p = F.softmax(logits, dim=-1)
x0_p = torch.squeeze(
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
elif remasking == 'random':
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
else:
raise NotImplementedError(remasking)
x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
x0 = torch.where(mask_index, x0, x)
x0_p = pc_sampler_function(
probabilities=x0_p[:, prompt.shape[1] + num_block * block_length:prompt.shape[1] + (num_block + 1) * block_length],
token_ids=x0[:, prompt.shape[1] + num_block * block_length:prompt.shape[1] + (num_block + 1) * block_length],
lambda_val=lambd,
alpha=alpha,
bg_freq_tensor=BASE_LINE
)
confidence = torch.where(mask_index[:, prompt.shape[1] + num_block * block_length:prompt.shape[1] + (num_block + 1) * block_length], x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
for j in range(confidence.shape[0]):
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
transfer_index[j, select_index+prompt.shape[1]+num_block*block_length] = True
if return_order:
if num_block+1 not in orders:
orders[num_block+1] = []
orders[num_block+1].append(select_index.tolist())
x[transfer_index] = x0[transfer_index]
if return_order:
return x, orders
return x
@torch.no_grad()
def generate_with_eb_sampler(model, prompt, gamma=0.1, gen_length=128, temperature=0.,
cfg_scale=0., mask_id=126336):
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
x[:, :prompt.shape[1]] = prompt.clone()
prompt_index = (x != mask_id)
while (x == mask_id).any():
mask_index = (x == mask_id)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
predicted_tokens = torch.argmax(logits_with_noise, dim=-1)
masked_logits = logits[mask_index]
err_proxy = torch.distributions.Categorical(logits=masked_logits).entropy()
masked_token_indices = mask_index.nonzero(as_tuple=True)[1]
sorted_err_indices = torch.argsort(err_proxy)
sorted_indices = masked_token_indices[sorted_err_indices]
sorted_entropies = err_proxy[sorted_err_indices]
acc_entropy = torch.cumsum(sorted_entropies, dim=0)
cummax_entropy = torch.cummax(sorted_entropies, dim=0).values
k = (acc_entropy - cummax_entropy <= gamma).sum()
num_masks_available = len(sorted_indices)
k = torch.clamp(k, min=1, max=num_masks_available)
indices_to_unmask = sorted_indices[:k]
x[0, indices_to_unmask] = predicted_tokens[0, indices_to_unmask]
return x
@ torch.no_grad()
def generate_with_fast_dllm(model, prompt, steps=128, gen_length=128, block_length=128, temperature=0.,
remasking='low_confidence', mask_id=126336, threshold=None, factor=None):
'''
Args:
model: Mask predictor.
prompt: A tensor of shape (1, L).
steps: Sampling steps, less than or equal to gen_length.
gen_length: Generated answer length.
block_length: Block length, less than or equal to gen_length. If less than gen_length, it means using semi_autoregressive remasking.
temperature: Categorical distribution sampling temperature.
cfg_scale: Unsupervised classifier-free guidance scale.
remasking: Remasking strategy. 'low_confidence' or 'random'.
mask_id: The toke id of [MASK] is 126336.
'''
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
x[:, :prompt.shape[1]] = prompt.clone()
assert gen_length % block_length == 0
num_blocks = gen_length // block_length
assert steps % num_blocks == 0
steps = steps // num_blocks
nfe = 0
for num_block in range(num_blocks):
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length] == mask_id)
num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
i = 0
while True:
nfe += 1
mask_index = (x == mask_id)
logits = model(x).logits
mask_index[:, prompt.shape[1] + (num_block + 1) * block_length:] = 0
if factor is None:
x0, transfer_index = get_transfer_index(logits, temperature, remasking, mask_index, x, num_transfer_tokens[:, i] if threshold is None else None, threshold)
else:
x0, transfer_index = get_transfer_index_dynamic(logits, temperature, remasking, mask_index, x, None, factor)
x[transfer_index] = x0[transfer_index]
i += 1
if (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length] == mask_id).sum() == 0:
break
return x, nfe
@torch.no_grad()
def generate_with_entropy(model, prompt, steps=128, gen_length=128, block_length=128, temperature=0.,
cfg_scale=0., remasking='low_confidence', mask_id=126336, return_order=False):
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
x[:, :prompt.shape[1]] = prompt.clone()
if return_order:
orders = {}
prompt_index = (x != mask_id)
assert gen_length % block_length == 0
num_blocks = gen_length // block_length
assert steps % num_blocks == 0
steps = steps // num_blocks
for num_block in range(num_blocks):
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length:] == mask_id)
num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
for i in range(steps):
mask_index = (x == mask_id)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
if remasking == 'low_confidence':
p = F.softmax(logits, dim=-1)
x0_p = torch.squeeze(
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
else:
raise NotImplementedError(remasking)
x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
x0 = torch.where(mask_index, x0, x)
x0_p = entropy_function(p[:, prompt.shape[1]:])
confidence = torch.where(mask_index[:, prompt.shape[1]:], x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
for j in range(confidence.shape[0]):
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
transfer_index[j, select_index + prompt.shape[1]] = True
if return_order:
if num_block+1 not in orders:
orders[num_block+1] = []
orders[num_block+1].append(select_index.tolist())
x[transfer_index] = x0[transfer_index]
if return_order:
return x, orders
return x
@torch.no_grad()
def generate_with_margin(model, prompt, steps=128, gen_length=128, block_length=128, temperature=0.,
cfg_scale=0., remasking='low_confidence', mask_id=126336, return_order=False):
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
x[:, :prompt.shape[1]] = prompt.clone()
if return_order:
orders = {}
prompt_index = (x != mask_id)
assert gen_length % block_length == 0
num_blocks = gen_length // block_length
assert steps % num_blocks == 0
steps = steps // num_blocks
for num_block in range(num_blocks):
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length:] == mask_id)
num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
for i in range(steps):
mask_index = (x == mask_id)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
if remasking == 'low_confidence':
p = F.softmax(logits, dim=-1)
x0_p = torch.squeeze(
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
else:
raise NotImplementedError(remasking)
x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
x0 = torch.where(mask_index, x0, x)
x0_p = margin_function(p[:, prompt.shape[1]:])
confidence = torch.where(mask_index[:, prompt.shape[1]:], x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
for j in range(confidence.shape[0]):
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
transfer_index[j, select_index + prompt.shape[1]] = True
if return_order:
if num_block+1 not in orders:
orders[num_block+1] = []
orders[num_block+1].append(select_index.tolist())
x[transfer_index] = x0[transfer_index]
if return_order:
return x, orders
return x
@torch.no_grad()
def generate_with_linear_position(model, prompt, steps=128, gen_length=128, block_length=128, lambd=1, alpha=1, baseline_name='P_baseline.json', temperature=0.,
cfg_scale=0., remasking='low_confidence', mask_id=126336, return_order=False):
global BASE_LINE
if BASE_LINE is None:
load_baseline(model, baseline_name)
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
x[:, :prompt.shape[1]] = prompt.clone()
if return_order:
orders = {}
prompt_index = (x != mask_id)
assert gen_length % block_length == 0
num_blocks = gen_length // block_length
assert steps % num_blocks == 0
steps = steps // num_blocks
for num_block in range(num_blocks):
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length:] == mask_id)
num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
for i in range(steps):
mask_index = (x == mask_id)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
if remasking == 'low_confidence':
p = F.softmax(logits, dim=-1)
x0_p = torch.squeeze(
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
elif remasking == 'random':
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
else:
raise NotImplementedError(remasking)
x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
x0 = torch.where(mask_index, x0, x)
x0_p = linear_position(
probabilities=x0_p[:, prompt.shape[1] + num_block * block_length:prompt.shape[1] + (num_block + 1) * block_length],
token_ids=x0[:, prompt.shape[1] + num_block * block_length:prompt.shape[1] + (num_block + 1) * block_length],
lambda_val=lambd,
alpha=alpha,
bg_freq_tensor=BASE_LINE
)
confidence = torch.where(mask_index[:, prompt.shape[1] + num_block * block_length:prompt.shape[1] + (num_block + 1) * block_length], x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
for j in range(confidence.shape[0]):
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
transfer_index[j, select_index+prompt.shape[1]+num_block*block_length] = True
if return_order:
if num_block+1 not in orders:
orders[num_block+1] = []
orders[num_block+1].append(select_index.tolist())
x[transfer_index] = x0[transfer_index]
if return_order:
return x, orders
return x
@torch.no_grad()
def generate_with_remdm(model, prompt, gen_length=32, init_unmask_ratio=0.875, unmask_k=1, loop_steps=32, temperature=0., cfg_scale=0., remasking='low_confidence', mask_id=126336, tokenizer=None):
assert 0.0 <= init_unmask_ratio <= 1.0, "init_unmask_ratio must be between 0 and 1"
num_initial_tokens = gen_length * init_unmask_ratio
assert num_initial_tokens == int(num_initial_tokens), "gen_length * init_unmask_ratio must be an integer"
num_initial_tokens = int(num_initial_tokens)
assert gen_length % unmask_k == 0, "gen_length must be divisible by unmask_k"
assert num_initial_tokens % unmask_k == 0, "init_unmask_ratio * gen_length must be divisible by unmask_k"
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
x[:, :prompt.shape[1]] = prompt.clone()
prompt_index = (x != mask_id)
num_loops = num_initial_tokens // unmask_k
for _ in range(num_loops):
mask_index = (x == mask_id)
if not mask_index.any():
break
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1)
p = F.softmax(logits, dim=-1)
x0_p = torch.gather(p, dim=-1, index=x0.unsqueeze(-1)).squeeze(-1)
confidence = torch.where(mask_index, x0_p, -torch.inf)
_, select_indices = torch.topk(confidence, k=unmask_k)
x[0, select_indices] = x0[0, select_indices]
x_result = tokenizer.decode(x[0, prompt.shape[1]:], skip_special_tokens=False)
for _ in range(loop_steps):
unmasked_gen_index = (x != mask_id) & (~prompt_index)
num_unmasked_gen = torch.sum(unmasked_gen_index).item()
if num_unmasked_gen == 0:
continue
current_remask_k = min(unmask_k, num_unmasked_gen)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
p = F.softmax(logits, dim=-1)
current_token_p = torch.gather(p, dim=-1, index=x.unsqueeze(-1)).squeeze(-1)
confidence = torch.where(unmasked_gen_index, current_token_p, torch.inf)
_, remask_indices = torch.topk(confidence, k=current_remask_k, largest=False)
x[0, remask_indices] = mask_id
mask_index_after_remask = (x == mask_id)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1)
p_new = F.softmax(logits, dim=-1)
x0_p_new = torch.gather(p_new, dim=-1, index=x0.unsqueeze(-1)).squeeze(-1)
confidence_for_unmasking = torch.where(mask_index_after_remask, x0_p_new, -torch.inf)
_, unmask_indices = torch.topk(confidence_for_unmasking, k=current_remask_k)
x[0, unmask_indices] = x0[0, unmask_indices]
x_result = tokenizer.decode(x[0, prompt.shape[1]:], skip_special_tokens=False)
while (x == mask_id).any():
mask_index = (x == mask_id)
num_masked_left = torch.sum(mask_index).item()
if num_masked_left == 0:
break
current_unmask_k = min(unmask_k, num_masked_left)
if cfg_scale > 0.:
un_x = x.clone()
un_x[prompt_index] = mask_id
x_ = torch.cat([x, un_x], dim=0)
logits = model(x_).logits
logits, un_logits = torch.chunk(logits, 2, dim=0)
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
else:
logits = model(x).logits
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
x0 = torch.argmax(logits_with_noise, dim=-1)
p = F.softmax(logits, dim=-1)
x0_p = torch.gather(p, dim=-1, index=x0.unsqueeze(-1)).squeeze(-1)
confidence = torch.where(mask_index, x0_p, -torch.inf)
_, select_indices = torch.topk(confidence, k=current_unmask_k)
x[0, select_indices] = x0[0, select_indices]
x_result = tokenizer.decode(x[0, prompt.shape[1]:], skip_special_tokens=False)
return x