Troubleshooting Abnormal Characters and Repetitive Output in Large Language Models
This article breaks down two common large language model output issues: leaked special tokens and garbled characters, and repetitive or looping responses. It explains how to isolate each problem by layer, then applies targeted fixes for online chat services and local deployments, covering decoding settings, tokenizer behavior, chat templates, sampling parameters, context management, and engineering safeguards such as logging and regression testing.
1. Symptoms and Overall Troubleshooting Approach
When building or directly using large language model applications, developers frequently run into two troublesome types of output anomalies. The first is content mixed with low-level control strings that should never be exposed, such as <|im_start|>, escape sequences, or block characters. The second is a model that gets stuck in a loop, repeating the same sentence until it hits the length limit. These two problems look similar on the surface, but their root causes belong to different parts of the pipeline. The first usually occurs in the decoding and rendering stage after text generation; the second usually occurs in the sampling and context management stage during text generation. The correct troubleshooting order is therefore to isolate the problem by layer first, then apply a targeted fix, rather than blindly tuning parameters.
It is best to verify along two separate tracks: the online service scenario and the local deployment or API call scenario. The controllable variables are completely different in each case. In an online scenario, you can only adjust the input and the client environment. In a local scenario, you have full control over the decoder, the template, and the sampling parameters.
2. Special Strings and Garbled Characters in the Output
2.1 Online Chat Scenario
The most common cause in online services is that the role separator markers used on the inference side are not being filtered correctly by the frontend. During training and inference, the model relies on a set of reserved markers to distinguish system instructions, user input, and assistant replies. Under normal conditions, these markers should be stripped on the server side. If the rendering logic misbehaves or streaming chunk concatenation goes wrong, the reserved markers appear on the page as-is.
The second cause is client-side encoding and caching. If the page is not parsed correctly as UTF-8, Chinese characters and special symbols degrade into question marks, block characters, or leftover escape sequences in the \uXXXX form. This kind of problem is usually related to corrupted browser cache or stale frontend assets that have not been refreshed.
The third cause is context overload. When the conversation history approaches the window limit, the model’s available reasoning space is compressed, the output distribution becomes chaotic, and the probability of reserved marker leakage rises accordingly.
Apply the fixes from lowest to highest cost: start a new session to clear the history; clear the client cache and retest using incognito mode or a different browser engine; add an explicit constraint to the system prompt requiring natural language body text only and prohibiting any control markers. Note that prompt constraints can only reduce the probability; they cannot replace server-side filtering.
2.2 Local Deployment and API Call Scenario
The root causes are more clear-cut in a local setup. First, the decoding stage does not skip special markers, so the tokenizer prints the reserved markers along with the text when reconstructing it. This is the most frequent cause. Example code:
text = tokenizer.decode(output_ids,skip_special_tokens=True,clean_up_tokenization_spaces=True)
Second, the model weight file is downloaded incompletely or a quantized shard is missing, which causes decoding misalignment and garbled characters. Pull the files again in full and verify the hash values. Third, the API transport does not declare UTF-8, so Chinese characters and symbols leave escape residue as they pass across layers. Standardize the response header:
Content-Type: application/json; charset=utf-8
Fourth, the chat template is missing or does not match the model. The template determines the input concatenation format. If it is missing or a broken custom version is used, the model cannot see the correct role boundaries and will keep generating while treating internal markers as body text. Always use the official template that matches the model version, not a hand-written simplified one.
3. Repetitive and Looping Responses
3.1 Improper Sampling Parameter Configuration
The vast majority of repetition problems come from sampling configuration. A temperature that is too low makes the distribution overly sharp, so the model repeatedly picks the same high-probability token. A missing or neutral repetition penalty produces no suppression at all. A candidate pool threshold that is too low leaves too few selectable tokens, which further aggravates reuse. A maximum generation length set too high lets the model fill the quota by repeating itself when it has nothing left to say.
A reasonably safe general starting point is below; the exact values still need fine-tuning per task type:
temperature = 0.7top_p = 0.9repetition_penalty = 1.3 ~ 1.4presence_penalty = 0.6max_new_tokens = 512 (can be relaxed to 800 for technical documentation)
For deterministic tasks such as extraction and classification, adjust in the opposite direction: lower the temperature and tighten the length to avoid unnecessary divergence.
3.2 Context Overflow and Missing Structure
When the input exceeds the window, early instructions are truncated, the model loses its format constraints, and it tends to degrade into repetition. In addition, failing to trim history in multi-turn conversations, or stuffing an entire long document into the prompt, also squeezes the generation space. It is recommended to summarize and compress the history, split long documents and retrieve segments before concatenation, and keep the system instruction at the very front.
3.3 Additional Decoding Strategies
Beyond parameters, you can add structured suppression: enable repeated n-gram blocking, maintain a set of generated segments for post-processing deduplication, and add termination conditions to the output stream so that generation stops immediately and falls back to resampling once consecutive repetition is detected. In engineering practice, also write the generation parameters, template version, and model version into the logs to make reproduction and diagnosis easier.
4. Engineering Practices for Prevention
Turning the fixes above into default configurations and validation workflows is the key to long-term stability: encapsulate decoding and encoding settings uniformly at the inference entry point; verify model file integrity before release; run regression tests on output quality with a fixed set of test cases; and use a general logging service with monitoring and alerting to establish observability metrics for the abnormal output rate, average generation length, and truncation rate. If you adopt a cloud-based approach, you can combine a container platform to host the inference service, object storage to hold model assets, and a message queue to smooth out traffic spikes, keeping occasional anomalies within an observable and rollback-safe range.
