Weight decay bias exclusion

From wenmin-wu/ds-skills · View interactive version

Weight decay bias exclusion is an AI agent skill from the GitHub repository wenmin-wu/ds-skills. Exclude bias terms and LayerNorm weights from weight decay to prevent regularization from distorting normalization layers

How to use this skill

Skill file

Weight Decay Bias Exclusion

Overview

Weight decay (L2 regularization) should only apply to weight matrices, not to bias terms or LayerNorm parameters. Regularizing biases pushes them toward zero unnecessarily, and regularizing LayerNorm weights distorts the learned scale. Standard practice for fine-tuning transformers — split parameters into two groups with different decay rates.

Quick Start

from torch.optim import AdamW

def get_optimizer_grouped_parameters(model, lr=2e-5, weight_decay=0.01):
    """Split parameters into decay and no-decay groups."""
    no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
    
    return [
        {
            'params': [p for n, p in model.named_parameters()
                       if not any(nd in n for nd in no_decay)],
            'weight_decay': weight_decay
        },
        {
            'params': [p for n, p in model.named_parameters()
                       if any(nd in n for nd in no_decay)],
            'weight_decay': 0.0
        }
    ]

optimizer = AdamW(
    get_optimizer_grouped_parameters(model, lr=2e-5, weight_decay=0.01)
)

Key Decisions

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.