liger-kernel 0.1.1__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,138 @@
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch.nn import CrossEntropyLoss
5
+ from transformers.cache_utils import Cache
6
+ from transformers.modeling_outputs import CausalLMOutputWithPast
7
+ from transformers.models.gemma.modeling_gemma import (
8
+ _CONFIG_FOR_DOC,
9
+ GEMMA_INPUTS_DOCSTRING,
10
+ )
11
+ from transformers.utils import (
12
+ add_start_docstrings_to_model_forward,
13
+ replace_return_docstrings,
14
+ )
15
+
16
+ from liger_kernel.transformers.fused_linear_cross_entropy import (
17
+ LigerFusedLinearCrossEntropyLoss,
18
+ )
19
+
20
+
21
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
22
+ @replace_return_docstrings(
23
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
24
+ )
25
+ def lce_forward(
26
+ self,
27
+ input_ids: torch.LongTensor = None,
28
+ attention_mask: Optional[torch.Tensor] = None,
29
+ position_ids: Optional[torch.LongTensor] = None,
30
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
31
+ inputs_embeds: Optional[torch.FloatTensor] = None,
32
+ labels: Optional[torch.LongTensor] = None,
33
+ use_cache: Optional[bool] = None,
34
+ output_attentions: Optional[bool] = None,
35
+ output_hidden_states: Optional[bool] = None,
36
+ return_dict: Optional[bool] = None,
37
+ cache_position: Optional[torch.LongTensor] = None,
38
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
39
+ r"""
40
+
41
+ copy paste transformers.models.gemma.modeling_gemma causalLM with loss replaced with liger fused cross entropy
42
+
43
+ Args:
44
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
45
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
46
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
47
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
48
+
49
+ Returns:
50
+
51
+ Example:
52
+
53
+ ```python
54
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
55
+
56
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
57
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
58
+
59
+ >>> prompt = "What is your favorite condiment?"
60
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
61
+
62
+ >>> # Generate
63
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
64
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
65
+ "What is your favorite condiment?"
66
+ ```"""
67
+ output_attentions = (
68
+ output_attentions
69
+ if output_attentions is not None
70
+ else self.config.output_attentions
71
+ )
72
+ output_hidden_states = (
73
+ output_hidden_states
74
+ if output_hidden_states is not None
75
+ else self.config.output_hidden_states
76
+ )
77
+ return_dict = (
78
+ return_dict if return_dict is not None else self.config.use_return_dict
79
+ )
80
+
81
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
82
+ outputs = self.model(
83
+ input_ids=input_ids,
84
+ attention_mask=attention_mask,
85
+ position_ids=position_ids,
86
+ past_key_values=past_key_values,
87
+ inputs_embeds=inputs_embeds,
88
+ use_cache=use_cache,
89
+ output_attentions=output_attentions,
90
+ output_hidden_states=output_hidden_states,
91
+ return_dict=return_dict,
92
+ cache_position=cache_position,
93
+ )
94
+
95
+ hidden_states = outputs[0]
96
+
97
+ loss = None
98
+ logits = None
99
+
100
+ if self.training and (labels is not None):
101
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
102
+ shift_labels = labels[..., 1:].contiguous()
103
+
104
+ # flatten
105
+
106
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
107
+ shift_labels = shift_labels.view(-1)
108
+
109
+ lce = LigerFusedLinearCrossEntropyLoss()
110
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
111
+
112
+ else:
113
+ logits = self.lm_head(hidden_states)
114
+ if labels is not None:
115
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
116
+ logits = logits.float()
117
+ # Shift so that tokens < n predict n
118
+ shift_logits = logits[..., :-1, :].contiguous()
119
+ shift_labels = labels[..., 1:].contiguous()
120
+ # Flatten the tokens
121
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
122
+ shift_labels = shift_labels.view(-1)
123
+ # Ensure tensors are on the same device
124
+ shift_labels = shift_labels.to(shift_logits.device)
125
+ loss_fct = CrossEntropyLoss()
126
+ loss = loss_fct(shift_logits, shift_labels)
127
+
128
+ if not return_dict:
129
+ output = (logits,) + outputs[1:]
130
+ return (loss,) + output if loss is not None else output
131
+
132
+ return CausalLMOutputWithPast(
133
+ loss=loss,
134
+ logits=logits,
135
+ past_key_values=outputs.past_key_values,
136
+ hidden_states=outputs.hidden_states,
137
+ attentions=outputs.attentions,
138
+ )
@@ -97,7 +97,7 @@ def lce_forward(
97
97
  loss = None
98
98
  logits = None
99
99
 
100
- if self.training:
100
+ if self.training and (labels is not None):
101
101
  shift_hidden_states = hidden_states[..., :-1, :].contiguous()
102
102
  shift_labels = labels[..., 1:].contiguous()
103
103
 
@@ -0,0 +1,138 @@
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch.nn import CrossEntropyLoss
5
+ from transformers.cache_utils import Cache
6
+ from transformers.modeling_outputs import CausalLMOutputWithPast
7
+ from transformers.models.mistral.modeling_mistral import (
8
+ _CONFIG_FOR_DOC,
9
+ MISTRAL_INPUTS_DOCSTRING,
10
+ )
11
+ from transformers.utils import (
12
+ add_start_docstrings_to_model_forward,
13
+ replace_return_docstrings,
14
+ )
15
+
16
+ from liger_kernel.transformers.fused_linear_cross_entropy import (
17
+ LigerFusedLinearCrossEntropyLoss,
18
+ )
19
+
20
+
21
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
22
+ @replace_return_docstrings(
23
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
24
+ )
25
+ def lce_forward(
26
+ self,
27
+ input_ids: torch.LongTensor = None,
28
+ attention_mask: Optional[torch.Tensor] = None,
29
+ position_ids: Optional[torch.LongTensor] = None,
30
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
31
+ inputs_embeds: Optional[torch.FloatTensor] = None,
32
+ labels: Optional[torch.LongTensor] = None,
33
+ use_cache: Optional[bool] = None,
34
+ output_attentions: Optional[bool] = None,
35
+ output_hidden_states: Optional[bool] = None,
36
+ return_dict: Optional[bool] = None,
37
+ cache_position: Optional[torch.LongTensor] = None,
38
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
39
+ r"""
40
+ Copy paste Mistral's forward but replace torch cross entropy with liger fused linear cross entropy
41
+
42
+
43
+ Args:
44
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
45
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
46
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
47
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
48
+
49
+ Returns:
50
+
51
+ Example:
52
+
53
+ ```python
54
+ >>> from transformers import AutoTokenizer, MistralForCausalLM
55
+
56
+ >>> model = MistralForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
57
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")
58
+
59
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
60
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
61
+
62
+ >>> # Generate
63
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
64
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
65
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
66
+ ```"""
67
+
68
+ output_attentions = (
69
+ output_attentions
70
+ if output_attentions is not None
71
+ else self.config.output_attentions
72
+ )
73
+ output_hidden_states = (
74
+ output_hidden_states
75
+ if output_hidden_states is not None
76
+ else self.config.output_hidden_states
77
+ )
78
+ return_dict = (
79
+ return_dict if return_dict is not None else self.config.use_return_dict
80
+ )
81
+
82
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
83
+ outputs = self.model(
84
+ input_ids=input_ids,
85
+ attention_mask=attention_mask,
86
+ position_ids=position_ids,
87
+ past_key_values=past_key_values,
88
+ inputs_embeds=inputs_embeds,
89
+ use_cache=use_cache,
90
+ output_attentions=output_attentions,
91
+ output_hidden_states=output_hidden_states,
92
+ return_dict=return_dict,
93
+ cache_position=cache_position,
94
+ )
95
+
96
+ hidden_states = outputs[0]
97
+
98
+ loss = None
99
+ logits = None
100
+
101
+ if self.training and (labels is not None):
102
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
103
+ shift_labels = labels[..., 1:].contiguous()
104
+
105
+ # flatten tokens
106
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
107
+ shift_labels = shift_labels.view(-1)
108
+
109
+ lce = LigerFusedLinearCrossEntropyLoss()
110
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
111
+
112
+ else:
113
+ logits = self.lm_head(hidden_states)
114
+ if labels is not None:
115
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
116
+ logits = logits.float()
117
+ # Shift so that tokens < n predict n
118
+ shift_logits = logits[..., :-1, :].contiguous()
119
+ shift_labels = labels[..., 1:].contiguous()
120
+ # Flatten the tokens
121
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
122
+ shift_labels = shift_labels.view(-1)
123
+ # Ensure tensors are on the same device
124
+ shift_labels = shift_labels.to(shift_logits.device)
125
+ loss_fct = CrossEntropyLoss()
126
+ loss = loss_fct(shift_logits, shift_labels)
127
+
128
+ if not return_dict:
129
+ output = (logits,) + outputs[1:]
130
+ return (loss,) + output if loss is not None else output
131
+
132
+ return CausalLMOutputWithPast(
133
+ loss=loss,
134
+ logits=logits,
135
+ past_key_values=outputs.past_key_values,
136
+ hidden_states=outputs.hidden_states,
137
+ attentions=outputs.attentions,
138
+ )
@@ -0,0 +1,136 @@
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch.nn import CrossEntropyLoss
5
+ from transformers.modeling_outputs import CausalLMOutputWithPast
6
+ from transformers.models.phi3.modeling_phi3 import (
7
+ _CONFIG_FOR_DOC,
8
+ PHI3_INPUTS_DOCSTRING,
9
+ )
10
+ from transformers.utils import (
11
+ add_start_docstrings_to_model_forward,
12
+ replace_return_docstrings,
13
+ )
14
+
15
+ from liger_kernel.transformers.fused_linear_cross_entropy import (
16
+ LigerFusedLinearCrossEntropyLoss,
17
+ )
18
+
19
+
20
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
21
+ @replace_return_docstrings(
22
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
23
+ )
24
+ def lce_forward(
25
+ self,
26
+ input_ids: torch.LongTensor = None,
27
+ attention_mask: Optional[torch.Tensor] = None,
28
+ position_ids: Optional[torch.LongTensor] = None,
29
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
30
+ inputs_embeds: Optional[torch.FloatTensor] = None,
31
+ labels: Optional[torch.LongTensor] = None,
32
+ use_cache: Optional[bool] = None,
33
+ output_attentions: Optional[bool] = None,
34
+ output_hidden_states: Optional[bool] = None,
35
+ return_dict: Optional[bool] = None,
36
+ cache_position: Optional[torch.LongTensor] = None,
37
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
38
+ r"""
39
+ Copy paste phi3 forward from transfomers v4.44.2 but replace torch cross entropy with liger fused linear cross entropy
40
+
41
+
42
+ Args:
43
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
44
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
45
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
46
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
47
+
48
+ Returns:
49
+
50
+ Example:
51
+
52
+ ```python
53
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
54
+
55
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
56
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
57
+
58
+ >>> prompt = "This is an example script ."
59
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
60
+
61
+ >>> # Generate
62
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
63
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
64
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
65
+ ```"""
66
+
67
+ output_attentions = (
68
+ output_attentions
69
+ if output_attentions is not None
70
+ else self.config.output_attentions
71
+ )
72
+ output_hidden_states = (
73
+ output_hidden_states
74
+ if output_hidden_states is not None
75
+ else self.config.output_hidden_states
76
+ )
77
+ return_dict = (
78
+ return_dict if return_dict is not None else self.config.use_return_dict
79
+ )
80
+
81
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
82
+ outputs = self.model(
83
+ input_ids=input_ids,
84
+ attention_mask=attention_mask,
85
+ position_ids=position_ids,
86
+ past_key_values=past_key_values,
87
+ inputs_embeds=inputs_embeds,
88
+ use_cache=use_cache,
89
+ output_attentions=output_attentions,
90
+ output_hidden_states=output_hidden_states,
91
+ return_dict=return_dict,
92
+ )
93
+
94
+ hidden_states = outputs[0]
95
+
96
+ loss = None
97
+ logits = None
98
+
99
+ if self.training and labels is not None:
100
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
101
+ shift_labels = labels[..., 1:].contiguous()
102
+
103
+ # flatten tokens
104
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
105
+ shift_labels = shift_labels.view(-1)
106
+
107
+ lce = LigerFusedLinearCrossEntropyLoss()
108
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
109
+ else:
110
+ logits = self.lm_head(hidden_states)
111
+ logits = logits.float()
112
+
113
+ loss = None
114
+ if labels is not None:
115
+ # Shift so that tokens < n predict n
116
+ shift_logits = logits[..., :-1, :].contiguous()
117
+ shift_labels = labels[..., 1:].contiguous()
118
+ # Flatten the tokens
119
+ loss_fct = CrossEntropyLoss()
120
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
121
+ shift_labels = shift_labels.view(-1)
122
+ # Enable model parallelism
123
+ shift_labels = shift_labels.to(shift_logits.device)
124
+ loss = loss_fct(shift_logits, shift_labels)
125
+
126
+ if not return_dict:
127
+ output = (logits,) + outputs[1:]
128
+ return (loss,) + output if loss is not None else output
129
+
130
+ return CausalLMOutputWithPast(
131
+ loss=loss,
132
+ logits=logits,
133
+ past_key_values=outputs.past_key_values,
134
+ hidden_states=outputs.hidden_states,
135
+ attentions=outputs.attentions,
136
+ )
@@ -0,0 +1,135 @@
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch.nn import CrossEntropyLoss
5
+ from transformers.modeling_outputs import CausalLMOutputWithPast
6
+ from transformers.models.qwen2.modeling_qwen2 import (
7
+ _CONFIG_FOR_DOC,
8
+ QWEN2_INPUTS_DOCSTRING,
9
+ )
10
+ from transformers.utils import (
11
+ add_start_docstrings_to_model_forward,
12
+ replace_return_docstrings,
13
+ )
14
+
15
+ from liger_kernel.transformers.fused_linear_cross_entropy import (
16
+ LigerFusedLinearCrossEntropyLoss,
17
+ )
18
+
19
+
20
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
21
+ @replace_return_docstrings(
22
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
23
+ )
24
+ def lce_forward(
25
+ self,
26
+ input_ids: torch.LongTensor = None,
27
+ attention_mask: Optional[torch.Tensor] = None,
28
+ position_ids: Optional[torch.LongTensor] = None,
29
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
30
+ inputs_embeds: Optional[torch.FloatTensor] = None,
31
+ labels: Optional[torch.LongTensor] = None,
32
+ use_cache: Optional[bool] = None,
33
+ output_attentions: Optional[bool] = None,
34
+ output_hidden_states: Optional[bool] = None,
35
+ return_dict: Optional[bool] = None,
36
+ cache_position: Optional[torch.LongTensor] = None,
37
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
38
+ r"""
39
+ Copy paste Qwen2's forward but replace torch cross entropy with liger fused linear cross entropy
40
+
41
+
42
+ Args:
43
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
44
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
45
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
46
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
47
+
48
+ Returns:
49
+
50
+ Example:
51
+
52
+ ```python
53
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
54
+
55
+ >>> model = Qwen2ForCausalLM.from_pretrained("Qwen/Qwen2-1.5B")
56
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-1.5B")
57
+
58
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
59
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
60
+
61
+ >>> # Generate
62
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
63
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
64
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
65
+ ```"""
66
+ output_attentions = (
67
+ output_attentions
68
+ if output_attentions is not None
69
+ else self.config.output_attentions
70
+ )
71
+ output_hidden_states = (
72
+ output_hidden_states
73
+ if output_hidden_states is not None
74
+ else self.config.output_hidden_states
75
+ )
76
+ return_dict = (
77
+ return_dict if return_dict is not None else self.config.use_return_dict
78
+ )
79
+
80
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
81
+ outputs = self.model(
82
+ input_ids=input_ids,
83
+ attention_mask=attention_mask,
84
+ position_ids=position_ids,
85
+ past_key_values=past_key_values,
86
+ inputs_embeds=inputs_embeds,
87
+ use_cache=use_cache,
88
+ output_attentions=output_attentions,
89
+ output_hidden_states=output_hidden_states,
90
+ return_dict=return_dict,
91
+ cache_position=cache_position,
92
+ )
93
+
94
+ hidden_states = outputs[0]
95
+
96
+ loss = None
97
+ logits = None
98
+
99
+ if self.training and (labels is not None):
100
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
101
+ shift_labels = labels[..., 1:].contiguous()
102
+
103
+ # flatten tokens
104
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
105
+ shift_labels = shift_labels.view(-1)
106
+
107
+ lce = LigerFusedLinearCrossEntropyLoss()
108
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
109
+
110
+ else:
111
+ logits = self.lm_head(hidden_states)
112
+ logits = logits.float()
113
+ if labels is not None:
114
+ # Shift so that tokens < n predict n
115
+ shift_logits = logits[..., :-1, :].contiguous()
116
+ shift_labels = labels[..., 1:].contiguous()
117
+ # Flatten the tokens
118
+ loss_fct = CrossEntropyLoss()
119
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
120
+ shift_labels = shift_labels.view(-1)
121
+ # Enable model parallelism
122
+ shift_labels = shift_labels.to(shift_logits.device)
123
+ loss = loss_fct(shift_logits, shift_labels)
124
+
125
+ if not return_dict:
126
+ output = (logits,) + outputs[1:]
127
+ return (loss,) + output if loss is not None else output
128
+
129
+ return CausalLMOutputWithPast(
130
+ loss=loss,
131
+ logits=logits,
132
+ past_key_values=outputs.past_key_values,
133
+ hidden_states=outputs.hidden_states,
134
+ attentions=outputs.attentions,
135
+ )