Skip to content
Back to skills

Pack Padded Sequence Loss

ASecurity

Uses pack_padded_sequence to exclude padding tokens from cross-entropy loss in variable-length sequence generation.

  • 61 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added September 12, 2026
toolspython

Security analysis

A100/100

Scanned September 12, 2026

npx -y skills add wenmin-wu/ds-skills --skill pack-padded-sequence-loss --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Pack Padded Sequence Loss?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Pack Padded Sequence Loss
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/wenmin-wu-pack-padded-sequence-loss/badge)](https://www.skillsdirectory.com/skills/wenmin-wu-pack-padded-sequence-loss)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: cv-pack-padded-sequence-loss
description: >
  Uses pack_padded_sequence to exclude padding tokens from cross-entropy loss in variable-length sequence generation.
---
# Pack Padded Sequence Loss

## Overview

In image captioning and seq2seq tasks, target sequences have different lengths and are padded. Computing cross-entropy on padding tokens wastes compute and leaks gradient noise. `pack_padded_sequence` strips out padding positions before loss computation, giving a clean loss signal from real tokens only.

## Quick Start

```python
from torch.nn.utils.rnn import pack_padded_sequence

# Sort batch by decreasing sequence length (required by pack_padded_sequence)
caption_lengths, sort_ind = caption_lengths.squeeze(1).sort(dim=0, descending=True)
predictions = predictions[sort_ind]
targets = targets[sort_ind]
decode_lengths = (caption_lengths - 1).tolist()  # exclude <sos>

# Pack to strip padding, then compute loss on real tokens only
packed_preds = pack_padded_sequence(predictions, decode_lengths, batch_first=True).data
packed_targets = pack_padded_sequence(targets, decode_lengths, batch_first=True).data

loss = nn.CrossEntropyLoss()(packed_preds, packed_targets)
```

## Workflow

1. Sort batch by sequence length (descending)
2. Compute `decode_lengths` = actual length of each target sequence
3. Pack both predictions and targets with `pack_padded_sequence`
4. Compute cross-entropy on `.data` attribute (flattened real tokens)
5. Backpropagate — gradients only flow through non-padding positions

## Key Decisions

- **Sort requirement**: `pack_padded_sequence` requires descending sort; re-sort encoder outputs too
- **Alternative**: Use `ignore_index` in CrossEntropyLoss for padding token ID — simpler but slightly less efficient
- **Combine with**: Teacher forcing during training, greedy/beam search during inference
- **Metrics**: Compute Levenshtein distance or BLEU on unpacked decoded sequences

## References

- [InChI / Resnet + LSTM with attention / starter](https://www.kaggle.com/code/yasufuminakama/inchi-resnet-lstm-with-attention-starter)

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…