---
title: "Generating Human-level Text with Contrastive Search in Transformers 🤗"
description: "Contrastive search is a decoding method for neural text generation that picks each token from the model's top-k candidates by balancing model confidence against a degeneration penalty: the maximum cosine similarity between the candidate's hidden representation and those of prior context tokens."
url: "https://swe.quest/articles/generating-human-level-text-with-contrastive-search-in-transformers-e7358d1977f145fe"
canonical: "https://huggingface.co/blog/introducing-csearch"
source: "Hugging Face"
published: "2022-11-08"
difficulty: "medium"
kind: "How-to"
reading_minutes: 18
tags: ["llms","inference","python"]
---

# Generating Human-level Text with Contrastive Search in Transformers 🤗

A post on [Hugging Face](https://swe.quest/sources/hugging-face.md), published 2022-11-08, 18 min read, How-to. Original: [https://huggingface.co/blog/introducing-csearch](https://huggingface.co/blog/introducing-csearch)

## Summary

Contrastive search is a decoding method for neural text generation that picks each token from the model's top-k candidates by balancing model confidence against a degeneration penalty: the maximum cosine similarity between the candidate's hidden representation and those of prior context tokens. Greedy and beam search tend to produce repetitive text, and nucleus sampling tends to lose coherence. Contrastive search avoids both and is available in Hugging Face transformers via \`penalty\_alpha\` and \`top\_k\` in \`generate()\`. GPT-2 examples (k=4, α=0.6) and token-similarity matrices show it removes the off-diagonal repetition patterns that greedy search produces, and α=0 reduces it to greedy search.

Written by swe.quest, not by the author.

**Difficulty:** Medium: assumes a working developer; shows how it is built or done

## Topics

- [LLMs](https://swe.quest/tags/llms.md) (AI & ML)
- [Inference & serving](https://swe.quest/tags/inference.md) (AI & ML)
- [Python](https://swe.quest/tags/python.md) (Languages)

## Prerequisites

- language model decoding basics
- Hugging Face transformers
- Python ([easy posts on Python](https://swe.quest/tags/python.md?difficulty=easy))

## Keywords

Contrastive Search, Hugging Face Transformers, GPT-2, nucleus sampling, top-k sampling, beam search

## Related posts

- [Train a Sentence Embedding Model with 1B Training Pairs](https://swe.quest/articles/train-a-sentence-embedding-model-with-1b-training-pairs-f0642783223f8c14.md): Hugging Face · 2021-10-25 · Hard · 6 min read · Model training, Machine learning, Vector search
  Sentence embedding models trained with a contrastive multiple-negatives ranking loss (InfoNCE) on up to 1 billion sentence pairs, using in-batch negatives, a scaled similarity (C≈20), and cosine vs. dot-product tradeoffs for clustering and ANN search.
- [Direct Preference Optimization Beyond Chatbots](https://swe.quest/articles/direct-preference-optimization-beyond-chatbots-b552e31e2b3fa017.md): Hugging Face · 2026-06-03 · Hard · 13 min read · Model training, LLMs, Computer vision, Evaluation
  Adding a DPO stage after supervised fine-tuning reduced text degeneration (repetition loops) in every one of five vision-language model families tested on Brazilian Portuguese structured OCR.
- [Shaping Product Understanding with Contrastive Reinforcement Learning](https://swe.quest/articles/shaping-product-understanding-with-contrastive-reinforcement-learning-dd8440354bbdc8d2.md): Etsy Code as Craft · 2026-05-26 · Hard · 9 min read · Model training, LLMs, Search, Recommendations & ranking, E-commerce
  Etsy fine-tunes Qwen3-VL-8B with GRPO to generate natural-language listing summaries that capture distinguishing product details buried in long descriptions, attributes and images.
- [Building Deep Research: How we Achieved State of the Art](https://swe.quest/articles/building-deep-research-how-we-achieved-state-of-the-art-414ffb743a73bb80.md): Hugging Face · 2025-11-24 · Medium · 7 min read · AI agents, LLMs, Evaluation
  Tavily's deep research agent reached state of the art on DeepResearch Bench while using 66% fewer tokens than LangChain's Open Deep Research, mainly through context engineering.
- [Build a Domain-Specific Embedding Model in Under a Day](https://swe.quest/articles/build-a-domain-specific-embedding-model-in-under-a-day-f4f33fdd5dd688e6.md): Hugging Face · 2026-03-20 · Medium · 13 min read · RAG & retrieval, Model training, Search, Inference & serving
  A single-GPU pipeline fine-tunes Llama-Nemotron-Embed-1B-v2 for a specific domain in under a day without manual labels.

Browse: [Latest posts](https://swe.quest/index.md) · [Topics](https://swe.quest/tags.md) · [Sources](https://swe.quest/sources.md) · [Topic map](https://swe.quest/map.md) · [Site guide (llms.txt)](https://swe.quest/llms.txt)
