Todokete commited on
Commit
1973671
·
verified ·
1 Parent(s): 771dd5b

Upload generate.py

Browse files
Files changed (1) hide show
  1. custom_generate/generate.py +101 -0
custom_generate/generate.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import random
3
+
4
+ def generate(model, input_ids, generation_config=None, **kwargs):
5
+ print("✨ using XTC (Exclude Top Choices) generation ✨")
6
+
7
+ generation_config = generation_config or model.generation_config
8
+
9
+ # Setup generation parameters
10
+ cur_length = input_ids.shape[1]
11
+ max_length = generation_config.max_length or cur_length + generation_config.max_new_tokens
12
+
13
+ # Extract XTC parameters from config or kwargs, with defaults
14
+ # Note: You can pass these in the generate() call or set them in generation_config
15
+ xtc_threshold = kwargs.get("xtc_threshold", getattr(generation_config, "xtc_threshold", 0.1))
16
+ xtc_probability = kwargs.get("xtc_probability", getattr(generation_config, "xtc_probability", 0.0))
17
+ temperature = kwargs.get("temperature", getattr(generation_config, "temperature", 1.0))
18
+
19
+ # Identify special tokens to protect (EOS is critical, Newline is preferred if known)
20
+ eos_token_id = generation_config.eos_token_id
21
+ pad_token_id = generation_config.pad_token_id
22
+
23
+ # Try to find newline token if possible, though hard without direct tokenizer access in this scope.
24
+ # Users can pass `protected_token_ids` in kwargs to be specific.
25
+ protected_token_ids = kwargs.get("protected_token_ids", [])
26
+ if eos_token_id is not None:
27
+ protected_token_ids.append(eos_token_id)
28
+
29
+ # Basic handling for left_padding (from original example)
30
+ left_padding = kwargs.get("left_padding", None)
31
+ if left_padding is not None:
32
+ if not isinstance(left_padding, int) or left_padding < 0:
33
+ raise ValueError(f"left_padding must be an integer larger than 0, but is {left_padding}")
34
+
35
+ pad_token = kwargs.get("pad_token", None) or pad_token_id
36
+ if pad_token is None:
37
+ raise ValueError("pad_token is not defined")
38
+
39
+ batch_size = input_ids.shape[0]
40
+ pad_tensor = torch.full(size=(batch_size, left_padding), fill_value=pad_token).to(input_ids.device)
41
+ input_ids = torch.cat((pad_tensor, input_ids), dim=1)
42
+ cur_length = input_ids.shape[1]
43
+
44
+ # Sampling Loop
45
+ while cur_length < max_length:
46
+ with torch.no_grad():
47
+ outputs = model(input_ids)
48
+ next_token_logits = outputs.logits[:, -1, :]
49
+
50
+ # 1. Apply Temperature
51
+ if temperature != 1.0 and temperature > 0:
52
+ next_token_logits = next_token_logits / temperature
53
+
54
+ # 2. Apply XTC (Exclude Top Choices)
55
+ # Logic ported from text-generation-webui sampler_hijack.py
56
+ if xtc_probability > 0.0 and random.random() < xtc_probability:
57
+ # Calculate probabilities for sorting
58
+ # We sort descending to find the "Top" choices
59
+ sorted_logits, sorted_indices = torch.sort(next_token_logits, descending=True)
60
+ sorted_probs = sorted_logits.softmax(dim=-1)
61
+
62
+ # Identify tokens to remove
63
+ sorted_indices_to_remove = torch.full_like(sorted_probs, False, dtype=torch.bool)
64
+
65
+ # XTC Logic:
66
+ # If the *next* token in the sorted list is above threshold,
67
+ # it means the current token is a "Top Choice" that can be excluded,
68
+ # because we still have good alternatives remaining.
69
+ sorted_indices_to_remove[..., :-1] = sorted_probs[..., 1:] >= xtc_threshold
70
+
71
+ # Scatter back to original indices
72
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
73
+
74
+ # Safety Check: Don't remove if special tokens (EOS, etc) are targeted
75
+ # If any protected token is in the removal mask, we abort XTC for this step
76
+ should_abort = False
77
+ if protected_token_ids:
78
+ # Check if any protected token is marked for removal
79
+ # We convert list to tensor for indexing
80
+ protected_tensor = torch.tensor(protected_token_ids, device=input_ids.device)
81
+ # We check if any of the columns corresponding to protected tokens are True
82
+ if indices_to_remove[:, protected_tensor].any():
83
+ should_abort = True
84
+
85
+ if not should_abort:
86
+ next_token_logits = next_token_logits.masked_fill(indices_to_remove, -float("Inf"))
87
+
88
+ # 3. Sample
89
+ # Using multinomial sampling (softmax + random selection)
90
+ probs = torch.softmax(next_token_logits, dim=-1)
91
+ next_tokens = torch.multinomial(probs, num_samples=1)
92
+
93
+ # Update input_ids
94
+ input_ids = torch.cat((input_ids, next_tokens), dim=-1)
95
+ cur_length += 1
96
+
97
+ # Stop if all batch items have hit EOS (optional optimization)
98
+ if eos_token_id is not None and (next_tokens == eos_token_id).all():
99
+ break
100
+
101
+ return input_ids