How frequency_penalty and presence_penalty Differ in Long-Text Loop Prevention
Both frequency_penalty and presence_penalty adjust token logits before sampling based on whether a token has already appeared in the generated context (and sometimes the prompt, depending on the backend/API), but they scale the penalty differently—leading to distinct behavior in long generations:
frequency_penalty(proportional to occurrence count): Subtracts a penalty proportional to how many times token $t$ has already appeared in the context (commonly modeled as subtracting $\alpha_f \cdot \text{count}(t)$ from the logit of token $t$). A word appearing once gets a mild nudge; a word appearing 15 times in a long generation gets a heavy penalty, making it effective at suppressing runaway repetition of specific words or phrases while still allowing occasional reuse when genuinely needed.presence_penalty(flat binary/step penalty once present): Applies a fixed penalty ($\alpha_p$) as soon as token $t$ has appeared at least once (or above a threshold), regardless of whether it occurred 1 time or 20 times. This pushes the model to introduce new topics, synonyms, or vocabulary rather than reusing already-seen tokens.- Long-text behavior trade-offs: In long outputs, a high
frequency_penaltycan become overly aggressive on common function words or domain terms that recur naturally across many paragraphs, whereas a highpresence_penaltycan force unnatural synonym swapping or topic drift once a rich vocabulary has already been used.
Steps to Tune frequency_penalty and presence_penalty for Long Generations
- Diagnose the exact repetition failure mode: Distinguish between exact token/phrase loops (e.g., repeating a clause, bullet pattern, or word over and over) versus stagnant vocabulary/topic recycling (revisiting the same ideas without moving forward).
- Start with
frequency_penaltyfor verbatim/phrase loops: Apply a modestfrequency_penalty(for example,0.2to0.6) first when long responses get stuck repeating specific words or lines. - Add a light
presence_penaltyonly when broader lexical variety is needed: Use a smallpresence_penalty(for example,0.1to0.4) when you want fresh phrasing or new subtopics, keeping values low so technical terms, JSON keys, or identifiers aren’t penalized into awkward synonyms. - Test on long-form prompts and check schema/code safety: Evaluate at realistic
max_tokenslengths and avoid high penalties when generating strict JSON, code, or exact identifiers where repeating exact tokens is required.
TypeScript Example: Comparing frequency_penalty and presence_penalty Configurations
import OpenAI from "openai";
const openai = new OpenAI();
export interface PenaltyPreset {
name: string;
frequencyPenalty: number;
presencePenalty: number;
rationale: string;
}
export const LONG_TEXT_PENALTY_PRESETS: Record<string, PenaltyPreset> = {
loopSuppression: {
name: "Loop Suppression (Count-Based)",
frequencyPenalty: 0.45,
presencePenalty: 0.0,
rationale: "Penalizes heavily repeated tokens more as their count grows without forcing abrupt topic shifts.",
},
topicAndVocabularyDiversity: {
name: "Topic & Vocabulary Diversity (Presence-Based)",
frequencyPenalty: 0.1,
presencePenalty: 0.35,
rationale: "Applies a flat nudge once a token appears so the model branches into fresh terms and angles.",
},
balancedLongForm: {
name: "Balanced Long-Form Prose",
frequencyPenalty: 0.3,
presencePenalty: 0.2,
rationale: "Curbs recurring phrases in long outputs while keeping tone coherent and domain terms intact.",
},
};
export async function generateWithPenaltyPreset(
prompt: string,
presetKey: keyof typeof LONG_TEXT_PENALTY_PRESETS,
maxTokens = 1500
): Promise<string> {
const preset = LONG_TEXT_PENALTY_PRESETS[presetKey];
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0.7,
max_tokens: maxTokens,
frequency_penalty: preset.frequencyPenalty,
presence_penalty: preset.presencePenalty,
messages: [
{
role: "system",
content: "Write clear, well-structured technical prose without repeating sentences.",
},
{
role: "user",
content: prompt,
},
],
});
return response.choices[0]?.message.content ?? "";
}
Helpful Tips for Production Long-Text Orchestration
- Prefer lower penalties for structured outputs, code, and RAG: High
frequency_penaltyorpresence_penaltycan distort exact field names, variable names, citations, or factual terms—keep them near0for deterministic extraction or code generation. - Combine sampling controls with structural guardrails: Logit penalties help reduce repetitive loops, but for strict formatting or non-repeating sections, pair moderate penalties with clear section outlines, stop sequences, or post-generation repetition checks.
- Verify provider parameter support across backends: Not all OpenAI-compatible inference servers or reasoning models implement
frequency_penaltyandpresence_penaltyidentically (some ignore or restrict them), so validate behavior on your exact target model.
You must log in or register to comment.
