Improving Large Language Model Safety with Contrastive Representation Learning

Samuel Simko, Mrinmaya Sachan, Bernhard Schölkopf, Zhijing Jin
6/13/2025
cs.CLcs.AIcs.LG

Official code: samuelsimko/crl-llm-defense (5 stars, MIT, last commit 2025-06-20).

Abstract

Large Language Models (LLMs) are powerful tools with profound societal impacts, yet their ability to generate responses to diverse and uncontrolled inputs leaves them vulnerable to adversarial attacks. While existing defenses often struggle to generalize across varying attack types, recent advancements in representation engineering offer promising alternatives. In this work, we propose a defense framework that formulates model defense as a contrastive representation learning (CRL) problem. Our method finetunes a model using a triplet-based loss combined with adversarial hard negative mining to encourage separation between benign and harmful representations. Our experimental results across multiple models demonstrate that our approach outperforms prior representation engineering-based defenses, improving robustness against both input-level and embedding-space attacks without compromising standard performance. Our code is available at https://github.com/samuelsimko/crl-llm-defense

View on arXivView PDF

Code Implementations(1)

MIT
50Shell, PythonJun 12, 20251 years agoMIT

Similar Papers

Cite this paper

@article{simko2025improving,
  title  = {Improving Large Language Model Safety with Contrastive Representation Learning},
  author = {Samuel Simko and Mrinmaya Sachan and Bernhard Schölkopf and Zhijing Jin},
  year   = {2025},
  eprint = {2506.11938},
  archivePrefix = {arXiv},
  url    = {http://arxiv.org/abs/2506.11938v2}
}

Add a badge to your README

Shows whether official code is linked for this paper.

Code of Paper badge
[![Code of Paper](https://codeofpaper.com/badge/2506.11938.svg)](https://codeofpaper.com/paper/2506.11938)

Discussion