Weighted layer pooling

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

Weighted layer pooling is an AI agent skill from the GitHub repository wenmin-wu/ds-skills. Learns a weighted combination of CLS embeddings across all transformer layers instead of using only the last layer.

How to use this skill

Skill file

Weighted Layer Pooling

Overview

Different transformer layers capture different linguistic features — lower layers for syntax, higher for semantics. Instead of using only the final layer, weighted layer pooling learns a soft weight per layer and computes a weighted mean. This typically improves regression tasks where multiple levels of language understanding matter.

Quick Start

import torch
import torch.nn as nn

class WeightedLayerPooling(nn.Module):
    def __init__(self, num_hidden_layers, layer_start=4):
        super().__init__()
        self.layer_start = layer_start
        self.num_layers = num_hidden_layers - layer_start + 1
        self.layer_weights = nn.Parameter(torch.ones(self.num_layers))

    def forward(self, all_hidden_states):
        layers = torch.stack(all_hidden_states[self.layer_start:])  # (L, B, S, H)
        weights = self.layer_weights.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
        weights = weights.expand(layers.size())
        weighted = (weights * layers).sum(dim=0) / self.layer_weights.sum()
        return weighted[:, 0]  # CLS token

Workflow

  1. Set output_hidden_states=True in model config
  2. Collect all hidden states from the transformer
  3. Apply learnable weights across selected layers
  4. Use weighted output as input to regression/classification head

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.