Detoxification of large language models via regularized fine-tuning

Attribute-controlled fine-tuning can produce LLMs that adhere to policy while achieving competitive performance on general benchmarks.

Large language models (LLMs) have demonstrated impressive performance across a variety of tasks, but, as has been clear in multiple instances, they carry the risk of producing inappropriate, unsafe, or biased outputs. When generating responses, a successfully trained LLM should comply with a set of policies specified by its creator; for example, the developer may want to restrain the LLM from generating toxic responses. We refer to this as attribute control, as it regulates an attribute of the LLM output.

In a paper we presented at EMNLP 2024, we propose a novel method for training an LLM to adhere to a set of constraints while preserving its performance. We first define a successfully trained LLM as one that can satisfy the following constraints: (1) Attribute control — the LLM output adheres to a policy, defined by the creator in most cases; (2) Utility preservation — the LLM maintains performance comparable to that of the original LLM on utility benchmarks; and (3) Training efficiency — the cost of fine-tuning with attribute control is similar to that of typical fine-tuning.

Related content
Generative AI raises new challenges in defining, measuring, and mitigating concerns about fairness, toxicity, and intellectual property, among other things. But work has started on the solutions.

Our work is inspired by the classic idea of constraint-driven learning and posterior regularization, in which the model output is forced to adhere to a particular distribution. Specifically, we train an auxiliary model to control a specific output attribute — in this case, toxicity. During fine-tuning, the auxiliary model estimates the closest distribution that, given the current state of the LLM, satisfies the constraints, and it penalizes the gap between that estimate and the LLM’s current distribution.

The natural way to do this is to iteratively push the LLM closer to the feasible region of generations, making the estimation progressively more accurate. However, this approach is sequential, and it causes a significant increase in run time. In our paper, we also present a parallelized algorithm that updates the base LLM and regularizer simultaneously, based on their status in the last iteration. Empirically, parallelization achieves the same level of performance as sequential fine-tuning, and the time complexity is the same as that of typical, unregularized fine-tuning.

Detoxification.png
A comparison of sequential (left) and parallel (right) fine-tuning over three iterations.

We also explore adaptive regularization (i.e., the use of a domain-specific regularizer on related parts of the training data) to improve performance and prevent catastrophic forgetting.

Utility is preserved

In experiments, we fine-tuned Llama-7B and Falcon-7B models on a mixture corpus including ToxiGen (data containing toxic responses) and Wikitext (general corpus) in equal proportions. With the adaptive regularizer, our approach, overall, preserved performance better than the standard approaches of reinforcement learning (RL) and filtering, while meeting toxicity control standards.

Benchmark performance of Llama-7B and Falcon-7B with toxicity control

Model

ToxiGen (lower is better)

MMLU (5-shot) (higher is better)

Com. reasoning (0-shot) (higher is better)

Llama-7B

Baseline

23

35.1

75.6

Filtering

21.9

34.6

75.1

RL

15.2

33.6

73.2

NADO decoding

15.2

31.1

71.4

Ours w/o adaptive

15.2

30.4

71.9

Ours w/ adaptive

14.2

33.9

73.6

Falcon-7B

Baseline

14

27.2

76.1

Filtering

13.6

26.4

74.9

RL

9.8

25.4

74.4

NADO decoding

7.3

23.6

72.5

Ours w/o adaptive

7.1

23.1

71.8

Ours w/ adaptive

7.3

26.1

74.5

Generation quality is preserved

Sequences produced by our model were indistinguishable, in terms of quality, from those produced by the base model, when OPT-30B acted as a judge. This demonstrates that our method retains the quality of generation. Our model also outperformed models trained using filtering and RL approaches.

Win rate against baseline

Win rate

Base

Filter

RL

Ours

Base

N/A

44.3

45.1

51.4

Filtering

55.7

N/A

53.4

61.6

RL

54.9

46.6

N/A

61.3

Ours

48.6

38.4

38.7

N/A

Toxicity classification and generation

One of the most interesting aspects of our method is that it allows the LLM to learn from toxic content. In experiments, we fine-tuned Llama-7B models on a toxicity classification task using the Jigsaw dataset of toxic content. With standard supervised fine-tuning, the model’s performance on the classification task improved, but the increased exposure to toxic content made it more likely to generate toxic content itself. With our method, on the other hand, improving performance on the classification task reduced the generation toxicity.

Jigsaw performance using Llama-7B model with toxicity control

Model

API tox.

Classify ROC

Baseline

0.315

0.910

SFT (LLM loss)

0.344

0.966

Ours (LLM loss)

0.288

0.959

SFT (classification)

0.314

0.972

Acknowledgements: I would like to acknowledge our intern, Tao Meng (UCLA), who led the work on this paper, and our coauthors, Ninareh Mehrabi, Palash Goyal, Anil Ramakrishna, Aram Galstyan, Richard Zemel, Kai-Wei Chang, and Rahul Gupta, for their contributions.

Research areas

Related content

US, MA, N.reading
Amazon is seeking exceptional talent to help develop the next generation of advanced robotics systems that will transform automation at Amazon's scale. We're building revolutionary robotic systems that combine cutting-edge AI, sophisticated control systems, and advanced mechanical design to create adaptable automation solutions capable of working safely alongside humans in dynamic environments. This is a unique opportunity to shape the future of robotics and automation at an unprecedented scale, working with world-class teams pushing the boundaries of what's possible in robotic dexterous manipulation, locomotion, and human-robot interaction. This role presents an opportunity to shape the future of robotics through innovative applications of deep learning and large language models. At Amazon we leverage advanced robotics, machine learning, and artificial intelligence to solve complex operational challenges at an unprecedented scale. Our fleet of robots operates across hundreds of facilities worldwide, working in sophisticated coordination to fulfill our mission of customer excellence. The ideal candidate will contribute to research that bridges the gap between theoretical advancement and practical implementation in robotics. You will be part of a team that's revolutionizing how robots learn, adapt, and interact with their environment. Join us in building the next generation of intelligent robotics systems that will transform the future of automation and human-robot collaboration. Key job responsibilities - Design and implement whole body control methods for balance, locomotion, and dexterous manipulation - Utilize state-of-the-art in methods in learned and model-based control - Create robust and safe behaviors for different terrains and tasks - Implement real-time controllers with stability guarantees - Collaborate effectively with multi-disciplinary teams to co-design hardware and algorithms for loco-manipulation - Mentor junior engineer and scientists
US, CA, San Francisco
PXT Central Science is seeking an exceptional Data Scientist to join our team. The ideal candidate will thrive in a dynamic, multifaceted role where you'll translate complex business challenges into rigorous quantitative frameworks, extract actionable insights from structured and unstructured datasets, and architect science-backed, scalable solutions that elevate the experience of our 1 million+ employees worldwide. If you're energized by the opportunity to apply data science to our mission of making Amazon Earth's Best Employer, we want to hear from you. Key job responsibilities • Own the design, development, and maintenance of scalable models and prototypes leveraging statistical, machine learning, or GenAI methodologies to enhance employee experience. • Partner with scientists, engineers, and product leaders to solve for employee experience defects using scientific approaches, building new services and tools that deliverable measurable impact. • Author and maintain detailed technical documentation related to the projects you drive. • Communicate results to diverse audiences of varying technical background with effective writing, visualizations, and presentations • Stay current with emerging methods and technologies, and implement them strategically to amplify the team’s impact. About the team The Central Science Team within Amazon’s People Experience and Technology org (PXTCS) uses economics, behavioral science, statistics, machine learning, and Generative AI to proactively identify mechanisms and process improvements which simultaneously improve Amazon and the lives, well-being, and the value of work to Amazonians. We are an interdisciplinary team, which combines the talents of science, engineering, and UX to develop and deliver solutions that measurably achieve this goal.
US, WA, Seattle
Do you want to work on Reinforcement Learning (RL) post-training of frontier Large Language Models (LLMs) to revolutionize customer service? Come join the world class researchers and academics in the AWS AI endeavor, and develop the science that powers countless new businesses in cloud computing! AWS, the world-leading provider of cloud services. Our customers bring problems that will give Applied Scientists like you endless opportunities to see your research have a positive and immediate impact in the world. You will have the opportunity to partner with technology and business teams to solve real-world problems, have access to virtually endless data and computational resources, and to world-class engineers and developers that can help bring your ideas into the world. As part of the team, we expect that you will develop innovative solutions to hard problems, and publish your findings at peer reviewed conferences and journals. The scientific topics you are going to work on include, but are not limited to: LLM post-training to improve capabilities particularly for instruction following, reasoning over long context, and tool use, etc. About the team Why AWS Amazon Web Services (AWS) is the world’s most comprehensive and broadly adopted cloud platform. We pioneered cloud computing and never stopped innovating — that’s why customers from the most successful startups to Global 500 companies trust our robust suite of products and services to power their businesses. Inclusive Team Culture Here at AWS, it’s in our nature to learn and be curious. Our employee-led affinity groups foster a culture of inclusion that empower us to be proud of our differences. Ongoing events and learning experiences, including our Conversations on Race and Ethnicity (CORE) and AmazeCon (gender diversity) conferences, inspire us to never stop embracing our uniqueness. Work/Life Balance We value work-life harmony. Achieving success at work should never come at the expense of sacrifices at home, which is why we strive for flexibility as part of our working culture. When we feel supported in the workplace and at home, there’s nothing we can’t achieve in the cloud. Mentorship and Career Growth We’re continuously raising our performance bar as we strive to become Earth’s Best Employer. That’s why you’ll find endless knowledge-sharing, mentorship and other career-advancing resources here to help you develop into a better-rounded professional. Diverse Experiences Amazon values diverse experiences. Even if you do not meet all of the preferred qualifications and skills listed in the job description, we encourage candidates to apply. If your career is just starting, hasn’t followed a traditional path, or includes alternative experiences, don’t let it stop you from applying.
US, MA, North Reading
Are you inspired by invention? Is problem solving through teamwork in your DNA? Do you like the idea of seeing how your work impacts the bigger picture? Answer yes to any of these and you’ll fit right in here at Amazon Robotics. We are a smart team of doers that work passionately to apply advances in robotics and software to solve real-world challenges that will transform our customers’ experiences in ways we can’t even imagine yet. We invent new improvements every day. We are Amazon Robotics and we will give you the tools and support you need to invent with us in ways that are rewarding, fulfilling and fun. Amazon Robotics is seeking experienced and Senior Applied Scientist with a passion for robotic research. Our team works on challenging and high-impact projects within robotics. Examples of projects include allocating resources to complete a million orders a day, coordinating the motion of thousands of robots and identifying objects and damage. Key job responsibilities - Lead research initiatives advancing AI-driven structured field robotics (path planning, fleet coordination, control systems) and translate breakthroughs into production solutions at global scale - Own end-to-end delivery of complex algorithmic solutions from design through production deployment and operational maintenance - Drive technical decisions for Control, Coordination, and Path Planning systems meeting performance, scalability, and reliability requirements - Partner with cross-functional teams to translate business requirements into research problems and assess technical risks - Influence technical direction across the broader robotics organization through design reviews and technical discussions with senior engineers and scientists - Demonstrate measurable impact through AI-driven algorithmic improvements: fleet efficiency gains, operational cost reduction, system reliability improvements, and enhanced customer experience - Publish findings at top-tier AI and robotics conferences representing organizational technical leadership - Mentor junior Applied Scientists on research methodology and balancing innovation with production constraints - Operate independently on ambiguous, multi-quarter problems requiring novel AI approaches while navigating tradeoffs between research innovation and production constraints A day in the life Amazon offers a full range of benefits that support you and eligible family members, including domestic partners and their children. Benefits can vary by location, the number of regularly scheduled hours you work, length of employment, and job status such as seasonal or temporary employment. The benefits that generally apply to regular, full-time employees include: - Medical, Dental, and Vision Coverage - Maternity and Parental Leave Options - Paid Time Off (PTO) - 401(k) Plan If you are not sure that every qualification on the list above describes you exactly, we'd still love to hear from you! At Amazon, we value people with unique backgrounds, experiences, and skillsets. If you’re passionate about this role and want to make an impact on a global scale, please apply! About the team We're the structured field robotics organization powering large-scale mobile robotics operations globally. Our mission is to enable safe, efficient, and reliable robotic operations through intelligent Control, Coordination, and Path Planning systems. We operate at the intersection of planning, algorithmic, and ML research with production systems, owning the full stack from innovation to deployment. Our culture balances research excellence with operational ownership. Applied Scientists partner closely with engineers: reviewing code, contributing to research discussions, and solving problems together. We value deep technical expertise alongside pragmatic engineering judgment. We invest in our people through mentorship and encourage conference participation and knowledge sharing.
US, WA, Seattle
Prime Video is a first-stop entertainment destination offering customers a vast collection of premium programming in one app available across thousands of devices. Prime members can customize their viewing experience and find their favorite movies, series, documentaries, and live sports – including Amazon MGM Studios-produced series and movies; licensed fan favorites; and programming from Prime Video subscriptions such as Apple TV+, HBO Max, Peacock, Crunchyroll and MGM+. All customers, regardless of whether they have a Prime membership or not, can rent or buy titles via the Prime Video Store, and can enjoy even more content for free with ads. Are you interested in shaping the future of entertainment? Prime Video's technology teams are creating best-in-class digital video experience. As a Prime Video team member, you’ll have end-to-end ownership of the product, user experience, design, and technology required to deliver state-of-the-art experiences for our customers. You’ll get to work on projects that are fast-paced, challenging, and varied. You’ll also be able to experiment with new possibilities, take risks, and collaborate with remarkable people. We’ll look for you to bring your diverse perspectives, ideas, and skill-sets to make Prime Video even better for our customers. With global opportunities for talented technologists, you can decide where a career Prime Video Tech takes you! Key job responsibilities As a highly experienced and seasoned science leader, you will apply state of the art natural language processing and computer vision research to video centric digital media, while also responsible for creating and maintaining the best environment for applied science in order to recruit, retain and develop top talent. You will lead the research direction for a team of deeply talented applied scientists, creating the roadmaps for forward-looking research and communicate them effectively to senior leadership. You will also hire and develop applied scientists - growing the team to meet the evolving needs of our customers. About the team This team's mission is to deeply understand all content and empower all customers with relevant language options, innovative accessibility assists, and rich title-information across all their content-experiences on Prime Video. We create and publish content on-time that's meaningful, accurate, and accessible to every customer globally. We delight our customers by pushing the boundaries of content understanding and enrichment. Through inclusion and innovation, we do the most fulfilling work of our career.
US, CA, San Francisco
The Amazon General Intelligence “AGI” organization is looking for an Executive Assistant to support leaders of our Autonomy Team in our growing AI Lab space located in San Francisco. This role is ideal for exceptionally talented, dependable, customer-obsessed, and self-motivated individuals eager to work in a fast paced, exciting and growing team. This role serves as a strategic business partner, managing complex executive operations across the AGI organization. The position requires superior attention to detail, ability to meet tight deadlines, excellent organizational skills, and juggling multiple critical requests while proactively anticipating needs and driving improvements. High integrity, discretion with confidential information, and professionalism are essential. The successful candidate will complete complex tasks and projects quickly with minimal guidance, react with appropriate urgency, and take effective action while navigating ambiguity. Flexibility to change direction at a moment's notice is critical for success in this role. Key job responsibilities Key job responsibilities Serve as strategic partner to senior leadership, identifying opportunities to improve organizational effectiveness and drive operational excellence Manage complex calendars and scheduling for multiple executives Drive continuous improvement through process optimization and new mechanisms Coordinate team activities including staff meetings, offsites, and events Schedule and manage cost-effective travel Attend key meetings, track deliverables, and ensure timely follow-up Create expense reports and manage budget tracking Serve as liaison between executives and internal/external stakeholders Build collaborative relationships with Executive Assistants across the company and with critical external partners Help us build a great team culture in the Lab!
IN, KA, Bengaluru
RBS (Retail Business Services) Tech team works towards enhancing the customer experience (CX) and their trust in product data by providing technologies to find and fix Amazon CX defects at scale. Our platforms help in improving the CX in all phases of customer journey, including selection, discoverability & fulfilment, buying experience and post-buying experience (product quality and customer returns). The team also develops GenAI platforms for automation of Amazon Stores Operations. As a Sciences team in RBS Tech, we focus on foundational ML research and develop scalable state-of-the-art ML solutions to solve the problems covering customer experience (CX) and Selling partner experience (SPX). We work to solve problems related to multi-modal understanding (text and images), task automation through multi-modal LLM Agents, supervised and unsupervised techniques, multi-task learning, multi-label classification, aspect and topic extraction for Customer Anecdote Mining, image and text similarity and retrieval using NLP and Computer Vision for product groupings and identifying duplicate listings in product search results. Key job responsibilities As a Data Scientist, you will be responsible to design and deploy scalable GenAI, NLP and Computer Vision solutions that will impact the content visible to millions of customer and solve key customer experience issues. You will develop novel LLM, deep learning and statistical techniques for task automation, text processing, image processing, pattern recognition, and anomaly detection problems. You will define the research and experiments strategy with an iterative execution approach to develop AI/ML models and progressively improve the results over time. You will partner with business and engineering teams to identify and solve large and significantly complex problems that require scientific innovation. You will help the team leverage your expertise, by coaching and mentoring. You will contribute to the professional development of colleagues, improving their technical knowledge and the engineering practices. You will independently as well as guide team to file for patents and/or publish research work where opportunities arise. The RBS org deals with problems that are directly related to the selling partners and end customers and the ML team drives resolution to organization level problems. Therefore, the Data Scientist role will impact the large product strategy, identifies new business opportunities and provides strategic direction which is very exciting.
IN, KA, Bengaluru
We are looking for a Senior Applied Scientist to help establish and lead the technical direction of our newly formed team in Bangalore. In this role, you will drive the research and development of next-generation machine learning models spanning computer vision, audio processing, and multimodal semantic understanding. You will help define the science roadmap, tackle high-ambiguity problems across modalities, and deliver solutions that operate at scale. This is a rare opportunity to shape the technical vision, culture, and long-term research agenda of a greenfield site. Key job responsibilities Model Development & Technical Leadership: Architect and drive development of advanced deep learning models for CV, audio understanding, and multimodal semantic fusion — setting the technical bar and defining best practices for the team. End-to-End Ownership: Own complex ML programs end-to-end — from identifying high-impact problems, designing data strategies and evaluation frameworks, through experimentation, optimization, and deployment at production scale. Research & Innovation: Define the science roadmap for your area; drive novel research directions in multimodal learning and deliver results that advance both the product and the broader field. Publications & Thought Leadership: Maintain an active publication record at top-tier venues (e.g. CVPR, NeurIPS, ICASSP, ICCV, ACL) and represent the team externally in the research community. Mentorship & Culture Building: Mentor scientists and engineers, raise the technical bar through hiring, and play a foundational role in establishing the Bangalore site's culture, processes, and scientific identity. A day in the life An Applied Scientist with the Alexa Edge AI team will lead science solution design, run experiments, research new algorithms, and find new ways of optimizing the customer experience; while setting examples for the team on good science practice and standards. Besides theoretical analysis and innovation, a Sr. Applied Scientist will also drive cross functional collaboration with talented engineers and scientists to put algorithms and models into production. About the team The Alexa Edge AI team has a mission to deliver best in class, resource efficient multimodal AI models in support of various perception (vision, audio and speech) and semantic understanding based applications for devices like Echo Show series within Amazon.
IN, KA, Bengaluru
The Alexa Edge AI team is seeking a talented and motivated Applied Scientist to join our newly established team in Bangalore. In this role, you will design, develop, and deploy state-of-the-art machine learning models spanning computer vision (CV), audio (including speech) processing, and multimodal semantic understanding for both edge and cloud deployment. You will work at the intersection of multiple modalities to build systems that can perceive, interpret, and reason about the world — pushing the boundaries of what's possible in unified multimodal intelligence. This is a unique opportunity to be a founding member of a brand-new site, shaping the team culture, technical direction, and research agenda from the ground up. Key job responsibilities Model Development: Design and build deep learning models for computer vision, audio understanding, and multimodal semantic fusion — including architectures that enable joint reasoning across visual, auditory, and textual modalities. End-to-End Ownership: Own the full ML lifecycle — from problem formulation, data strategy, and annotation design through experimentation, evaluation frameworks, model optimization, and deployment at scale. Research & Innovation: Stay at the frontier of CV, audio ML, and multimodal learning; identify and apply cutting-edge techniques and contribute to the scientific community through papers at top-tier venues (CVPR, NeurIPS, ICASSP, ICCV, ACL). Mentorship & Culture Building: As a founding member of the Bangalore site, help hire, onboard, and establish the technical practices that define the team's culture. A day in the life An Applied Scientist with the Alexa Edge AI team will support science solution design, run experiments, research new algorithms, and find new ways of optimizing the customer experience; while setting examples for the team on good science practice and standards. Besides theoretical analysis and innovation, an Applied Scientist will also work closely with talented engineers and scientists to put algorithms and models into production. About the team The Alexa Edge AI team has a mission to deliver best in class, resource efficient multimodal AI models in support of various perception (vision, audio and speech) and semantic understanding based applications for devices like Echo Show series within Amazon.
IN, KA, Bengaluru
The Alexa Edge AI team is seeking a talented and motivated Applied Scientist to join our newly established team in Bangalore. In this role, you will design, develop, and deploy state-of-the-art machine learning models spanning computer vision (CV), audio (including speech) processing, and multimodal semantic understanding for both edge and cloud deployment. You will work at the intersection of multiple modalities to build systems that can perceive, interpret, and reason about the world — pushing the boundaries of what's possible in unified multimodal intelligence. This is a unique opportunity to be a founding member of a brand-new site, shaping the team culture, technical direction, and research agenda from the ground up. Key job responsibilities Model Development: Design and build deep learning models for computer vision, audio understanding, and multimodal semantic fusion — including architectures that enable joint reasoning across visual, auditory, and textual modalities. End-to-End Ownership: Own the full ML lifecycle — from problem formulation, data strategy, and annotation design through experimentation, evaluation frameworks, model optimization, and deployment at scale. Research & Innovation: Stay at the frontier of CV, audio ML, and multimodal learning; identify and apply SOTA techniques and contribute to the scientific community through papers at top-tier venues (CVPR, NeurIPS, ICASSP, ICCV, ACL). Mentorship & Culture Building: As a founding member of the Bangalore site, help hire, onboard, and establish the technical practices that define the team's culture. A day in the life An Applied Scientist with the Alexa Edge AI team will support science solution design, run experiments, research new algorithms, and find new ways of optimizing the customer experience; while setting examples for the team on good science practice and standards. Besides theoretical analysis and innovation, an Applied Scientist will also work closely with talented engineers and scientists to put algorithms and models into production. About the team The Alexa Edge AI team has a mission to deliver best in class, resource efficient multimodal AI models in support of various perception (vision, audio and speech) and semantic understanding based applications for devices like Echo Show series within Amazon.