-
Notifications
You must be signed in to change notification settings - Fork 39
activation-level disillation #388
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
RaymondLi0
wants to merge
32
commits into
main
Choose a base branch
from
raymond/activation_disillation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
9fa4c46
activation distillation: first draft
RaymondLi0 11708ff
fix kwargs
RaymondLi0 9437310
remove count, add auxiliaryLoss hook
RaymondLi0 d3ac964
fix auxiliary loss
RaymondLi0 56fc8db
wrap in method
RaymondLi0 5d75f01
fixes
RaymondLi0 f1bfca9
move activation distillation loss reporting to decoder block
RaymondLi0 8b16752
fix logging
RaymondLi0 efa8cf0
remove root kwargs
RaymondLi0 4cda56d
fix mistral mlp conversion
RaymondLi0 9ca2347
Merge branch 'raymond/fix_mistral_conv' into raymond/activation_disil…
RaymondLi0 41692e9
remove duplicate from apriel conversion
RaymondLi0 99c42c0
fix
RaymondLi0 d3df7a5
move assert
RaymondLi0 f2f097e
Merge branch 'raymond/fix_mistral_conv' into raymond/activation_disil…
RaymondLi0 8e04aba
remove tp-1 check for reference models
RaymondLi0 3ebda84
fix reduce op
RaymondLi0 6a8732f
Merge branch 'raymond/fix_distill_tp' into raymond/activation_disilla…
RaymondLi0 f729625
try: loss after norm
RaymondLi0 0effa24
handle non-fixed-sequence decoder
RaymondLi0 f7a0837
patch creeping config params
RaymondLi0 6f2d5e3
support pattern-block-sequence with compatible configs in export
RaymondLi0 90da831
move activation-distillation loss pre-norm again
RaymondLi0 5251719
support PatternBlockSequenceConfig in llama converter
RaymondLi0 d2858d6
add distillation tests
RaymondLi0 280db13
update tests
RaymondLi0 a46ed18
update tests, add reverse_kl
RaymondLi0 01b5530
Merge branch 'main' into raymond/activation_disillation
RaymondLi0 6e42944
remove comments
RaymondLi0 4c75e10
handle stp
RaymondLi0 035d36c
set distillation test as broken
RaymondLi0 e3ac422
remove unused code
RaymondLi0 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,16 +4,19 @@ | |
|
|
||
| import torch | ||
|
|
||
| from fast_llm.core.distributed import set_generator | ||
| from fast_llm.core.distributed import ReduceOp, all_reduce, set_generator | ||
| from fast_llm.engine.base_model.config import LossDef, ResourceUsageConfig | ||
| from fast_llm.engine.config_utils.tensor_dim import TensorDim | ||
| from fast_llm.engine.distributed.config import DistributedConfig | ||
| from fast_llm.engine.distributed.distributed import Distributed | ||
| from fast_llm.layers.block.block import Block | ||
| from fast_llm.layers.block.config import BlockKwargs | ||
| from fast_llm.layers.common.auxiliary_loss import AuxiliaryLoss | ||
| from fast_llm.layers.common.peft.config import PeftConfig | ||
| from fast_llm.layers.decoder.config import BlockWithBiasConfig, DecoderBlockConfig | ||
| from fast_llm.layers.language_model.head import _format_name | ||
| from fast_llm.tensor import TensorMeta | ||
| from fast_llm.utils import Assert | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
@@ -134,6 +137,9 @@ def forward( | |
| hidden_states = self.norm_1(input_) | ||
| self._debug(hidden_states, "norm_1", kwargs.get(BlockKwargs.hidden_dims), kwargs) | ||
| hidden_states, bias = self.mixer(hidden_states, kwargs) | ||
|
|
||
| hidden_states, bias = self.activation_distillation_loss(hidden_states, bias, kwargs, losses) | ||
|
|
||
| with set_generator(generator): | ||
| input_ = self._bias_dropout_add(hidden_states, bias, input_) | ||
| self._debug(input_, "mixer_residual", kwargs.get(BlockKwargs.hidden_dims), kwargs) | ||
|
|
@@ -148,6 +154,51 @@ def forward( | |
| hidden_states = torch.stack((fw_input, hidden_states), dim=0) | ||
| return hidden_states | ||
|
|
||
| def activation_distillation_loss(self, hidden_states, bias, kwargs, losses): | ||
| """ | ||
| Maybe apply activation distillation loss and setup backward hooks | ||
| """ | ||
| mixer_output = hidden_states if bias is None else hidden_states + bias | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should only be evaluated if needed. |
||
| # Teacher populates mixer activations for distillation. | ||
| activation_storage = kwargs.get(BlockKwargs.activation_distillation_storage) | ||
| if activation_storage is not None: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider using the new |
||
| activation_storage[self.module_name] = mixer_output.detach() | ||
| # Student gets teacher activations and computes the activation-level loss. | ||
| activation_targets = kwargs.get(BlockKwargs.activation_distillation_targets) | ||
| if ( | ||
| activation_targets is not None | ||
| and self.training | ||
| and (teacher_output := activation_targets.pop(self.module_name, None)) is not None | ||
| ): | ||
| # Compare student mixer output with the teacher's stored activation and accumulate the loss. | ||
| teacher_tensor = teacher_output.detach().to(device=mixer_output.device, dtype=mixer_output.dtype) | ||
| Assert.eq(teacher_tensor.shape, mixer_output.shape) | ||
| # TODO: un-scaled loss for reporting? Average loss over layers? | ||
| # L2 loss | ||
| activation_loss_factor = self._config.activation_distillation_factor | ||
| # (batch, sequence, hidden) or (sequence, batch, hidden). Take the norm over hidden dim. | ||
| # TODO: handle possible padding? | ||
| local_loss_sum = torch.sum(torch.norm(mixer_output - teacher_tensor, p=2, dim=(2))) | ||
| # mixer_output.shape is (batch, sequence, hidden) or (sequence, batch, hidden) | ||
| # In either case, dims 0 and 1 are batch and sequence | ||
| total_count = mixer_output.shape[0] * mixer_output.shape[1] | ||
|
|
||
| # All-reduce across tensor-parallel group if sequence-parallel is enabled | ||
| if self._sequence_parallel and self._distributed.tensor_group is not None: | ||
| all_reduce(local_loss_sum, group=self._distributed.tensor_group, op=ReduceOp.SUM) | ||
| # Assume all ranks contribute the same count (not the case if padding) | ||
| total_count *= self._distributed.tensor_group.size() | ||
|
|
||
| activation_loss = activation_loss_factor * (local_loss_sum / total_count) | ||
|
|
||
| # Backward hooks | ||
| hidden_states = AuxiliaryLoss.apply(hidden_states, activation_loss, 1.0) | ||
| bias = AuxiliaryLoss.apply(bias, activation_loss, 1.0) if bias is not None else None | ||
| # Logging | ||
| if losses is not None and self._activation_distillation_loss_name in losses: | ||
| losses[self._activation_distillation_loss_name].append(activation_loss.detach()) | ||
| return hidden_states, bias | ||
|
|
||
| def get_compute_usage(self, input_: TensorMeta, kwargs: dict[str, typing.Any], config: ResourceUsageConfig) -> int: | ||
| # TODO: Add marginal compute? (normalization, bias_dropout_add) | ||
| return sum( | ||
|
|
@@ -161,5 +212,21 @@ def preprocess(self, kwargs: dict[str, typing.Any]) -> None: | |
| self.mixer.preprocess(kwargs) | ||
| self.mlp.preprocess(kwargs) | ||
|
|
||
| # TODO: add layer_index | ||
| _activation_distillation_loss_name = "activation_distillation_loss" | ||
|
|
||
| def get_loss_definitions(self, count: int = 1) -> list[LossDef]: | ||
| return self.mixer.get_loss_definitions(count=count) + self.mlp.get_loss_definitions(count=count) | ||
| loss_definitions = [] | ||
| if self._config.activation_distillation_factor > 0.0 and self._config.distillation_model is not None: | ||
| loss_definitions.append( | ||
| LossDef( | ||
| name=self._activation_distillation_loss_name, | ||
| formatted_name=_format_name(self._activation_distillation_loss_name), | ||
| count=count, | ||
| ) | ||
| ) | ||
| return ( | ||
| loss_definitions | ||
| + self.mixer.get_loss_definitions(count=count) | ||
| + self.mlp.get_loss_definitions(count=count) | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not needed, you can communicate through preprocessed meta kwargs.