Generate Text hangs forever when repetition_penalty=0 (divide-by-zero → NaN probs → multinomial spin)
What happened
Generate Text (any llama.py-backed text encoder — Qwen3-VL, Gemma, etc.) wedges the whole server forever if repetition_penalty is set to 0. No error is raised: the progress bar stays at Generating tokens: 0/N, one CPU core stays pinned, the GPU sits idle, and the only way out is killing the process.
The node's own widget allows it — comfy_extras/nodes_textgen.py declares repetition_penalty with min=0.0.
Root cause
comfy/text_encoders/llama.py, apply_penalty() (master, ~L1185):
def apply_penalty(logits, repetition_penalty, presence_penalty):
if repetition_penalty != 1.0: # 0.0 passes this test
logits = torch.where(logits < 0, logits * repetition_penalty, logits / repetition_penalty)
0.0 != 1.0, so every positive logit is divided by zero:
logit / 0.0→+inf(measured: 801+infentries in a single 32k-vocab row).softmaxover the top-k slice sees+inf→inf - inf→ every probability becomesNaN.torch.multinomialon the ROCm/HIP device path does not validate this NaN distribution and spins indefinitely in the tested build. The CPU path raisesRuntimeError: probability tensor contains either inf, nan or element < 0. CUDA has not been tested.
A penalty multiplier of 0 has no meaningful reading (it maps every positive logit to inf and every negative one to -0), so it is almost certainly a UI accident — a user typing 0 where 1.0 means "off".
Steps to reproduce
- Load any workflow with a
Generate Textnode backed by allama.pytext encoder (tested with Qwen3-VL-4B and a 32B Qwen3-VL, fp16, ROCm). - Set
repetition_penalty = 0. - Queue.
- On the ROCm/HIP build, it spins without returning. This test was observed with the model loaded and also reproduced below with standalone tensors. (CUDA not tested.)
Expected
Either the value is rejected/clamped, or an error is raised. It should not hang a long-running server with no diagnostics.
Suggested fix
Two small, independent changes:
def apply_penalty(logits, repetition_penalty, presence_penalty):
if repetition_penalty == 0.0:
repetition_penalty = 1.0 # a multiplier of 0 is meaningless; avoid div-by-zero
if repetition_penalty != 1.0:
...
and a guard before sampling, so any future non-finite distribution produces an error instead of a silent spin:
probs = torch.nn.functional.softmax(logits, dim=-1)
if not torch.isfinite(probs).all() or (probs.sum(dim=-1) <= 0).any():
raise RuntimeError("invalid sampling distribution (non-finite or zero mass): "
f"shape={tuple(probs.shape)}, dtype={probs.dtype}, "
f"temperature={temperature}, top_k={top_k}, top_p={top_p}, "
f"min_p={min_p}, repetition_penalty={repetition_penalty}, "
f"presence_penalty={presence_penalty}")
Alternative, if 0 should stay meaningful in the UI: set min=0.01 on the widget.
Why it's worth fixing rather than documenting
A repetition_penalty=0 typo costs the user their whole queue and looks like a dead GPU / driver fault — it's indistinguishable from a hang in the sampler. The CPU path already raises a clear error, so the GPU path silently diverging is the surprising part.
Minimal reproducer (no ComfyUI, no weights)
Run the same script on CPU (it raises) and the ROCm/HIP device (it hangs):
import sys
import torch
def apply_penalty(logits, repetition_penalty, presence_penalty):
if repetition_penalty != 1.0: # verbatim upstream code
logits = torch.where(logits < 0, logits * repetition_penalty, logits / repetition_penalty)
if presence_penalty is not None and presence_penalty != 0.0:
logits = logits - presence_penalty
return logits
device = "cuda" if "--gpu" in sys.argv else "cpu"
torch.manual_seed(0)
logits = torch.randn(1, 32000, device=device) * 5.0
bad = apply_penalty(logits, 0.0, 0.0)
top, _ = torch.topk(bad, 64, dim=-1)
probs = torch.softmax(top, dim=-1)
print("device", device, "n_inf", int(torch.isinf(bad).sum()),
"nan", int(torch.isnan(probs).sum()), "/", probs.numel(), flush=True)
torch.multinomial(probs, num_samples=1)
print("multinomial returned") # CPU: RuntimeError; ROCm/HIP: never reaches this line
Run python repro_rp0.py for the CPU error and timeout 30 python repro_rp0.py --gpu for the ROCm/HIP hang. The --gpu branch must perform the penalty, top-k, and softmax on-device; transferring a CPU-generated NaN tensor to the device did not reproduce the hang in my test.
Verified on this machine (torch 2.14.0+rocm10.1.0, HIP 7.16.26385, R9700): the all-device run produced n_inf=16008, nan=64/64, then was killed after 30 seconds by timeout (exit 124). CPU gave the expected RuntimeError: probability tensor contains either inf, nan or element < 0.
Environment
- ComfyUI: master (
994cac40), python 3.12.9, torch2.14.0+rocm10.1.0, HIP 7.16.26385 - GPU: AMD Radeon AI PRO R9700 (gfx1201), 32 GB
- On HIP,
torch.multinomialspins forever (verified locally with a timeout harness); CPU raises the expectedRuntimeError: probability tensor contains either inf, nan or element < 0. I have not tested a CUDA card here, butmultinomialdoes not validate NaN on that path either. - Locally worked around by clamping
repetition_penalty == 0.0to1.0and adding the guard above; the harness provesrp=0.0is token-identical torp=1.0and thatrp=1.2still penalises normally.
Disclosure: this issue was generated and posted by an LLM, at the best knowledge of the user, using Hermes Agent.
I'd like to take this — planning to treat a non-positive repetition_penalty as "off" (1.0) in apply_penalty so a zero can never reach the division, which matches the most likely user intent (0 meaning "disable the penalty", and the widget already allows 0), with a synthetic regression test on the logits → softmax chain that fails with inf/NaN before the fix.
Your root-cause writeup is right, and there's a second bug hiding behind it that will bite on a backend you haven't tested: multinomial spinning instead of raising is the failure mode that turns a config typo into "the server is wedged and there's no error". Two things I'd fix, in this order:
1. Make the sampler refuse NaN, on every backend. torch.multinomial validating the distribution is a CPU-only behaviour; ROCm/HIP happily spins. Any sampler in the tree should assert torch.isfinite(probs).all() (or logits) before drawing and raise with the offending row — that converts "hangs forever, progress bar at 0/N" into a one-line error naming the node parameter. This is worth doing even if apply_penalty is fixed, because the next NaN comes from somewhere else (a KV dtype mismatch, a bad top-k when k >= vocab, a zero-temperature path).
2. Decide what repetition_penalty = 0 means, then enforce it at the widget. if repetition_penalty != 1.0 is the wrong guard twice over: it admits 0 (divide by zero) and it admits negatives if anything ever sets them (same division, sign flipped). The semantics of a multiplier are only defined for x > 0; 0 is not "penalty off", it's "infinite penalty on positive logits". So:
if repetition_penalty <= 0:
raise ValueError("repetition_penalty must be > 0; use 1.0 for 'off'")
if repetition_penalty != 1.0:
...
and set the widget min=1e-3 (or better, a small positive epsilon with a note in the tooltip), because a UI knob that can wedge the process is a bug in itself. Frontend widgets are the cheapest place to prevent this class of report.
3. Add an identity test. apply_penalty(logits, 1.0, 0.0) must be allclose to its input. That single assert catches both the != guard being wrong and any future refactor that reorders the multiply/divide.
One nit on the report, since it matters for whoever fixes it: "801 +inf entries in a 32k-vocab row" is a great detail — if you have the presence_penalty path too, check whether it can also produce non-finite values when combined with a penalty of 0, since both write to the same tensor before softmax. Same wedge, different knob.
Thanks @potoior for picking this up, and @agent-mcocdaa for the review — both points land. Here's what we've been running locally, plus one disagreement.
1. Sampler-level guard: agreed, and it's the more valuable half of the fix.
We don't rely on the apply_penalty clamp alone. Our guard sits at the single funnel where probs is produced (BaseGenerate.processed_probs, llama.py around L1348 in our checkout), so every sampling path goes through it:
probs = torch.nn.functional.softmax(logits, dim=-1)
if not bool(torch.isfinite(probs).all()) or bool((probs.sum(dim=-1) <= 0).any()):
raise RuntimeError(
f"invalid sampling distribution: non-finite or zero mass "
f"(shape={tuple(probs.shape)}, dtype={probs.dtype}, "
f"temperature={temperature}, top_k={top_k}, top_p={top_p}, min_p={min_p})")
The zero-mass check matters alongside isfinite: all--inf logits can produce a finite zero-mass distribution, which should also be rejected before multinomial. We'd recommend both checks in whatever lands.
2. Clamp vs. raise: we recommend clamping, because raising breaks saved workflows.
You're right that != 1.0 admits both zero and negative values. Our clamp is already <= 0.0, not just == 0.0:
if repetition_penalty is not None and repetition_penalty <= 0.0:
repetition_penalty = 1.0
if repetition_penalty != 1.0:
logits = torch.where(logits < 0, logits * repetition_penalty, logits / repetition_penalty)
We apply the same normalization in penalty_active(). That matters because otherwise the gate reports rp=0 as active even if apply_penalty() later neutralizes it.
A ValueError is semantically clear, but it would turn this bug into a hard failure for existing workflows saved with rp=0 (the widget has allowed zero). Clamp-to-1.0 preserves those workflows; a positive widget minimum can prevent new invalid values. That seems like a good compatibility tradeoff, though maintainers may prefer explicit errors.
3. Widget floor: agreed. nodes_textgen.py currently declares repetition_penalty with default=1.05, min=0.0, max=5.0. It should not offer a value that can wedge the server. A positive minimum would close that UI path independently of the runtime guard.
4. Identity test: agreed — and our CPU-only harness covers it.
The harness AST-extracts penalty_active, apply_penalty, and processed_probs from llama.py, then runs plain torch without importing ComfyUI or initializing a GPU. It checks:
rp=0stays finite and is identical torp=1.0/ the raw logits;rpvalues0.9,1.05,1.1, and1.2stay finite, while1.2still changes the logits;presence_penalty=0.5still subtracts as expected;penalty_active(0.0, 0.0)is false, and negativerpis treated as off;- the guard raises on NaN logits and zero-mass probabilities; and
- a healthy distribution still sums to 1.
5. On presence_penalty: the subtraction itself (logits - presence_penalty) cannot create a non-finite result from finite inputs; it can only propagate one already present. The general probability guard is still valuable for catching any such upstream invalid value.
We can share the test harness and the two compatibility patches (penalty_active / apply_penalty, plus the processed_probs guard) if useful. Our validation is on torch 2.14.0+rocm10.1.0, HIP 7.16.26385, R9700/gfx1201; we can't validate CUDA here.
Disclosure: written with LLM assistance, as in the original report.
Taking the disagreement seriously, because I think you're right about the outcome and wrong about what's being preserved — and the zero-mass catch is a real improvement on what I wrote.
1. "Clamping preserves saved workflows" preserves a workflow that was never working.
Trace rp=0 through the exact code you pasted: torch.where(logits < 0, logits * 0, logits / 0). The first branch yields exactly 0.0 (sign lost, value zero — not -inf), the second yields +inf. So the logits handed to softmax are a mix of {+inf, 0, finite}, which softmax turns into NaN mass, which is the wedge. Any rp=0 graph that has ever run to completion did so on a path that didn't call apply_penalty — i.e. the setting was inert, not effective. So the compatibility argument is weaker than it looks: there is no correct output being preserved, only a saved value that happens to be a landmine. Clamping is still the right call (see 3), but the justification should be "don't hard-fail a graph at load time for a value the old UI allowed", not "keep old behaviour".
2. Your zero-mass check is the better half of the guard — one addition.
isfinite alone misses the all--inf logits case exactly as you say; and NaN-vs-zero-mass are different failures that produce the same symptom (multinomial either raises a cryptic CPU-only error or spins). Worth also keeping the offending row, not just the shape: on a batched generate the first bad row tells you which node/config, and shape= alone doesn't. Cheap version: bad = (~torch.isfinite(probs)).any(-1) | (probs.sum(-1) <= 0) then index the first True and include top_k/top_p/min_p for that row only.
3. Synthesis I'd argue for: clamp at the entry (your <= 0.0 normalisation) plus a one-time warning that names the node, and keep the hard raise only at the sampling funnel. Then rp=0 graphs load and run with rp=1.0 (compat), the user gets told once that the value was ignored (learning), and a genuine NaN from any other cause still fails loudly instead of spinning. The thing that must not happen is a silent clamp with no log line — that's how this bug stayed invisible in the first place.
4. penalty_active() and apply_penalty() sharing normalisation by copy is the next drift bug. Both currently repeat <= 0.0 → 1.0 inline. Pull it into one normalize_rp() that both call, and let the test assert the two agree for {-1, 0, 1e-9, 1.0, 1.05} — the gate and the sampler disagreeing is a class of bug your harness can catch for free.
5. Harness offer: yes please, and one request. Your AST-extract approach is better than what I assumed. What I'd ask for: a bitwise-identity assertion (rp=1.0 output tensor equals raw logits exactly, torch.equal, not allclose) plus the differential case presence_penalty set and rp off — those two catch accidental changes to the arithmetic, which finiteness checks pass silently.
Limits on my side, stated plainly: I have no GPU here, so I cannot validate your ROCm/HIP numbers or the CUDA claim either — CPU-only torch is what I can run, which is enough to check the harness itself but says nothing about the wedge. So treat this as code review, not independent verification.