qwen2_5_vl_custom ¶
Classes¶
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2RMSNorm ¶
Bases: Module
Qwen2RMSNorm is equivalent to T5LayerNorm
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
Methods:¶
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLAttention ¶
Bases: Module
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer and "Generating Long Sequences with Sparse Transformers".
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLCausalLMOutputWithPast dataclass ¶
Qwen2_5_VLCausalLMOutputWithPast(loss: Optional[FloatTensor] = None, logits: FloatTensor = None, past_key_values: Optional[List[FloatTensor]] = None, hidden_states: Optional[Tuple[FloatTensor]] = None, attentions: Optional[Tuple[FloatTensor]] = None, rope_deltas: Optional[LongTensor] = None)
Bases: ModelOutput
Base class for Qwen2_5_VL causal language model (or autoregressive) outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss | `torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided | Language modeling loss (for next-token prediction). | None |
logits | `torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)` | Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). | None |
past_key_values | `tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True` | Tuple of Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see | None |
hidden_states | `tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` | Tuple of Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. | None |
attentions | `tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True` | Tuple of Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. | None |
rope_deltas | `torch.LongTensor` of shape `(batch_size, )`, *optional* | The rope index difference between sequence length and multimodal rope. | None |
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLDecoderLayer ¶
Qwen2_5_VLDecoderLayer(config: Qwen2_5_VLConfig, layer_idx: int)
Bases: Module
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
Methods:¶
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLDecoderLayer.forward ¶
forward(hidden_states: Tensor, attention_mask: Optional[Tensor] = None, position_ids: Optional[LongTensor] = None, past_key_value: Optional[Tuple[Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, cache_position: Optional[LongTensor] = None, position_embeddings: Optional[Tuple[Tensor, Tensor]] = None, cp_mesh: DeviceMesh | None = None, **kwargs) -> Tuple[FloatTensor, Optional[Tuple[FloatTensor, FloatTensor]]]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hidden_states | `torch.FloatTensor` | input to the layer of shape | required |
attention_mask | `torch.FloatTensor`, *optional* | attention mask of size | None |
output_attentions | `bool`, *optional* | Whether or not to return the attentions tensors of all attention layers. See | False |
use_cache | `bool`, *optional* | If set to | False |
past_key_value | `Tuple(torch.FloatTensor)`, *optional* | cached past key and value projection states | None |
cache_position | `torch.LongTensor` of shape `(sequence_length)`, *optional* | Indices depicting the position of the input sequence tokens in the sequence. | None |
position_embeddings | `Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional* | Tuple containing the cosine and sine positional embeddings of shape | None |
cp_mesh | DeviceMesh | Device mesh over which context parallelism is done. | None |
kwargs | `dict`, *optional* | Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code into the model | {} |
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 | |
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLFlashAttention2 ¶
Bases: Qwen2_5_VLAttention
Qwen2_5_VL flash attention module, following Qwen2_5_VL attention module. This module inherits from Qwen2_5_VLAttention as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom config.max_window_layers layers.
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
Methods:¶
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLFlashAttention2.forward ¶
forward(hidden_states: Tensor, attention_mask: Optional[Tensor] = None, position_ids: Optional[LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, cache_position: Optional[LongTensor] = None, position_embeddings: Optional[Tuple[Tensor, Tensor]] = None, cp_mesh: DeviceMesh | None = None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cp_mesh | DeviceMesh | Device mesh over which context parallelism is done. | None |
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 | |
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLForConditionalGenerationSimple ¶
Bases: Module
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
Methods:¶
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLForConditionalGenerationSimple.forward ¶
forward(input_ids: LongTensor = None, attention_mask: Optional[Tensor] = None, position_ids: Optional[LongTensor] = None, past_key_values: Optional[List[FloatTensor]] = None, inputs_embeds: Optional[FloatTensor] = None, labels: Optional[LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, pixel_values: Optional[Tensor] = None, pixel_values_videos: Optional[FloatTensor] = None, image_grid_thw: Optional[LongTensor] = None, video_grid_thw: Optional[LongTensor] = None, rope_deltas: Optional[LongTensor] = None, cache_position: Optional[LongTensor] = None, second_per_grid_ts: Optional[Tensor] = None) -> Union[Tuple, Qwen2_5_VLCausalLMOutputWithPast]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels | `torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional* | Labels for computing the masked language modeling loss. Indices should either be in | None |
Returns:
Example:
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
>>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
>>> messages = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": "What is shown in this image?"},
],
},
]
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
>>> # 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]
"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 ..."
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 | |
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLForConditionalGenerationSimple.get_rope_index ¶
get_rope_index(input_ids: Optional[LongTensor] = None, image_grid_thw: Optional[LongTensor] = None, video_grid_thw: Optional[LongTensor] = None, second_per_grid_ts: Optional[Tensor] = None, attention_mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]
Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
Explanation
Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs. Examples: input_ids: [T T T T T], here T is for text. temporal position_ids: [0, 1, 2, 3, 4] height position_ids: [0, 1, 2, 3, 4] width position_ids: [0, 1, 2, 3, 4]
For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part and 1D rotary position embeddin for text part. Examples: Temporal (Time): 3 patches, representing different segments of the video in time. Height: 2 patches, dividing each frame vertically. Width: 2 patches, dividing each frame horizontally. We also have some important parameters: fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second. tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity. temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames. interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100] vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] text temporal position_ids: [101, 102, 103, 104, 105] text height position_ids: [101, 102, 103, 104, 105] text width position_ids: [101, 102, 103, 104, 105] Here we calculate the text start position_ids as the max vision position_ids plus 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids | `torch.LongTensor` of shape `(batch_size, sequence_length)` | Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. | None |
image_grid_thw | `torch.LongTensor` of shape `(num_images, 3)`, *optional* | The temporal, height and width of feature shape of each image in LLM. | None |
video_grid_thw | `torch.LongTensor` of shape `(num_videos, 3)`, *optional* | The temporal, height and width of feature shape of each video in LLM. | None |
second_per_grid_ts | `torch.Tensor` of shape `(num_videos)`, *optional* | The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs. | None |
attention_mask | `torch.Tensor` of shape `(batch_size, sequence_length)`, *optional* | Mask to avoid performing attention on padding token indices. Mask values selected in
| None |
Returns:
| Type | Description |
|---|---|
Tensor | position_ids ( |
Tensor | mrope_position_deltas ( |
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 | |
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLModel ¶
Bases: Module
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VLSdpaAttention ¶
Bases: Qwen2_5_VLAttention
Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from Qwen2Attention as the weights of the module stays untouched. The only changes are on the forward pass to adapt to SDPA API.
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VisionTransformerPretrainedModel ¶
Bases: Module
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
Methods:¶
fastvideo.models.encoders.qwen2_5_vl_custom.Qwen2_5_VisionTransformerPretrainedModel.forward ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hidden_states | `torch.Tensor` of shape `(batch_size, seq_len, hidden_size)` | The final hidden states of the model. | required |
grid_thw | `torch.Tensor` of shape `(num_images_or_videos, 3)` | The temporal, height and width of feature shape of each image in LLM. | required |
Returns:
| Type | Description |
|---|---|
Tensor |
|
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
Functions:¶
fastvideo.models.encoders.qwen2_5_vl_custom.apply_multimodal_rotary_pos_emb ¶
Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
Explanation
Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For vision embedding part, we apply rotary position embedding on temporal, height and width dimension seperately. Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding. For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal, height and width) of text embedding is always the same, so the text embedding rotary position embedding has no difference with modern LLMs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | `torch.Tensor` | The query tensor. | required |
k | `torch.Tensor` | The key tensor. | required |
cos | `torch.Tensor` | The cosine part of the rotary embedding. | required |
sin | `torch.Tensor` | The sine part of the rotary embedding. | required |
position_ids | `torch.Tensor` | The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. | required |
mrope_section | `List(int)` | Multimodal rope section is for channel dimension of temporal, height and width in rope calculation. | required |
unsqueeze_dim | `int`, *optional*, defaults to 1 | The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. | 1 |
Returns: tuple(torch.Tensor) comprising of the query and key tensors rotated using the Rotary Position Embedding.
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
fastvideo.models.encoders.qwen2_5_vl_custom.get_rope_index ¶
get_rope_index(model_config, input_ids: Optional[LongTensor] = None, image_grid_thw: Optional[LongTensor] = None, video_grid_thw: Optional[LongTensor] = None, second_per_grid_ts: Optional[Tensor] = None, attention_mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]
Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
Explanation
Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs. Examples: input_ids: [T T T T T], here T is for text. temporal position_ids: [0, 1, 2, 3, 4] height position_ids: [0, 1, 2, 3, 4] width position_ids: [0, 1, 2, 3, 4]
For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part and 1D rotary position embeddin for text part. Examples: Temporal (Time): 3 patches, representing different segments of the video in time. Height: 2 patches, dividing each frame vertically. Width: 2 patches, dividing each frame horizontally. We also have some important parameters: fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second. tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity. temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames. interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100] vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] text temporal position_ids: [101, 102, 103, 104, 105] text height position_ids: [101, 102, 103, 104, 105] text width position_ids: [101, 102, 103, 104, 105] Here we calculate the text start position_ids as the max vision position_ids plus 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids | `torch.LongTensor` of shape `(batch_size, sequence_length)` | Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. | None |
image_grid_thw | `torch.LongTensor` of shape `(num_images, 3)`, *optional* | The temporal, height and width of feature shape of each image in LLM. | None |
video_grid_thw | `torch.LongTensor` of shape `(num_videos, 3)`, *optional* | The temporal, height and width of feature shape of each video in LLM. | None |
second_per_grid_ts | `torch.Tensor` of shape `(num_videos)`, *optional* | The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs. | None |
attention_mask | `torch.Tensor` of shape `(batch_size, sequence_length)`, *optional* | Mask to avoid performing attention on padding token indices. Mask values selected in
| None |
Returns:
| Type | Description |
|---|---|
Tensor | position_ids ( |
Tensor | mrope_position_deltas ( |
Source code in fastvideo/models/encoders/qwen2_5_vl_custom.py
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 | |
fastvideo.models.encoders.qwen2_5_vl_custom.repeat_kv ¶
repeat_kv(hidden_states: Tensor, n_rep: int) -> Tensor
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)