forked from turboderp/exllama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.py
715 lines (473 loc) · 24.5 KB
/
generator.py
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
import cuda_ext
from model import ExLlama, ExLlamaCache
from lora import ExLlamaLora
import torch
import torch.nn.functional as F
class ExLlamaGenerator:
class Settings:
temperature = 0.95
top_k = 40 # consider the most probable top_k samples, 0 to disable top_k sampling
top_p = 0.65 # consider tokens up to a cumulative probabiltiy of top_p, 0.0 to disable top_p sampling
min_p = 0.0 # Do not consider tokens with probability less than this
typical = 0.0 # Locally typical sampling threshold, 0.0 to disable typical sampling
token_repetition_penalty_max = 1.15 # Repetition penalty for most recent tokens
token_repetition_penalty_sustain = 256 # No. most recent tokens to repeat penalty for, -1 to apply to whole context
token_repetition_penalty_decay = 128 # Gradually decrease penalty over this many tokens
beams = 1
beam_length = 1
model: ExLlama
sequence: torch.Tensor or None
sequence_actual: torch.Tensor or None
settings: Settings
beams: int or None
max_beam_length: int
in_beam_search: True
disallowed_tokens: list[int] or None
lora: ExLlamaLora or None
def __init__(self, model, tokenizer, cache):
self.model = model
self.tokenizer = tokenizer
self.cache = cache
self.reset()
def reset(self):
self.cache.current_seq_len = 0
self.sequence = None
self.sequence_actual = None
self.settings = ExLlamaGenerator.Settings()
self.beams = None
self.max_beam_length = 0
self.in_beam_search = False
self.disallowed_tokens = None
self.lora = None
def make_rep_mask(self, penalty_max, sustain, decay):
return cuda_ext.ext_rep_penalty_mask_cpu(self.model.config.vocab_size, self.sequence, penalty_max, sustain, decay)
def batched_sample(self, logits, temperature, top_k, top_p, min_p, typical, num = 1):
if logits.shape[0] == 1: return self.sample(logits, temperature, top_k, top_p, min_p, typical, num)
samples = []
scores = []
for i in range(logits.shape[0]):
t, s = self.sample(logits[i, :, :], temperature, top_k, top_p, min_p, typical)
samples.append(t)
scores.append(s)
return torch.cat(samples, dim = 0), torch.cat(scores, dim = 0)
# Sample one token from logits with current settings
def sample_current(self, logits, num = 1):
return self.sample(logits,
self.settings.temperature,
self.settings.top_k,
self.settings.top_p,
self.settings.min_p,
self.settings.typical)
# Sample one token from logits
def sample(self, logits, temperature, top_k, top_p, min_p, typical, num = 1):
# torch.manual_seed(42)
if logits.dim() == 3: logits = logits[0, -1, :]
elif logits.dim() == 2: logits = logits[-1, :]
else: raise ValueError("Bad logits dimension")
# Disallow tokens
if self.disallowed_tokens is not None:
logits[self.disallowed_tokens] = float("-inf")
# Base probabilities
logits /= temperature
logits += 1e-8
probs = torch.softmax(logits, dim = -1)
# Top K
if top_k == 0:
top_probs, top_indices = torch.sort(probs, descending = True)
else:
top_probs, top_indices = torch.topk(probs, top_k)
top_probs = F.normalize(top_probs, p = 1, dim = -1)
# Top P
if top_p > 0.0:
num_top_p_probs = 0
cum_prob = top_probs[0].item()
while True:
num_top_p_probs += 1
if num_top_p_probs == top_probs.shape[-1]: break
if top_probs[num_top_p_probs].item() < min_p: break
cum_prob += top_probs[num_top_p_probs].item()
if cum_prob > top_p: break
top_probs = top_probs[:num_top_p_probs]
top_probs = F.normalize(top_probs, p = 1, dim = -1)
top_indices = top_indices[:num_top_p_probs]
# Locally typical sampling
if typical > 0.0:
epsilon = 1e-10
log_probs = (top_probs + epsilon).log()
neg_entropy = (top_probs * log_probs).sum()
entropy_dev = (neg_entropy - log_probs).abs()
_, entropy_dev_order = torch.sort(entropy_dev)
top_probs = top_probs.gather(-1, entropy_dev_order)
top_indices = top_indices.gather(-1, entropy_dev_order)
num_typical_probs = 0
cum_prob = top_probs[0].item()
while True:
num_typical_probs += 1
if num_typical_probs == top_probs.shape[-1]: break
cum_prob += top_probs[num_typical_probs].item()
if cum_prob > typical: break
top_probs = top_probs[:num_typical_probs]
top_probs = F.normalize(top_probs, p = 1, dim = -1)
top_indices = top_indices[:num_typical_probs]
# Multinomial sampling from top_probs, kept in same order as top_indices
sampled_ind = torch.multinomial(top_probs, top_probs.shape[-1] if num == -1 else min(num, top_probs.shape[-1]))
sampled_tokens = top_indices[sampled_ind]
sampled_probs = top_probs[sampled_ind] # Return probs before second norm
if sampled_tokens.shape[0] > 1:
sampled_tokens, ind = sampled_tokens.sort()
sampled_probs = sampled_probs[ind]
return sampled_tokens.unsqueeze(0), sampled_probs.unsqueeze(0)
def disallow_tokens(self, tokens):
self.disallowed_tokens = tokens
def gen_begin(self, in_tokens, mask = None):
self.end_beam_search()
self.sequence = in_tokens.clone()
self.sequence_actual = in_tokens.clone()
self.cache.current_seq_len = 0
self.model.forward(self.sequence[:, :-1], self.cache, preprocess_only = True, lora = self.lora, input_mask = mask)
def gen_begin_empty(self):
self.end_beam_search()
self.sequence = None
self.sequence_actual = None
self.cache.current_seq_len = 0
def gen_begin_reuse(self, in_tokens, mask = None):
self.end_beam_search()
if self.sequence is None or self.cache.current_seq_len == 0:
self.gen_begin(in_tokens, mask = mask)
return 0
# if in_tokens.shape[-1] < self.sequence.shape[-1]:
# self.sequence = self.sequence[:, :in_tokens.shape[-1]]
reuse = 0
while reuse < self.sequence.shape[-1] and reuse < in_tokens.shape[-1] and self.sequence[0, reuse] == in_tokens[0, reuse]:
reuse += 1
if reuse < 2:
self.gen_begin(in_tokens, mask = mask)
return 0
# print (f"Reusing cache: {reuse} tokens")
self.cache.current_seq_len = reuse - 1
self.sequence = self.sequence[:, :reuse]
self.sequence_actual = self.sequence.clone()
if reuse < in_tokens.shape[-1]: self.gen_feed_tokens(in_tokens[:, reuse:], mask = mask)
return reuse
def gen_feed_tokens(self, in_tokens, mask = None):
if self.sequence is None:
self.gen_begin(in_tokens, mask = mask)
return
self.end_beam_search()
start = self.sequence.shape[-1] - 1
if start < 0:
start = 0
self.sequence = in_tokens.clone()
else:
self.sequence = torch.cat((self.sequence, in_tokens), dim = 1)
if start < self.sequence.shape[-1] - 1:
self.model.forward(self.sequence[:, start : -1], self.cache, preprocess_only = True, lora = self.lora, input_mask = mask)
self.sequence_actual = self.sequence
def gen_accept_token(self, token):
self.end_beam_search()
if self.sequence is None: self.sequence = token
else: self.sequence = torch.cat((self.sequence, token), dim = 1)
self.sequence_actual = self.sequence
def gen_rewind(self, num_tokens):
if num_tokens == 0: return
self.end_beam_search()
self.sequence = self.sequence[:, :-num_tokens]
self.cache.current_seq_len -= num_tokens
self.sequence_actual = self.sequence
def gen_prune_right(self, tokens, mask = None):
self.end_beam_search()
if tokens > self.sequence.shape[-1] - 1: return
self.gen_begin(self.sequence[:, tokens:], mask = mask)
self.sequence_actual = self.sequence
def gen_prune_to(self, min_tokens_to_keep, token_id, mask = None):
self.end_beam_search()
if self.gen_num_tokens() <= min_tokens_to_keep: return
while self.gen_num_tokens() > min_tokens_to_keep:
pruned = False
for i in range(self.sequence.shape[-1] - 1):
if self.sequence[0, i] == token_id:
self.sequence = self.sequence[:, i + 1:]
pruned = True
break
if not pruned: return
self.gen_begin(self.sequence, mask = mask)
def gen_prune_left(self, num_tokens, mask = None):
num_tokens = min(num_tokens, self.sequence_actual.shape[-1] - 1)
if self.in_beam_search:
self.end_beam_search() # TODO: Try to avoid restarting beam search when generating past chunk boundary
self.sequence = self.sequence[:, num_tokens:]
self.begin_beam_search()
else:
self.sequence = self.sequence[:, num_tokens:]
self.gen_begin(self.sequence, mask = mask)
def gen_num_tokens(self):
return self.sequence_actual.shape[-1]
# Simple generator function
def generate_simple(self, prompt, max_new_tokens = 128):
self.end_beam_search()
ids, mask = self.tokenizer.encode(prompt, return_mask = True, max_seq_len = self.model.config.max_seq_len)
self.gen_begin(ids, mask = mask)
max_new_tokens = min(max_new_tokens, self.model.config.max_seq_len - ids.shape[1])
eos = torch.zeros((ids.shape[0],), dtype = torch.bool)
for i in range(max_new_tokens):
token = self.gen_single_token(mask = mask)
for j in range(token.shape[0]):
if token[j, 0].item() == self.tokenizer.eos_token_id: eos[j] = True
if eos.all(): break
text = self.tokenizer.decode(self.sequence[0] if self.sequence.shape[0] == 1 else self.sequence)
return text
# Apply repetition penalty with current settings
def apply_rep_penalty(self, logits):
cuda_ext.ext_apply_rep_penalty_mask_cpu(self.sequence,
self.settings.token_repetition_penalty_max,
self.settings.token_repetition_penalty_sustain,
self.settings.token_repetition_penalty_decay,
logits)
# Generate a single token with the current settings, append to sequence
def gen_single_token(self, constraints = None, mask = None):
self.end_beam_search()
# Simple sampling case:
if self.sequence is not None:
logits = self.model.forward(self.sequence[:, -1:], self.cache, lora = self.lora, input_mask = mask)
self.apply_rep_penalty(logits)
logits[:, :, self.tokenizer.bos_token_id] = -10000.0
if constraints is not None:
for c in constraints: logits[:, :, c] += 10000.0
logits[:, :, :] -= 10000.0
token, _ = self.batched_sample(logits,
self.settings.temperature,
self.settings.top_k,
self.settings.top_p,
self.settings.min_p + 0.01 if constraints is not None else 0.0,
self.settings.typical)
else:
# bos = torch.Tensor([[self.tokenizer.bos_token_id]]).long()
# logits = self.model.forward(bos, self.cache)
# self.cache.current_seq_len = 0
if constraints is not None:
token = constraints[0]
else:
token = torch.Tensor([[self.tokenizer.bos_token_id]]).long()
self.gen_accept_token(token)
return token
# Beam search
class Beam:
sequence: torch.Tensor # tokens generated in beam
probs: torch.Tensor # probability score per token
cache: ExLlamaCache # cached keys/values for this beam
current_seq_pos: int # position of beam in current sequence
settings = None
generator = None
sampled_tokens: torch.Tensor
sampled_probs: torch.Tensor
moved: bool = False
def __init__(self, settings, generator, first_token = None, first_prob = None, seq_pos = None):
self.settings = settings
self.generator = generator
self.sequence = first_token.unsqueeze(0).unsqueeze(0) if first_token is not None else None
self.probs = first_prob.unsqueeze(0).unsqueeze(0) if first_prob is not None else None
self.cache = ExLlamaCache(self.generator.model, max_seq_len = self.settings.beam_length)
self.current_seq_pos = seq_pos
def __len__(self):
return self.sequence.shape[-1]
def clone(self):
new = ExLlamaGenerator.Beam(self.settings, self.generator)
new.sequence = self.sequence.clone()
new.probs = self.probs.clone()
new.cache = self.cache.clone()
new.current_seq_pos = self.current_seq_pos
new.sampled_tokens = self.sampled_tokens.clone()
new.sampled_probs = self.sampled_probs.clone()
new.moved = self.moved
return new
# List of references to this instance
def advance(self):
self.cache.roll_left()
self.sequence = self.sequence[:, 1:]
self.probs = self.probs[:, 1:]
self.current_seq_pos += 1
# Cumulative probabilities
def cum_log_probs(self):
cum_log_prob = torch.sum(torch.log(self.probs))
return cum_log_prob
def sampled_cum_log_probs(self):
cum_log_prob = torch.sum(torch.log(self.probs))
return torch.log(self.sampled_probs) + cum_log_prob
# Insert current beam in sequence
def to_sequence(self):
# Extend generator sequence and cache if needed
new_tokens = 0
added_tokens = 0
slen = self.generator.sequence.shape[-1]
tlen = self.current_seq_pos + len(self)
if tlen > slen:
new_tokens = tlen - slen
added_tokens = new_tokens
self.generator.sequence = torch.cat((self.generator.sequence, self.sequence[:, -new_tokens:]), dim = 1)
self.generator.cache.current_seq_len = tlen - 1
# Determine how much of generator sequence needs to be updated
new_tokens_ = new_tokens
for i in range(new_tokens_, len(self)):
if self.generator.sequence[0, -i - 1] != self.sequence[0, -i - 1]: new_tokens = i + 1
# Update sequence and cache
if new_tokens > added_tokens:
self.generator.sequence[0, -new_tokens:] = self.sequence[0, -new_tokens:]
if new_tokens > len(self) - 1: new_tokens = len(self) - 1
if new_tokens > 0:
self.cache.copy_states(self.generator.cache,
len(self) - 1 - new_tokens, new_tokens,
self.generator.cache.current_seq_len - new_tokens, new_tokens,
0, 1, 0, 1)
# Copy last column of cache to this beam (after generation)
def record_last_cache_column(self):
self.generator.cache.copy_states(self.cache,
self.generator.cache.current_seq_len - 1, 1,
len(self) - 1, 1,
0, 1, 0, 1)
def begin_beam_search(self):
self.beams = None
if self.settings.beams == 1 and self.settings.beam_length == 1: return
self.in_beam_search = True
# self.testl = []
def beam_search(self):
if self.settings.beams == 1 and self.settings.beam_length == 1: return self.gen_single_token()
assert self.in_beam_search
# Kludge: The first token returned with an empty context is generated without beam search
if self.sequence is None: return self.gen_single_token()
c_cache_len = self.cache.current_seq_len
c_seq_len = self.sequence_actual.shape[-1]
# Begin here
max_beam_length = min(self.model.config.max_seq_len - self.settings.beam_length, self.settings.beam_length)
while self.beams is None or len(self.beams[0]) < max_beam_length:
if self.beams is None:
# Initial tokens for initial beams
# self.cache.debug()
logits = self.model.forward(self.sequence[:, -1:], self.cache, lora = self.lora)
cuda_ext.ext_apply_rep_penalty_mask_cpu(self.sequence,
self.settings.token_repetition_penalty_max,
self.settings.token_repetition_penalty_sustain,
self.settings.token_repetition_penalty_decay,
logits)
tokens, probs = self.sample(logits,
self.settings.temperature,
self.settings.top_k,
self.settings.top_p,
self.settings.min_p,
self.settings.typical,
num = self.settings.beams)
# self.cache is updated with k/v for last token
# Setup initial beams
self.beams = []
while len(self.beams) < min(self.settings.beams, tokens.shape[-1]):
beam = ExLlamaGenerator.Beam(self.settings, self, tokens[0, len(self.beams)], probs[0, len(self.beams)], c_seq_len)
self.beams.append(beam)
else:
# Sample from each beam
# print(len(self.beams), end = "")
for beam in self.beams:
beam.to_sequence()
# self.cache.debug()
logits = self.model.forward(self.sequence[:, -1:], self.cache, lora = self.lora)
cuda_ext.ext_apply_rep_penalty_mask_cpu(self.sequence,
self.settings.token_repetition_penalty_max,
self.settings.token_repetition_penalty_sustain,
self.settings.token_repetition_penalty_decay,
logits)
tokens, probs = self.sample(logits,
self.settings.temperature,
self.settings.top_k,
self.settings.top_p,
self.settings.min_p,
self.settings.typical,
num = -1)
beam.sampled_tokens = tokens
beam.sampled_probs = probs
beam.record_last_cache_column()
self.cache.current_seq_len -= 1
# Collect options for all beams
tokens_ = []
probs_ = []
cum_log_probs_ = []
beams_ = []
for i, beam in enumerate(self.beams):
tokens_.append(beam.sampled_tokens.squeeze(0))
probs_.append(beam.sampled_probs.squeeze(0))
cum_log_probs_.append(beam.sampled_cum_log_probs().squeeze(0))
beams_.append(torch.Tensor([i] * beam.sampled_tokens.shape[-1]).to(torch.int))
tokens_all = torch.cat(tokens_, dim = 0)
probs_all = torch.cat(probs_, dim = 0)
cum_log_probs_all = torch.cat(cum_log_probs_, dim = 0)
beams_all = torch.cat(beams_, dim = 0)
# Sort by cumulative probability
cum_log_probs_all, ind = cum_log_probs_all.sort(descending = True)
probs_all = probs_all[ind]
tokens_all = tokens_all[ind]
beams_all = beams_all[ind]
# Reduce to beam limit
cum_log_probs_all = cum_log_probs_all[:self.settings.beams]
probs_all = probs_all[:self.settings.beams]
tokens_all = tokens_all[:self.settings.beams]
beams_all = beams_all[:self.settings.beams]
# Re-sort by beam index
beams_all, ind = beams_all.sort()
cum_log_probs_all = cum_log_probs_all[ind]
tokens_all = tokens_all[ind]
probs_all = probs_all[ind]
# test = [self.tokenizer.decode(beam.sequence) for beam in self.beams]
# Rebuild beams/caches
for beam in self.beams: beam.moved = False
beams_new = []
for i in range(len(beams_all)):
new_token = tokens_all[i]
new_prob = probs_all[i]
beam_idx = beams_all[i].item()
if not self.beams[beam_idx].moved:
self.beams[beam_idx].sequence = torch.cat((self.beams[beam_idx].sequence, new_token.unsqueeze(0).unsqueeze(0)), dim = 1)
self.beams[beam_idx].probs = torch.cat((self.beams[beam_idx].probs, new_prob.unsqueeze(0).unsqueeze(0)), dim = 1)
self.beams[beam_idx].moved = True
beams_new.append(self.beams[beam_idx])
else:
nbeam = self.beams[beam_idx].clone()
nbeam.sequence[:, -1] = new_token
nbeam.probs[:, -1] = new_prob
beams_new.append(nbeam)
self.beams = beams_new
# Beam length is filled up, select winning beam
max_log_probs = float("-inf")
best_beam = None
best_beam_idx = -1
for beam_idx, beam in enumerate(self.beams):
beam_log_probs = beam.cum_log_probs()
if beam_log_probs > max_log_probs:
max_log_probs = beam_log_probs
best_beam = beam
best_beam_idx = beam_idx
best_token = best_beam.sequence[:, 0]
# Insert in sequence
self.sequence[0, c_seq_len] = best_token
self.sequence_actual = torch.cat((self.sequence_actual, best_token.unsqueeze(0)), dim = 1)
# Copy cache state for winning beam
best_beam.to_sequence()
# Prune other beams that don't begin with the winning token
beams_new = [best_beam]
for idx, beam in enumerate(self.beams):
if idx != best_beam_idx and beam.sequence[:, 0] == best_token:
beams_new.append(beam)
self.beams = beams_new
# Advance all remaining beams and caches
for beam in self.beams: beam.advance()
# Done
return best_token
def end_beam_search(self):
if not self.in_beam_search: return
self.sequence = self.sequence_actual.clone()
self.cache.current_seq_len = self.sequence.shape[-1] - 1
self.in_beam_search = False
def replace_last_token(self, token, seq = False):
self.sequence_actual[:, -1] = token
if seq: self.sequence[:, -1] = token
def sequence_ends_with(self, tokens):
if self.sequence_actual.shape[-1] < tokens.shape[-1] + 1: return False
for i in range(tokens.shape[-1]):
if self.sequence_actual[0, -i - 1] != tokens[0, -i - 1]: return False
return True