Skip to content

Reduce memory usage by computing SPLADE activations in-place - #15

Merged
takashi-wada-1322 merged 1 commit into
mainfrom
fix/inplace-embedding-computation
Sep 11, 2026
Merged

takashi-wada-1322 merged 1 commit into
mainfrom
fix/inplace-embedding-computation

Conversation

@takashi-wada-1322

Copy link
Copy Markdown
Collaborator

Summary

Compute the SPLADE activation (relu → log1p → mask multiplication) in-place when gradients are not required, roughly halving peak memory for the (b, N, V) intermediate tensors

Rewrite the activation formula relu -> log1p -> mask multiplication to
run in-place when gradients are not required (inference or frozen
encoder), halving peak memory for the (b, N, V) intermediates. When
gradients are required, keep out-of-place ops but switch log(1 + x) to
log1p(x) so both paths produce identical values (log1p is also more
accurate in fp16). Apply the same in-place formula to the README
quickstart snippet.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

# Eq. (1) in [2]
if logits.requires_grad:
activations = torch.log1p(torch.relu(logits)) * attention_mask.unsqueeze(-1) # (b, N, V)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unified both branches to log1p(x) instead of log(1 + x), since log1p is more accurate for small values — this prevents any discrepancy between training and inference outputs.

https://docs.pytorch.org/docs/2.14/generated/torch.log1p.html

# Compute in-place to reduce memory usage when gradients are not required
activations = torch.relu_(logits).log1p_().mul_(attention_mask.unsqueeze(-1)) # (b, N, V)
vecs, indices_ = self.agg_func(
torch.log(1 + torch.relu(logits)) * attention_mask.unsqueeze(-1), # (b, N, 1)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding the comment: apologies if I'm misreading this, but wasn't the actual shape here (b, N, V) all along?

@takashi-wada-1322
takashi-wada-1322 marked this pull request as ready for review September 11, 2026 02:13

@nptdat nptdat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@takashi-wada-1322
takashi-wada-1322 merged commit cdb4bf8 into main Sep 11, 2026
6 checks passed
@takashi-wada-1322
takashi-wada-1322 deleted the fix/inplace-embedding-computation branch September 11, 2026 02:25

This branch was successfully deployed

1 active deployment
dev — d6555019 Deployed Sep 11, 2026 by takashi-wada-1322 via unit-test #38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants