liger-kernel 0.1.0__py3-none-any.whl → 0.3.1__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.
Files changed (39) hide show
  1. liger_kernel/env_report.py +46 -0
  2. liger_kernel/ops/cross_entropy.py +130 -63
  3. liger_kernel/ops/experimental/embedding.py +143 -0
  4. liger_kernel/ops/fused_linear_cross_entropy.py +203 -126
  5. liger_kernel/ops/geglu.py +56 -44
  6. liger_kernel/ops/kl_div.py +258 -0
  7. liger_kernel/ops/layer_norm.py +236 -0
  8. liger_kernel/ops/rms_norm.py +220 -84
  9. liger_kernel/ops/rope.py +91 -84
  10. liger_kernel/ops/swiglu.py +50 -43
  11. liger_kernel/ops/utils.py +12 -0
  12. liger_kernel/transformers/__init__.py +22 -0
  13. liger_kernel/transformers/auto_model.py +45 -0
  14. liger_kernel/transformers/cross_entropy.py +11 -1
  15. liger_kernel/transformers/experimental/embedding.py +28 -0
  16. liger_kernel/transformers/functional.py +19 -0
  17. liger_kernel/transformers/fused_linear_cross_entropy.py +8 -2
  18. liger_kernel/transformers/geglu.py +4 -2
  19. liger_kernel/transformers/kl_div.py +14 -0
  20. liger_kernel/transformers/layer_norm.py +30 -0
  21. liger_kernel/transformers/model/gemma.py +138 -0
  22. liger_kernel/transformers/model/llama.py +1 -1
  23. liger_kernel/transformers/model/mistral.py +138 -0
  24. liger_kernel/transformers/model/mixtral.py +158 -0
  25. liger_kernel/transformers/model/phi3.py +136 -0
  26. liger_kernel/transformers/model/qwen2.py +135 -0
  27. liger_kernel/transformers/model/qwen2_vl.py +172 -0
  28. liger_kernel/transformers/monkey_patch.py +579 -14
  29. liger_kernel/transformers/rms_norm.py +23 -4
  30. liger_kernel/transformers/swiglu.py +24 -0
  31. liger_kernel/transformers/trainer_integration.py +2 -45
  32. liger_kernel-0.3.1.dist-info/METADATA +395 -0
  33. liger_kernel-0.3.1.dist-info/RECORD +42 -0
  34. {liger_kernel-0.1.0.dist-info → liger_kernel-0.3.1.dist-info}/WHEEL +1 -1
  35. liger_kernel-0.1.0.dist-info/METADATA +0 -16
  36. liger_kernel-0.1.0.dist-info/RECORD +0 -27
  37. {liger_kernel-0.1.0.dist-info → liger_kernel-0.3.1.dist-info}/LICENSE +0 -0
  38. {liger_kernel-0.1.0.dist-info → liger_kernel-0.3.1.dist-info}/NOTICE +0 -0
  39. {liger_kernel-0.1.0.dist-info → liger_kernel-0.3.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,158 @@
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch.nn import CrossEntropyLoss
5
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast
6
+ from transformers.models.mixtral.modeling_mixtral import (
7
+ _CONFIG_FOR_DOC,
8
+ MIXTRAL_INPUTS_DOCSTRING,
9
+ load_balancing_loss_func,
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(MIXTRAL_INPUTS_DOCSTRING)
22
+ @replace_return_docstrings(
23
+ output_type=MoeCausalLMOutputWithPast, 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[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
+ output_router_logits: Optional[bool] = None,
37
+ return_dict: Optional[bool] = None,
38
+ cache_position: Optional[torch.LongTensor] = None,
39
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
40
+ r"""
41
+ Copy paste Mixtral's forward from transfomers v4.44.2 but replace torch cross entropy with liger fused linear cross entropy
42
+
43
+
44
+ Args:
45
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
46
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
47
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
48
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
49
+
50
+ Returns:
51
+
52
+ Example:
53
+
54
+ ```python
55
+ >>> from transformers import AutoTokenizer, MixtralForCausalLM
56
+
57
+ >>> model = MixtralForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
58
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
59
+
60
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
61
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
62
+
63
+ >>> # Generate
64
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
65
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
66
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
67
+ ```"""
68
+
69
+ output_attentions = (
70
+ output_attentions
71
+ if output_attentions is not None
72
+ else self.config.output_attentions
73
+ )
74
+ output_router_logits = (
75
+ output_router_logits
76
+ if output_router_logits is not None
77
+ else self.config.output_router_logits
78
+ )
79
+
80
+ output_hidden_states = (
81
+ output_hidden_states
82
+ if output_hidden_states is not None
83
+ else self.config.output_hidden_states
84
+ )
85
+ return_dict = (
86
+ return_dict if return_dict is not None else self.config.use_return_dict
87
+ )
88
+
89
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
90
+ outputs = self.model(
91
+ input_ids=input_ids,
92
+ attention_mask=attention_mask,
93
+ position_ids=position_ids,
94
+ past_key_values=past_key_values,
95
+ inputs_embeds=inputs_embeds,
96
+ use_cache=use_cache,
97
+ output_attentions=output_attentions,
98
+ output_hidden_states=output_hidden_states,
99
+ output_router_logits=output_router_logits,
100
+ return_dict=return_dict,
101
+ cache_position=cache_position,
102
+ )
103
+
104
+ hidden_states = outputs[0]
105
+ logits = self.lm_head(hidden_states)
106
+ logits = logits.float()
107
+
108
+ loss = None
109
+ if self.training and (labels is not None):
110
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
111
+ shift_labels = labels[..., 1:].contiguous()
112
+ # Flatten the tokens
113
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
114
+ shift_labels = shift_labels.view(-1)
115
+
116
+ lce = LigerFusedLinearCrossEntropyLoss()
117
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
118
+ elif labels is not None:
119
+ # Shift so that tokens < n predict n
120
+ shift_logits = logits[..., :-1, :].contiguous()
121
+ shift_labels = labels[..., 1:].contiguous()
122
+ # Flatten the tokens
123
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
124
+ shift_labels = shift_labels.view(-1)
125
+ # Enable model parallelism
126
+ shift_labels = shift_labels.to(shift_logits.device)
127
+
128
+ loss_fct = CrossEntropyLoss()
129
+ loss = loss_fct(logits.weight, shift_labels)
130
+
131
+ aux_loss = None
132
+ if output_router_logits:
133
+ aux_loss = load_balancing_loss_func(
134
+ outputs.router_logits if return_dict else outputs[-1],
135
+ self.num_experts,
136
+ self.num_experts_per_tok,
137
+ attention_mask,
138
+ )
139
+ if labels is not None:
140
+ loss += self.router_aux_loss_coef * aux_loss.to(
141
+ loss.device
142
+ ) # make sure to reside in the same device
143
+
144
+ if not return_dict:
145
+ output = (logits,) + outputs[1:]
146
+ if output_router_logits:
147
+ output = (aux_loss,) + output
148
+ return (loss,) + output if loss is not None else output
149
+
150
+ return MoeCausalLMOutputWithPast(
151
+ loss=loss,
152
+ aux_loss=aux_loss,
153
+ logits=logits,
154
+ past_key_values=outputs.past_key_values,
155
+ hidden_states=outputs.hidden_states,
156
+ attentions=outputs.attentions,
157
+ router_logits=outputs.router_logits,
158
+ )
@@ -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
+ )
@@ -0,0 +1,172 @@
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch.nn import CrossEntropyLoss
5
+ from transformers.models.qwen2_vl.modeling_qwen2_vl import (
6
+ _CONFIG_FOR_DOC,
7
+ QWEN2_VL_INPUTS_DOCSTRING,
8
+ Qwen2VLCausalLMOutputWithPast,
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_VL_INPUTS_DOCSTRING)
21
+ @replace_return_docstrings(
22
+ output_type=Qwen2VLCausalLMOutputWithPast, 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
+ pixel_values: Optional[torch.Tensor] = None,
37
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
38
+ image_grid_thw: Optional[torch.LongTensor] = None,
39
+ video_grid_thw: Optional[torch.LongTensor] = None,
40
+ rope_deltas: Optional[torch.LongTensor] = None,
41
+ ) -> Union[Tuple, Qwen2VLCausalLMOutputWithPast]:
42
+ r"""
43
+ Copy paste Qwen2VL's forward but replace torch cross entropy with liger fused linear cross entropy
44
+
45
+ Args:
46
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
47
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
48
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
49
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
50
+
51
+ Returns:
52
+
53
+ Example:
54
+
55
+ ```python
56
+ >>> from PIL import Image
57
+ >>> import requests
58
+ >>> from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
59
+
60
+ >>> model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
61
+ >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
62
+
63
+ >>> messages = [
64
+ {
65
+ "role": "user",
66
+ "content": [
67
+ {"type": "image"},
68
+ {"type": "text", "text": "What is shown in this image?"},
69
+ ],
70
+ },
71
+ ]
72
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
73
+ >>> image = Image.open(requests.get(url, stream=True).raw)
74
+
75
+ >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
76
+ >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
77
+
78
+ >>> # Generate
79
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
80
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
81
+ "The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
82
+ ```"""
83
+
84
+ output_attentions = (
85
+ output_attentions
86
+ if output_attentions is not None
87
+ else self.config.output_attentions
88
+ )
89
+ output_hidden_states = (
90
+ output_hidden_states
91
+ if output_hidden_states is not None
92
+ else self.config.output_hidden_states
93
+ )
94
+ return_dict = (
95
+ return_dict if return_dict is not None else self.config.use_return_dict
96
+ )
97
+
98
+ if inputs_embeds is None:
99
+ inputs_embeds = self.model.embed_tokens(input_ids)
100
+ if pixel_values is not None:
101
+ pixel_values = pixel_values.type(self.visual.get_dtype())
102
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw).to(
103
+ inputs_embeds.device
104
+ )
105
+ image_mask = input_ids == self.config.image_token_id
106
+ if self.training:
107
+ inputs_embeds = inputs_embeds.clone()
108
+ inputs_embeds[image_mask] = image_embeds
109
+ if pixel_values_videos is not None:
110
+ pixel_values_videos = pixel_values_videos.type(self.visual.get_dtype())
111
+ video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw).to(
112
+ inputs_embeds.device
113
+ )
114
+ video_mask = input_ids == self.config.video_token_id
115
+ inputs_embeds[video_mask] = video_embeds
116
+ if attention_mask is not None:
117
+ attention_mask = attention_mask.to(inputs_embeds.device)
118
+
119
+ outputs = self.model(
120
+ input_ids=None,
121
+ position_ids=position_ids,
122
+ attention_mask=attention_mask,
123
+ past_key_values=past_key_values,
124
+ inputs_embeds=inputs_embeds,
125
+ use_cache=use_cache,
126
+ output_attentions=output_attentions,
127
+ output_hidden_states=output_hidden_states,
128
+ return_dict=return_dict,
129
+ )
130
+
131
+ hidden_states = outputs[0]
132
+
133
+ loss = None
134
+ logits = None
135
+
136
+ if self.training and (labels is not None):
137
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
138
+ shift_labels = labels[..., 1:].contiguous()
139
+
140
+ # Flatten tokens
141
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
142
+ shift_labels = shift_labels.view(-1)
143
+
144
+ lce = LigerFusedLinearCrossEntropyLoss()
145
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
146
+ else:
147
+ logits = self.lm_head(hidden_states)
148
+ logits = logits.float()
149
+ if labels is not None:
150
+ # Shift so that tokens < n predict n
151
+ shift_logits = logits[..., :-1, :].contiguous()
152
+ shift_labels = labels[..., 1:].contiguous()
153
+ # Flatten the tokens
154
+ loss_fct = CrossEntropyLoss()
155
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
156
+ shift_labels = shift_labels.view(-1)
157
+ # Enable model parallelism
158
+ shift_labels = shift_labels.to(shift_logits.device)
159
+ loss = loss_fct(shift_logits, shift_labels)
160
+
161
+ if not return_dict:
162
+ output = (logits,) + outputs[1:]
163
+ return (loss,) + output if loss is not None else output
164
+
165
+ return Qwen2VLCausalLMOutputWithPast(
166
+ loss=loss,
167
+ logits=logits,
168
+ past_key_values=outputs.past_key_values,
169
+ hidden_states=outputs.hidden_states,
170
+ attentions=outputs.attentions,
171
+ rope_deltas=rope_deltas,
172
+ )