Hidden States Aggregation
About
The d9d.module.block.hidden_states_aggregator package collects and reduces model hidden states during execution. Use it to keep hidden states for later use, such as reward modeling, custom distillation objectives or analysis. A reducing aggregator does not keep the full hidden states in memory. Create an aggregator with the create_hidden_states_aggregator factory.
Snapshots
pack_with_snapshot returns the collected states after an earlier "snapshot" tensor. The snapshot can hold data from earlier iterations or pipeline stages. This lets you build up states over iterative loops.
Modes
HiddenStatesAggregationMode.no
Collects nothing. pack_with_snapshot always returns None.
HiddenStatesAggregationMode.mean
Reduces the hidden states as soon as it receives them. It needs an aggregation mask with shape (batch, seq_len). For each call to add_hidden_states, it:
- Computes the masked mean of the hidden states over the sequence.
- Stores only the result with shape
(batch, hidden_size), not the full(batch, seq_len, hidden_size)tensor.
This reduces memory use when you collect states over many iterations.
If the aggregator collected nothing, pack_with_snapshot returns the snapshot unchanged.
Usage
API Reference
d9d.module.block.hidden_states_aggregator
Aggregation of model hidden states.
BaseHiddenStatesAggregator
Bases: ABC
Abstract base class for hidden states aggregation strategies.
An aggregator collects hidden states and then packs them together with an optional earlier snapshot.
add_hidden_states(hidden_states)
abstractmethod
Accumulates a batch of hidden states into the aggregator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hidden_states
|
Tensor
|
Hidden states to aggregate. Shape: |
required |
pack_with_snapshot(snapshot)
abstractmethod
Finalizes the aggregation and combines it with an optional earlier snapshot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snapshot
|
Tensor | None
|
Previously aggregated states to prepend to the current collection, or |
required |
Returns:
| Type | Description |
|---|---|
Tensor | None
|
The snapshot followed by the newly aggregated states, or only the snapshot if no states were collected. |
HiddenStatesAggregationMode
Bases: StrEnum
Available hidden states aggregation strategies.
Attributes:
| Name | Type | Description |
|---|---|---|
no |
Performs no aggregation. |
|
mean |
Computes the masked mean of hidden states over the sequence. |
create_hidden_states_aggregator(mode, agg_mask)
Creates a hidden states aggregator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
HiddenStatesAggregationMode
|
Aggregation mode. |
required |
agg_mask
|
Tensor | None
|
Aggregation mask. Required for the |
required |
Returns:
| Type | Description |
|---|---|
BaseHiddenStatesAggregator
|
The hidden states aggregator. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |