ritikraj2425 commited on
Commit
3fa3abf
·
1 Parent(s): 38902bc

Fixed indentation syntax error

Browse files
Files changed (1) hide show
  1. app.py +94 -93
app.py CHANGED
@@ -64,114 +64,115 @@ def generate_step_by_step(history):
64
 
65
  prompt = history[-1][0]
66
  print(f"Generating for prompt: {prompt}")
67
-
68
- steps = 20
69
- temp = 0.2
70
- top_k = 10
71
-
72
- bos_id = tokenizer.token_to_id("[BOS]")
73
- eos_id = tokenizer.token_to_id("[EOS]")
74
- mask_id = tokenizer.token_to_id("[MASK]")
75
- pad_id = tokenizer.token_to_id("[PAD]")
76
- unk_id = tokenizer.token_to_id("[UNK]")
77
- special_ids = {bos_id, eos_id, mask_id, pad_id, unk_id}
78
 
79
- formatted_prompt = f"user: {prompt.lower().strip()} bot:"
80
- input_ids = tokenizer.encode(formatted_prompt).ids
 
 
 
 
81
 
82
- max_resp = min(40, MAX_SEQ_LENGTH - len(input_ids) - 2)
 
83
 
84
- sequence = [bos_id] + input_ids + [mask_id] * max_resp + [eos_id]
85
- sequence += [pad_id] * (MAX_SEQ_LENGTH - len(sequence))
86
- seq_tensor = torch.tensor([sequence], dtype=torch.long, device=device)
87
 
88
- response_start = 1 + len(input_ids)
89
- response_end = response_start + max_resp
90
- mask_indices = list(range(response_start, response_end))
91
- num_masks = len(mask_indices)
92
 
93
- running_confidence = torch.zeros(num_masks, device=device)
 
 
 
94
 
95
- def get_output(seq_tensor, is_final=False):
96
- response_ids = seq_tensor[0][response_start:response_end]
97
- return decode_with_masks(response_ids, is_final)
98
 
99
- out_text = get_output(seq_tensor, is_final=False)
100
- history[-1][1] = out_text
101
- yield history
102
 
103
- current_seq = seq_tensor.squeeze(0).clone()
 
 
104
 
105
- # Pre-calculate penalty indices once
106
- vocab_size = model.fc_out.out_features
107
- penalty_indices = torch.tensor([i for i in range(vocab_size) if i not in special_ids], device=device)
108
 
109
- for step in range(1, steps + 1):
110
- t_val = max(1.0 - step / steps, 0.05)
111
- t = torch.tensor([t_val], device=device)
112
- pad_mask = (seq_tensor == pad_id)
113
 
114
- with torch.no_grad():
115
- logits = model(seq_tensor, t, src_key_padding_mask=pad_mask)
 
 
116
 
117
- response_logits = logits[0, mask_indices]
118
-
119
- # Optimized Vectorized Repetition Penalty
120
- if step > 1:
121
- prev_pred = current_seq[mask_indices]
122
- # Get counts only for tokens present in context to avoid giant loops
123
- unique_tokens, counts = torch.unique(prev_pred, return_counts=True)
124
- for i, tok_id in enumerate(unique_tokens):
125
- t_id = tok_id.item()
126
- if t_id not in special_ids and counts[i] > 1:
127
- penalty = 5.0 ** (counts[i].item() - 1)
128
- response_logits[:, t_id] = torch.where(
129
- response_logits[:, t_id] < 0,
130
- response_logits[:, t_id] * penalty,
131
- response_logits[:, t_id] / penalty
132
- )
133
-
134
- if top_k > 0:
135
- top_k_vals, _ = torch.topk(response_logits, top_k, dim=-1)
136
- min_top_k = top_k_vals[:, -1].unsqueeze(-1)
137
- response_logits = response_logits.masked_fill(response_logits < min_top_k, float('-inf'))
138
 
139
- # Nan protection and sampling
140
- if torch.isnan(probs).any():
141
- print("WARNING: NaNs detected in probabilities, falling back to uniform")
142
- probs = torch.ones_like(probs) / probs.size(-1)
143
-
144
- if step == steps:
145
- predicted = torch.argmax(probs, dim=-1)
146
- else:
147
- try:
148
- predicted = torch.multinomial(probs, 1).squeeze(-1)
149
- except RuntimeError as e:
150
- print(f"Sampling error: {e}")
151
- predicted = torch.argmax(probs, dim=-1) # fallback to greedy
 
152
 
153
- true_probs = F.softmax(response_logits, dim=-1)
154
- confidences = true_probs[torch.arange(num_masks), predicted]
155
-
156
- running_confidence = 0.7 * running_confidence + 0.3 * confidences
157
-
158
- for i, idx in enumerate(mask_indices):
159
- current_seq[idx] = predicted[i]
160
 
161
- if step < steps:
162
- target_revealed = int(num_masks * step / steps)
163
- num_remask = num_masks - target_revealed
164
- if num_remask > 0:
165
- _, low_idx = torch.topk(running_confidence, k=num_remask, largest=False)
166
- for li in low_idx:
167
- current_seq[mask_indices[li]] = mask_id
168
-
169
- seq_tensor = current_seq.unsqueeze(0)
170
- out_text = get_output(seq_tensor, is_final=(step == steps))
171
-
172
- history[-1][1] = out_text
173
- yield history
174
- time.sleep(0.02)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  except Exception as e:
176
  import traceback
177
  error_msg = f"Inference Error: {str(e)}"
 
64
 
65
  prompt = history[-1][0]
66
  print(f"Generating for prompt: {prompt}")
67
+
68
+ steps = 20
69
+ temp = 0.2
70
+ top_k = 10
 
 
 
 
 
 
 
71
 
72
+ bos_id = tokenizer.token_to_id("[BOS]")
73
+ eos_id = tokenizer.token_to_id("[EOS]")
74
+ mask_id = tokenizer.token_to_id("[MASK]")
75
+ pad_id = tokenizer.token_to_id("[PAD]")
76
+ unk_id = tokenizer.token_to_id("[UNK]")
77
+ special_ids = {bos_id, eos_id, mask_id, pad_id, unk_id}
78
 
79
+ formatted_prompt = f"user: {prompt.lower().strip()} bot:"
80
+ input_ids = tokenizer.encode(formatted_prompt).ids
81
 
82
+ max_resp = min(40, MAX_SEQ_LENGTH - len(input_ids) - 2)
 
 
83
 
84
+ sequence = [bos_id] + input_ids + [mask_id] * max_resp + [eos_id]
85
+ sequence += [pad_id] * (MAX_SEQ_LENGTH - len(sequence))
86
+ seq_tensor = torch.tensor([sequence], dtype=torch.long, device=device)
 
87
 
88
+ response_start = 1 + len(input_ids)
89
+ response_end = response_start + max_resp
90
+ mask_indices = list(range(response_start, response_end))
91
+ num_masks = len(mask_indices)
92
 
93
+ running_confidence = torch.zeros(num_masks, device=device)
 
 
94
 
95
+ def get_output(seq_tensor, is_final=False):
96
+ response_ids = seq_tensor[0][response_start:response_end]
97
+ return decode_with_masks(response_ids, is_final)
98
 
99
+ out_text = get_output(seq_tensor, is_final=False)
100
+ history[-1][1] = out_text
101
+ yield history
102
 
103
+ current_seq = seq_tensor.squeeze(0).clone()
 
 
104
 
105
+ # Pre-calculate penalty indices once
106
+ vocab_size = model.fc_out.out_features
 
 
107
 
108
+ for step in range(1, steps + 1):
109
+ t_val = max(1.0 - step / steps, 0.05)
110
+ t = torch.tensor([t_val], device=device)
111
+ pad_mask = (seq_tensor == pad_id)
112
 
113
+ with torch.no_grad():
114
+ logits = model(seq_tensor, t, src_key_padding_mask=pad_mask)
115
+
116
+ response_logits = logits[0, mask_indices]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ # Optimized Vectorized Repetition Penalty
119
+ if step > 1:
120
+ prev_pred = current_seq[mask_indices]
121
+ # Get counts only for tokens present in context to avoid giant loops
122
+ unique_tokens, counts = torch.unique(prev_pred, return_counts=True)
123
+ for i, tok_id in enumerate(unique_tokens):
124
+ t_id = tok_id.item()
125
+ if t_id not in special_ids and counts[i] > 1:
126
+ penalty = 5.0 ** (counts[i].item() - 1)
127
+ response_logits[:, t_id] = torch.where(
128
+ response_logits[:, t_id] < 0,
129
+ response_logits[:, t_id] * penalty,
130
+ response_logits[:, t_id] / penalty
131
+ )
132
 
133
+ if top_k > 0:
134
+ top_k_vals, _ = torch.topk(response_logits, top_k, dim=-1)
135
+ min_top_k = top_k_vals[:, -1].unsqueeze(-1)
136
+ response_logits = response_logits.masked_fill(response_logits < min_top_k, float('-inf'))
137
+
138
+ probs = F.softmax(response_logits / max(temp, 1e-6), dim=-1)
 
139
 
140
+ # Nan protection and sampling
141
+ if torch.isnan(probs).any():
142
+ print("WARNING: NaNs detected in probabilities, falling back to uniform")
143
+ probs = torch.ones_like(probs) / probs.size(-1)
144
+
145
+ if step == steps:
146
+ predicted = torch.argmax(probs, dim=-1)
147
+ else:
148
+ try:
149
+ predicted = torch.multinomial(probs, 1).squeeze(-1)
150
+ except RuntimeError as e:
151
+ print(f"Sampling error: {e}")
152
+ predicted = torch.argmax(probs, dim=-1) # fallback to greedy
153
+
154
+ true_probs = F.softmax(response_logits, dim=-1)
155
+ confidences = true_probs[torch.arange(num_masks), predicted]
156
+
157
+ running_confidence = 0.7 * running_confidence + 0.3 * confidences
158
+
159
+ for i, idx in enumerate(mask_indices):
160
+ current_seq[idx] = predicted[i]
161
+
162
+ if step < steps:
163
+ target_revealed = int(num_masks * step / steps)
164
+ num_remask = num_masks - target_revealed
165
+ if num_remask > 0:
166
+ _, low_idx = torch.topk(running_confidence, k=num_remask, largest=False)
167
+ for li in low_idx:
168
+ current_seq[mask_indices[li]] = mask_id
169
+
170
+ seq_tensor = current_seq.unsqueeze(0)
171
+ out_text = get_output(seq_tensor, is_final=(step == steps))
172
+
173
+ history[-1][1] = out_text
174
+ yield history
175
+ time.sleep(0.02)
176
  except Exception as e:
177
  import traceback
178
  error_msg = f"Inference Error: {str(e)}"