Copy-Constrained Tagging: Turning a Language Model into a Toxic Span Tagger

Content moderators need to know which words make a comment toxic, not only whether it is. Large language models understand context much better than keyword lists, yet they are poor at this localization task. When asked to name the offending span, they paraphrase it, invent text that is not in the comment, or miscount character positions. The best systems on the standard benchmark are therefore still fine-tuned BERT-style taggers, and those taggers behave largely like profanity detectors. They find single swear words and almost never recover toxic phrases of five or more words.

We propose to remove the LLM's freedom to fail at copying. The model rewrites the input comment character-for-character, and its only permitted choice at each position is whether to insert an opening or closing <toxic> marker. This rule is enforced during decoding by masking any token that would break the copy, a technique called grammar-constrained decoding: the model's vocabulary is filtered at every step so that only continuations allowed by a formal rule can be produced. Because every copied character is forced, the output always aligns exactly with the source. The model's probability of inserting a marker at each position also becomes a boundary score that can be read out, calibrated, and thresholded. In effect, a generative LLM becomes a context-aware span tagger, with no offset arithmetic and no rewrite-then-diff step.

Core Claim

The claim is that copy-constrained inline tagging lets an open-weight LLM match fine-tuned encoder taggers on overall character-level F1 for toxic spans, and clearly beat them on multi-word spans, which are the regime where encoders collapse. The constraint contributes more than well-formed output. It turns each tag decision into a probability conditioned on the full comment, and that probability supports threshold tuning and combination with an encoder. Prompting followed by post-hoc alignment cannot provide either.

We define the constraint precisely. Let $s$ be the source comment as a character string. Let $c_t$ be the number of source characters already copied after $t$ decoding steps, and let $o_t \in \{0,1\}$ record whether a toxic span is currently open. The set of allowed next tokens is

$$ A_t = \{\, v \in V : \mathrm{str}(v) \text{ is a prefix of } s[c_t{:}] \,\} \;\cup\; \{\texttt{<toxic>} \text{ if } o_t=0,\ \texttt{</toxic>} \text{ if } o_t=1\}, $$

where $V$ is the model's vocabulary and $\mathrm{str}(v)$ is the text a token decodes to. The match is on characters, not on how the tokenizer would split the original comment. This matters for noisy toxic text: obfuscated spellings, emoji, and agglutinative morphology fragment unpredictably under subword tokenization, and inserted tags change the split further. With character matching, every tokenization that reproduces the source stays legal.

Relation to Prior Work

Two toxicity papers motivate the proposal by showing that unconstrained generation cannot localize spans.

  • You Only Prompt Once prompt-tunes T5 and GPT-2 to rewrite a comment without its toxic parts. It then aligns the rewrite to the source to infer offsets and reaches 0.643 F1 on SemEval-2021 Task 5. Any paraphrase in the rewrite corrupts that alignment. Our method never lets the model paraphrase.
  • CMD (also released as Detoxify Language Model Step-by-Step) builds a detect-then-rewrite chain of thought. Its authors fell back on an external Segment-CNN because the LLMs could not reliably find spans themselves.
  • HATECAT-TR finds that decoder LLMs trail the Turkish encoder BERTurk on span detection. It also reports that GPT-4o's prompted annotations needed two rounds of human correction.

We read all three as evidence that the failure lies in the output interface, and we test that reading directly.

The structured-output papers supply the method.

  • Grammar-Constrained Decoding for Structured NLP Tasks without Finetuning masks logits with an incremental grammar parser. It introduces input-dependent grammars, whose legal outputs are built from the specific input, for entity disambiguation, where they raise LLaMA-33B's average accuracy from 54.1% to 80.3%. Our copy grammar is an input-dependent grammar of a new kind: it constrains where the model may annotate, not which candidate it may name.
  • SynCode identifies the mismatch between subword tokens and grammar symbols as the central difficulty in constrained decoding. It resolves the mismatch for code and JSON with precomputed masks. We face the same problem in noisy social media text, which neither paper evaluates.
  • CodeIE shows that code-style prompts cut unparseable extraction outputs from 10–30% to nearly zero. It outputs surface strings on clean named-entity benchmarks and never computes character offsets, so it is a format baseline for us, not a solution.
  • Lazy-k decoding searches alternative label assignments only when the top prediction violates a global constraint. We adapt its search idea to tag placement.

One finding constrains our expectations. In the GCD paper, constrained LLaMA still trailed supervised constituency parsers, because guaranteed validity did not produce accuracy. We therefore do not claim that the constraint alone yields accuracy. We claim it makes the model's contextual judgment readable at character granularity. The encoder literature says where that judgment should matter most:

- Cisco at SemEval-2021 reports F1 around 0.65 on single-word spans and below 0.10 on spans of five or more words.

Research Program

We will build the constrained decoder as an extension of epfl-dlab/GCD (Transformers-CFG). Per input, we replace its static grammar with the character-prefix mask above. We will precompute a trie over decoded token strings so that each step's mask is a trie walk over the remaining source.

Decoding is a search over marker placements. Greedy decoding inserts a tag whenever its probability beats the best copy token. The variant we expect to be better treats tag insertion as a binary decision with a tunable threshold $\tau$: open a span at position $i$ if $p(\texttt{<toxic>} \mid \text{prefix}) > \tau$, and close it analogously. We will add a Lazy-k-style search that revisits the lowest-margin tag decisions when a global check fails, for example a span left open at the end of the comment. We will also derive a per-character toxicity score by teacher-forcing the copy and reading the marker probabilities. This score can be averaged with an encoder tagger's marginals.

We will run the method in three regimes on open-weight decoder models of two sizes from the LLaMA and Gemma families used in HATECAT-TR:

  • zero-shot, with instruction only;
  • few-shot;
  • LoRA fine-tuning on the SemEval training split, rendered in the inline-tag format.

The fine-tuned regime is essential. Without it, any loss to encoders could be blamed on lack of supervision.

Alongside, we will run a controlled format study that crosses output format with enforcement. The three formats are JSON character offsets, JSON verbatim substrings, and inline tags. Each is run unconstrained, with the format enforced by a grammar, and, for substrings and tags, with the input-dependent copy constraint. Holding the model and training data fixed, the study separates three effects: format choice, constraint on syntax alone, and constraint on copying. It also tests the concern from the structured-output literature that heavy syntax overhead degrades reasoning. Inline tags add two marker types. JSON offsets add brackets, quotes, and arithmetic.

Baselines

The do-nothing reference points are the official SemEval baselines reported in the task overview: 69.89%, 50.98%, and 12.22% character F1. We will also run two floors ourselves: predicting no spans, and matching against a profanity lexicon. The lexicon floor stands in for the dictionary expansion that HITSZ-HLT found raised recall but badly hurt precision.

The strongest existing methods are fine-tuned encoder taggers. The winning HITSZ-HLT ensemble reports 70.83% character F1 on the SemEval-2021 Task 5 test set. Its single BERT+CRF reports 69.44%, and Cisco's XLNet-Large BiLSTM-CRF reports 0.6922.

We will retrain BERT+CRF and a span-boundary variant ourselves. They will use the same training split, the same development-set early stopping, and a hyperparameter search budget matched in GPU-hours to the LoRA runs. We will apply the whitespace and punctuation normalization that Cisco found worth over 16 points to every system, so that preprocessing does not decide the comparison.

Beating the encoder means one of two outcomes:

  • overall test F1 within one point of our retrained BERT+CRF, together with a clear gain on the five-plus-word bucket, where Cisco reports below 0.10;
  • overall F1 above 70.83 when our character scores are combined with the encoder's.

The generative reference is You Only Prompt Once at 0.643 F1. We will reimplement its rewrite-then-align procedure on our LLMs so that model scale is held constant.

The key ablation removes the copy constraint while keeping everything else fixed. It uses the same model, the same inline-tag prompt or LoRA weights, unconstrained decoding, and alignment of the output back to the source by edit distance. This isolates what the constraint contributes beyond the format.

Why not just…?

Why not just fine-tune BERT+CRF, which already scores 70.83? This is the most serious threat, and we may not beat it on overall F1. SemEval is dominated by short profanities, which encoders handle well. The case for our method rests on long and contextual spans, where Cisco shows encoder F1 below 0.10, and on combination with encoders. The span-length breakdown will show whether the LLM's contextual advantage is real. If LLM tagging does not beat the encoder on the five-plus-word bucket even after fine-tuning, the proposal's central claim fails and we will report that.

Why not just prompt for inline tags and align the output back to the source afterwards? Fuzzy alignment will often recover valid offsets, so validity alone is a weak argument. The ablation above measures the F1 gap directly. We expect the gap to concentrate on noisy and obfuscated comments, where alignment is ambiguous. More importantly, unconstrained decoding gives no per-position marker probability conditioned on an exact copy of the source. Threshold tuning and encoder combination depend on that probability. If the ablation ties on F1 and the thresholded or combined variants add nothing, the constraint is not earning its cost.

Why not just put a token-classification head on the LLM and drop generation entirely? A decoder read left to right, with a classification head, sees only left context at each token. Our model sees the whole comment in the prompt before it begins copying. We will still run this head as a baseline, with the same LoRA budget and the same bidirectional prompt prefix, because it is the cheapest way to exploit an LLM's representations. If it matches copy-constrained tagging, the generative format is unnecessary and we will say so.

Proposed Experiments and Decisive Checks

The primary benchmark is SemEval-2021 Task 5, with its 6,894 training, 1,723 development, and 2,000 test comments. We will report:

  • character-level precision, recall, and F1 under the official convention for comments with no gold span;
  • F1 broken down by span length (one word, two to four words, five or more words), following Cisco's analysis;
  • F1 on toxic comments with no gold span, which the task overview identifies as a persistent failure;
  • the rate of valid, exactly aligned outputs;
  • latency per comment, compared against GCD's reported 1–4 ms per token overhead.

The second benchmark is HATECAT-TR. Its Turkish morphology stresses the character-matching claim, and its human detection agreement of F1 = 0.77 serves as a practical ceiling. There we compare against BERTurk, which is the paper's best model. The file reports no global span F1 for it, so we retrain it under the matched budget.

Three results would be decisive:

  1. Long spans. The fine-tuned, copy-constrained LLM clearly exceeds the retrained encoder on five-plus-word spans without losing more than a point overall.
  2. Constraint versus alignment. Copy-constrained decoding beats unconstrained decoding with post-hoc alignment at equal model and weights, with most of the gain on obfuscated text.
  3. Combination. Averaging the LLM's character scores with the encoder's pushes test F1 past the 70.83 reported for the HITSZ-HLT ensemble.

The format study additionally settles whether JSON offsets are worse than inline tags under identical enforcement. If they are, that is direct evidence that output syntax affects span judgment on this task.