-
Notifications
You must be signed in to change notification settings - Fork 246
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
Add FusedLinerCrossEntropy support for Phi3 #103
Merged
Merged
Changes from all commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
0055dc8
Monkeypatch for Phi3
tyler-romero 859b5d5
checkstyle
tyler-romero b80b319
some cleanup
tyler-romero 853b3f5
Test for LigerPhi3SwiGLUMLP
tyler-romero cb6f109
Update Readme
tyler-romero e11c2d6
Merge branch 'main' into tyler/monkeypatch-phi3
tyler-romero ae9e060
Address PR nit
tyler-romero 95b0ca2
Checkstyle
tyler-romero 5baa8ee
Correctly resolve test.utils dir for make test command
tyler-romero 2162490
Merge branch 'main' into tyler/monkeypatch-phi3
tyler-romero f001ff5
Bump transformers version
tyler-romero b617c77
Bump transformers version in README
tyler-romero 2499b16
Add FusedLinerCrossEntropy support for Phi3
tyler-romero 546ae4c
modify phi3 monkeypatch
tyler-romero 43c8def
Add convergence tests for phi3 and qwen2
tyler-romero e8db468
Update README
tyler-romero 53c1374
Add qwen2 to trainer integration
tyler-romero a407b0a
Merge branch 'main' into tyler/fused-ce-phi3
tyler-romero 2ef2984
Merge branch 'main' into tyler/fused-ce-phi3
tyler-romero 54160df
Merge branch 'main' into tyler/fused-ce-phi3
tyler-romero fd05b62
checkstyle
tyler-romero cbf7358
Typo fix
tyler-romero c2fc797
Merge branch 'main' into tyler/fused-ce-phi3
tyler-romero 37aeb38
Merge branch 'main' into tyler/fused-ce-phi3
tyler-romero d27770a
checkstyle
tyler-romero 6b4a147
Merge branch 'main' into tyler/fused-ce-phi3
tyler-romero 7ab60c4
fallback to torch native linear+CE when without label
tyler-romero 8c7fd83
fallback to torch native linear+CE when without label
tyler-romero 76c6a76
Merge branch 'main' into tyler/fused-ce-phi3
tyler-romero 6d6b01c
Fix for broken tests on main
tyler-romero ca5e8a0
Merge branch 'main' into tyler/fused-ce-phi3
lancerts dfdd40e
Merge branch 'main' into tyler/fused-ce-phi3
tyler-romero 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 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 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 |
---|---|---|
@@ -0,0 +1,136 @@ | ||
from typing import List, Optional, Tuple, Union | ||
|
||
import torch | ||
from torch.nn import CrossEntropyLoss | ||
from transformers.modeling_outputs import CausalLMOutputWithPast | ||
from transformers.models.phi3.modeling_phi3 import ( | ||
_CONFIG_FOR_DOC, | ||
PHI3_INPUTS_DOCSTRING, | ||
) | ||
from transformers.utils import ( | ||
add_start_docstrings_to_model_forward, | ||
replace_return_docstrings, | ||
) | ||
|
||
from liger_kernel.transformers.fused_linear_cross_entropy import ( | ||
LigerFusedLinearCrossEntropyLoss, | ||
) | ||
|
||
|
||
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING) | ||
@replace_return_docstrings( | ||
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC | ||
) | ||
def lce_forward( | ||
self, | ||
input_ids: torch.LongTensor = None, | ||
attention_mask: Optional[torch.Tensor] = None, | ||
position_ids: Optional[torch.LongTensor] = None, | ||
past_key_values: Optional[List[torch.FloatTensor]] = None, | ||
inputs_embeds: Optional[torch.FloatTensor] = None, | ||
labels: Optional[torch.LongTensor] = None, | ||
use_cache: Optional[bool] = None, | ||
output_attentions: Optional[bool] = None, | ||
output_hidden_states: Optional[bool] = None, | ||
return_dict: Optional[bool] = None, | ||
cache_position: Optional[torch.LongTensor] = None, | ||
) -> Union[Tuple, CausalLMOutputWithPast]: | ||
r""" | ||
Copy paste phi3 forward from transfomers v4.44.2 but replace torch cross entropy with liger fused linear cross entropy | ||
|
||
|
||
Args: | ||
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): | ||
Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., | ||
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored | ||
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. | ||
|
||
Returns: | ||
|
||
Example: | ||
|
||
```python | ||
>>> from transformers import AutoTokenizer, Phi3ForCausalLM | ||
|
||
>>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct") | ||
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct") | ||
|
||
>>> prompt = "This is an example script ." | ||
>>> inputs = tokenizer(prompt, return_tensors="pt") | ||
|
||
>>> # Generate | ||
>>> generate_ids = model.generate(inputs.input_ids, max_length=30) | ||
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] | ||
'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum' | ||
```""" | ||
|
||
output_attentions = ( | ||
output_attentions | ||
if output_attentions is not None | ||
else self.config.output_attentions | ||
) | ||
output_hidden_states = ( | ||
output_hidden_states | ||
if output_hidden_states is not None | ||
else self.config.output_hidden_states | ||
) | ||
return_dict = ( | ||
return_dict if return_dict is not None else self.config.use_return_dict | ||
) | ||
|
||
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) | ||
outputs = self.model( | ||
input_ids=input_ids, | ||
attention_mask=attention_mask, | ||
position_ids=position_ids, | ||
past_key_values=past_key_values, | ||
inputs_embeds=inputs_embeds, | ||
use_cache=use_cache, | ||
output_attentions=output_attentions, | ||
output_hidden_states=output_hidden_states, | ||
return_dict=return_dict, | ||
) | ||
|
||
hidden_states = outputs[0] | ||
|
||
loss = None | ||
logits = None | ||
|
||
if self.training and labels is not None: | ||
shift_hidden_states = hidden_states[..., :-1, :].contiguous() | ||
shift_labels = labels[..., 1:].contiguous() | ||
|
||
# flatten tokens | ||
shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size) | ||
shift_labels = shift_labels.view(-1) | ||
|
||
lce = LigerFusedLinearCrossEntropyLoss() | ||
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels) | ||
else: | ||
logits = self.lm_head(hidden_states) | ||
logits = logits.float() | ||
|
||
loss = None | ||
if labels is not None: | ||
# Shift so that tokens < n predict n | ||
shift_logits = logits[..., :-1, :].contiguous() | ||
shift_labels = labels[..., 1:].contiguous() | ||
# Flatten the tokens | ||
loss_fct = CrossEntropyLoss() | ||
shift_logits = shift_logits.view(-1, self.config.vocab_size) | ||
shift_labels = shift_labels.view(-1) | ||
# Enable model parallelism | ||
shift_labels = shift_labels.to(shift_logits.device) | ||
loss = loss_fct(shift_logits, shift_labels) | ||
|
||
if not return_dict: | ||
output = (logits,) + outputs[1:] | ||
return (loss,) + output if loss is not None else output | ||
|
||
return CausalLMOutputWithPast( | ||
loss=loss, | ||
logits=logits, | ||
past_key_values=outputs.past_key_values, | ||
hidden_states=outputs.hidden_states, | ||
attentions=outputs.attentions, | ||
) |
This file contains 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 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 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.
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.
This was breaking one of the monkeypatch tests on main
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.
@tyler-romero what is the root cause? Is it still breaking on the current main?
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.
Yes as of now its still broken on main:
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.
The test is just checking for the presence of this function in the mapping
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.
I think there were simultaneous commits merged with this test added and a new model type added. Are you able to fix the test? It's just making sure all the patching APIs are accounted for in the mapping (used with AutoModel class)
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.
Yes the test is also fixed by this PR!