devoppro commited on
Commit
5c5f48d
·
verified ·
1 Parent(s): 9113dc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -2
app.py CHANGED
@@ -26,15 +26,26 @@ def generate(prompt, max_new_tokens, temperature, top_k):
26
  with torch.no_grad():
27
  for _ in range(max_new_tokens):
28
  outputs = model(input_ids)
29
- logits = outputs["logits"][:, -1, :]
30
 
31
- logits = logits / max(temperature, 1e-5)
 
 
 
 
32
 
33
  if top_k > 0:
34
  v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
35
  logits[logits < v[:, [-1]]] = -float("Inf")
36
 
37
  probs = torch.softmax(logits, dim=-1)
 
 
 
 
 
 
 
 
38
  next_token = torch.multinomial(probs, num_samples=1)
39
 
40
  input_ids = torch.cat([input_ids, next_token], dim=-1)
 
26
  with torch.no_grad():
27
  for _ in range(max_new_tokens):
28
  outputs = model(input_ids)
 
29
 
30
+ # Cast to fp32 for the sampling math — fp16 logits from an
31
+ # early/undertrained checkpoint can overflow fp16's range,
32
+ # which turns softmax output into inf/nan and crashes
33
+ # multinomial with a CUDA device-side assert.
34
+ logits = outputs["logits"][:, -1, :].float() / max(temperature, 1e-5)
35
 
36
  if top_k > 0:
37
  v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
38
  logits[logits < v[:, [-1]]] = -float("Inf")
39
 
40
  probs = torch.softmax(logits, dim=-1)
41
+
42
+ # Defensive fallback: if anything still slips through as
43
+ # nan/inf/negative, fall back to a safe uniform distribution
44
+ # instead of crashing the whole generation call.
45
+ probs = torch.nan_to_num(probs, nan=0.0, posinf=0.0, neginf=0.0)
46
+ if probs.sum().item() <= 0:
47
+ probs = torch.ones_like(probs) / probs.size(-1)
48
+
49
  next_token = torch.multinomial(probs, num_samples=1)
50
 
51
  input_ids = torch.cat([input_ids, next_token], dim=-1)