mfarre commited on
Commit
71923bb
·
verified ·
1 Parent(s): e8945cf

Upload 5 files

Browse files
Chapter_10.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
Chapter_10_Blip3o_Training_Script.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
Chapter_10_Qwen_Omni_Training_Script.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
Chapter_4.ipynb ADDED
@@ -0,0 +1,1049 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "source": [
6
+ "# Chapter 4 - Training Data and Preprocessing for VLMs"
7
+ ],
8
+ "metadata": {
9
+ "id": "_Q1EXjtG0LEs"
10
+ }
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {
16
+ "id": "wa4KqZMLaSY2",
17
+ "colab": {
18
+ "base_uri": "https://localhost:8080/"
19
+ },
20
+ "outputId": "9e52e684-f7a3-4068-ee5a-b8f8b5cdf851"
21
+ },
22
+ "outputs": [
23
+ {
24
+ "output_type": "stream",
25
+ "name": "stdout",
26
+ "text": [
27
+ "Requirement already satisfied: datasets in /usr/local/lib/python3.12/dist-packages (4.0.0)\n",
28
+ "Requirement already satisfied: pillow in /usr/local/lib/python3.12/dist-packages (11.3.0)\n",
29
+ "Requirement already satisfied: huggingface_hub in /usr/local/lib/python3.12/dist-packages (1.5.0)\n",
30
+ "Requirement already satisfied: requests in /usr/local/lib/python3.12/dist-packages (2.32.4)\n",
31
+ "Requirement already satisfied: filelock in /usr/local/lib/python3.12/dist-packages (from datasets) (3.24.3)\n",
32
+ "Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.12/dist-packages (from datasets) (2.0.2)\n",
33
+ "Requirement already satisfied: pyarrow>=15.0.0 in /usr/local/lib/python3.12/dist-packages (from datasets) (18.1.0)\n",
34
+ "Requirement already satisfied: dill<0.3.9,>=0.3.0 in /usr/local/lib/python3.12/dist-packages (from datasets) (0.3.8)\n",
35
+ "Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (from datasets) (2.2.2)\n",
36
+ "Requirement already satisfied: tqdm>=4.66.3 in /usr/local/lib/python3.12/dist-packages (from datasets) (4.67.3)\n",
37
+ "Requirement already satisfied: xxhash in /usr/local/lib/python3.12/dist-packages (from datasets) (3.6.0)\n",
38
+ "Requirement already satisfied: multiprocess<0.70.17 in /usr/local/lib/python3.12/dist-packages (from datasets) (0.70.16)\n",
39
+ "Requirement already satisfied: fsspec<=2025.3.0,>=2023.1.0 in /usr/local/lib/python3.12/dist-packages (from fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (2025.3.0)\n",
40
+ "Requirement already satisfied: packaging in /usr/local/lib/python3.12/dist-packages (from datasets) (26.0)\n",
41
+ "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.12/dist-packages (from datasets) (6.0.3)\n",
42
+ "Requirement already satisfied: hf-xet<2.0.0,>=1.2.0 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (1.3.1)\n",
43
+ "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (0.28.1)\n",
44
+ "Requirement already satisfied: typer in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (0.24.1)\n",
45
+ "Requirement already satisfied: typing-extensions>=4.1.0 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (4.15.0)\n",
46
+ "Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.12/dist-packages (from requests) (3.4.4)\n",
47
+ "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.12/dist-packages (from requests) (3.11)\n",
48
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.12/dist-packages (from requests) (2.5.0)\n",
49
+ "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.12/dist-packages (from requests) (2026.2.25)\n",
50
+ "Requirement already satisfied: aiohttp!=4.0.0a0,!=4.0.0a1 in /usr/local/lib/python3.12/dist-packages (from fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (3.13.3)\n",
51
+ "Requirement already satisfied: anyio in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface_hub) (4.12.1)\n",
52
+ "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface_hub) (1.0.9)\n",
53
+ "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.12/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->huggingface_hub) (0.16.0)\n",
54
+ "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas->datasets) (2.9.0.post0)\n",
55
+ "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas->datasets) (2025.2)\n",
56
+ "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas->datasets) (2025.3)\n",
57
+ "Requirement already satisfied: click>=8.2.1 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface_hub) (8.3.1)\n",
58
+ "Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface_hub) (1.5.4)\n",
59
+ "Requirement already satisfied: rich>=12.3.0 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface_hub) (13.9.4)\n",
60
+ "Requirement already satisfied: annotated-doc>=0.0.2 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface_hub) (0.0.4)\n",
61
+ "Requirement already satisfied: aiohappyeyeballs>=2.5.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (2.6.1)\n",
62
+ "Requirement already satisfied: aiosignal>=1.4.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (1.4.0)\n",
63
+ "Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (25.4.0)\n",
64
+ "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (1.8.0)\n",
65
+ "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (6.7.1)\n",
66
+ "Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (0.4.1)\n",
67
+ "Requirement already satisfied: yarl<2.0,>=1.17.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (1.22.0)\n",
68
+ "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas->datasets) (1.17.0)\n",
69
+ "Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.12/dist-packages (from rich>=12.3.0->typer->huggingface_hub) (4.0.0)\n",
70
+ "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.12/dist-packages (from rich>=12.3.0->typer->huggingface_hub) (2.19.2)\n",
71
+ "Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.12/dist-packages (from markdown-it-py>=2.2.0->rich>=12.3.0->typer->huggingface_hub) (0.1.2)\n",
72
+ "Collecting transformers==5.2.0\n",
73
+ " Downloading transformers-5.2.0-py3-none-any.whl.metadata (32 kB)\n",
74
+ "Requirement already satisfied: huggingface-hub<2.0,>=1.3.0 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (1.5.0)\n",
75
+ "Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (2.0.2)\n",
76
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (26.0)\n",
77
+ "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (6.0.3)\n",
78
+ "Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (2025.11.3)\n",
79
+ "Requirement already satisfied: tokenizers<=0.23.0,>=0.22.0 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (0.22.2)\n",
80
+ "Requirement already satisfied: typer-slim in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (0.24.0)\n",
81
+ "Requirement already satisfied: safetensors>=0.4.3 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (0.7.0)\n",
82
+ "Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (4.67.3)\n",
83
+ "Requirement already satisfied: filelock>=3.10.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (3.24.3)\n",
84
+ "Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (2025.3.0)\n",
85
+ "Requirement already satisfied: hf-xet<2.0.0,>=1.2.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (1.3.1)\n",
86
+ "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.28.1)\n",
87
+ "Requirement already satisfied: typer in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.24.1)\n",
88
+ "Requirement already satisfied: typing-extensions>=4.1.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (4.15.0)\n",
89
+ "Requirement already satisfied: anyio in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (4.12.1)\n",
90
+ "Requirement already satisfied: certifi in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (2026.2.25)\n",
91
+ "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (1.0.9)\n",
92
+ "Requirement already satisfied: idna in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (3.11)\n",
93
+ "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.12/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.16.0)\n",
94
+ "Requirement already satisfied: click>=8.2.1 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (8.3.1)\n",
95
+ "Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (1.5.4)\n",
96
+ "Requirement already satisfied: rich>=12.3.0 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (13.9.4)\n",
97
+ "Requirement already satisfied: annotated-doc>=0.0.2 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.0.4)\n",
98
+ "Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.12/dist-packages (from rich>=12.3.0->typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (4.0.0)\n",
99
+ "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.12/dist-packages (from rich>=12.3.0->typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (2.19.2)\n",
100
+ "Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.12/dist-packages (from markdown-it-py>=2.2.0->rich>=12.3.0->typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.1.2)\n",
101
+ "Downloading transformers-5.2.0-py3-none-any.whl (10.4 MB)\n",
102
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.4/10.4 MB\u001b[0m \u001b[31m38.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
103
+ "\u001b[?25hInstalling collected packages: transformers\n",
104
+ " Attempting uninstall: transformers\n",
105
+ " Found existing installation: transformers 5.0.0\n",
106
+ " Uninstalling transformers-5.0.0:\n",
107
+ " Successfully uninstalled transformers-5.0.0\n",
108
+ "Successfully installed transformers-5.2.0\n",
109
+ "Get:1 https://cloud.r-project.org/bin/linux/ubuntu jammy-cran40/ InRelease [3,632 B]\n",
110
+ "Get:2 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64 InRelease [1,581 B]\n",
111
+ "Get:3 https://cli.github.com/packages stable InRelease [3,917 B]\n",
112
+ "Get:4 https://cloud.r-project.org/bin/linux/ubuntu jammy-cran40/ Packages [85.2 kB]\n",
113
+ "Get:5 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64 Packages [2,388 kB]\n",
114
+ "Get:6 https://r2u.stat.illinois.edu/ubuntu jammy InRelease [6,555 B]\n",
115
+ "Hit:7 http://archive.ubuntu.com/ubuntu jammy InRelease\n",
116
+ "Get:8 http://security.ubuntu.com/ubuntu jammy-security InRelease [129 kB]\n",
117
+ "Get:9 https://cli.github.com/packages stable/main amd64 Packages [357 B]\n",
118
+ "Get:10 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [128 kB]\n",
119
+ "Get:11 https://r2u.stat.illinois.edu/ubuntu jammy/main all Packages [9,802 kB]\n",
120
+ "Get:12 https://ppa.launchpadcontent.net/deadsnakes/ppa/ubuntu jammy InRelease [18.1 kB]\n",
121
+ "Hit:13 https://ppa.launchpadcontent.net/graphics-drivers/ppa/ubuntu jammy InRelease\n",
122
+ "Hit:14 https://ppa.launchpadcontent.net/ubuntugis/ppa/ubuntu jammy InRelease\n",
123
+ "Get:15 http://security.ubuntu.com/ubuntu jammy-security/universe amd64 Packages [1,301 kB]\n",
124
+ "Get:16 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [127 kB]\n",
125
+ "Get:17 https://ppa.launchpadcontent.net/deadsnakes/ppa/ubuntu jammy/main amd64 Packages [39.2 kB]\n",
126
+ "Get:18 https://r2u.stat.illinois.edu/ubuntu jammy/main amd64 Packages [2,919 kB]\n",
127
+ "Get:19 http://archive.ubuntu.com/ubuntu jammy-updates/universe amd64 Packages [1,613 kB]\n",
128
+ "Get:20 http://security.ubuntu.com/ubuntu jammy-security/restricted amd64 Packages [6,662 kB]\n",
129
+ "Get:21 http://archive.ubuntu.com/ubuntu jammy-updates/restricted amd64 Packages [6,887 kB]\n",
130
+ "Get:22 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages [4,122 kB]\n",
131
+ "Get:23 http://security.ubuntu.com/ubuntu jammy-security/main amd64 Packages [3,782 kB]\n",
132
+ "Fetched 40.0 MB in 4s (11.0 MB/s)\n",
133
+ "Reading package lists... Done\n",
134
+ "Building dependency tree... Done\n",
135
+ "Reading state information... Done\n",
136
+ "88 packages can be upgraded. Run 'apt list --upgradable' to see them.\n",
137
+ "\u001b[1;33mW: \u001b[0mSkipping acquire of configured file 'main/source/Sources' as repository 'https://r2u.stat.illinois.edu/ubuntu jammy InRelease' does not seem to provide it (sources.list entry misspelt?)\u001b[0m\n",
138
+ "Reading package lists... Done\n",
139
+ "Building dependency tree... Done\n",
140
+ "Reading state information... Done\n",
141
+ "ffmpeg is already the newest version (7:4.4.2-0ubuntu0.22.04.1).\n",
142
+ "0 upgraded, 0 newly installed, 0 to remove and 88 not upgraded.\n"
143
+ ]
144
+ }
145
+ ],
146
+ "source": [
147
+ "# Here some installs that we will be using in multiple parts of the chapter\n",
148
+ "!pip install datasets pillow huggingface_hub requests\n",
149
+ "!pip install transformers==5.2.0\n",
150
+ "!apt update && apt install -y ffmpeg"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "execution_count": null,
156
+ "metadata": {
157
+ "id": "WDv1_NAkEFlr"
158
+ },
159
+ "outputs": [],
160
+ "source": [
161
+ "# Very important to be logged in!\n",
162
+ "from huggingface_hub import login\n",
163
+ "login()\n"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "markdown",
168
+ "metadata": {
169
+ "id": "0oWU8mV_Emo5"
170
+ },
171
+ "source": [
172
+ "## 4.1 Looking at the data\n",
173
+ "### 4.1.1 Image-Text Datasets\n",
174
+ "\n",
175
+ "*Looking at LAION dataset*\n",
176
+ "\n",
177
+ "Remember: some datasets are gated, this means that you first have to go to the dataset page and accept the terms and conditions and then you will be able to browse it.\n",
178
+ "\n",
179
+ "\n",
180
+ "\n"
181
+ ]
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "execution_count": null,
186
+ "metadata": {
187
+ "colab": {
188
+ "base_uri": "https://localhost:8080/",
189
+ "height": 205,
190
+ "referenced_widgets": [
191
+ "6fb4c46f20c341cea17b28f01ac3875c",
192
+ "01cc8005bcbd490a87fbfbb80aa14c5f",
193
+ "7ff3c9983e3d485dafcbf61ddaf7dff5",
194
+ "d9230e48433241a885b378eec94dc1e0",
195
+ "f9bbe2539c894dbda093d123e7e6c6cf",
196
+ "931d5409dfa842d59ea3d5e12f13991b",
197
+ "95a6409bf61e4ecaa1b3f705eb6483e6",
198
+ "7f2aee6daa8642a1a22100cd5adbe2a2",
199
+ "e03116fd32e0467687c479bdcf9ef6c2",
200
+ "47e4ace1c6be41e0b6bf6bf42e8919a0",
201
+ "7531a9c6fec842ffa8b73425d4b25569"
202
+ ]
203
+ },
204
+ "id": "06n46XuGERPe",
205
+ "outputId": "371f3e84-b8d6-4da7-8f6b-403347f18b1a"
206
+ },
207
+ "outputs": [
208
+ {
209
+ "output_type": "display_data",
210
+ "data": {
211
+ "text/plain": [
212
+ "Resolving data files: 0%| | 0/128 [00:00<?, ?it/s]"
213
+ ],
214
+ "application/vnd.jupyter.widget-view+json": {
215
+ "version_major": 2,
216
+ "version_minor": 0,
217
+ "model_id": "6fb4c46f20c341cea17b28f01ac3875c"
218
+ }
219
+ },
220
+ "metadata": {}
221
+ },
222
+ {
223
+ "output_type": "stream",
224
+ "name": "stdout",
225
+ "text": [
226
+ "Caption: \"\"\"Brent Payne \"\"\"\"Brent Payne\"\"\"\" 1999 Self Released Country Nm/Nm Out Of Print Cd\"\"\"\n",
227
+ "Image URL: https://www.picclickimg.com/d/l400/pict/333262346250_/Brent-Payne-Brent-Payne-1999-Self-Released-Country.jpg\n",
228
+ "---\n",
229
+ "Caption: Universal Orlando 2012 The Ultimate Guide to the Ultimate Theme Park Adventure\n",
230
+ "Image URL: https://nationalbookswap.com/pbs/m/42/0942/9781887140942.jpg\n",
231
+ "---\n",
232
+ "Caption: Unique 14k Gold Yellow and Blue Diamond Engagement Ring 2.64ct.\n",
233
+ "Image URL: https://d1251d0o0760fi.cloudfront.net/catalog/product/1/4/14k-gold-diamond-engagement-ring-264-ct-p-64.jpg\n",
234
+ "---\n"
235
+ ]
236
+ }
237
+ ],
238
+ "source": [
239
+ "# Stream LAION dataset without downloading terabytes using the streaming functionality\n",
240
+ "from datasets import load_dataset\n",
241
+ "\n",
242
+ "dataset = load_dataset(\"laion/relaion2B-en-research-safe\", streaming=True)\n",
243
+ "\n",
244
+ "for example in dataset['train'].take(3):\n",
245
+ " print(f\"Caption: {example['caption']}\")\n",
246
+ " print(f\"Image URL: {example['url']}\")\n",
247
+ " print(\"---\")\n"
248
+ ]
249
+ },
250
+ {
251
+ "cell_type": "markdown",
252
+ "metadata": {
253
+ "id": "w-x35KMLaFRI"
254
+ },
255
+ "source": [
256
+ "## 4.2 Building a dataset\n",
257
+ "### 4.2.2 Data Filtering at Scale\n",
258
+ "\n",
259
+ "Complementing the snippet in section 4.2.2, here is the full code to read videos from a HF Dataset and push back to another repo the videos that are not static"
260
+ ]
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "execution_count": null,
265
+ "metadata": {
266
+ "id": "lZBIVXVIag1f"
267
+ },
268
+ "outputs": [],
269
+ "source": [
270
+ "import os\n",
271
+ "import math\n",
272
+ "import subprocess\n",
273
+ "import tempfile\n",
274
+ "import requests\n",
275
+ "from datasets import Dataset, DatasetDict\n",
276
+ "from huggingface_hub import HfApi\n"
277
+ ]
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "execution_count": null,
282
+ "metadata": {
283
+ "id": "tCeVkb5Iax1a"
284
+ },
285
+ "outputs": [],
286
+ "source": [
287
+ "# CONFIG, set here your input dataset with videos and your output dataset where you want to push the results\n",
288
+ "INPUT_DATASET_REPO = \"vlmbook/videos\"\n",
289
+ "OUTPUT_DATASET_REPO = \"<yourUsername>/filtered-videos\""
290
+ ]
291
+ },
292
+ {
293
+ "cell_type": "code",
294
+ "execution_count": null,
295
+ "metadata": {
296
+ "id": "XTq0f4LbaOii"
297
+ },
298
+ "outputs": [],
299
+ "source": [
300
+ "\n",
301
+ "# A couple of auxiliar functions to explore the input dataset, find MP4 files and download those to analyze them\n",
302
+ "def get_mp4_files_in_repo():\n",
303
+ " \"\"\"Check which MP4 files are available in the repository root.\"\"\"\n",
304
+ " api = HfApi()\n",
305
+ "\n",
306
+ " try:\n",
307
+ " repo_files = api.list_repo_files(INPUT_DATASET_REPO, repo_type=\"dataset\")\n",
308
+ " # Filter for MP4 files in root only\n",
309
+ " mp4_files = [f for f in repo_files if f.endswith('.mp4') and '/' not in f]\n",
310
+ "\n",
311
+ " print(f\"Found {len(mp4_files)} MP4 files:\")\n",
312
+ " for mp4_file in mp4_files:\n",
313
+ " print(f\" - {mp4_file}\")\n",
314
+ "\n",
315
+ " return mp4_files\n",
316
+ "\n",
317
+ " except Exception as e:\n",
318
+ " print(f\"Error accessing repository: {e}\")\n",
319
+ " return []\n",
320
+ "\n",
321
+ "\n",
322
+ "def download_video_from_hf(video_filename):\n",
323
+ " \"\"\"Download a specific MP4 file from the HF repository.\"\"\"\n",
324
+ " url = f\"https://huggingface.co/datasets/{INPUT_DATASET_REPO}/resolve/main/{video_filename}\"\n",
325
+ "\n",
326
+ " try:\n",
327
+ " response = requests.get(url, stream=True)\n",
328
+ " response.raise_for_status()\n",
329
+ "\n",
330
+ " # Create temporary file\n",
331
+ " temp_file = tempfile.NamedTemporaryFile(suffix=\".mp4\", delete=False)\n",
332
+ "\n",
333
+ " # Download video data\n",
334
+ " for chunk in response.iter_content(chunk_size=8192):\n",
335
+ " temp_file.write(chunk)\n",
336
+ "\n",
337
+ " temp_file.close()\n",
338
+ " print(f\"Downloaded {video_filename}\")\n",
339
+ " return temp_file.name\n",
340
+ "\n",
341
+ " except Exception as e:\n",
342
+ " print(f\"Error downloading {video_filename}: {e}\")\n",
343
+ " return None\n",
344
+ "\n"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": null,
350
+ "metadata": {
351
+ "id": "n05DQOWldhbu"
352
+ },
353
+ "outputs": [],
354
+ "source": [
355
+ "\n",
356
+ "\n",
357
+ "# The magic of the script - how we use ffmpeg and its plugin freezedetect to discard videos quickly\n",
358
+ "\n",
359
+ "def is_video_static(video_file, threshold=0.4):\n",
360
+ " \"\"\"Check if video has static content using ffmpeg freezedetect.\"\"\"\n",
361
+ "\n",
362
+ " # Get video duration\n",
363
+ " result = subprocess.run([\n",
364
+ " \"ffprobe\", \"-v\", \"quiet\", \"-show_entries\", \"format=duration\",\n",
365
+ " \"-of\", \"csv=p=0\", video_file\n",
366
+ " ], capture_output=True, text=True)\n",
367
+ "\n",
368
+ " duration = float(result.stdout.strip())\n",
369
+ " segments = math.ceil(duration / 60) # 60-second segments\n",
370
+ " freeze_count = 0\n",
371
+ "\n",
372
+ " # Check each segment for freezes\n",
373
+ " for start in range(0, int(duration), 60):\n",
374
+ " result = subprocess.run([\n",
375
+ " \"ffmpeg\", \"-ss\", str(start), \"-i\", video_file, \"-t\", \"60\",\n",
376
+ " \"-vf\", \"freezedetect=n=0.05:d=50\", \"-f\", \"null\", \"-\"\n",
377
+ " ], capture_output=True, text=True)\n",
378
+ "\n",
379
+ " if \"freezedetect\" in result.stderr:\n",
380
+ " freeze_count += 1\n",
381
+ "\n",
382
+ " freeze_percentage = freeze_count / segments\n",
383
+ " print(f\" Freeze percentage: {freeze_percentage:.1%}\")\n",
384
+ "\n",
385
+ " return freeze_percentage >= threshold\n",
386
+ "\n"
387
+ ]
388
+ },
389
+ {
390
+ "cell_type": "code",
391
+ "execution_count": null,
392
+ "metadata": {
393
+ "colab": {
394
+ "base_uri": "https://localhost:8080/"
395
+ },
396
+ "id": "rrQlzPILdqbF",
397
+ "outputId": "14668220-d37a-4833-f9fc-b744a23f9625"
398
+ },
399
+ "outputs": [
400
+ {
401
+ "output_type": "stream",
402
+ "name": "stdout",
403
+ "text": [
404
+ "Checking for MP4 files in repository...\n",
405
+ "Found 4 MP4 files:\n",
406
+ " - 09KmKSz4r_Y.mp4\n",
407
+ " - MewNUHRGOm0.mp4\n",
408
+ " - StKxb6z-MHk.mp4\n",
409
+ " - solid_rgb_3min_640x480.mp4\n",
410
+ "\n",
411
+ "Processing 09KmKSz4r_Y.mp4...\n",
412
+ "Downloaded 09KmKSz4r_Y.mp4\n",
413
+ " Freeze percentage: 0.0%\n",
414
+ "09KmKSz4r_Y passed filter\n",
415
+ "\n",
416
+ "Processing MewNUHRGOm0.mp4...\n",
417
+ "Downloaded MewNUHRGOm0.mp4\n",
418
+ " Freeze percentage: 0.0%\n",
419
+ "MewNUHRGOm0 passed filter\n",
420
+ "\n",
421
+ "Processing StKxb6z-MHk.mp4...\n",
422
+ "Downloaded StKxb6z-MHk.mp4\n",
423
+ " Freeze percentage: 0.0%\n",
424
+ "StKxb6z-MHk passed filter\n",
425
+ "\n",
426
+ "Processing solid_rgb_3min_640x480.mp4...\n",
427
+ "Downloaded solid_rgb_3min_640x480.mp4\n",
428
+ " Freeze percentage: 100.0%\n",
429
+ "solid_rgb_3min_640x480 filtered out\n"
430
+ ]
431
+ }
432
+ ],
433
+ "source": [
434
+ "\n",
435
+ "# Discover MP4 files in the repository\n",
436
+ "print(\"Checking for MP4 files in repository...\")\n",
437
+ "mp4_files = get_mp4_files_in_repo()\n",
438
+ "\n",
439
+ "\n",
440
+ "# Process each MP4 file\n",
441
+ "filtered_videos = []\n",
442
+ "\n",
443
+ "\n",
444
+ "for mp4_file in mp4_files:\n",
445
+ " print(f\"\\nProcessing {mp4_file}...\")\n",
446
+ "\n",
447
+ " # Extract video ID from filename\n",
448
+ " video_id = mp4_file.replace('.mp4', '')\n",
449
+ "\n",
450
+ " # Download video from HF repo\n",
451
+ " temp_video_path = download_video_from_hf(mp4_file)\n",
452
+ " if not temp_video_path:\n",
453
+ " continue\n",
454
+ "\n",
455
+ " # Analyze video for static content\n",
456
+ " try:\n",
457
+ " if not is_video_static(temp_video_path):\n",
458
+ " # Video passes filter - read file data\n",
459
+ " with open(temp_video_path, 'rb') as f:\n",
460
+ " video_bytes = f.read()\n",
461
+ "\n",
462
+ " filtered_videos.append({\n",
463
+ " 'video_id': video_id,\n",
464
+ " 'filename': mp4_file,\n",
465
+ " 'video_data': video_bytes\n",
466
+ " })\n",
467
+ " print(f\"{video_id} passed filter\")\n",
468
+ " else:\n",
469
+ " print(f\"{video_id} filtered out\")\n",
470
+ "\n",
471
+ " except Exception as e:\n",
472
+ " print(f\"Error analyzing {video_id}: {e}\")\n",
473
+ "\n",
474
+ " finally:\n",
475
+ " # Clean up temporary file\n",
476
+ " if os.path.exists(temp_video_path):\n",
477
+ " os.unlink(temp_video_path)\n"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "code",
482
+ "execution_count": null,
483
+ "metadata": {
484
+ "colab": {
485
+ "base_uri": "https://localhost:8080/",
486
+ "height": 331,
487
+ "referenced_widgets": [
488
+ "d043aca0454e41aeafa0314eb52e3de1",
489
+ "5df17c962fea448f9ab65840d5348191",
490
+ "71105a58216543dd97f89b21d3c52e46",
491
+ "7ae0acc5a455476e92660d66ed0aa654",
492
+ "8231960b067a44838bb511c0683b356e",
493
+ "7a94bbecb5ef45ca848e303e4260072a",
494
+ "b1d72d695d24457cb0c38ddf41142d45",
495
+ "af877034a8fe4ed5a1f04b15b793a85d",
496
+ "935fd711ec3445ee93552b836d8db66b",
497
+ "8e8c3aa012b343918a1b63d94d6a05d5",
498
+ "9136a68daf2849c38845db321bb6a92f",
499
+ "e9f7a808209b4f1097938619a2da36be",
500
+ "27207ee74d08460490fb53904e67136e",
501
+ "77e2a74dbd8149da9c283629c31bff54",
502
+ "2ca8a18ca66d4bc0b7e4a4876554ad8a",
503
+ "2e12213a8e20463f8d1fcbb371000f91",
504
+ "17eebc11f7474c18a97b85bc21a01fb1",
505
+ "e916b950fabe45f3904cfdf5b489ccec",
506
+ "d54396afdac541bc9e39a01e990934e8",
507
+ "be26502380d145e3be399a772b64ce61",
508
+ "1e09a0ec58c94ce7b7d513523f4502e6",
509
+ "9617edbffb0e4c7da3bca89c8d174ed1",
510
+ "d6ae988b5b254549a11265d5f614f097",
511
+ "891505d1669840eaa653258f32e0c68f",
512
+ "6fb8d978614f496da180b49db99d6e16",
513
+ "fe1dbafda42c4f4199ff16ed4b771d6e",
514
+ "ebb3dbe62b28422e95d6156a500efffa",
515
+ "bab64793b7774f34a7f595ba9d959f57",
516
+ "0393f0d884984c25b592c1e522c322ce",
517
+ "3558cf3c25604c7fb1e6534b9e7f79ea",
518
+ "05fd4ba3ab0349aab985be2af838955f",
519
+ "85ae0cf070234107aea7c5054c2309eb",
520
+ "d8f1ae4b0cb743f4be8a714910a303e3",
521
+ "3d7142c20d9f404db34aace5f02f9217",
522
+ "47ad1f400e804c9a974d499733c4ea3f",
523
+ "92e36f6cea7d440d9146b1f82fcb340c",
524
+ "e055d11e35374fe28ec11f22c0e84856",
525
+ "53d3fc6165ef496b8ea5313251196183",
526
+ "5c720b1e69cd4e51bbda86fe07b6c69f",
527
+ "48e762b5761e42af9303f1164b735a52",
528
+ "23648c140cc34acd864b28bd174c3728",
529
+ "f58de732c3b041acb241212138f25a57",
530
+ "a82fdc777f1a4137a52766d02294f909",
531
+ "b4d74937b3214e1b9719e939a5ad53e1",
532
+ "057374af98334017aafd3b09920fc73a",
533
+ "4e11cd0e2804402ab2b728818fe98d73",
534
+ "393ee0d241ee40a292335a31b6eecfdc",
535
+ "19bb9cd225f744fd9acdbe5fba4c9542",
536
+ "bac5fb32e8df4ecab39f2257ebfdbbf2",
537
+ "a7e02099e0724f69b780800dd8da5e50",
538
+ "f30c317ba4714e5ba52214d64f7e2130",
539
+ "dc872bfe82bb4c148f4ace719fd11def",
540
+ "06ac820a1bf7419a8a84728b360baf2f",
541
+ "a44429bb16c54d76b4cc0711d077ffc6",
542
+ "8027761326584bb99a492f8c4c7b6179",
543
+ "67e2fc1789cc4578b2774b569a22b5b1",
544
+ "3ac1ef8db8594dd39bb17e50e4a34a9a",
545
+ "125b5880409a423b990fc0fa0c3a1191",
546
+ "7fcad37186c14deeb5995c1b90b6de06",
547
+ "27e1492f25a74ed39bbfae072a797cd4",
548
+ "3dd571ff3dd44c2997307b38772ccf5c",
549
+ "010f292ede174e049bb68cfd2250b1f7",
550
+ "fdfe81254b414ec4b2639a7095f1732c",
551
+ "8503e41b70b047e3aee82fcabac20e16",
552
+ "b42a5c02ffe947a48a58aaed080fd528",
553
+ "e0240d1a25934d26811f01c448da2eec"
554
+ ]
555
+ },
556
+ "id": "VxNtFeLcdv7V",
557
+ "outputId": "460c297e-3ed1-4984-a488-d5bd3b23ac53"
558
+ },
559
+ "outputs": [
560
+ {
561
+ "output_type": "stream",
562
+ "name": "stdout",
563
+ "text": [
564
+ "\n",
565
+ "Saving 3 filtered videos...\n"
566
+ ]
567
+ },
568
+ {
569
+ "output_type": "display_data",
570
+ "data": {
571
+ "text/plain": [
572
+ "Uploading the dataset shards: 0%| | 0/1 [00:00<?, ? shards/s]"
573
+ ],
574
+ "application/vnd.jupyter.widget-view+json": {
575
+ "version_major": 2,
576
+ "version_minor": 0,
577
+ "model_id": "d043aca0454e41aeafa0314eb52e3de1"
578
+ }
579
+ },
580
+ "metadata": {}
581
+ },
582
+ {
583
+ "output_type": "display_data",
584
+ "data": {
585
+ "text/plain": [
586
+ "Creating parquet from Arrow format: 0%| | 0/1 [00:00<?, ?ba/s]"
587
+ ],
588
+ "application/vnd.jupyter.widget-view+json": {
589
+ "version_major": 2,
590
+ "version_minor": 0,
591
+ "model_id": "e9f7a808209b4f1097938619a2da36be"
592
+ }
593
+ },
594
+ "metadata": {}
595
+ },
596
+ {
597
+ "output_type": "display_data",
598
+ "data": {
599
+ "text/plain": [
600
+ "Processing Files (0 / 0) : | | 0.00B / 0.00B "
601
+ ],
602
+ "application/vnd.jupyter.widget-view+json": {
603
+ "version_major": 2,
604
+ "version_minor": 0,
605
+ "model_id": "d6ae988b5b254549a11265d5f614f097"
606
+ }
607
+ },
608
+ "metadata": {}
609
+ },
610
+ {
611
+ "output_type": "display_data",
612
+ "data": {
613
+ "text/plain": [
614
+ "New Data Upload : | | 0.00B / 0.00B "
615
+ ],
616
+ "application/vnd.jupyter.widget-view+json": {
617
+ "version_major": 2,
618
+ "version_minor": 0,
619
+ "model_id": "3d7142c20d9f404db34aace5f02f9217"
620
+ }
621
+ },
622
+ "metadata": {}
623
+ },
624
+ {
625
+ "output_type": "display_data",
626
+ "data": {
627
+ "text/plain": [
628
+ " : 100%|##########| 10.6MB / 10.6MB "
629
+ ],
630
+ "application/vnd.jupyter.widget-view+json": {
631
+ "version_major": 2,
632
+ "version_minor": 0,
633
+ "model_id": "057374af98334017aafd3b09920fc73a"
634
+ }
635
+ },
636
+ "metadata": {}
637
+ },
638
+ {
639
+ "output_type": "display_data",
640
+ "data": {
641
+ "text/plain": [
642
+ "README.md: 0%| | 0.00/354 [00:00<?, ?B/s]"
643
+ ],
644
+ "application/vnd.jupyter.widget-view+json": {
645
+ "version_major": 2,
646
+ "version_minor": 0,
647
+ "model_id": "67e2fc1789cc4578b2774b569a22b5b1"
648
+ }
649
+ },
650
+ "metadata": {}
651
+ },
652
+ {
653
+ "output_type": "stream",
654
+ "name": "stderr",
655
+ "text": [
656
+ "No files have been modified since last commit. Skipping to prevent empty commit.\n",
657
+ "WARNING:huggingface_hub.hf_api:No files have been modified since last commit. Skipping to prevent empty commit.\n"
658
+ ]
659
+ },
660
+ {
661
+ "output_type": "stream",
662
+ "name": "stdout",
663
+ "text": [
664
+ "\n",
665
+ "Filtered dataset available at: mfarre/testing\n",
666
+ "Filtered videos saved successfully!\n"
667
+ ]
668
+ }
669
+ ],
670
+ "source": [
671
+ "\n",
672
+ "\n",
673
+ "# Save filtered results\n",
674
+ "if filtered_videos:\n",
675
+ " print(f\"\\nSaving {len(filtered_videos)} filtered videos...\")\n",
676
+ "\n",
677
+ " # Create dataset from filtered videos\n",
678
+ " filtered_dataset = Dataset.from_list(filtered_videos)\n",
679
+ "\n",
680
+ " # Push filtered videos to new repository\n",
681
+ " if OUTPUT_DATASET_REPO is not None:\n",
682
+ " filtered_dataset.push_to_hub(f\"{OUTPUT_DATASET_REPO}\")\n",
683
+ "\n",
684
+ " print(f\"\\nFiltered dataset available at: {OUTPUT_DATASET_REPO}\")\n",
685
+ "\n",
686
+ " print(\"Filtered videos saved successfully!\")\n",
687
+ "\n",
688
+ "else:\n",
689
+ "\n",
690
+ " print(\"No videos passed the filter.\")"
691
+ ]
692
+ },
693
+ {
694
+ "cell_type": "markdown",
695
+ "metadata": {
696
+ "id": "BCx7QFDee8qx"
697
+ },
698
+ "source": [
699
+ "### 4.2.4 Build your own synthesis pipeline\n",
700
+ "Below the full code to synthesize Q&A using Apple's FastVLM. Note that we use the 1.5B model to make it easier to run in a colab but expect better Q&A pairs with the 7B."
701
+ ]
702
+ },
703
+ {
704
+ "cell_type": "code",
705
+ "execution_count": null,
706
+ "metadata": {
707
+ "id": "8ag3ZUh7EGu7"
708
+ },
709
+ "outputs": [],
710
+ "source": [
711
+ "# Import libraries\n",
712
+ "import torch\n",
713
+ "import json\n",
714
+ "from PIL import Image\n",
715
+ "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
716
+ "from datasets import load_dataset, Dataset\n",
717
+ "from huggingface_hub import login\n",
718
+ "import requests\n",
719
+ "from io import BytesIO"
720
+ ]
721
+ },
722
+ {
723
+ "cell_type": "code",
724
+ "execution_count": null,
725
+ "metadata": {
726
+ "colab": {
727
+ "base_uri": "https://localhost:8080/",
728
+ "height": 104,
729
+ "referenced_widgets": [
730
+ "1e57069ccfca419c9766848e1e483f36",
731
+ "dc40b9401c204aaca7e189afe0fbf44b",
732
+ "9508c6fcbbec456fa9254c959bca94e8",
733
+ "4ca6b0d38f8e45dda8a3559c927c5343",
734
+ "ef16ac573a6548f8ab352d068939a328",
735
+ "9d16aae28af94083999e587d2253e298",
736
+ "74ebf8a676c3433989a066a04d31e595",
737
+ "7e76adfb940c4abeb4ce0a4299fd5aab",
738
+ "29156ef77e604895ad5764e0e8d68e22",
739
+ "7ff7f19358324d1bb0a1543525ad63d9",
740
+ "2920d545b6dd43929ad1d542512bde4a"
741
+ ]
742
+ },
743
+ "id": "8xLhei0afKpV",
744
+ "outputId": "9e0a86d9-3572-4809-d7fd-78cbd1c0461b"
745
+ },
746
+ "outputs": [
747
+ {
748
+ "output_type": "stream",
749
+ "name": "stdout",
750
+ "text": [
751
+ "Loading FastVLM model...\n"
752
+ ]
753
+ },
754
+ {
755
+ "output_type": "display_data",
756
+ "data": {
757
+ "text/plain": [
758
+ "Loading weights: 0%| | 0/972 [00:00<?, ?it/s]"
759
+ ],
760
+ "application/vnd.jupyter.widget-view+json": {
761
+ "version_major": 2,
762
+ "version_minor": 0,
763
+ "model_id": "1e57069ccfca419c9766848e1e483f36"
764
+ }
765
+ },
766
+ "metadata": {}
767
+ },
768
+ {
769
+ "output_type": "stream",
770
+ "name": "stderr",
771
+ "text": [
772
+ "The tied weights mapping and config for this model specifies to tie model.embed_tokens.weight to lm_head.weight, but both are present in the checkpoints, so we will NOT tie them. You should update the config with `tie_word_embeddings=False` to silence this warning\n"
773
+ ]
774
+ }
775
+ ],
776
+ "source": [
777
+ "# Load the model from the hub\n",
778
+ "# Note: we are loading the 1.5B because it fits in a free Google Colab but for\n",
779
+ "# better quality Q&A you can use the 7B\n",
780
+ "\n",
781
+ "model_id = \"apple/FastVLM-1.5B\"\n",
782
+ "#model_id = \"apple/FastVLM-7B\"\n",
783
+ "\n",
784
+ "IMAGE_TOKEN_INDEX = -200\n",
785
+ "\n",
786
+ "print(\"Loading FastVLM model...\")\n",
787
+ "tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)\n",
788
+ "model = AutoModelForCausalLM.from_pretrained(\n",
789
+ " model_id,\n",
790
+ " dtype=torch.bfloat16,\n",
791
+ " device_map=\"auto\",\n",
792
+ " trust_remote_code=True\n",
793
+ ")\n",
794
+ "\n"
795
+ ]
796
+ },
797
+ {
798
+ "cell_type": "code",
799
+ "execution_count": null,
800
+ "metadata": {
801
+ "id": "7YqzQdjgEiyh"
802
+ },
803
+ "outputs": [],
804
+ "source": [
805
+ "\n",
806
+ "# Given an image, FastVLM returns us three Q&As for our dataset\n",
807
+ "\n",
808
+ "def generate_qa_pairs(image_url):\n",
809
+ " try:\n",
810
+ " # Download image\n",
811
+ " response = requests.get(image_url, timeout=10)\n",
812
+ " img = Image.open(BytesIO(response.content)).convert(\"RGB\")\n",
813
+ "\n",
814
+ " # Build chat template for Q&A generation\n",
815
+ " messages = [\n",
816
+ " {\"role\": \"user\", \"content\": \"<image>\\nGenerate 3 question-answer pairs about this image. Format as JSON: [{\\\"question\\\": \\\"...\\\", \\\"answer\\\": \\\"...\\\"}]\"}\n",
817
+ " ]\n",
818
+ " rendered = tok.apply_chat_template(\n",
819
+ " messages, add_generation_prompt=True, tokenize=False\n",
820
+ " )\n",
821
+ " pre, post = rendered.split(\"<image>\", 1)\n",
822
+ "\n",
823
+ " # Tokenize around image token\n",
824
+ " pre_ids = tok(pre, return_tensors=\"pt\", add_special_tokens=False).input_ids\n",
825
+ " post_ids = tok(post, return_tensors=\"pt\", add_special_tokens=False).input_ids\n",
826
+ " img_tok = torch.tensor([[IMAGE_TOKEN_INDEX]], dtype=pre_ids.dtype)\n",
827
+ " input_ids = torch.cat([pre_ids, img_tok, post_ids], dim=1).to(model.device)\n",
828
+ " attention_mask = torch.ones_like(input_ids, device=model.device)\n",
829
+ "\n",
830
+ " # Process image\n",
831
+ " px = model.get_vision_tower().image_processor(images=img, return_tensors=\"pt\")[\"pixel_values\"]\n",
832
+ " px = px.to(model.device, dtype=model.dtype)\n",
833
+ "\n",
834
+ " # Generate Q&A pairs\n",
835
+ " out = model.generate(\n",
836
+ " inputs=input_ids,\n",
837
+ " attention_mask=attention_mask,\n",
838
+ " images=px,\n",
839
+ " max_new_tokens=256,\n",
840
+ " )\n",
841
+ "\n",
842
+ " result = tok.decode(out[0], skip_special_tokens=True)\n",
843
+ " # Extract JSON part after the prompt\n",
844
+ " qa_text = result.split(\"Format as JSON:\")[-1].strip()\n",
845
+ " return qa_text\n",
846
+ "\n",
847
+ " except Exception as e:\n",
848
+ " return f\"Error: {str(e)}\"\n",
849
+ "\n"
850
+ ]
851
+ },
852
+ {
853
+ "cell_type": "code",
854
+ "execution_count": null,
855
+ "metadata": {
856
+ "id": "jkZID9yIEuJc",
857
+ "colab": {
858
+ "base_uri": "https://localhost:8080/",
859
+ "height": 885,
860
+ "referenced_widgets": [
861
+ "888fda19ae204839b1914490290efc36",
862
+ "75c03a2b90634cb18e02beb0345d4d5d",
863
+ "406b705a7c43405b9a0d1f8f01620db1",
864
+ "80899375b61c46559fc69641e8fc0be5",
865
+ "faf1003fc2c94c9fbbb842cfa64997ba",
866
+ "a3f5aaabc7e148d2a40255352bafd5e4",
867
+ "7fcc8215550c458fa902d54dd1d8e266",
868
+ "e7728dddd387461a98fc23b0755de6ba",
869
+ "45503561975246199b7d2e6eef94d8bb",
870
+ "2afefd33049844cba03b9cd159be5240",
871
+ "f026fad6c7d04a7e89ccc536e9549e7b"
872
+ ]
873
+ },
874
+ "outputId": "f0463fea-db0f-4cae-f68e-ab363fd58b4c"
875
+ },
876
+ "outputs": [
877
+ {
878
+ "output_type": "stream",
879
+ "name": "stdout",
880
+ "text": [
881
+ "Streaming LAION dataset...\n"
882
+ ]
883
+ },
884
+ {
885
+ "output_type": "display_data",
886
+ "data": {
887
+ "text/plain": [
888
+ "Resolving data files: 0%| | 0/128 [00:00<?, ?it/s]"
889
+ ],
890
+ "application/vnd.jupyter.widget-view+json": {
891
+ "version_major": 2,
892
+ "version_minor": 0,
893
+ "model_id": "888fda19ae204839b1914490290efc36"
894
+ }
895
+ },
896
+ "metadata": {}
897
+ },
898
+ {
899
+ "output_type": "stream",
900
+ "name": "stdout",
901
+ "text": [
902
+ "\n",
903
+ "Example 1:\n",
904
+ "Original caption: \"\"\"Brent Payne \"\"\"\"Brent Payne\"\"\"\" 1999 Self Released Country Nm/Nm Out Of Print Cd\"\"\"\n",
905
+ "Image URL: https://www.picclickimg.com/d/l400/pict/333262346250_/Brent-Payne-Brent-Payne-1999-Self-Released-Country.jpg\n",
906
+ "Generated Q&A: Error: cannot identify image file <_io.BytesIO object at 0x790e8e165b70>\n",
907
+ "---\n",
908
+ "\n",
909
+ "Example 2:\n",
910
+ "Original caption: Universal Orlando 2012 The Ultimate Guide to the Ultimate Theme Park Adventure\n",
911
+ "Image URL: https://nationalbookswap.com/pbs/m/42/0942/9781887140942.jpg\n",
912
+ "Generated Q&A: Error: HTTPSConnectionPool(host='nationalbookswap.com', port=443): Max retries exceeded with url: /pbs/m/42/0942/9781887140942.jpg (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1010)')))\n",
913
+ "---\n",
914
+ "\n",
915
+ "Example 3:\n",
916
+ "Original caption: Unique 14k Gold Yellow and Blue Diamond Engagement Ring 2.64ct.\n",
917
+ "Image URL: https://d1251d0o0760fi.cloudfront.net/catalog/product/1/4/14k-gold-diamond-engagement-ring-264-ct-p-64.jpg\n",
918
+ "Generated Q&A: Error: cannot identify image file <_io.BytesIO object at 0x790e94133420>\n",
919
+ "---\n",
920
+ "\n",
921
+ "Example 4:\n",
922
+ "Original caption: Herd of cows on alpine pasture among mountains in Alps, northern Italy. Stock Photo\n",
923
+ "Image URL: https://c8.alamy.com/comp/C84HAM/herd-of-cows-on-alpine-pasture-among-mountains-in-alps-northern-italy-C84HAM.jpg\n",
924
+ "Generated Q&A: There are several potential questions and answers that could be derived from this image:\n",
925
+ "\n",
926
+ "1. **Question:** What type of animals are seen grazing in the image?\n",
927
+ " **Answer:** The animals in the image appear to be cows, identifiable by their size, color, and the typical udder visible on some of the herd.\n",
928
+ "\n",
929
+ "2. **Question:** Describe the terrain where these cows are grazing.\n",
930
+ " **Answer:** The cows are grazing on a grassy field that appears to be at the base of a mountainous region. The field has patches of brown grass, typical of late spring or early summer, and the surrounding terrain includes sloping hills covered with more green vegetation.\n",
931
+ "\n",
932
+ "3. **Question:** What kind of environment is depicted in the background of the image?\n",
933
+ " **Answer:** The background showcases a deep valley flanked by steep, forest-covered mountains. The forest appears dense, with coniferous trees covering much of the mountain slopes, indicative of a high-altitude or alpine environment.\n",
934
+ "\n",
935
+ "4. **Question:** What could the cows be utilizing in terms of food sources within this image?\n",
936
+ " **Answer:** The cows are grazing on the grass and other vegetation present in the field, which is a common food source for cattle. The mixture of green grass and patches of\n",
937
+ "---\n",
938
+ "\n",
939
+ "Example 5:\n",
940
+ "Original caption: Farmaderbe - Max color vegetal 24 Castano moka\n",
941
+ "Image URL: https://ss-pics.s3.eu-west-1.amazonaws.com/files/1619887/page-V.987024.jpg?1600681301\n",
942
+ "Generated Q&A: {\"question\": \"What company produces the MAXCOLORE vegetable coloring product?\", \"answer\": \"The product is produced by Castando Moka,\" which is indicated in the branding at the top right of the box. This is supported by the brand name and the company logo on the packaging.\"}\n",
943
+ "{\"question\": \"What are the main ingredients in the MAXCOLORE vegetable coloring product as stated on the packaging?\", \"answer\": \"The main ingredients are 'Tricologie' combined with 'Stimtex AS,' 'Argan,' 'Marine Oil,' 'Litchi Chinesis,' 'Chloride,' 'Calcium,' 'Sodium Phosphate,' 'Maltodextrin,' 'Potassium Chloride,' 'BHT,' and 'Sodium Benzoate' according to the ingredients list. These ingredients are listed for their specific functions and properties related to hair coloring and preservation.\"}\n",
944
+ "{\"question\": \"Does the MAXCOLORE vegetable coloring product contain any metal components?\", \"answer\": \"No, the product specifies that it is devoid of metal components, indicated by 'ZERO METAL CONT Laurent' in the description.\"}\n",
945
+ "This question-answer format is designed to address potential customer inquiries about the product, providing\n",
946
+ "---\n",
947
+ "[{'original_caption': '\"\"\"Brent Payne \"\"\"\"Brent Payne\"\"\"\" 1999 Self Released Country Nm/Nm Out Of Print Cd\"\"\"', 'image_url': 'https://www.picclickimg.com/d/l400/pict/333262346250_/Brent-Payne-Brent-Payne-1999-Self-Released-Country.jpg', 'generated_qa': 'Error: cannot identify image file <_io.BytesIO object at 0x790e8e165b70>'}, {'original_caption': 'Universal Orlando 2012 The Ultimate Guide to the Ultimate Theme Park Adventure', 'image_url': 'https://nationalbookswap.com/pbs/m/42/0942/9781887140942.jpg', 'generated_qa': \"Error: HTTPSConnectionPool(host='nationalbookswap.com', port=443): Max retries exceeded with url: /pbs/m/42/0942/9781887140942.jpg (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1010)')))\"}, {'original_caption': 'Unique 14k Gold Yellow and Blue Diamond Engagement Ring 2.64ct.', 'image_url': 'https://d1251d0o0760fi.cloudfront.net/catalog/product/1/4/14k-gold-diamond-engagement-ring-264-ct-p-64.jpg', 'generated_qa': 'Error: cannot identify image file <_io.BytesIO object at 0x790e94133420>'}, {'original_caption': 'Herd of cows on alpine pasture among mountains in Alps, northern Italy. Stock Photo', 'image_url': 'https://c8.alamy.com/comp/C84HAM/herd-of-cows-on-alpine-pasture-among-mountains-in-alps-northern-italy-C84HAM.jpg', 'generated_qa': 'There are several potential questions and answers that could be derived from this image:\\n\\n1. **Question:** What type of animals are seen grazing in the image?\\n **Answer:** The animals in the image appear to be cows, identifiable by their size, color, and the typical udder visible on some of the herd.\\n\\n2. **Question:** Describe the terrain where these cows are grazing.\\n **Answer:** The cows are grazing on a grassy field that appears to be at the base of a mountainous region. The field has patches of brown grass, typical of late spring or early summer, and the surrounding terrain includes sloping hills covered with more green vegetation.\\n\\n3. **Question:** What kind of environment is depicted in the background of the image?\\n **Answer:** The background showcases a deep valley flanked by steep, forest-covered mountains. The forest appears dense, with coniferous trees covering much of the mountain slopes, indicative of a high-altitude or alpine environment.\\n\\n4. **Question:** What could the cows be utilizing in terms of food sources within this image?\\n **Answer:** The cows are grazing on the grass and other vegetation present in the field, which is a common food source for cattle. The mixture of green grass and patches of'}, {'original_caption': 'Farmaderbe - Max color vegetal 24 Castano moka', 'image_url': 'https://ss-pics.s3.eu-west-1.amazonaws.com/files/1619887/page-V.987024.jpg?1600681301', 'generated_qa': '{\"question\": \"What company produces the MAXCOLORE vegetable coloring product?\", \"answer\": \"The product is produced by Castando Moka,\" which is indicated in the branding at the top right of the box. This is supported by the brand name and the company logo on the packaging.\"}\\n{\"question\": \"What are the main ingredients in the MAXCOLORE vegetable coloring product as stated on the packaging?\", \"answer\": \"The main ingredients are \\'Tricologie\\' combined with \\'Stimtex AS,\\' \\'Argan,\\' \\'Marine Oil,\\' \\'Litchi Chinesis,\\' \\'Chloride,\\' \\'Calcium,\\' \\'Sodium Phosphate,\\' \\'Maltodextrin,\\' \\'Potassium Chloride,\\' \\'BHT,\\' and \\'Sodium Benzoate\\' according to the ingredients list. These ingredients are listed for their specific functions and properties related to hair coloring and preservation.\"}\\n{\"question\": \"Does the MAXCOLORE vegetable coloring product contain any metal components?\", \"answer\": \"No, the product specifies that it is devoid of metal components, indicated by \\'ZERO METAL CONT Laurent\\' in the description.\"}\\nThis question-answer format is designed to address potential customer inquiries about the product, providing'}]\n"
948
+ ]
949
+ }
950
+ ],
951
+ "source": [
952
+ "# Here you do three things:\n",
953
+ "# 1- Stream the LAION dataset (limited to 5 samples in this example)\n",
954
+ "# 2- Get Q&A pairs from Fast VLM\n",
955
+ "# 3- Push the results to your own repo\n",
956
+ "\n",
957
+ "#OUTPUT_REPO = \"<yourUsername>/laion-vlm-analysis\" # If set to None, it skips the push\n",
958
+ "OUTPUT_REPO = None\n",
959
+ "print(\"Streaming LAION dataset...\")\n",
960
+ "dataset = load_dataset(\"laion/relaion2B-en-research-safe\", streaming=True)\n",
961
+ "\n",
962
+ "analyzed_examples = []\n",
963
+ "\n",
964
+ "for i, example in enumerate(dataset['train'].take(5)):\n",
965
+ " print(f\"\\nExample {i+1}:\")\n",
966
+ " print(f\"Original caption: {example['caption']}\")\n",
967
+ " print(f\"Image URL: {example['url']}\")\n",
968
+ "\n",
969
+ " # Generate Q&A pairs with VLM\n",
970
+ " qa_pairs = generate_qa_pairs(example['url'])\n",
971
+ " print(f\"Generated Q&A: {qa_pairs}\")\n",
972
+ "\n",
973
+ " analyzed_examples.append({\n",
974
+ " 'original_caption': example['caption'],\n",
975
+ " 'image_url': example['url'],\n",
976
+ " 'generated_qa': qa_pairs,\n",
977
+ " })\n",
978
+ " print(\"---\")\n",
979
+ "\n",
980
+ "# Create and push dataset\n",
981
+ "analyzed_dataset = Dataset.from_list(analyzed_examples)\n",
982
+ "print(analyzed_examples)\n",
983
+ "if OUTPUT_REPO is not None:\n",
984
+ " analyzed_dataset.push_to_hub(OUTPUT_REPO)\n",
985
+ " print(f\"Dataset available at: {OUTPUT_REPO}\")"
986
+ ]
987
+ },
988
+ {
989
+ "cell_type": "markdown",
990
+ "source": [
991
+ "### 4.2.5 Preparing the dataset for consumption\n",
992
+ "Getting data from a webdataset sample. Here you can see how we stream data from inside a tar file from a webdataset\n"
993
+ ],
994
+ "metadata": {
995
+ "id": "hMQKJo-2Bm_l"
996
+ }
997
+ },
998
+ {
999
+ "cell_type": "code",
1000
+ "execution_count": null,
1001
+ "metadata": {
1002
+ "id": "gvzSv7ADFk_-",
1003
+ "colab": {
1004
+ "base_uri": "https://localhost:8080/"
1005
+ },
1006
+ "outputId": "789ee25c-4329-44f5-84e3-874eedc83f34"
1007
+ },
1008
+ "outputs": [
1009
+ {
1010
+ "output_type": "stream",
1011
+ "name": "stdout",
1012
+ "text": [
1013
+ "Sample PMC4991227_00003\n",
1014
+ "Annotations: {'annotations': [{'area': 11114.139543321944, 'bbox': [313.74, 51.71, 235.78, 50.59], 'category_id': 1, 'category_name': 'text', 'id': 1690135, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[313.74, 51.71, 549.51, 51.71, 549.51, 64.75, 549.52, 64.75, 549.52, 76.34, 549.45, 76.34, 549.45, 89.32, 486.89, 89.32, 486.89, 102.3, 313.74, 102.3, 313.74, 90.7, 313.74, 77.73, 313.74, 64.75, 313.74, 51.71]]}, {'area': 36452.22784148902, 'bbox': [59.98, 363.82, 235.83, 154.6], 'category_id': 1, 'category_name': 'text', 'id': 1690136, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[59.98, 363.82, 295.8, 363.82, 295.8, 375.41, 295.74, 375.41, 295.74, 389.67, 295.75, 389.67, 295.75, 401.43, 295.75, 401.43, 295.75, 415.86, 295.75, 415.86, 295.75, 428.84, 295.81, 428.84, 295.81, 440.43, 295.75, 440.43, 295.75, 454.86, 295.77, 454.86, 295.77, 466.45, 295.74, 466.45, 295.74, 480.81, 295.78, 480.81, 295.78, 492.41, 295.77, 492.41, 295.77, 505.38, 295.75, 505.38, 295.75, 518.42, 59.98, 518.42, 59.98, 506.83, 59.98, 493.79, 59.98, 480.81, 59.98, 467.84, 59.98, 454.86, 59.98, 441.82, 59.98, 428.84, 59.98, 415.86, 59.98, 402.82, 59.98, 389.67, 59.98, 376.86, 59.98, 363.82]]}, {'area': 20601.87269781693, 'bbox': [313.74, 103.68, 235.76, 89.59], 'category_id': 1, 'category_name': 'text', 'id': 1690137, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[325.7, 103.68, 549.48, 103.68, 549.48, 116.72, 549.49, 116.72, 549.49, 128.31, 549.46, 128.31, 549.46, 142.68, 549.47, 142.68, 549.47, 154.27, 549.44, 154.27, 549.44, 168.7, 549.5, 168.7, 549.5, 180.29, 521.66, 180.29, 521.66, 193.27, 313.74, 193.27, 313.74, 181.68, 313.74, 168.7, 313.74, 155.72, 313.74, 142.68, 313.74, 129.7, 313.74, 116.72, 325.7, 116.72, 325.7, 103.68]]}, {'area': 24022.353919701418, 'bbox': [313.74, 194.72, 235.76, 102.56], 'category_id': 1, 'category_name': 'text', 'id': 1690138, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[325.7, 194.72, 549.48, 194.72, 549.48, 206.31, 549.47, 206.31, 549.47, 220.67, 549.47, 220.67, 549.47, 233.71, 549.49, 233.71, 549.49, 246.69, 549.5, 246.69, 549.5, 258.28, 549.44, 258.28, 549.44, 271.26, 549.43, 271.26, 549.43, 285.35, 549.47, 285.35, 549.47, 297.28, 313.74, 297.28, 313.74, 285.35, 313.74, 272.26, 313.74, 259.67, 313.74, 246.69, 313.74, 233.71, 313.74, 220.67, 313.74, 207.7, 325.7, 207.7, 325.7, 194.72]]}, {'area': 51573.07954365853, 'bbox': [313.74, 298.67, 235.78, 219.56], 'category_id': 1, 'category_name': 'text', 'id': 1690139, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[325.7, 298.67, 549.49, 298.67, 549.49, 310.26, 549.45, 310.26, 549.45, 323.24, 549.43, 323.24, 549.43, 337.67, 549.47, 337.67, 549.47, 349.26, 547.37, 349.26, 547.37, 363.14, 549.43, 363.14, 549.43, 376.66, 549.47, 376.66, 549.47, 389.64, 549.52, 389.64, 549.52, 401.23, 549.51, 401.23, 549.51, 414.21, 549.5, 414.21, 549.5, 428.64, 549.51, 428.64, 549.51, 440.23, 549.43, 440.23, 549.43, 454.66, 549.49, 454.66, 549.49, 467.64, 549.5, 467.64, 549.5, 479.23, 549.43, 479.23, 549.43, 493.66, 549.45, 493.66, 549.45, 506.63, 549.51, 506.63, 549.51, 518.23, 313.74, 518.23, 313.74, 506.63, 313.74, 493.66, 313.74, 480.23, 313.74, 467.64, 313.74, 454.66, 313.74, 441.22, 313.74, 428.64, 313.74, 415.66, 313.74, 402.62, 313.74, 389.64, 313.74, 376.66, 313.74, 363.14, 313.74, 350.26, 313.74, 337.67, 313.74, 324.3, 313.74, 311.65, 325.7, 311.65, 325.7, 298.67]]}, {'area': 3647.5442417136946, 'bbox': [60.04, 50.43, 235.74, 22.63], 'category_id': 1, 'category_name': 'text', 'id': 1690140, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[60.04, 50.43, 295.77, 50.43, 295.77, 62.07, 142.33, 62.07, 142.33, 73.07, 60.04, 73.07, 60.04, 62.07, 60.04, 62.07, 60.04, 50.43]]}, {'area': 6928.976886857068, 'bbox': [59.98, 544.21, 489.43, 22.32], 'category_id': 1, 'category_name': 'text', 'id': 1690141, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[59.98, 544.21, 549.41, 544.21, 549.41, 555.52, 186.4, 555.52, 186.4, 566.52, 59.98, 566.52, 59.98, 555.84, 59.98, 555.84, 59.98, 544.21]]}, {'area': 2128.087193914893, 'bbox': [60.04, 331.74, 230.57, 9.23], 'category_id': 1, 'category_name': 'text', 'id': 1690142, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[60.04, 331.74, 290.6, 331.74, 290.6, 340.97, 60.04, 340.97, 60.04, 331.74]]}, {'area': 60529.66627771362, 'bbox': [60.03, 74.11, 235.79, 256.7], 'category_id': 4, 'category_name': 'table', 'id': 1690143, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[60.03, 74.11, 295.83, 74.11, 295.83, 330.82, 60.03, 330.82, 60.03, 74.11]]}, {'area': 81781.74340952508, 'bbox': [59.98, 567.57, 489.49, 167.08], 'category_id': 4, 'category_name': 'table', 'id': 1690144, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[59.98, 567.57, 549.47, 567.57, 549.47, 734.64, 59.98, 734.64, 59.98, 567.57]]}], 'file_name': 'PMC4991227_00003.jpg', 'height': 794, 'id': 174179, 'width': 610}\n"
1015
+ ]
1016
+ }
1017
+ ],
1018
+ "source": [
1019
+ "\n",
1020
+ "\n",
1021
+ "base_url = \"https://huggingface.co/datasets/vlmbook/small-publaynet-wds/resolve/main/publaynet-train-{i:06d}.tar\"\n",
1022
+ "urls = [base_url.format(i=i) for i in range(4)]\n",
1023
+ "dataset = load_dataset(\"webdataset\", data_files={\"train\": urls}, split=\"train\", streaming=True)\n",
1024
+ "# From here, use like any HF dataset\n",
1025
+ "for sample in dataset:\n",
1026
+ " print(f\"Sample {sample['__key__']}\")\n",
1027
+ " img_value = sample['png']\n",
1028
+ " print(f\"Annotations: {sample['json']}\")\n",
1029
+ " break\n"
1030
+ ]
1031
+ }
1032
+ ],
1033
+ "metadata": {
1034
+ "colab": {
1035
+ "provenance": [],
1036
+ "gpuType": "T4"
1037
+ },
1038
+ "kernelspec": {
1039
+ "display_name": "Python 3",
1040
+ "name": "python3"
1041
+ },
1042
+ "language_info": {
1043
+ "name": "python"
1044
+ },
1045
+ "accelerator": "GPU"
1046
+ },
1047
+ "nbformat": 4,
1048
+ "nbformat_minor": 0
1049
+ }
Chapter_9.ipynb ADDED
@@ -0,0 +1,2726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "TuSjQA1mLSYU"
7
+ },
8
+ "source": [
9
+ "# Chapter 9 - Video-Language Models"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {
16
+ "id": "a14ycJDJLi68",
17
+ "colab": {
18
+ "base_uri": "https://localhost:8080/"
19
+ },
20
+ "outputId": "302afd2e-8b46-4e84-fbca-cbce0ec731a8"
21
+ },
22
+ "outputs": [
23
+ {
24
+ "output_type": "stream",
25
+ "name": "stdout",
26
+ "text": [
27
+ "\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/10.4 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━\u001b[0m\u001b[90m╺\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.7/10.4 MB\u001b[0m \u001b[31m80.9 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m10.4/10.4 MB\u001b[0m \u001b[31m198.4 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.4/10.4 MB\u001b[0m \u001b[31m120.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
28
+ "\u001b[?25h Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
29
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m13.6/13.6 MB\u001b[0m \u001b[31m179.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
30
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m41.2/41.2 MB\u001b[0m \u001b[31m76.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
31
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m163.5/163.5 kB\u001b[0m \u001b[31m22.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
32
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m23.8/23.8 MB\u001b[0m \u001b[31m143.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
33
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m520.7/520.7 kB\u001b[0m \u001b[31m58.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
34
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m60.7/60.7 MB\u001b[0m \u001b[31m46.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
35
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m47.6/47.6 MB\u001b[0m \u001b[31m64.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
36
+ "\u001b[?25h Building wheel for docopt (setup.py) ... \u001b[?25l\u001b[?25hdone\n"
37
+ ]
38
+ }
39
+ ],
40
+ "source": [
41
+ "# Here some installs that we will be using in multiple parts of the chapter\n",
42
+ "!pip -q install -U transformers==5.2.0\n",
43
+ "!pip -q install -U torchcodec huggingface_hub\n",
44
+ "!pip -q install -U decord av qwen_vl_utils num2words faiss-cpu datasets peft bitsandbytes"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": null,
50
+ "metadata": {
51
+ "colab": {
52
+ "base_uri": "https://localhost:8080/",
53
+ "height": 331,
54
+ "referenced_widgets": [
55
+ "48135d5683db40d5ac96bfe3a94d1597",
56
+ "534edd2081034b2da978cf69e6ad59f1",
57
+ "de74a555d6cc43049d28d137247e6a05",
58
+ "f03d9d66c30b4652af74cf85f4fbe5ad",
59
+ "38084b19d0c94c4bb67bb2ca4f8e00db",
60
+ "28da51371045497cb3fa7e17017bcb10",
61
+ "1a7043d1937b481c9ab944cfa81224d0",
62
+ "c6339eb79877444ba033d7687ef16f8d",
63
+ "2da12a658e914db49610a9c1c73ee8b5",
64
+ "15031c1be3504e7e93297acf0e56354c",
65
+ "c6080d5977e942209b43bd5e91edefac",
66
+ "5e79580ee0ad455bbd92aab866cb3b51",
67
+ "3363fd43f7e84defb71938a8dbceb572",
68
+ "394323de55a144f681164de44b808ffd",
69
+ "1626da0d92ec428e87f45f2eaf7dff3f",
70
+ "121161d5494e40cfb9e6fad70ca2c4c3",
71
+ "6b9ad4ec9ae747d6b2be9a549a786f83"
72
+ ]
73
+ },
74
+ "id": "1ds0adbXMC5l",
75
+ "outputId": "ec946830-eaf7-4731-e2d1-680ba03beb70"
76
+ },
77
+ "outputs": [
78
+ {
79
+ "data": {
80
+ "application/vnd.jupyter.widget-view+json": {
81
+ "model_id": "48135d5683db40d5ac96bfe3a94d1597",
82
+ "version_major": 2,
83
+ "version_minor": 0
84
+ },
85
+ "text/plain": [
86
+ "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
87
+ ]
88
+ },
89
+ "metadata": {},
90
+ "output_type": "display_data"
91
+ }
92
+ ],
93
+ "source": [
94
+ "# Very important to be logged in!\n",
95
+ "from huggingface_hub import login\n",
96
+ "login()\n"
97
+ ]
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "execution_count": null,
102
+ "metadata": {
103
+ "id": "6G5HlZP166mk"
104
+ },
105
+ "outputs": [],
106
+ "source": [
107
+ "# We could compact all the imports in this single cell, remember to run it before going through the different sections of the notebook\n",
108
+ "from huggingface_hub import hf_hub_download\n",
109
+ "from transformers import pipeline, AutoProcessor, AutoModelForImageTextToText, AutoTokenizer, BitsAndBytesConfig, TrainingArguments, Trainer\n",
110
+ "from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training, PeftModel\n",
111
+ "import numpy as np\n",
112
+ "from typing import Dict, List, Tuple\n",
113
+ "from pathlib import Path\n",
114
+ "from datasets import load_dataset\n",
115
+ "\n",
116
+ "import faiss\n",
117
+ "import torch\n",
118
+ "import importlib.util\n",
119
+ "import sys\n",
120
+ "import os\n",
121
+ "import subprocess\n"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "metadata": {
128
+ "id": "P94Iun_T6x3s",
129
+ "colab": {
130
+ "base_uri": "https://localhost:8080/",
131
+ "height": 81,
132
+ "referenced_widgets": [
133
+ "f6bd76a87a7648ae97eec0c8a1dde2f3",
134
+ "f9d536f268a14218abef6c0d2f46e33d",
135
+ "46d56d6435c04525b45b052a17bd212e",
136
+ "5a2a184a835c4a09a6c954f6c92bb550",
137
+ "a72178fcb99d4a3d8d777ef90dc95c60",
138
+ "00f636ba95fa47c9b99f0dc5635d26ff",
139
+ "5b376c1dd27b4ed3b2a758f4ff19f5c1",
140
+ "12a2a53d18414edb9722b3a7dc9c474a",
141
+ "a98a50f55506432b8d3126ff6a22aa9a",
142
+ "acfe63dcd72b488381eab500fe94643c",
143
+ "738e62ebdce947b0bf367a55196f0c34",
144
+ "287e37d277b243639c06b4eeb62278c1",
145
+ "9fc7acdf686848a385e83960cef62987",
146
+ "0db444c06eaf4cb4a34ed8258b9aee76",
147
+ "ba33e9cdeac44461835fcf139da0795e",
148
+ "5f13de5d937945c4812201431e32569b",
149
+ "137ab5d2502f4c6d809806736d0f29d9",
150
+ "da3dc66b94194d3299ece0bc75d7e76b",
151
+ "b19518316af940f7b670a4614590b068",
152
+ "5960e343c5e341da8e1fc3d73c367659",
153
+ "dbb8243270894ce2a3c55359f213d26c",
154
+ "ffd06327199e4bcf8a494eccf015ca53"
155
+ ]
156
+ },
157
+ "outputId": "6130e841-e314-42e3-9b66-9e84928fd10e"
158
+ },
159
+ "outputs": [
160
+ {
161
+ "output_type": "display_data",
162
+ "data": {
163
+ "text/plain": [
164
+ "eating_spaghetti.mp4: 0%| | 0.00/1.01M [00:00<?, ?B/s]"
165
+ ],
166
+ "application/vnd.jupyter.widget-view+json": {
167
+ "version_major": 2,
168
+ "version_minor": 0,
169
+ "model_id": "f6bd76a87a7648ae97eec0c8a1dde2f3"
170
+ }
171
+ },
172
+ "metadata": {}
173
+ },
174
+ {
175
+ "output_type": "display_data",
176
+ "data": {
177
+ "text/plain": [
178
+ "09KmKSz4r_Y.mp4: 0%| | 0.00/2.73M [00:00<?, ?B/s]"
179
+ ],
180
+ "application/vnd.jupyter.widget-view+json": {
181
+ "version_major": 2,
182
+ "version_minor": 0,
183
+ "model_id": "287e37d277b243639c06b4eeb62278c1"
184
+ }
185
+ },
186
+ "metadata": {}
187
+ }
188
+ ],
189
+ "source": [
190
+ "# We will be using those two videos as examples across several part of the notebook\n",
191
+ "spaghetti_mp4 = hf_hub_download(\"vlmbook/videos\", \"eating_spaghetti.mp4\", repo_type=\"dataset\")\n",
192
+ "minecraft_mp4 = hf_hub_download(\"vlmbook/videos\", \"09KmKSz4r_Y.mp4\", repo_type=\"dataset\")\n"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "markdown",
197
+ "metadata": {
198
+ "id": "lRfgi6gP62mB"
199
+ },
200
+ "source": [
201
+ "# 9.1 Foundations\n",
202
+ "## 9.1.1 Video-Language tasks"
203
+ ]
204
+ },
205
+ {
206
+ "cell_type": "markdown",
207
+ "metadata": {
208
+ "id": "b5IAFzw075ay"
209
+ },
210
+ "source": [
211
+ "### Video Classification"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": null,
217
+ "metadata": {
218
+ "colab": {
219
+ "base_uri": "https://localhost:8080/",
220
+ "height": 251,
221
+ "referenced_widgets": [
222
+ "221adffcb7db454680c60320c021b373",
223
+ "011a536a206c45f39272ff13254df6c9",
224
+ "57bee38da1e240798b475c2739f6ff87",
225
+ "43a9c83071434a48bdf50dfb0a4fb58b",
226
+ "d34b883380d241ea8cd3d3913e7f141b",
227
+ "f9b706e668234d26880fa8ef5c035895",
228
+ "01a98b7ba499470183b1e06844535c30",
229
+ "d810de30edc74df5ae79c72c0a6a9d67",
230
+ "40960f1df477482a8ce2b7bcf09820a9",
231
+ "4821a99afece4e4eb4b8e2652c2eea06",
232
+ "19e8fd4f1b0345708e63ca71dd98fbca",
233
+ "c534471f6c1c44fbb17eb98567d45849",
234
+ "b4334d4496834954b176354a9ba7dcd2",
235
+ "2e2031f8319c49b496b56ff01f6ca774",
236
+ "abb0adb1049c4a23869114d787843a39",
237
+ "9c46a44cf15a4e5eab01d6442c2ee93d",
238
+ "f6cf2a67b38e4fd1bc01f9e8bd50b8ac",
239
+ "7f965bb61cf54e708ca7a6ade0469497",
240
+ "caf7678f142f4bcfa5e95ed94e5d673d",
241
+ "df06e879dade41d3a3fe2153505da443",
242
+ "68cb981332e64152abf0c3a137962021",
243
+ "fb5c9af4a1c947d1b6cf69fbdb4efa8e",
244
+ "bceab80698144e428f9efd297d22d835",
245
+ "a1d19e4eb1c04e5593f79cb8ce3c612b",
246
+ "29faf5e30bf04d07b8c8f9142919a6bf",
247
+ "19b359c0c4044c8d87fbce5cb29bced9",
248
+ "437365275362402abf4474eac36e2c8b",
249
+ "29b2ce71302246538fae17d1463e0e32",
250
+ "b5160bf0499f4834af9f50659b2492f3",
251
+ "72625e61f9e740ad8815a2ebfee3d9f0",
252
+ "e1a69017915644b1a9b1bf652c39f95a",
253
+ "f9e0efbb2ef44150b469bfcc7c9cd77c",
254
+ "5ef8fba81fa149e696a2fec8b452af69",
255
+ "167e79332d1d414a82f9112dc832aa8a",
256
+ "af1ac9277c3e4bb5b0b095b5a3db4605",
257
+ "c1ff043db6c24b768660d0646a124d91",
258
+ "3eb46306b1b14e008719f65ee6e0f2dd",
259
+ "2a3781d3a38c42e599fe9d53dfe2ec14",
260
+ "c1872f7823e64553a68875de1ed2d03b",
261
+ "31e0dccad34d48cfbfec77054e68271a",
262
+ "270d6093c6ea42bea0c634600ffb0c1b",
263
+ "51be3e38a6cb45bfb16a283c317560cc",
264
+ "5085ea5f2c514f29b100d76ec1aee457",
265
+ "59726bf8b21f4458b416fb075ca59be0",
266
+ "b1186512de504c7581691bb557c0d83d",
267
+ "9a9bc7e169a04482bc4028503f7ba7d2",
268
+ "99869b5c1deb42a8b2358e276f6d401d",
269
+ "274d3390ccd94306b0b502d176a0075e",
270
+ "8ee3b63448674d70b4aab59bb2f21c6d",
271
+ "0631ec54fb2b4d208f23630238d3e60c",
272
+ "c170bc75768f42e8b7fdc6fea907e82f",
273
+ "02635e62f5af44b58070ecff7ecc6cca",
274
+ "1c2fe8d47a554e99b19096a730feb9df",
275
+ "1a1e105b27c8485fb88a26104b209167",
276
+ "89af34a783314d9bbcb0bab8160dca84"
277
+ ]
278
+ },
279
+ "id": "_nFpGYoH7JhO",
280
+ "outputId": "103ece50-d663-4482-dcdd-6f376d1aaa0c"
281
+ },
282
+ "outputs": [
283
+ {
284
+ "output_type": "display_data",
285
+ "data": {
286
+ "text/plain": [
287
+ "config.json: 0.00B [00:00, ?B/s]"
288
+ ],
289
+ "application/vnd.jupyter.widget-view+json": {
290
+ "version_major": 2,
291
+ "version_minor": 0,
292
+ "model_id": "221adffcb7db454680c60320c021b373"
293
+ }
294
+ },
295
+ "metadata": {}
296
+ },
297
+ {
298
+ "output_type": "display_data",
299
+ "data": {
300
+ "text/plain": [
301
+ "pytorch_model.bin: 0%| | 0.00/88.2M [00:00<?, ?B/s]"
302
+ ],
303
+ "application/vnd.jupyter.widget-view+json": {
304
+ "version_major": 2,
305
+ "version_minor": 0,
306
+ "model_id": "c534471f6c1c44fbb17eb98567d45849"
307
+ }
308
+ },
309
+ "metadata": {}
310
+ },
311
+ {
312
+ "output_type": "display_data",
313
+ "data": {
314
+ "text/plain": [
315
+ "Loading weights: 0%| | 0/186 [00:00<?, ?it/s]"
316
+ ],
317
+ "application/vnd.jupyter.widget-view+json": {
318
+ "version_major": 2,
319
+ "version_minor": 0,
320
+ "model_id": "bceab80698144e428f9efd297d22d835"
321
+ }
322
+ },
323
+ "metadata": {}
324
+ },
325
+ {
326
+ "output_type": "display_data",
327
+ "data": {
328
+ "text/plain": [
329
+ "model.safetensors: 0%| | 0.00/88.2M [00:00<?, ?B/s]"
330
+ ],
331
+ "application/vnd.jupyter.widget-view+json": {
332
+ "version_major": 2,
333
+ "version_minor": 0,
334
+ "model_id": "167e79332d1d414a82f9112dc832aa8a"
335
+ }
336
+ },
337
+ "metadata": {}
338
+ },
339
+ {
340
+ "output_type": "display_data",
341
+ "data": {
342
+ "text/plain": [
343
+ "preprocessor_config.json: 0%| | 0.00/271 [00:00<?, ?B/s]"
344
+ ],
345
+ "application/vnd.jupyter.widget-view+json": {
346
+ "version_major": 2,
347
+ "version_minor": 0,
348
+ "model_id": "b1186512de504c7581691bb557c0d83d"
349
+ }
350
+ },
351
+ "metadata": {}
352
+ },
353
+ {
354
+ "output_type": "stream",
355
+ "name": "stderr",
356
+ "text": [
357
+ "The image processor of type `VideoMAEImageProcessor` is now loaded as a fast processor by default, even if the model checkpoint was saved with a slow processor. This is a breaking change and may produce slightly different outputs. To continue using the slow processor, instantiate this class with `use_fast=False`. \n",
358
+ "`use_fast` is set to `True` but the image processor class does not have a fast version. Falling back to the slow version.\n"
359
+ ]
360
+ },
361
+ {
362
+ "output_type": "stream",
363
+ "name": "stdout",
364
+ "text": [
365
+ "[{'score': 0.765625, 'label': 'eating spaghetti'}, {'score': 0.0185546875, 'label': 'eating burger'}, {'score': 0.015625, 'label': 'feeding fish'}, {'score': 0.00933837890625, 'label': 'eating ice cream'}, {'score': 0.009033203125, 'label': 'making pizza'}]\n"
366
+ ]
367
+ }
368
+ ],
369
+ "source": [
370
+ "\n",
371
+ "clf = pipeline(\n",
372
+ " \"video-classification\",\n",
373
+ " model=\"MCG-NJU/videomae-small-finetuned-kinetics\",\n",
374
+ " device=0,\n",
375
+ " dtype=torch.bfloat16,\n",
376
+ ")\n",
377
+ "print(clf(spaghetti_mp4, top_k=5))\n"
378
+ ]
379
+ },
380
+ {
381
+ "cell_type": "markdown",
382
+ "metadata": {
383
+ "id": "Q0qZ05ro9v-Y"
384
+ },
385
+ "source": [
386
+ "### Text-to-Video Retrieval"
387
+ ]
388
+ },
389
+ {
390
+ "cell_type": "code",
391
+ "execution_count": null,
392
+ "metadata": {
393
+ "colab": {
394
+ "base_uri": "https://localhost:8080/",
395
+ "height": 433,
396
+ "referenced_widgets": [
397
+ "ea42279de4d746f3a2c14c7bb1af1004",
398
+ "f721f619cf904d418af513d6ffe8b437",
399
+ "2489cfaa82a945359b7e4ed77c52e5c7",
400
+ "161ac361da0144448f01e4b60fb13846",
401
+ "466073c8fe9b48aca1c1c8a6c0181b1a",
402
+ "13c08ad929ce463fa7d669477d2441a6",
403
+ "e0d4873a508949d8b265ed4b4ce6983c",
404
+ "6fe88297d5564e4ebfcd8db614e5779d",
405
+ "f1c794dda3d749b09292ea36b93a5578",
406
+ "3d6e39233e704a3783f778bcd17815db",
407
+ "9b813e09d81c4f4bbfcd11d0d0ca8b4f",
408
+ "b9d57891e94a4756b401d0aa280c8cd1",
409
+ "5d64764ae6b3483891b96e063acd0805",
410
+ "c9a9db8e228642e08a1917b014d5449f",
411
+ "7590ca71f3234b1fb57e70028c19c09c",
412
+ "a65df27075a74bddb1a16886206dc2af",
413
+ "61fe4ccd478d47dda6ba729a80b17772",
414
+ "456f90059dd44de1987430826ca545f9",
415
+ "1d0b0c3bc7824bc783af09d3e02fce51",
416
+ "af84c1f51db1490c8b27f7b2ff978483",
417
+ "a397a362e18a45c08eb796494f478e62",
418
+ "eb75fe95e9354f2f9ed8d655dea4805b",
419
+ "d8d29f62c94546b49b6eb8c42a211594",
420
+ "d5a272deb9ec404c87d0a481aaf2503c",
421
+ "ca69c88b812d44828b59e49d4e042ab7",
422
+ "44fd2027e7394cc4ac961596f1c40863",
423
+ "2676bf3ee817496da4e9972541b1871a",
424
+ "61d7f1a660b74dccac53ffa8ff22a602",
425
+ "8b9d72e18c684566a862d837a9c4d6a5",
426
+ "1914d15f665e4095896f6100104a9b83",
427
+ "9bbb6e7f0cb044aa9fc65eae80876036",
428
+ "cfe7bf477c22487eacab9031ecd9f1a2",
429
+ "e03b4b1a39414952982e505b4a60c5eb",
430
+ "08272cf26bb7484a82f21b4cd14d734b",
431
+ "b2afbf5bab1149aeb2d963ece0947f13",
432
+ "315e11417f254410acd4cf281f36831c",
433
+ "0fdf12a5d4f6463bb20b8ab05dfe822d",
434
+ "c720651fbf5a471e934500cda647f373",
435
+ "39c41bce26e84b0885e0af4d61a36825",
436
+ "a0ab8b3025b14451a476c9dc170dc4f0",
437
+ "def7c83d6ee04891bc4e3e2ef5004e99",
438
+ "674a46c0d16d4af18ab6eda44781ba25",
439
+ "91f38a76c67844e3900a4648635a927c",
440
+ "96662600df154170bf9331056a6560da",
441
+ "1c0013c53c7d4c0ab89956305570732d",
442
+ "9aa8a102ba1f47a4af9495d75f0d1ffd",
443
+ "500ff8ad1d8e4d169f0c94ef33e78cd4",
444
+ "ed6e770a558e46639dc50b153a5da8c9",
445
+ "32d6e3c9af1e4ebfbdcf0f8e23065b7b",
446
+ "ec4094d73346421faeae713d72ceb506",
447
+ "f9cd3299c8d04bdcb49f28edd825b8d4",
448
+ "75325c34bde546d8808728e7f67d87c5",
449
+ "f88403889ff74517b7a9398e16354fd1",
450
+ "5071d8462fa149609d106813de08f644",
451
+ "1325185b7ff341d8a0d8c64d00fd32d9",
452
+ "47920165b3e44a78853073ccad054e30",
453
+ "3437db039603455498c93edb4499e7e5",
454
+ "8feb9af5f86b42aabd0d1c32f98fa3b4",
455
+ "be78c511a7574dab8a0c62eaf0ed7768",
456
+ "42e0c09d4fef4eedb2bcba79cb59bbb7",
457
+ "6e67073b852b4b43bea24068bc3fdb95",
458
+ "c2d2ee1b38da45bfb031801a166877e6",
459
+ "b797d56cf87c401a92218f0cb0c32e6e",
460
+ "c2cd4adf6a5e4de3a51641afa167ab6c",
461
+ "53289b00163846f1a9195e3288b0fcd3",
462
+ "0c2473bf7ae14c7ab92db5474e7a81d4",
463
+ "f005e1eeb88543bf95b42ba35df7184d",
464
+ "8a4b6e12ce3a4aa0acc58d19244608ff",
465
+ "1b15fbe5c8054042b3322837034e92e1",
466
+ "5934508cd21243efaf76fb1e83a948e0",
467
+ "a9a23a7fc24c4588a671d24ffbf02323",
468
+ "be3ff154e9384bb191f347613f0e66b6",
469
+ "42c46ad3beeb4aec9a01c1d5b413e8c4",
470
+ "c11312c309544fcd896f842ee23eaa57",
471
+ "af6cc1aaa2e04bada7f5e5362b95c7c2",
472
+ "8510a65404e74a8bb47f9b23c5d04785",
473
+ "94b3ed5cc03847459d3ef488d70091a6",
474
+ "56eb73eb58c142f1bf247385dce7f48e",
475
+ "26bde8e896b64cffaba79bcab1da46b3",
476
+ "58260656cd0e423e9155255fe7732359",
477
+ "50b146976cf64c3baf20650db0c79d2d",
478
+ "728549a380854afdbc45679d6329c52a",
479
+ "fa9f09b325684c5ba514367f7d0b13ad",
480
+ "49efa7362a3f415fbe124370c8df0061",
481
+ "6e8cc0532e774d3ebfbc2af93ec5d57d",
482
+ "a5ea83d948f04e559ba1eb4b0aa91193",
483
+ "a628c51cedce40858198598049df1ec2",
484
+ "e5d26ca26cda47c288b5fff781350a19",
485
+ "7b94cc1e6d9c4d98a9782c09e6433fbd",
486
+ "6f9e2960a4a54815b860bfb369e84347",
487
+ "c4238316d63e4e0e96ea9030a8429dda",
488
+ "eb2b947740794da6a908766f177f8617",
489
+ "1a9f14f686b148faa9b24183516b0447",
490
+ "34aedc7d6ea44c3b9efb8d315465b33e",
491
+ "859633a54df14b6ea43ef3ea9fc97adb",
492
+ "d2c728352033486682be6b7ef95ec0f2",
493
+ "49b442685a1f4273981d2639ee2820b3",
494
+ "e6c2f678db6b41fb87f6f9665e385e2d",
495
+ "81b780e5518047aca43df41d5a50f524",
496
+ "df29d144911848499e9e7dfd94b0ba75",
497
+ "98b2642944cc431cb5ad96121a4ef222",
498
+ "aa8d3fca60b34ec487316cad4a15c3fa",
499
+ "dec4af6cc65341abbb1e7772be54e6af",
500
+ "510fab09863c49e7bbeec8a8250bf958",
501
+ "09376d27037f433e89cb27f1b4fe3e5c",
502
+ "9b2f0aece0cc4c04ae3974fb330de440",
503
+ "86338526a6b342d59b52d423f438c479",
504
+ "f0b6a1a3fd5c423284d0e4e83178f340",
505
+ "9d58decc338c48e89569b1fa2600b2bb",
506
+ "9967d80f667245ad8b3d886405c82a50",
507
+ "88d097a5c3f543d4be441c146259dd4d",
508
+ "5eb78c35515e4bd0b6a5d3740c31ce5e",
509
+ "970ab756b45d43f588f42ff894e798b2",
510
+ "46e5dd36d7f649529f94a90997628a2e",
511
+ "0427a0b593a84e6c85d08f9487c5337b",
512
+ "748a51f7c1f9453c9f4b8821216d360b",
513
+ "25b4f7a5d3864fa9a3e759998c4c91d8",
514
+ "11edbe87770f4e8f9c646073c2bbf4ae",
515
+ "1b7f4dbf3bda47e9980598d076e01005",
516
+ "0e72743345d24f2ca613f3db75b5a1f9",
517
+ "93305f25444340a084e468ec207b027a",
518
+ "9b4deb0a945a42a5b6a0af816331bcf5",
519
+ "5cb798bffc45425599754e6dec268261",
520
+ "b554c6b1a69048699a50a35bc7e0eb4c",
521
+ "1b38a177fc8d4ffb9f87b49a8a55baff",
522
+ "0f141952b8e34c498165f75668cc96d6",
523
+ "e5cb1cc7b2394e448a46ddd6809cd8ae",
524
+ "6c8b75b6e6c54420ad5257bfcba54ec5",
525
+ "af2f1905e92a4cfea8c4f4aeed05b65a",
526
+ "3b51ad0e06b241b5b89e15559bb6b0c8",
527
+ "144e5eb9b12b43b69e97d8aaed183d98",
528
+ "0fc100a6f6b04be3816ee56c6b1a5372",
529
+ "dbbe017b83744e8a8af645a2a9eaff0c",
530
+ "35caa3176105432c9017cb218c50faec",
531
+ "c1eb4e9aead445198b5e055c2b2a3d49",
532
+ "8885951a9c6e48a39189a1a57acf26be",
533
+ "db2691d3255b45239102234c1256a4ab",
534
+ "b0a29e78eff648a1a8ef23efa6bfc5ff",
535
+ "03c26dad583b4420bba1065396b7d9ac",
536
+ "a258cd5404824becb653b809afda2167",
537
+ "ea15801e11394cdd9d8e3c92c09099c0",
538
+ "0ac0303c2c9844819c080f995d172f2b",
539
+ "4f84cf005d294f4cbf308488044b0cbb"
540
+ ]
541
+ },
542
+ "id": "e8Yp10Kb90xl",
543
+ "outputId": "bfe39a92-e4bc-479b-9967-cfd78b570242"
544
+ },
545
+ "outputs": [
546
+ {
547
+ "output_type": "display_data",
548
+ "data": {
549
+ "text/plain": [
550
+ "qwen3_vl_embedding.py: 0.00B [00:00, ?B/s]"
551
+ ],
552
+ "application/vnd.jupyter.widget-view+json": {
553
+ "version_major": 2,
554
+ "version_minor": 0,
555
+ "model_id": "ea42279de4d746f3a2c14c7bb1af1004"
556
+ }
557
+ },
558
+ "metadata": {}
559
+ },
560
+ {
561
+ "output_type": "display_data",
562
+ "data": {
563
+ "text/plain": [
564
+ "config.json: 0.00B [00:00, ?B/s]"
565
+ ],
566
+ "application/vnd.jupyter.widget-view+json": {
567
+ "version_major": 2,
568
+ "version_minor": 0,
569
+ "model_id": "b9d57891e94a4756b401d0aa280c8cd1"
570
+ }
571
+ },
572
+ "metadata": {}
573
+ },
574
+ {
575
+ "output_type": "display_data",
576
+ "data": {
577
+ "text/plain": [
578
+ "model.safetensors: 0%| | 0.00/4.26G [00:00<?, ?B/s]"
579
+ ],
580
+ "application/vnd.jupyter.widget-view+json": {
581
+ "version_major": 2,
582
+ "version_minor": 0,
583
+ "model_id": "d8d29f62c94546b49b6eb8c42a211594"
584
+ }
585
+ },
586
+ "metadata": {}
587
+ },
588
+ {
589
+ "output_type": "display_data",
590
+ "data": {
591
+ "text/plain": [
592
+ "Loading weights: 0%| | 0/625 [00:00<?, ?it/s]"
593
+ ],
594
+ "application/vnd.jupyter.widget-view+json": {
595
+ "version_major": 2,
596
+ "version_minor": 0,
597
+ "model_id": "08272cf26bb7484a82f21b4cd14d734b"
598
+ }
599
+ },
600
+ "metadata": {}
601
+ },
602
+ {
603
+ "output_type": "display_data",
604
+ "data": {
605
+ "text/plain": [
606
+ "chat_template.jinja: 0.00B [00:00, ?B/s]"
607
+ ],
608
+ "application/vnd.jupyter.widget-view+json": {
609
+ "version_major": 2,
610
+ "version_minor": 0,
611
+ "model_id": "1c0013c53c7d4c0ab89956305570732d"
612
+ }
613
+ },
614
+ "metadata": {}
615
+ },
616
+ {
617
+ "output_type": "display_data",
618
+ "data": {
619
+ "text/plain": [
620
+ "preprocessor_config.json: 0%| | 0.00/783 [00:00<?, ?B/s]"
621
+ ],
622
+ "application/vnd.jupyter.widget-view+json": {
623
+ "version_major": 2,
624
+ "version_minor": 0,
625
+ "model_id": "47920165b3e44a78853073ccad054e30"
626
+ }
627
+ },
628
+ "metadata": {}
629
+ },
630
+ {
631
+ "output_type": "display_data",
632
+ "data": {
633
+ "text/plain": [
634
+ "tokenizer_config.json: 0.00B [00:00, ?B/s]"
635
+ ],
636
+ "application/vnd.jupyter.widget-view+json": {
637
+ "version_major": 2,
638
+ "version_minor": 0,
639
+ "model_id": "f005e1eeb88543bf95b42ba35df7184d"
640
+ }
641
+ },
642
+ "metadata": {}
643
+ },
644
+ {
645
+ "output_type": "display_data",
646
+ "data": {
647
+ "text/plain": [
648
+ "vocab.json: 0.00B [00:00, ?B/s]"
649
+ ],
650
+ "application/vnd.jupyter.widget-view+json": {
651
+ "version_major": 2,
652
+ "version_minor": 0,
653
+ "model_id": "56eb73eb58c142f1bf247385dce7f48e"
654
+ }
655
+ },
656
+ "metadata": {}
657
+ },
658
+ {
659
+ "output_type": "display_data",
660
+ "data": {
661
+ "text/plain": [
662
+ "merges.txt: 0.00B [00:00, ?B/s]"
663
+ ],
664
+ "application/vnd.jupyter.widget-view+json": {
665
+ "version_major": 2,
666
+ "version_minor": 0,
667
+ "model_id": "7b94cc1e6d9c4d98a9782c09e6433fbd"
668
+ }
669
+ },
670
+ "metadata": {}
671
+ },
672
+ {
673
+ "output_type": "display_data",
674
+ "data": {
675
+ "text/plain": [
676
+ "tokenizer.json: 0%| | 0.00/11.4M [00:00<?, ?B/s]"
677
+ ],
678
+ "application/vnd.jupyter.widget-view+json": {
679
+ "version_major": 2,
680
+ "version_minor": 0,
681
+ "model_id": "df29d144911848499e9e7dfd94b0ba75"
682
+ }
683
+ },
684
+ "metadata": {}
685
+ },
686
+ {
687
+ "output_type": "display_data",
688
+ "data": {
689
+ "text/plain": [
690
+ "added_tokens.json: 0%| | 0.00/707 [00:00<?, ?B/s]"
691
+ ],
692
+ "application/vnd.jupyter.widget-view+json": {
693
+ "version_major": 2,
694
+ "version_minor": 0,
695
+ "model_id": "88d097a5c3f543d4be441c146259dd4d"
696
+ }
697
+ },
698
+ "metadata": {}
699
+ },
700
+ {
701
+ "output_type": "display_data",
702
+ "data": {
703
+ "text/plain": [
704
+ "special_tokens_map.json: 0%| | 0.00/613 [00:00<?, ?B/s]"
705
+ ],
706
+ "application/vnd.jupyter.widget-view+json": {
707
+ "version_major": 2,
708
+ "version_minor": 0,
709
+ "model_id": "9b4deb0a945a42a5b6a0af816331bcf5"
710
+ }
711
+ },
712
+ "metadata": {}
713
+ },
714
+ {
715
+ "output_type": "display_data",
716
+ "data": {
717
+ "text/plain": [
718
+ "video_preprocessor_config.json: 0%| | 0.00/817 [00:00<?, ?B/s]"
719
+ ],
720
+ "application/vnd.jupyter.widget-view+json": {
721
+ "version_major": 2,
722
+ "version_minor": 0,
723
+ "model_id": "dbbe017b83744e8a8af645a2a9eaff0c"
724
+ }
725
+ },
726
+ "metadata": {}
727
+ }
728
+ ],
729
+ "source": [
730
+ "from huggingface_hub import hf_hub_download\n",
731
+ "import importlib.util\n",
732
+ "import sys\n",
733
+ "import torch\n",
734
+ "\n",
735
+ "# Temporary patch!!\n",
736
+ "# While we wait for this PR https://huggingface.co/Qwen/Qwen3-VL-Embedding-2B/discussions/19\n",
737
+ "# to merge, you can run the code with the patch:\n",
738
+ "\n",
739
+ "import transformers.utils.generic as t_generic\n",
740
+ "\n",
741
+ "if not hasattr(t_generic, \"check_model_inputs\"):\n",
742
+ " def check_model_inputs(fn=None, *args, **kwargs):\n",
743
+ " # Suporta tant @check_model_inputs com @check_model_inputs()\n",
744
+ " if fn is None:\n",
745
+ " def deco(f):\n",
746
+ " return f\n",
747
+ " return deco\n",
748
+ " return fn\n",
749
+ "\n",
750
+ " t_generic.check_model_inputs = check_model_inputs\n",
751
+ "# End of temporary patch\n",
752
+ "\n",
753
+ "\n",
754
+ "# Qwen3-VL-Embedding ships a helper script in its model repo.\n",
755
+ "# We download it and import the Qwen3VLEmbedder class directly.\n",
756
+ "\n",
757
+ "script_path = hf_hub_download(\n",
758
+ " repo_id=\"Qwen/Qwen3-VL-Embedding-2B\",\n",
759
+ " filename=\"scripts/qwen3_vl_embedding.py\",\n",
760
+ ")\n",
761
+ "spec = importlib.util.spec_from_file_location(\"qwen3_vl_embedding\", script_path)\n",
762
+ "mod = importlib.util.module_from_spec(spec)\n",
763
+ "spec.loader.exec_module(mod)\n",
764
+ "sys.modules['qwen3_vl_embedding'] = mod\n",
765
+ "Qwen3VLEmbedder = mod.Qwen3VLEmbedder\n",
766
+ "embedder = Qwen3VLEmbedder(\n",
767
+ " model_name_or_path=\"Qwen/Qwen3-VL-Embedding-2B\",\n",
768
+ " torch_dtype=torch.bfloat16\n",
769
+ ")"
770
+ ]
771
+ },
772
+ {
773
+ "cell_type": "code",
774
+ "execution_count": null,
775
+ "metadata": {
776
+ "colab": {
777
+ "base_uri": "https://localhost:8080/"
778
+ },
779
+ "id": "MZgyZNRW-Yzi",
780
+ "outputId": "6eeace64-8de6-40cf-99f2-9855fd50035f"
781
+ },
782
+ "outputs": [
783
+ {
784
+ "output_type": "stream",
785
+ "name": "stderr",
786
+ "text": [
787
+ "qwen-vl-utils using torchcodec to read video.\n"
788
+ ]
789
+ },
790
+ {
791
+ "output_type": "stream",
792
+ "name": "stdout",
793
+ "text": [
794
+ "Query: a person eating spaghetti\n",
795
+ " score=0.750 video=eating_spaghetti.mp4\n",
796
+ " score=0.164 video=09KmKSz4r_Y.mp4\n"
797
+ ]
798
+ }
799
+ ],
800
+ "source": [
801
+ "videos = [spaghetti_mp4, minecraft_mp4]\n",
802
+ "# Embed one text query and two videos in a single call.\n",
803
+ "# The embedder returns L2-normalized vectors, so dot product = cosine similarity.\n",
804
+ "inputs = [\n",
805
+ " {\"text\": \"a person eating spaghetti\"},\n",
806
+ " {\"video\": videos[0], \"fps\": 1.0, \"max_frames\": 32},\n",
807
+ " {\"video\": videos[1], \"fps\": 1.0, \"max_frames\": 32},\n",
808
+ "]\n",
809
+ "emb = embedder.process(inputs) # (3, D) tensor, L2-normalized\n",
810
+ "q = emb[0:1] # query embedding (1, D)\n",
811
+ "V = emb[1:] # video embeddings (2, D)\n",
812
+ "scores = (V @ q.T).squeeze(1)\n",
813
+ "rank = scores.argsort(descending=True).tolist()\n",
814
+ "print(\"Query:\", inputs[0][\"text\"])\n",
815
+ "for i in rank:\n",
816
+ " print(f\" score={scores[i].item():.3f} video={videos[i].split(\"/\")[-1]}\")"
817
+ ]
818
+ },
819
+ {
820
+ "cell_type": "markdown",
821
+ "metadata": {
822
+ "id": "9mhZmUexFbJm"
823
+ },
824
+ "source": [
825
+ "## Captioning, Summarization, and Video QA\n"
826
+ ]
827
+ },
828
+ {
829
+ "cell_type": "code",
830
+ "execution_count": null,
831
+ "metadata": {
832
+ "colab": {
833
+ "base_uri": "https://localhost:8080/",
834
+ "height": 369,
835
+ "referenced_widgets": [
836
+ "89343fd1e3104a4fb0ad9038165faa60",
837
+ "9233b2b77a544d16a031fac839059e55",
838
+ "309078c397ec40fca09718a8cac7eb48",
839
+ "fa714c8757794fddab2d304d73d57d91",
840
+ "f2fd6148f0d94e7a99cd7a0a1b0ddce2",
841
+ "32ea0123767c41c88183e457eb2b1048",
842
+ "9daf65f771c64800b09712ffadbc7e31",
843
+ "27999e93dda3401aa5e6aafa9ee194ab",
844
+ "647ff8f2048540e8926075a7f4a5b1e8",
845
+ "9ebbbcbc668049979cb816e1e69b65e1",
846
+ "f28b26e52b234d578ffe813f980f4d2d",
847
+ "8ac4388e104c4c59b9040fa56c6cc0de",
848
+ "e054b5ff7451438eb03e60edadb79181",
849
+ "50b550e181694c0fa6632adb75e5687b",
850
+ "1663d5b18a63466d954afcb8c1cfbbb3",
851
+ "a7899acbeb6e445db2ef228fad6732a3",
852
+ "0b2bc3342473421ab0a14f89bea5c4df",
853
+ "74da1d3ebf5f48c39b0a232304995675",
854
+ "15899f4187f44e7e8c20003694e2c8c4",
855
+ "2a6248b2458a4bd9862f7a1d2f1f5811",
856
+ "6b03e047f1274796adc095bfa61c5c53",
857
+ "d673d55adcdb42069b786d142fdcc384",
858
+ "0e6559778bb64f9f8edcf71a2b03d3aa",
859
+ "c0a6f857d31f43a58700b8cfcfdc5595",
860
+ "e271e8c0c3d948d98dc9c9b7b83b4ce7",
861
+ "d7b463cde5df486cb66848965b897958",
862
+ "79810d17d2044f63a255370284e8133d",
863
+ "a53e62c0866e4544b1a242dd449e673e",
864
+ "1ac08911226e4a429fbdaa5e5498dd81",
865
+ "e3a5c82d370d4109b0c624ca35097911",
866
+ "08021cce4a44492e9ca4731211a16119",
867
+ "f49fb4c7195a489982430724e9397ad6",
868
+ "8ed8822d94f3442db55813545dfce80e",
869
+ "86fe35c2dc534b25a53ed2d38c19ae8e",
870
+ "5d975cca729d43c6be8948a04c6f7353",
871
+ "0402a049be34456faac4d28ee0be4d41",
872
+ "ef09e51b7d1f422db7638a958867afb8",
873
+ "c3d6c5cdf2734c46bd836f103397137c",
874
+ "823c31c5772649669973d6ec3d192c7e",
875
+ "f30f842b698a48688fb71aec32c9f973",
876
+ "4ac611b68b4640c487f959caba10086f",
877
+ "2ac21137b7434ceca8e11cc0f9522731",
878
+ "fbab3704be564b81aac28f217fd078b2",
879
+ "e3285fa00ef6465a8938d25a0378af5e",
880
+ "3320c1ce5668416fac13fe0f684a4994",
881
+ "3ddee27be3fd413e8bc8a4caec794fdc",
882
+ "cc69d581e8ee4377b412b9b68a79e13a",
883
+ "60a1396d791449c2bef8bedbbce386f9",
884
+ "3a8c4103700f410a942d91c852ee6990",
885
+ "09df6c39e5f143688a82b98690c84622",
886
+ "3d87e1047f214302810b330e0d0be0aa",
887
+ "5fa7d89836b14a0dbb9b6d3312bd1304",
888
+ "e18d7b235f874f01b1d3cb15d4039000",
889
+ "286ad28c2ef041c3b5beca1cdfdc3567",
890
+ "f68e93122a9c4369807e7787f41d51ec",
891
+ "3d933f4fdccb488b803c2e550c915f66",
892
+ "ad223e1f755b42d890730026cb8cf5e3",
893
+ "04b9399df2b74155a04c7f718d726ab3",
894
+ "8a1ccd5e126e441b9b150f2f8bc34a1f",
895
+ "9d39f416be42466a93230239b1a7eb5f",
896
+ "743665dcafd848059e5cf7fe8d0fd7d3",
897
+ "c2e86080451941f59bbd1757e7812a87",
898
+ "909846ef91344a37a51b9e546570115d",
899
+ "5e1e405a4698447290420eb4279fe391",
900
+ "364078ff28e540f6ae0993bd5b434ce5",
901
+ "255b261fd976423b8cdee997a15b31b0",
902
+ "ff3f03c4b8c14f2cb99778e5740feb3a",
903
+ "69443f86f19d4b74a495e64b9f906d47",
904
+ "dd5727a026b641e992897129a5a6e3f4",
905
+ "e1901698e7504042ab513ba2cf3d9329",
906
+ "aef1c7da8f494cfd8e0ad1dacdd6d954",
907
+ "30803c85ad53414ea3cb517e0c11c66d",
908
+ "25b24903972e4472acd0b6639649b934",
909
+ "a27d50ca59d04d2c89b6330ea6cf99df",
910
+ "e9ecd8be228c4f1286bc1d1fefdb18f1",
911
+ "c457962725dd4619a713548e5754046f",
912
+ "3aeb9b7afd0b49918d7b831aebd07f51",
913
+ "f972bd8002b949edae75b5990c09b177",
914
+ "7b0e01e67fff4fc5b134f2a102144b24",
915
+ "84dc1045c62e43af963aeb2398706f51",
916
+ "8ee589e033624ef9a14e86fb07aac7c5",
917
+ "04475db995534931b00bbb3890346c8a",
918
+ "2131f9aeaf434c85bf53b3f120c27e0f",
919
+ "bb28b88e37e64d378aaa38438d6ffa3e",
920
+ "22a6fc30115e4c49bab3429646baca6d",
921
+ "ee36e77546ba41fcb026eec63bb20a64",
922
+ "460ac2149ad24a008f4b2df1dcb988dc",
923
+ "4a8d9700712b4b198dd24a64c9b9ca38",
924
+ "1cbd889c70f04521b2f5cb04803b6888",
925
+ "e906100467c7459e806d4282e57af190",
926
+ "f727009556eb416f8963d2f471bf23c9",
927
+ "9bad27d24dd242bf930cbab1f2d1553c",
928
+ "a46f49220ec642dab52e6017b7fdb791",
929
+ "c1b87a516c524363a63e0a63fc330bd2",
930
+ "c61c310ee3e44c609e56615f70c22b88",
931
+ "acf130e732f94bd1ae0a5ab8b8e358d8",
932
+ "23e64d342667427e8e8481ada5100b92",
933
+ "3d73d30e987e4dafa5ff7d79d32328a6",
934
+ "dbd0990973f24b808f5e2506abf77e78",
935
+ "a7bf7618d5a5469492f423c3f5a3244b",
936
+ "093d7d1a34d14cb8ba27cdd4d63a4a49",
937
+ "a0765c221bbd4a4d927ab393a3b1453d",
938
+ "b79cf909d14a4755913ab22c4dff46cb",
939
+ "8b64f427462c4759a06cb3fe300d3dba",
940
+ "f1f23277669f4dd2b58cfe796080b29a",
941
+ "958e0f4f87bb4916a824d886be7a4afe",
942
+ "f3cffe7facce480680801109580638a7",
943
+ "8aadb9af4b0c469bac249bce25bc8a8a",
944
+ "ad734a72ae274b20bc6af7db8bbcff80",
945
+ "4f6638286d0b450883bd6a148ae7835b",
946
+ "398d39f2df4047979538ae21e4163f95",
947
+ "68c6a293150a499e8d67e8b584dd4252",
948
+ "ebe0eb11f08c4ffe8ac7271eeed522aa",
949
+ "5e44f70069ef4f7588f733ee4817b8ec",
950
+ "80cfd14809244b23864cb7897ee1cd1b",
951
+ "72816a8182d5404b882f40f829aa878a",
952
+ "5bc01c42a68946e9959a212167640569",
953
+ "18adc76261c3452595588590317e5354",
954
+ "092e09c5177c43259820bc8556ecb103",
955
+ "9531c541121e49ce965be3378365fd3e",
956
+ "4bf17a6163db404d81492c89cb824c5a"
957
+ ]
958
+ },
959
+ "id": "HlotacGlFjfb",
960
+ "outputId": "811f1db1-9f50-484c-ec7e-bc394dee4ced"
961
+ },
962
+ "outputs": [
963
+ {
964
+ "output_type": "display_data",
965
+ "data": {
966
+ "text/plain": [
967
+ "processor_config.json: 0%| | 0.00/67.0 [00:00<?, ?B/s]"
968
+ ],
969
+ "application/vnd.jupyter.widget-view+json": {
970
+ "version_major": 2,
971
+ "version_minor": 0,
972
+ "model_id": "89343fd1e3104a4fb0ad9038165faa60"
973
+ }
974
+ },
975
+ "metadata": {}
976
+ },
977
+ {
978
+ "output_type": "display_data",
979
+ "data": {
980
+ "text/plain": [
981
+ "chat_template.json: 0%| | 0.00/430 [00:00<?, ?B/s]"
982
+ ],
983
+ "application/vnd.jupyter.widget-view+json": {
984
+ "version_major": 2,
985
+ "version_minor": 0,
986
+ "model_id": "8ac4388e104c4c59b9040fa56c6cc0de"
987
+ }
988
+ },
989
+ "metadata": {}
990
+ },
991
+ {
992
+ "output_type": "display_data",
993
+ "data": {
994
+ "text/plain": [
995
+ "preprocessor_config.json: 0%| | 0.00/599 [00:00<?, ?B/s]"
996
+ ],
997
+ "application/vnd.jupyter.widget-view+json": {
998
+ "version_major": 2,
999
+ "version_minor": 0,
1000
+ "model_id": "0e6559778bb64f9f8edcf71a2b03d3aa"
1001
+ }
1002
+ },
1003
+ "metadata": {}
1004
+ },
1005
+ {
1006
+ "output_type": "display_data",
1007
+ "data": {
1008
+ "text/plain": [
1009
+ "config.json: 0.00B [00:00, ?B/s]"
1010
+ ],
1011
+ "application/vnd.jupyter.widget-view+json": {
1012
+ "version_major": 2,
1013
+ "version_minor": 0,
1014
+ "model_id": "86fe35c2dc534b25a53ed2d38c19ae8e"
1015
+ }
1016
+ },
1017
+ "metadata": {}
1018
+ },
1019
+ {
1020
+ "output_type": "display_data",
1021
+ "data": {
1022
+ "text/plain": [
1023
+ "tokenizer_config.json: 0.00B [00:00, ?B/s]"
1024
+ ],
1025
+ "application/vnd.jupyter.widget-view+json": {
1026
+ "version_major": 2,
1027
+ "version_minor": 0,
1028
+ "model_id": "3320c1ce5668416fac13fe0f684a4994"
1029
+ }
1030
+ },
1031
+ "metadata": {}
1032
+ },
1033
+ {
1034
+ "output_type": "display_data",
1035
+ "data": {
1036
+ "text/plain": [
1037
+ "tokenizer.json: 0.00B [00:00, ?B/s]"
1038
+ ],
1039
+ "application/vnd.jupyter.widget-view+json": {
1040
+ "version_major": 2,
1041
+ "version_minor": 0,
1042
+ "model_id": "3d933f4fdccb488b803c2e550c915f66"
1043
+ }
1044
+ },
1045
+ "metadata": {}
1046
+ },
1047
+ {
1048
+ "output_type": "display_data",
1049
+ "data": {
1050
+ "text/plain": [
1051
+ "added_tokens.json: 0.00B [00:00, ?B/s]"
1052
+ ],
1053
+ "application/vnd.jupyter.widget-view+json": {
1054
+ "version_major": 2,
1055
+ "version_minor": 0,
1056
+ "model_id": "ff3f03c4b8c14f2cb99778e5740feb3a"
1057
+ }
1058
+ },
1059
+ "metadata": {}
1060
+ },
1061
+ {
1062
+ "output_type": "display_data",
1063
+ "data": {
1064
+ "text/plain": [
1065
+ "special_tokens_map.json: 0%| | 0.00/868 [00:00<?, ?B/s]"
1066
+ ],
1067
+ "application/vnd.jupyter.widget-view+json": {
1068
+ "version_major": 2,
1069
+ "version_minor": 0,
1070
+ "model_id": "f972bd8002b949edae75b5990c09b177"
1071
+ }
1072
+ },
1073
+ "metadata": {}
1074
+ },
1075
+ {
1076
+ "output_type": "display_data",
1077
+ "data": {
1078
+ "text/plain": [
1079
+ "model.safetensors: 0%| | 0.00/2.03G [00:00<?, ?B/s]"
1080
+ ],
1081
+ "application/vnd.jupyter.widget-view+json": {
1082
+ "version_major": 2,
1083
+ "version_minor": 0,
1084
+ "model_id": "1cbd889c70f04521b2f5cb04803b6888"
1085
+ }
1086
+ },
1087
+ "metadata": {}
1088
+ },
1089
+ {
1090
+ "output_type": "display_data",
1091
+ "data": {
1092
+ "text/plain": [
1093
+ "Loading weights: 0%| | 0/489 [00:00<?, ?it/s]"
1094
+ ],
1095
+ "application/vnd.jupyter.widget-view+json": {
1096
+ "version_major": 2,
1097
+ "version_minor": 0,
1098
+ "model_id": "a7bf7618d5a5469492f423c3f5a3244b"
1099
+ }
1100
+ },
1101
+ "metadata": {}
1102
+ },
1103
+ {
1104
+ "output_type": "display_data",
1105
+ "data": {
1106
+ "text/plain": [
1107
+ "generation_config.json: 0%| | 0.00/136 [00:00<?, ?B/s]"
1108
+ ],
1109
+ "application/vnd.jupyter.widget-view+json": {
1110
+ "version_major": 2,
1111
+ "version_minor": 0,
1112
+ "model_id": "398d39f2df4047979538ae21e4163f95"
1113
+ }
1114
+ },
1115
+ "metadata": {}
1116
+ }
1117
+ ],
1118
+ "source": [
1119
+ "model_id = \"HuggingFaceTB/SmolVLM2-500M-Video-Instruct\"\n",
1120
+ "processor = AutoProcessor.from_pretrained(model_id)\n",
1121
+ "model = AutoModelForImageTextToText.from_pretrained(\n",
1122
+ " model_id,\n",
1123
+ " dtype=torch.bfloat16,\n",
1124
+ " device_map=\"auto\"\n",
1125
+ ").eval()\n"
1126
+ ]
1127
+ },
1128
+ {
1129
+ "cell_type": "code",
1130
+ "execution_count": null,
1131
+ "metadata": {
1132
+ "colab": {
1133
+ "base_uri": "https://localhost:8080/"
1134
+ },
1135
+ "id": "zb1iA30YF6wN",
1136
+ "outputId": "082db1e3-475f-4ee0-e5cc-1235266cfb39"
1137
+ },
1138
+ "outputs": [
1139
+ {
1140
+ "output_type": "stream",
1141
+ "name": "stderr",
1142
+ "text": [
1143
+ "You have used fast image processor with LANCZOS resample which not yet supported for torch.Tensor. BICUBIC resample will be used as an alternative. Please fall back to image processor if you want full consistency with the original model.\n"
1144
+ ]
1145
+ },
1146
+ {
1147
+ "output_type": "stream",
1148
+ "name": "stdout",
1149
+ "text": [
1150
+ "CAPTION:\n",
1151
+ " The video showcases a Minecraft character in a dark, stone-walled room, performing various actions such as jumping, running, and shooting, with the player's inventory visible in the bottom right corner.\n",
1152
+ "\n",
1153
+ "SUMMARY:\n",
1154
+ " The video shows a character in a room with a stone wall and a glowing blue block, followed by a character in a blue outfit with a red mask and a yellow sword, and then a character in a black outfit with a red mask and a yellow sword.\n",
1155
+ "\n",
1156
+ "QA:\n",
1157
+ " Preparing food.\n"
1158
+ ]
1159
+ }
1160
+ ],
1161
+ "source": [
1162
+ "\n",
1163
+ "def ask_video(video_path: str, prompt: str, num_frames: int = 8) -> str:\n",
1164
+ " messages = [{\n",
1165
+ " \"role\": \"user\",\n",
1166
+ " \"content\": [\n",
1167
+ " {\"type\": \"video\", \"path\": video_path},\n",
1168
+ " {\"type\": \"text\", \"text\": prompt},\n",
1169
+ " ],\n",
1170
+ " }]\n",
1171
+ " inputs = processor.apply_chat_template(\n",
1172
+ " messages,\n",
1173
+ " tokenize=True,\n",
1174
+ " add_generation_prompt=True,\n",
1175
+ " return_dict=True,\n",
1176
+ " return_tensors=\"pt\",\n",
1177
+ " do_sample_frames=True,\n",
1178
+ " num_frames=num_frames,\n",
1179
+ " ).to(model.device)\n",
1180
+ " if \"pixel_values_videos\" in inputs:\n",
1181
+ " inputs[\"pixel_values_videos\"] = inputs[\"pixel_values_videos\"].to(dtype)\n",
1182
+ " with torch.no_grad():\n",
1183
+ " out = model.generate(**inputs, max_new_tokens=128, do_sample=False)\n",
1184
+ "\n",
1185
+ " prompt_len = inputs[\"input_ids\"].shape[-1]\n",
1186
+ " return processor.batch_decode(\n",
1187
+ " out[:, prompt_len:], skip_special_tokens=True\n",
1188
+ " )[0].strip()\n",
1189
+ "\n",
1190
+ "\n",
1191
+ "# Captioning\n",
1192
+ "print(\"CAPTION:\\n\", ask_video(minecraft_mp4, \"Write a one-sentence caption for this video.\"))\n",
1193
+ "\n",
1194
+ "# Summarization\n",
1195
+ "print(\"\\nSUMMARY:\\n\", ask_video(minecraft_mp4, \"Summarize the video in 3 bullet points.\"))\n",
1196
+ "\n",
1197
+ "# Video QA\n",
1198
+ "print(\"\\nQA:\\n\", ask_video(spaghetti_mp4, \"What is the person doing? Answer briefly.\"))"
1199
+ ]
1200
+ },
1201
+ {
1202
+ "cell_type": "markdown",
1203
+ "metadata": {
1204
+ "id": "atoJoRd0G3zh"
1205
+ },
1206
+ "source": [
1207
+ "# 9.3.2 Retrieval Pipelines That Scale\n"
1208
+ ]
1209
+ },
1210
+ {
1211
+ "cell_type": "markdown",
1212
+ "metadata": {
1213
+ "id": "bNp8dxIIyqva"
1214
+ },
1215
+ "source": [
1216
+ "### Step 1: Segment videos\n",
1217
+ "We prepare a function to split videos in small segments"
1218
+ ]
1219
+ },
1220
+ {
1221
+ "cell_type": "code",
1222
+ "execution_count": null,
1223
+ "metadata": {
1224
+ "id": "oy09p744G46H"
1225
+ },
1226
+ "outputs": [],
1227
+ "source": [
1228
+ "def segment_video(\n",
1229
+ " video_path: str, out_dir: str, segment_seconds: int = 5\n",
1230
+ ") -> List[str]:\n",
1231
+ " \"\"\"\n",
1232
+ " Split a video into fixed-length MP4 segments using ffmpeg.\n",
1233
+ " Returns sorted list of segment file paths.\n",
1234
+ " \"\"\"\n",
1235
+ " out_dir_path = Path(out_dir).resolve()\n",
1236
+ " out_dir_path.mkdir(parents=True, exist_ok=True)\n",
1237
+ " pattern = str(out_dir_path / \"seg_%05d.mp4\")\n",
1238
+ "\n",
1239
+ " subprocess.run(\n",
1240
+ " [\n",
1241
+ " \"ffmpeg\", \"-y\",\n",
1242
+ " \"-i\", video_path,\n",
1243
+ " \"-c\", \"copy\", # stream copy — fast, no re-encoding\n",
1244
+ " \"-map\", \"0\",\n",
1245
+ " \"-f\", \"segment\",\n",
1246
+ " \"-segment_time\", str(segment_seconds),\n",
1247
+ " \"-reset_timestamps\", \"1\",\n",
1248
+ " pattern,\n",
1249
+ " ],\n",
1250
+ " check=True,\n",
1251
+ " stdout=subprocess.DEVNULL,\n",
1252
+ " stderr=subprocess.DEVNULL,\n",
1253
+ " )\n",
1254
+ " # Return absolute paths for the segments\n",
1255
+ " return sorted(str(p.resolve()) for p in out_dir_path.glob(\"seg_*.mp4\"))"
1256
+ ]
1257
+ },
1258
+ {
1259
+ "cell_type": "code",
1260
+ "execution_count": null,
1261
+ "metadata": {
1262
+ "colab": {
1263
+ "base_uri": "https://localhost:8080/",
1264
+ "height": 49,
1265
+ "referenced_widgets": [
1266
+ "39f6a6eb689f4262af439b375d5b2abb",
1267
+ "d0b891c5fae14455b41eb10ffdedc936",
1268
+ "a52a8aa9f3054101a9ba258d38d803e7",
1269
+ "9e5ba30d525845279fddde78d88c47f2",
1270
+ "9843fd65e959478294017a5c0acbdef4",
1271
+ "1e3779dea0464aec858d841e2ddb429d",
1272
+ "8ca41427f84c4d4395c14432eb92fc2f",
1273
+ "427252bbdc524c84a98f2353074136a5",
1274
+ "f1805253451342ce90a0d8afc25208af",
1275
+ "1c1fbace15a046de89bf42a4f0167028",
1276
+ "cfd79a9d5caf4bf4bef40810b7ee691b"
1277
+ ]
1278
+ },
1279
+ "id": "DxO03PaTy91Q",
1280
+ "outputId": "a74fb9db-c300-4166-d4c2-ec12efa9822e"
1281
+ },
1282
+ "outputs": [
1283
+ {
1284
+ "output_type": "display_data",
1285
+ "data": {
1286
+ "text/plain": [
1287
+ "Loading weights: 0%| | 0/625 [00:00<?, ?it/s]"
1288
+ ],
1289
+ "application/vnd.jupyter.widget-view+json": {
1290
+ "version_major": 2,
1291
+ "version_minor": 0,
1292
+ "model_id": "39f6a6eb689f4262af439b375d5b2abb"
1293
+ }
1294
+ },
1295
+ "metadata": {}
1296
+ }
1297
+ ],
1298
+ "source": [
1299
+ "# We get the Qwen3-VL Embedding model again and we prepare the functions to embed text/video\n",
1300
+ "script_path = hf_hub_download(\n",
1301
+ " repo_id=\"Qwen/Qwen3-VL-Embedding-2B\",\n",
1302
+ " filename=\"scripts/qwen3_vl_embedding.py\",\n",
1303
+ ")\n",
1304
+ "spec = importlib.util.spec_from_file_location(\"qwen3_vl_embedding\", script_path)\n",
1305
+ "mod = importlib.util.module_from_spec(spec)\n",
1306
+ "spec.loader.exec_module(mod)\n",
1307
+ "sys.modules['qwen3_vl_embedding'] = mod # Explicitly add the module to sys.modules\n",
1308
+ "Qwen3VLEmbedder = mod.Qwen3VLEmbedder\n",
1309
+ "embedder = Qwen3VLEmbedder(\n",
1310
+ " model_name_or_path=\"Qwen/Qwen3-VL-Embedding-2B\",\n",
1311
+ " torch_dtype=torch.float16\n",
1312
+ ")\n",
1313
+ "\n",
1314
+ "# Embedding helpers\n",
1315
+ "def embed_text(text: str) -> np.ndarray:\n",
1316
+ " \"\"\"Embed a text query. Returns (D,) numpy array, L2-normalized.\"\"\"\n",
1317
+ " emb = embedder.process([{\"text\": text}])\n",
1318
+ " return emb[0].detach().cpu().float().numpy()\n",
1319
+ "\n",
1320
+ "def embed_video_segment(path: str, fps: float = 1.0, max_frames: int = 32) -> np.ndarray:\n",
1321
+ " \"\"\"Embed a video segment. Returns (D,) numpy array, L2-normalized.\"\"\"\n",
1322
+ " emb = embedder.process([{\"video\": path, \"fps\": fps, \"max_frames\": max_frames}])\n",
1323
+ " return emb[0].detach().cpu().float().numpy()\n"
1324
+ ]
1325
+ },
1326
+ {
1327
+ "cell_type": "code",
1328
+ "execution_count": null,
1329
+ "metadata": {
1330
+ "colab": {
1331
+ "base_uri": "https://localhost:8080/"
1332
+ },
1333
+ "id": "iQu8FLq3z-eg",
1334
+ "outputId": "ab0448fd-e60f-46a6-f9b6-16e3d3837c05"
1335
+ },
1336
+ "outputs": [
1337
+ {
1338
+ "output_type": "stream",
1339
+ "name": "stdout",
1340
+ "text": [
1341
+ "Total segments: 11\n"
1342
+ ]
1343
+ }
1344
+ ],
1345
+ "source": [
1346
+ "\n",
1347
+ "#Segment, embed, and index our demo videos\n",
1348
+ "\n",
1349
+ "all_segments: List[str] = []\n",
1350
+ "segment_meta: List[Dict] = []\n",
1351
+ "\n",
1352
+ "for vid in [spaghetti_mp4, minecraft_mp4]:\n",
1353
+ " out_dir = Path(\"video_segments\") / Path(vid).stem\n",
1354
+ " segs = segment_video(vid, str(out_dir), segment_seconds=5)\n",
1355
+ " for seg in segs:\n",
1356
+ " all_segments.append(seg)\n",
1357
+ " segment_meta.append({\"source_video\": vid, \"segment_path\": seg})\n",
1358
+ "\n",
1359
+ "print(f\"Total segments: {len(all_segments)}\")\n",
1360
+ "\n"
1361
+ ]
1362
+ },
1363
+ {
1364
+ "cell_type": "code",
1365
+ "execution_count": null,
1366
+ "metadata": {
1367
+ "id": "cExp68Pt0ejE"
1368
+ },
1369
+ "outputs": [],
1370
+ "source": [
1371
+ "\n",
1372
+ "# Embed all segments (offline step — do this once)\n",
1373
+ "vectors = np.stack(\n",
1374
+ " [embed_video_segment(seg) for seg in all_segments], axis=0\n",
1375
+ ") # (N, D)\n"
1376
+ ]
1377
+ },
1378
+ {
1379
+ "cell_type": "code",
1380
+ "execution_count": null,
1381
+ "metadata": {
1382
+ "id": "4PtNc1CL0hJx"
1383
+ },
1384
+ "outputs": [],
1385
+ "source": [
1386
+ "\n",
1387
+ "# Build FAISS index. Since embeddings are L2-normalized,\n",
1388
+ "# inner product (IndexFlatIP) equals cosine similarity.\n",
1389
+ "index = faiss.IndexFlatIP(vectors.shape[1])\n",
1390
+ "index.add(vectors.astype(np.float32))\n"
1391
+ ]
1392
+ },
1393
+ {
1394
+ "cell_type": "code",
1395
+ "execution_count": null,
1396
+ "metadata": {
1397
+ "colab": {
1398
+ "base_uri": "https://localhost:8080/"
1399
+ },
1400
+ "id": "nWItL6yE0ixr",
1401
+ "outputId": "fb8a19b6-730a-4064-f5b1-fe4646179022"
1402
+ },
1403
+ "outputs": [
1404
+ {
1405
+ "output_type": "stream",
1406
+ "name": "stdout",
1407
+ "text": [
1408
+ "\n",
1409
+ "Query: someone eating pasta\n",
1410
+ " score=0.729 seg=/content/video_segments/eating_spaghetti/seg_00000.mp4\n",
1411
+ " score=0.507 seg=/content/video_segments/eating_spaghetti/seg_00001.mp4\n",
1412
+ " score=0.329 seg=/content/video_segments/09KmKSz4r_Y/seg_00003.mp4\n",
1413
+ "\n",
1414
+ "Query: a videogame\n",
1415
+ " score=0.600 seg=/content/video_segments/09KmKSz4r_Y/seg_00003.mp4\n",
1416
+ " score=0.570 seg=/content/video_segments/09KmKSz4r_Y/seg_00006.mp4\n",
1417
+ " score=0.562 seg=/content/video_segments/09KmKSz4r_Y/seg_00005.mp4\n"
1418
+ ]
1419
+ }
1420
+ ],
1421
+ "source": [
1422
+ "\n",
1423
+ "# Query function\n",
1424
+ "def search_segments(query: str, k: int = 5) -> List[Tuple[float, Dict]]:\n",
1425
+ " \"\"\"Retrieve top-k segments for a text query.\"\"\"\n",
1426
+ " q = embed_text(query)[None, :] # (1, D)\n",
1427
+ " scores, ids = index.search(q.astype(np.float32), k)\n",
1428
+ " return [\n",
1429
+ " (float(s), segment_meta[i])\n",
1430
+ " for s, i in zip(scores[0], ids[0])\n",
1431
+ " if i >= 0\n",
1432
+ " ]\n",
1433
+ "\n",
1434
+ "# Try it\n",
1435
+ "for q in [\"someone eating pasta\", \"a videogame\"]:\n",
1436
+ " print(f\"\\nQuery: {q}\")\n",
1437
+ " for score, meta in search_segments(q, k=3):\n",
1438
+ " print(f\" score={score:.3f} seg={meta['segment_path']}\")"
1439
+ ]
1440
+ },
1441
+ {
1442
+ "cell_type": "markdown",
1443
+ "metadata": {
1444
+ "id": "YPuk-vfbchX3"
1445
+ },
1446
+ "source": [
1447
+ "### Optional: ReRank"
1448
+ ]
1449
+ },
1450
+ {
1451
+ "cell_type": "code",
1452
+ "execution_count": null,
1453
+ "metadata": {
1454
+ "colab": {
1455
+ "base_uri": "https://localhost:8080/",
1456
+ "height": 465,
1457
+ "referenced_widgets": [
1458
+ "bc5ca56ae39a4824bb95c607026076da",
1459
+ "c03e2bddeda34398bb5e4ea7818549ff",
1460
+ "a3b75ff09bae469bba9c2e1e20e419fc",
1461
+ "b1137e4a767847698905b23be25f346a",
1462
+ "e6e274b1060e48fb944e2e39ab815aad",
1463
+ "fc0eed5efad54e99a9647b1a11b3243e",
1464
+ "eada1b3612014e86b24445d10afc263a",
1465
+ "6fb6b35c26e44b2b9116fbfdbd29381c",
1466
+ "d704143dc56c4a1bb8b38d64cf78df1f",
1467
+ "caf3438a5ce64a51bab97b72c9bb329c",
1468
+ "040ab494cad244dab4c5f727aba122bd",
1469
+ "817bef6866884bc8ab997aa4b2280661",
1470
+ "044e351b330348da97bf68f5582b316f",
1471
+ "1e9e638412b8432883e428f902265e8d",
1472
+ "e1be340af5e349dd862523133f8c9800",
1473
+ "964939558f194f828efe75d070aa1ca6",
1474
+ "f9f0bb0ddada4180b557c030745ec089",
1475
+ "f8b96bc6922042079b73899616ea08e3",
1476
+ "5e708a5c44ed4311a3db2cd0edd8bdf8",
1477
+ "6b462a9720af4331b9c30a2bffc3fa10",
1478
+ "e244b8451d71495eafc0b02d5c51f3c2",
1479
+ "b54517f658e54be48160c33744336b98",
1480
+ "40f6c04d250349b994bdfcfc0651a4e8",
1481
+ "01058dd6f37144199362fde0a2cd913c",
1482
+ "a9e8a9f4690e4db5abaf3847e677b12b",
1483
+ "e7c5f48a50a3496288c454ee6f91fb3b",
1484
+ "90903de228ba43f788938abab945eada",
1485
+ "c579ae966cfc407ebc441d99a9bbe66d",
1486
+ "5050b7f18c004ce6b7b64ccc2494bc6c",
1487
+ "59270d06591d4169afd71290d6a58dc6",
1488
+ "076fe8c214b9455c804451dd3ec4080e",
1489
+ "8e6929fb7a394363b91e53222089238c",
1490
+ "adbb2e6e8754401bbea23375d1e80dd9",
1491
+ "f7e61959e1f14ac0aed243ef50ae0e3c",
1492
+ "b59ccc27219443fe90ff733a4f875eca",
1493
+ "7577650b47714b10a9b84d5d22505cba",
1494
+ "67bc3ae93e034a60aca156141768c8be",
1495
+ "2d6c8a410a804d96a7be8e7751b3a5ac",
1496
+ "51f69db1640c4bca927690a7a78b39cf",
1497
+ "d179ea186d214bb3abf0e4f1fdc8a8d9",
1498
+ "0a1d7b91e1d747248c16d351e29f8f98",
1499
+ "653f4394eef447c9b8152ba0fe0f90b0",
1500
+ "fe3d548547834be1a5714d91cc236705",
1501
+ "dd778ded9fee4817bbf324a24a054bb0",
1502
+ "e8568139de7f4446b00b0806afc0e99a",
1503
+ "f6987cefb33f434593c3f194eb43aa23",
1504
+ "4d4b9756bafc42d4813ba13a331e40eb",
1505
+ "41a388b09a9f4473a393a883e0741ee4",
1506
+ "a4010d3d132848ae8a264756f794ea12",
1507
+ "76bfb788fdc84d9aa0d5ad4b0e412af0",
1508
+ "b6e028312dc149599a6c4bb2e2cf787b",
1509
+ "dbf32ff7227542a3831c85616e01d777",
1510
+ "ebc14ab3ec7d4aaab4def8f821329de0",
1511
+ "2e16b09298074eea8db303cc61b6be9c",
1512
+ "80b01d8e4c664914854576d3d2bf2420",
1513
+ "50903c8c7cd848a7b79a4bff1951c592",
1514
+ "1b83f7cd00b64a04ac20a90d05a629a2",
1515
+ "df2a75ad2f1848b7990e50ca21b52a8a",
1516
+ "257d328ef5994c2c9b5c51132d967845",
1517
+ "8d7894fd93af4327bfda96d0b07fb540",
1518
+ "6d09abcb63d9400e8345c7b54efbf60c",
1519
+ "642a54316d0f46b886179a2385716975",
1520
+ "07eb92a3a9ac4d26b0bff32f1563f2f5",
1521
+ "dd7fc3e99b6b4c13a8f6449fb21119e5",
1522
+ "edfb9e44859c48789df13802b054ef08",
1523
+ "fb701fe45bfb4efb8779ffd24bbf13e2",
1524
+ "7d61f693c2b244b882f248067d337c7d",
1525
+ "491ccfdde29a46ec86b6e55b852bb858",
1526
+ "c1a9822c0b7344ea984c77f7d95a9e5a",
1527
+ "e3ef30b1dc594658999b5de9e0b89c2f",
1528
+ "174866dfd1fa4c56b4aa055d52bd4255",
1529
+ "e742b7edba1246ca9c203a9a8d23cc90",
1530
+ "ad4e7a83fef74eaf92ee49bd072c5f64",
1531
+ "16820a26828545d2aab10f873ee41f41",
1532
+ "4e2637d6e902458d9d2fecba39633def",
1533
+ "18fc74aa20bf4723994be04bd8d6ad95",
1534
+ "82712102bb814809a183a177f83f3714",
1535
+ "ddf58b8debf145b0bc1f9966551b0d35",
1536
+ "0d9602402e514b5694faab0d583a1103",
1537
+ "7a1ad78a592b404386dcb7fd098c036c",
1538
+ "382dab58c01d40afbdc75dbee9b9f5d6",
1539
+ "205e14de3b1e49ef85e9331e7239ad50",
1540
+ "a9103cf1307a468bb15ac3aed3f937c8",
1541
+ "6497c9ee64c44e1faa9d26c9fdf9add6",
1542
+ "17368607eb2a4dd7a65cf35dde6275fe",
1543
+ "73da81c1ad87469fbf09960d738ccebe",
1544
+ "15719579d5d04f78aef74b6f7f0102e3",
1545
+ "ebe16cad608749d5a9959320ae614464",
1546
+ "01cad5bb781a4fb88ecf0ebd34be2090",
1547
+ "a7309066a2244ce2ad756d0a1634e2d2",
1548
+ "6d90024bce5c4d218e3e2e0df7bf9e73",
1549
+ "616f73bb531c43879f631eea22b32c8b",
1550
+ "f13b05ca20d94607ac2cc25e5444c9c5",
1551
+ "30d19bb8d84a4c37902ddae688416c2d",
1552
+ "d97aa9a0507e4b9c8cc33d794bf631b7",
1553
+ "9c4185e304a84927b68583ab666a8b2e",
1554
+ "8f2308bc07ba4933ad1409b14f1cf19e",
1555
+ "e93270fb208949d09471ead75d19da35",
1556
+ "cb44d9e393fc4c7597660e58271a096f",
1557
+ "0b9a125c486447ef8215c89c7e006b01",
1558
+ "cd5c094ce28442fbb946a920a5338a04",
1559
+ "29e12bad77e3491e804e90a2ea8db6ad",
1560
+ "3af51c4900d945738e3d790ee01e0c70",
1561
+ "444e328be51d4665aa5c5b954c952e98",
1562
+ "79fc4025f59c49ccb39558d980944d40",
1563
+ "24077c6c1ec84cffa259f4eaedcae53e",
1564
+ "458e409f95254834872131f21f2a95f4",
1565
+ "b1120a88ad5c41f3b5fed72e4dbbd2d6",
1566
+ "60073b3fe7364c77bef3edd0c01a9ff7",
1567
+ "7b897d5ef0f44f66a2d498c7d48c5c91",
1568
+ "483dde24d0a14a9684c83188ed0b26e6",
1569
+ "a17f173eecbe4563b22b15c703aea423",
1570
+ "82d331ee31d547bb86298722aaaaa189",
1571
+ "6a6a3d9088a344c6b1813fbbcf46326d",
1572
+ "d1d0328a004142479664d7a58f9e3d50",
1573
+ "89248263858b40d29baf681bb73f5df7",
1574
+ "579d4aaae94c4bc6866e63c3b620c23e",
1575
+ "833514a28e244f7484b2c9c4f05b155e",
1576
+ "ae8d03a03dd3473aa4fb22bb830a4b31",
1577
+ "7dddf56c3355415cb0e90c5ffc69326e",
1578
+ "538d9cc0f3e442a89906a834000f62de",
1579
+ "14c037b7cf8a42f492a4a48a8aa0c82e",
1580
+ "b56ea77a901e495cb5e937d390c78953",
1581
+ "87290d60ad424ca79efa838da61a76f3",
1582
+ "315e2e858aa5475d83e02c98df719540",
1583
+ "8e673a8527374f889da61e25c6fc6771",
1584
+ "34f6d51f814d4fa590ea49fbcd2d5a54",
1585
+ "aeea997163f84575a8060782c7c0fde6",
1586
+ "5dbbf8f5aca64eceb862ba27f4d63200",
1587
+ "d01dc85668de41d7bc0eb62d184e9334",
1588
+ "5d41bb25cb7740b2b3361fc50322ad39",
1589
+ "9411fa1807ef45b08b773aee689dde4f",
1590
+ "d9e2038e8f674e7783ba3a853abb4fd2",
1591
+ "c8fb44359ab64601976ce4e5d494a620",
1592
+ "ec63e39ef47e4b88a673a33445f78406",
1593
+ "70d7044af4684647a14b5de7b6bc80c1",
1594
+ "72b9fbaa2bfc47e9bfa02768a3294314",
1595
+ "1904248ba7b2493abf37e2681d02670d",
1596
+ "9024111110934c84b0e016bf5cce3562",
1597
+ "af94ae0e623345babd2887da38c46501",
1598
+ "b389a7266fdd485ba2158d614047e03f",
1599
+ "ea250575648a465b83c2c98bd9bca1e1",
1600
+ "ea1a341091404c87b6a4f64deea540a7",
1601
+ "36198a90cd2e42858748265f5d63d095",
1602
+ "3011485e755346c29e81b97405f6ef31",
1603
+ "e11643359d1e4e18803d5fc802671b7b",
1604
+ "f5384bfed6b146cab84773c8beba8a2b",
1605
+ "cd2ecd7cc8c141c6a2b9916b62760e30",
1606
+ "0f8a8605f247476abaa1d9a569c73afd",
1607
+ "45d2caf136ff424db1bc2481a374bafb",
1608
+ "538e2a41ecd740dfb5c0fe91b7808955",
1609
+ "3eed3dcc7fc143f28d0cde5770790026",
1610
+ "9be02c2fb64c48a7b5e19a2490ece474",
1611
+ "fdd8306fa84f4e18a481e84e40a9d78a"
1612
+ ]
1613
+ },
1614
+ "id": "kCd_u_B9cmZt",
1615
+ "outputId": "ff38088f-c4e6-4b91-a77c-f46d597705d3"
1616
+ },
1617
+ "outputs": [
1618
+ {
1619
+ "output_type": "display_data",
1620
+ "data": {
1621
+ "text/plain": [
1622
+ "qwen3_vl_reranker.py: 0.00B [00:00, ?B/s]"
1623
+ ],
1624
+ "application/vnd.jupyter.widget-view+json": {
1625
+ "version_major": 2,
1626
+ "version_minor": 0,
1627
+ "model_id": "bc5ca56ae39a4824bb95c607026076da"
1628
+ }
1629
+ },
1630
+ "metadata": {}
1631
+ },
1632
+ {
1633
+ "output_type": "display_data",
1634
+ "data": {
1635
+ "text/plain": [
1636
+ "config.json: 0.00B [00:00, ?B/s]"
1637
+ ],
1638
+ "application/vnd.jupyter.widget-view+json": {
1639
+ "version_major": 2,
1640
+ "version_minor": 0,
1641
+ "model_id": "817bef6866884bc8ab997aa4b2280661"
1642
+ }
1643
+ },
1644
+ "metadata": {}
1645
+ },
1646
+ {
1647
+ "output_type": "display_data",
1648
+ "data": {
1649
+ "text/plain": [
1650
+ "model.safetensors: 0%| | 0.00/4.26G [00:00<?, ?B/s]"
1651
+ ],
1652
+ "application/vnd.jupyter.widget-view+json": {
1653
+ "version_major": 2,
1654
+ "version_minor": 0,
1655
+ "model_id": "40f6c04d250349b994bdfcfc0651a4e8"
1656
+ }
1657
+ },
1658
+ "metadata": {}
1659
+ },
1660
+ {
1661
+ "output_type": "display_data",
1662
+ "data": {
1663
+ "text/plain": [
1664
+ "Loading weights: 0%| | 0/625 [00:00<?, ?it/s]"
1665
+ ],
1666
+ "application/vnd.jupyter.widget-view+json": {
1667
+ "version_major": 2,
1668
+ "version_minor": 0,
1669
+ "model_id": "f7e61959e1f14ac0aed243ef50ae0e3c"
1670
+ }
1671
+ },
1672
+ "metadata": {}
1673
+ },
1674
+ {
1675
+ "output_type": "display_data",
1676
+ "data": {
1677
+ "text/plain": [
1678
+ "generation_config.json: 0%| | 0.00/213 [00:00<?, ?B/s]"
1679
+ ],
1680
+ "application/vnd.jupyter.widget-view+json": {
1681
+ "version_major": 2,
1682
+ "version_minor": 0,
1683
+ "model_id": "e8568139de7f4446b00b0806afc0e99a"
1684
+ }
1685
+ },
1686
+ "metadata": {}
1687
+ },
1688
+ {
1689
+ "output_type": "display_data",
1690
+ "data": {
1691
+ "text/plain": [
1692
+ "preprocessor_config.json: 0%| | 0.00/628 [00:00<?, ?B/s]"
1693
+ ],
1694
+ "application/vnd.jupyter.widget-view+json": {
1695
+ "version_major": 2,
1696
+ "version_minor": 0,
1697
+ "model_id": "50903c8c7cd848a7b79a4bff1951c592"
1698
+ }
1699
+ },
1700
+ "metadata": {}
1701
+ },
1702
+ {
1703
+ "output_type": "display_data",
1704
+ "data": {
1705
+ "text/plain": [
1706
+ "chat_template.jinja: 0.00B [00:00, ?B/s]"
1707
+ ],
1708
+ "application/vnd.jupyter.widget-view+json": {
1709
+ "version_major": 2,
1710
+ "version_minor": 0,
1711
+ "model_id": "7d61f693c2b244b882f248067d337c7d"
1712
+ }
1713
+ },
1714
+ "metadata": {}
1715
+ },
1716
+ {
1717
+ "output_type": "display_data",
1718
+ "data": {
1719
+ "text/plain": [
1720
+ "tokenizer_config.json: 0.00B [00:00, ?B/s]"
1721
+ ],
1722
+ "application/vnd.jupyter.widget-view+json": {
1723
+ "version_major": 2,
1724
+ "version_minor": 0,
1725
+ "model_id": "ddf58b8debf145b0bc1f9966551b0d35"
1726
+ }
1727
+ },
1728
+ "metadata": {}
1729
+ },
1730
+ {
1731
+ "output_type": "display_data",
1732
+ "data": {
1733
+ "text/plain": [
1734
+ "vocab.json: 0.00B [00:00, ?B/s]"
1735
+ ],
1736
+ "application/vnd.jupyter.widget-view+json": {
1737
+ "version_major": 2,
1738
+ "version_minor": 0,
1739
+ "model_id": "01cad5bb781a4fb88ecf0ebd34be2090"
1740
+ }
1741
+ },
1742
+ "metadata": {}
1743
+ },
1744
+ {
1745
+ "output_type": "display_data",
1746
+ "data": {
1747
+ "text/plain": [
1748
+ "merges.txt: 0.00B [00:00, ?B/s]"
1749
+ ],
1750
+ "application/vnd.jupyter.widget-view+json": {
1751
+ "version_major": 2,
1752
+ "version_minor": 0,
1753
+ "model_id": "0b9a125c486447ef8215c89c7e006b01"
1754
+ }
1755
+ },
1756
+ "metadata": {}
1757
+ },
1758
+ {
1759
+ "output_type": "display_data",
1760
+ "data": {
1761
+ "text/plain": [
1762
+ "tokenizer.json: 0%| | 0.00/11.4M [00:00<?, ?B/s]"
1763
+ ],
1764
+ "application/vnd.jupyter.widget-view+json": {
1765
+ "version_major": 2,
1766
+ "version_minor": 0,
1767
+ "model_id": "483dde24d0a14a9684c83188ed0b26e6"
1768
+ }
1769
+ },
1770
+ "metadata": {}
1771
+ },
1772
+ {
1773
+ "output_type": "display_data",
1774
+ "data": {
1775
+ "text/plain": [
1776
+ "added_tokens.json: 0%| | 0.00/707 [00:00<?, ?B/s]"
1777
+ ],
1778
+ "application/vnd.jupyter.widget-view+json": {
1779
+ "version_major": 2,
1780
+ "version_minor": 0,
1781
+ "model_id": "14c037b7cf8a42f492a4a48a8aa0c82e"
1782
+ }
1783
+ },
1784
+ "metadata": {}
1785
+ },
1786
+ {
1787
+ "output_type": "display_data",
1788
+ "data": {
1789
+ "text/plain": [
1790
+ "special_tokens_map.json: 0%| | 0.00/613 [00:00<?, ?B/s]"
1791
+ ],
1792
+ "application/vnd.jupyter.widget-view+json": {
1793
+ "version_major": 2,
1794
+ "version_minor": 0,
1795
+ "model_id": "d9e2038e8f674e7783ba3a853abb4fd2"
1796
+ }
1797
+ },
1798
+ "metadata": {}
1799
+ },
1800
+ {
1801
+ "output_type": "display_data",
1802
+ "data": {
1803
+ "text/plain": [
1804
+ "video_preprocessor_config.json: 0%| | 0.00/817 [00:00<?, ?B/s]"
1805
+ ],
1806
+ "application/vnd.jupyter.widget-view+json": {
1807
+ "version_major": 2,
1808
+ "version_minor": 0,
1809
+ "model_id": "36198a90cd2e42858748265f5d63d095"
1810
+ }
1811
+ },
1812
+ "metadata": {}
1813
+ }
1814
+ ],
1815
+ "source": [
1816
+ "# Download and import the reranker helper (same pattern as the embedder)\n",
1817
+ "rerank_script = hf_hub_download(\n",
1818
+ " repo_id=\"Qwen/Qwen3-VL-Reranker-2B\",\n",
1819
+ " filename=\"scripts/qwen3_vl_reranker.py\",\n",
1820
+ ")\n",
1821
+ "spec = importlib.util.spec_from_file_location(\"qwen3_vl_reranker\", rerank_script)\n",
1822
+ "rerank_mod = importlib.util.module_from_spec(spec)\n",
1823
+ "spec.loader.exec_module(rerank_mod)\n",
1824
+ "\n",
1825
+ "reranker = rerank_mod.Qwen3VLReranker(\n",
1826
+ " model_name_or_path=\"Qwen/Qwen3-VL-Reranker-2B\",\n",
1827
+ ")\n",
1828
+ "\n"
1829
+ ]
1830
+ },
1831
+ {
1832
+ "cell_type": "code",
1833
+ "execution_count": null,
1834
+ "metadata": {
1835
+ "colab": {
1836
+ "base_uri": "https://localhost:8080/"
1837
+ },
1838
+ "id": "UFRHbB4PcsLz",
1839
+ "outputId": "a63950aa-b841-4472-9944-c8dbda9a50f8"
1840
+ },
1841
+ "outputs": [
1842
+ {
1843
+ "output_type": "stream",
1844
+ "name": "stderr",
1845
+ "text": [
1846
+ "/usr/local/lib/python3.12/dist-packages/transformers/tokenization_utils_base.py:2299: UserWarning: `max_length` is ignored when `padding`=`True` and there is no truncation strategy. To pad to max length, use `padding='max_length'`.\n",
1847
+ " warnings.warn(\n"
1848
+ ]
1849
+ },
1850
+ {
1851
+ "output_type": "stream",
1852
+ "name": "stdout",
1853
+ "text": [
1854
+ "Query: someone eating pasta\n",
1855
+ "Top reranked segments:\n",
1856
+ " rerank_score=0.645 seg=/content/video_segments/eating_spaghetti/seg_00000.mp4\n",
1857
+ " rerank_score=0.451 seg=/content/video_segments/eating_spaghetti/seg_00001.mp4\n",
1858
+ " rerank_score=0.305 seg=/content/video_segments/09KmKSz4r_Y/seg_00005.mp4\n",
1859
+ " rerank_score=0.299 seg=/content/video_segments/09KmKSz4r_Y/seg_00003.mp4\n",
1860
+ " rerank_score=0.277 seg=/content/video_segments/09KmKSz4r_Y/seg_00007.mp4\n"
1861
+ ]
1862
+ }
1863
+ ],
1864
+ "source": [
1865
+ "\n",
1866
+ "def rerank_segments(\n",
1867
+ " query: str, candidates: List[Dict], fps: float = 1.0, max_frames: int = 32\n",
1868
+ ") -> List[Tuple[float, Dict]]:\n",
1869
+ " \"\"\"Re-score retrieved segments with a cross-encoder for higher precision.\"\"\"\n",
1870
+ " payload = {\n",
1871
+ " \"query\": {\"text\": query},\n",
1872
+ " \"documents\": [{\"video\": c[\"segment_path\"]} for c in candidates],\n",
1873
+ " \"fps\": fps,\n",
1874
+ " \"max_frames\": max_frames,\n",
1875
+ " }\n",
1876
+ " scores = reranker.process(payload) # list[float], aligned with candidates\n",
1877
+ " return sorted(zip(scores, candidates), key=lambda x: x[0], reverse=True)\n",
1878
+ "\n",
1879
+ "# Two-stage retrieval\n",
1880
+ "query = \"someone eating pasta\"\n",
1881
+ "\n",
1882
+ "# Stage 1: fast approximate retrieval (embedding + FAISS)\n",
1883
+ "stage1 = search_segments(query, k=10)\n",
1884
+ "candidates = [meta for _, meta in stage1]\n",
1885
+ "\n",
1886
+ "# Stage 2: precise reranking (cross-encoder)\n",
1887
+ "ranked = rerank_segments(query, candidates)\n",
1888
+ "\n",
1889
+ "print(f\"Query: {query}\")\n",
1890
+ "print(\"Top reranked segments:\")\n",
1891
+ "for score, meta in ranked[:5]:\n",
1892
+ " print(f\" rerank_score={score:.3f} seg={meta['segment_path']}\")"
1893
+ ]
1894
+ },
1895
+ {
1896
+ "cell_type": "markdown",
1897
+ "metadata": {
1898
+ "id": "cds6i2Dzc7Ea"
1899
+ },
1900
+ "source": [
1901
+ "# 9.3.3 Video-RAG: Retrieval-Augmented Video QA"
1902
+ ]
1903
+ },
1904
+ {
1905
+ "cell_type": "code",
1906
+ "execution_count": null,
1907
+ "metadata": {
1908
+ "colab": {
1909
+ "base_uri": "https://localhost:8080/",
1910
+ "height": 49,
1911
+ "referenced_widgets": [
1912
+ "131d930966834363ac98969ac37e0ce4",
1913
+ "424e1b4da84e4eb9905427e81bc62cfd",
1914
+ "9edfd817bee648968622406b142d65be",
1915
+ "9c633ab349b44720825ae8b0ec20dfdb",
1916
+ "4549b38dfbf047d5859135c126abb90f",
1917
+ "c1593bb526d14e288837711f6fffb9de",
1918
+ "0236662167ca4dc8b815d935e8ec614a",
1919
+ "850736fd37cf44f3951340948bf92ffc",
1920
+ "0ba0bdad221e45c39436778160613561",
1921
+ "c7d473a3920246ea93a88a30226945b5",
1922
+ "f1b10ecef056436193a7beeda6d856a9"
1923
+ ]
1924
+ },
1925
+ "id": "dRLQDIBadCWh",
1926
+ "outputId": "e718fd34-86a7-4436-bbfc-c3cc968a3987"
1927
+ },
1928
+ "outputs": [
1929
+ {
1930
+ "output_type": "display_data",
1931
+ "data": {
1932
+ "text/plain": [
1933
+ "Loading weights: 0%| | 0/489 [00:00<?, ?it/s]"
1934
+ ],
1935
+ "application/vnd.jupyter.widget-view+json": {
1936
+ "version_major": 2,
1937
+ "version_minor": 0,
1938
+ "model_id": "131d930966834363ac98969ac37e0ce4"
1939
+ }
1940
+ },
1941
+ "metadata": {}
1942
+ }
1943
+ ],
1944
+ "source": [
1945
+ "# We get again our tiny and powerful SmolVLM2\n",
1946
+ "model_id = \"HuggingFaceTB/SmolVLM2-500M-Video-Instruct\"\n",
1947
+ "rag_processor = AutoProcessor.from_pretrained(model_id)\n",
1948
+ "rag_model = AutoModelForImageTextToText.from_pretrained(\n",
1949
+ " model_id,\n",
1950
+ " dtype=torch.bfloat16,\n",
1951
+ " device_map=\"auto\"\n",
1952
+ ").eval()\n",
1953
+ "\n",
1954
+ "def answer_with_segments(\n",
1955
+ " segment_paths: List[str],\n",
1956
+ " question: str,\n",
1957
+ " num_frames: int = 2, # Reduced num_frames further to ensure consistency\n",
1958
+ " max_new_tokens: int = 128,\n",
1959
+ ") -> str:\n",
1960
+ " \"\"\"\n",
1961
+ " Feed multiple retrieved video segments plus a question to SmolVLM2.\n",
1962
+ " Each segment becomes a separate {\"type\": \"video\"} entry in the\n",
1963
+ " chat message, so the model sees all of them as context.\n",
1964
+ " \"\"\"\n",
1965
+ " content = [{\"type\": \"video\", \"path\": p} for p in segment_paths]\n",
1966
+ " content.append({\"type\": \"text\", \"text\": question})\n",
1967
+ "\n",
1968
+ " messages = [{\"role\": \"user\", \"content\": content}]\n",
1969
+ "\n",
1970
+ " inputs = rag_processor.apply_chat_template(\n",
1971
+ " messages,\n",
1972
+ " tokenize=True,\n",
1973
+ " add_generation_prompt=True,\n",
1974
+ " return_dict=True,\n",
1975
+ " return_tensors=\"pt\",\n",
1976
+ " do_sample_frames=True,\n",
1977
+ " num_frames=num_frames,\n",
1978
+ " ).to(rag_model.device)\n",
1979
+ "\n",
1980
+ " if \"pixel_values_videos\" in inputs and torch.is_floating_point(\n",
1981
+ " inputs[\"pixel_values_videos\"]\n",
1982
+ " ):\n",
1983
+ " inputs[\"pixel_values_videos\"] = inputs[\"pixel_values_videos\"].to(dtype)\n",
1984
+ "\n",
1985
+ " with torch.no_grad():\n",
1986
+ " out = rag_model.generate(\n",
1987
+ " **inputs, do_sample=False, max_new_tokens=max_new_tokens\n",
1988
+ " )\n",
1989
+ " prompt_len = inputs[\"input_ids\"].shape[-1]\n",
1990
+ " return rag_processor.batch_decode(\n",
1991
+ " out[:, prompt_len:], skip_special_tokens=True\n",
1992
+ " )[0].strip()"
1993
+ ]
1994
+ },
1995
+ {
1996
+ "cell_type": "code",
1997
+ "execution_count": null,
1998
+ "metadata": {
1999
+ "colab": {
2000
+ "base_uri": "https://localhost:8080/",
2001
+ "height": 214
2002
+ },
2003
+ "id": "sso7OyaBnTe9",
2004
+ "outputId": "2f13a4f9-99e0-42f5-f9c8-1abfaf762184"
2005
+ },
2006
+ "outputs": [
2007
+ {
2008
+ "output_type": "stream",
2009
+ "name": "stdout",
2010
+ "text": [
2011
+ "Question: Which food do you see in the video?\n",
2012
+ "\n",
2013
+ "Retrieved 5 segments:\n",
2014
+ " score=0.516 /content/video_segments/eating_spaghetti/seg_00001.mp4\n",
2015
+ " score=0.477 /content/video_segments/eating_spaghetti/seg_00000.mp4\n",
2016
+ " score=0.399 /content/video_segments/09KmKSz4r_Y/seg_00003.mp4\n",
2017
+ " score=0.391 /content/video_segments/09KmKSz4r_Y/seg_00006.mp4\n",
2018
+ " score=0.386 /content/video_segments/09KmKSz4r_Y/seg_00007.mp4\n",
2019
+ "\n",
2020
+ "Answer: spaghetti\n"
2021
+ ]
2022
+ },
2023
+ {
2024
+ "output_type": "execute_result",
2025
+ "data": {
2026
+ "text/plain": [
2027
+ "'spaghetti'"
2028
+ ],
2029
+ "application/vnd.google.colaboratory.intrinsic+json": {
2030
+ "type": "string"
2031
+ }
2032
+ },
2033
+ "metadata": {},
2034
+ "execution_count": 18
2035
+ }
2036
+ ],
2037
+ "source": [
2038
+ "# Here is the pipeline - first retrieve and then asnwer\n",
2039
+ "\n",
2040
+ "def video_rag(question: str, k: int = 5) -> str:\n",
2041
+ " \"\"\"\n",
2042
+ " End-to-end Video-RAG: retrieve relevant segments, then generate\n",
2043
+ " a grounded answer using only those segments as context.\n",
2044
+ " \"\"\"\n",
2045
+ " # Step 1: Retrieve (fast — embedding + FAISS)\n",
2046
+ " retrieved = search_segments(question, k=k)\n",
2047
+ " segment_paths = [meta[\"segment_path\"] for _, meta in retrieved]\n",
2048
+ "\n",
2049
+ " # Step 2: Generate (expensive — but only over k segments, not the whole library)\n",
2050
+ " prompt = (\n",
2051
+ " \"Answer the question using ONLY the provided video clips. \"\n",
2052
+ " \"If the clips do not contain enough information, say so.\\n\\n\"\n",
2053
+ " f\"Question: {question}\"\n",
2054
+ " )\n",
2055
+ " answer = answer_with_segments(segment_paths, prompt)\n",
2056
+ "\n",
2057
+ " print(f\"Question: {question}\")\n",
2058
+ " print(f\"\\nRetrieved {len(segment_paths)} segments:\")\n",
2059
+ " for score, meta in retrieved:\n",
2060
+ " print(f\" score={score:.3f} {meta['segment_path']}\")\n",
2061
+ " print(f\"\\nAnswer: {answer}\")\n",
2062
+ " return answer\n",
2063
+ "\n",
2064
+ "video_rag(\"Which food do you see in the video?\", k=5)\n"
2065
+ ]
2066
+ },
2067
+ {
2068
+ "cell_type": "markdown",
2069
+ "metadata": {
2070
+ "id": "dyx_UmhJpNhD"
2071
+ },
2072
+ "source": [
2073
+ "## 9.3.4 Fine-Tuning a Video Language Model for Your Domain\n"
2074
+ ]
2075
+ },
2076
+ {
2077
+ "cell_type": "code",
2078
+ "execution_count": null,
2079
+ "metadata": {
2080
+ "colab": {
2081
+ "base_uri": "https://localhost:8080/",
2082
+ "height": 177,
2083
+ "referenced_widgets": [
2084
+ "44f65ec249ed41f5a32e1540982a45aa",
2085
+ "1fc11185649448269433f703a96a2d2c",
2086
+ "0e32e2356a234aecb99e8fe8955fc433",
2087
+ "497e3568073249d3b4925656d6212e52",
2088
+ "596db5e6aad24a8698aee7e787b572d3",
2089
+ "82d6a0fbd7e747cdba2597549fe90525",
2090
+ "69cc5862198c4c7d9a568cbf909ea9e4",
2091
+ "f95b0d2eee6d4342b8ad356617e222c8",
2092
+ "32c4534d3e5c47639f3597b5442cdb0d",
2093
+ "e22862d088f746ea9cc548595eb94b72",
2094
+ "4969fd579bf5466991c33a953c110a19",
2095
+ "22016ebd5c774b71b31d3a2e5678b54d",
2096
+ "db5797ccb0644af29abd88840681430a",
2097
+ "f64c1cdf1ca440b3a9026035c43132bf",
2098
+ "85496f2f2dab4baea475bf1932c0e42a",
2099
+ "2cc10c5e43b24068bed9b9b2427f505d",
2100
+ "f5a346e7c0eb4b73aef157eb5af4d9ff",
2101
+ "1914ea4e030f49398f82638455d055bb",
2102
+ "795271815d3f4310910ea2907506b968",
2103
+ "f50b9a888dde42929a125c7a707c9d4b",
2104
+ "bdf21b8bdefe494b9ce26b0f392ae235",
2105
+ "5d4054325922409a8504277eb20850ba",
2106
+ "ba6b1a10b1964cbab94923a2d7324777",
2107
+ "75fc75aac65743fc906a94752f65ecd2",
2108
+ "57434838af5f4b239f3d0fe82c3f6a1d",
2109
+ "d328cd1ae21342d19952c004f747e317",
2110
+ "c9ffac940ace408f999b9673b9c73ed1",
2111
+ "2f9972a275484804af4b13ac82430acd",
2112
+ "767422a469fb47c0b11d518d6a0bb015",
2113
+ "a8bb4e81e2214ae18d138281d7e00276",
2114
+ "37c6512e07a24462a1906bddfeaa2aa0",
2115
+ "bec954fdffed41359683aef59d84d5b7",
2116
+ "6d3ec6efdc6a4784a3f4b163207526a4",
2117
+ "9fee077c9f0c41f88941c621f295466b",
2118
+ "b3bfacc853f34335bc2735f124e8e9cb",
2119
+ "ebbf934dd5734cf7a9aab9cd40c1f11b",
2120
+ "ee35aed827754b30abfb018a2fb34826",
2121
+ "51d09426fc2f454abc4245ea88d4ba14",
2122
+ "bdd09a32c45b41e2a97c89c503bd4075",
2123
+ "492aa74145614bca80585f95fa687c9f",
2124
+ "67cb8d47b5f046e79dbf697f025ef10a",
2125
+ "9b832dc299bc4a0484382789745de9c3",
2126
+ "2f43b2173f3e4f0a924ef40279f3c59a",
2127
+ "eb881852888d45ab996461591f87b098",
2128
+ "a069126bb2104ef7bd6b87302f55b265",
2129
+ "495a6938fc3d46e899c16b498684b7cc",
2130
+ "e3762aed113b4653a55e2b63d248c6be",
2131
+ "00504b6655c34e3b9b540a80d8928ac8",
2132
+ "f1bba53cb0e34444a8c77b233c296204",
2133
+ "03390e62a447431d9d9d0100df026d50",
2134
+ "735f1cea9a40430f8b838155073717af",
2135
+ "606053abbd1a412fb420498937d3c33b",
2136
+ "15f1c644b2fc41bbb09fa971215fb01d",
2137
+ "53836ca3bd4a495f9754031f60999440",
2138
+ "e6710a5b919540918f84392e04a54114"
2139
+ ]
2140
+ },
2141
+ "id": "JpNm216qqmkH",
2142
+ "outputId": "5bd6e9e7-44cb-4419-ebfc-945deb35c1b6"
2143
+ },
2144
+ "outputs": [
2145
+ {
2146
+ "output_type": "display_data",
2147
+ "data": {
2148
+ "text/plain": [
2149
+ "README.md: 0.00B [00:00, ?B/s]"
2150
+ ],
2151
+ "application/vnd.jupyter.widget-view+json": {
2152
+ "version_major": 2,
2153
+ "version_minor": 0,
2154
+ "model_id": "44f65ec249ed41f5a32e1540982a45aa"
2155
+ }
2156
+ },
2157
+ "metadata": {}
2158
+ },
2159
+ {
2160
+ "output_type": "display_data",
2161
+ "data": {
2162
+ "text/plain": [
2163
+ "real/test-00000-of-00001.parquet: 0%| | 0.00/35.8k [00:00<?, ?B/s]"
2164
+ ],
2165
+ "application/vnd.jupyter.widget-view+json": {
2166
+ "version_major": 2,
2167
+ "version_minor": 0,
2168
+ "model_id": "22016ebd5c774b71b31d3a2e5678b54d"
2169
+ }
2170
+ },
2171
+ "metadata": {}
2172
+ },
2173
+ {
2174
+ "output_type": "display_data",
2175
+ "data": {
2176
+ "text/plain": [
2177
+ "real/train-00000-of-00001.parquet: 0%| | 0.00/1.23M [00:00<?, ?B/s]"
2178
+ ],
2179
+ "application/vnd.jupyter.widget-view+json": {
2180
+ "version_major": 2,
2181
+ "version_minor": 0,
2182
+ "model_id": "ba6b1a10b1964cbab94923a2d7324777"
2183
+ }
2184
+ },
2185
+ "metadata": {}
2186
+ },
2187
+ {
2188
+ "output_type": "display_data",
2189
+ "data": {
2190
+ "text/plain": [
2191
+ "Generating test split: 0%| | 0/80 [00:00<?, ? examples/s]"
2192
+ ],
2193
+ "application/vnd.jupyter.widget-view+json": {
2194
+ "version_major": 2,
2195
+ "version_minor": 0,
2196
+ "model_id": "9fee077c9f0c41f88941c621f295466b"
2197
+ }
2198
+ },
2199
+ "metadata": {}
2200
+ },
2201
+ {
2202
+ "output_type": "display_data",
2203
+ "data": {
2204
+ "text/plain": [
2205
+ "Generating train split: 0%| | 0/4000 [00:00<?, ? examples/s]"
2206
+ ],
2207
+ "application/vnd.jupyter.widget-view+json": {
2208
+ "version_major": 2,
2209
+ "version_minor": 0,
2210
+ "model_id": "a069126bb2104ef7bd6b87302f55b265"
2211
+ }
2212
+ },
2213
+ "metadata": {}
2214
+ }
2215
+ ],
2216
+ "source": [
2217
+ "# We load a dataset\n",
2218
+ "ds = load_dataset(\"TIGER-Lab/VideoFeedback\", \"real\")\n",
2219
+ "split_ds = ds[\"train\"].train_test_split(test_size=0.5)\n",
2220
+ "train_ds = split_ds[\"train\"]\n",
2221
+ "del split_ds, ds\n"
2222
+ ]
2223
+ },
2224
+ {
2225
+ "cell_type": "code",
2226
+ "execution_count": null,
2227
+ "metadata": {
2228
+ "colab": {
2229
+ "base_uri": "https://localhost:8080/"
2230
+ },
2231
+ "id": "DY6bcu-wXo1U",
2232
+ "outputId": "ff1617a8-d929-46d1-f608-cb637268f51c"
2233
+ },
2234
+ "outputs": [
2235
+ {
2236
+ "output_type": "stream",
2237
+ "name": "stdout",
2238
+ "text": [
2239
+ "prompt: There is a bottle of apple cider vinegar sitting on a wooden surface., video: https://huggingface.co/datasets/hexuan21/VideoFeedback-videos-mp4/resolve/main/p/p106007.mp4\n"
2240
+ ]
2241
+ }
2242
+ ],
2243
+ "source": [
2244
+ "# Take a sneak peek.\n",
2245
+ "\n",
2246
+ "print(f\"prompt: {train_ds[0]['text prompt']}, video: {train_ds[0]['video link']}\")"
2247
+ ]
2248
+ },
2249
+ {
2250
+ "cell_type": "code",
2251
+ "execution_count": null,
2252
+ "metadata": {
2253
+ "colab": {
2254
+ "base_uri": "https://localhost:8080/",
2255
+ "height": 49,
2256
+ "referenced_widgets": [
2257
+ "c9fb9850414b4bf0b355f16ca76e5fd2",
2258
+ "c3a6d15af04b4c208db0ddfa394ddf6f",
2259
+ "e59ef7626dcb4f55a65605277a8ddade",
2260
+ "10677249ce6e43d6b2140b309f4a2df3",
2261
+ "33e1d2621916408d80da242293ad3da6",
2262
+ "c54199dba1ba4c43ae7fb1e689704991",
2263
+ "e9399f58034b40e6841c45fda6df407b",
2264
+ "36c5c964ee304c0986edd2eb4ee41a97",
2265
+ "b9272ebe1cee405d92c82d4939348175",
2266
+ "4eac43bbd75a496f9791659bc0f3984f",
2267
+ "c70af14481a94bf69c06855cd82daf3e"
2268
+ ]
2269
+ },
2270
+ "id": "WiEjN_7UYD1W",
2271
+ "outputId": "03c74865-ae26-4c25-a5fb-6f764541e052"
2272
+ },
2273
+ "outputs": [
2274
+ {
2275
+ "output_type": "display_data",
2276
+ "data": {
2277
+ "text/plain": [
2278
+ "Loading weights: 0%| | 0/489 [00:00<?, ?it/s]"
2279
+ ],
2280
+ "application/vnd.jupyter.widget-view+json": {
2281
+ "version_major": 2,
2282
+ "version_minor": 0,
2283
+ "model_id": "c9fb9850414b4bf0b355f16ca76e5fd2"
2284
+ }
2285
+ },
2286
+ "metadata": {}
2287
+ }
2288
+ ],
2289
+ "source": [
2290
+ "# We will fine-tune SmolVLM2\n",
2291
+ "\n",
2292
+ "model_id = \"HuggingFaceTB/SmolVLM2-500M-Video-Instruct\"\n",
2293
+ "your_model_folder = \"smolvlm2-qa-qlora\"\n",
2294
+ "tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)\n",
2295
+ "\n",
2296
+ "# Define the quantization configuration for 4-bit loading\n",
2297
+ "quantization_config = BitsAndBytesConfig(\n",
2298
+ " load_in_4bit=True,\n",
2299
+ " bnb_4bit_quant_type=\"nf4\",\n",
2300
+ " bnb_4bit_use_double_quant=True,\n",
2301
+ " bnb_4bit_compute_dtype=torch.bfloat16,\n",
2302
+ ")\n",
2303
+ "\n",
2304
+ "model = AutoModelForImageTextToText.from_pretrained(\n",
2305
+ " model_id,\n",
2306
+ " quantization_config=quantization_config, # Use quantization_config instead of load_in_4bit\n",
2307
+ " device_map=\"auto\"\n",
2308
+ ")\n",
2309
+ "\n",
2310
+ "model = prepare_model_for_kbit_training(model)\n",
2311
+ "cfg = LoraConfig(\n",
2312
+ " r=16, lora_alpha=32, target_modules=[\"q_proj\",\"k_proj\",\"v_proj\",\"gate_proj\"],\n",
2313
+ " lora_dropout=0.05, task_type=\"CAUSAL_LM\"\n",
2314
+ ")\n",
2315
+ "model = get_peft_model(model, cfg)\n"
2316
+ ]
2317
+ },
2318
+ {
2319
+ "cell_type": "code",
2320
+ "execution_count": null,
2321
+ "metadata": {
2322
+ "colab": {
2323
+ "base_uri": "https://localhost:8080/",
2324
+ "height": 337
2325
+ },
2326
+ "id": "jNwgwk3YYUm2",
2327
+ "outputId": "3bf13c60-4a1e-4395-8cd0-9bda0de6ec37"
2328
+ },
2329
+ "outputs": [
2330
+ {
2331
+ "output_type": "stream",
2332
+ "name": "stderr",
2333
+ "text": [
2334
+ "warmup_ratio is deprecated and will be removed in v5.2. Use `warmup_steps` instead.\n",
2335
+ "/usr/local/lib/python3.12/dist-packages/torch/_dynamo/eval_frame.py:1181: UserWarning: torch.utils.checkpoint: the use_reentrant parameter should be passed explicitly. Starting in PyTorch 2.9, calling checkpoint without use_reentrant will raise an exception. use_reentrant=False is recommended, but if you need to preserve the current default behavior, you can pass use_reentrant=True. Refer to docs for more details on the differences between the two variants.\n",
2336
+ " return fn(*args, **kwargs)\n"
2337
+ ]
2338
+ },
2339
+ {
2340
+ "output_type": "display_data",
2341
+ "data": {
2342
+ "text/plain": [
2343
+ "<IPython.core.display.HTML object>"
2344
+ ],
2345
+ "text/html": [
2346
+ "\n",
2347
+ " <div>\n",
2348
+ " \n",
2349
+ " <progress value='63' max='63' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
2350
+ " [63/63 02:23, Epoch 1/1]\n",
2351
+ " </div>\n",
2352
+ " <table border=\"1\" class=\"dataframe\">\n",
2353
+ " <thead>\n",
2354
+ " <tr style=\"text-align: left;\">\n",
2355
+ " <th>Step</th>\n",
2356
+ " <th>Training Loss</th>\n",
2357
+ " </tr>\n",
2358
+ " </thead>\n",
2359
+ " <tbody>\n",
2360
+ " <tr>\n",
2361
+ " <td>10</td>\n",
2362
+ " <td>1.519478</td>\n",
2363
+ " </tr>\n",
2364
+ " <tr>\n",
2365
+ " <td>20</td>\n",
2366
+ " <td>0.856389</td>\n",
2367
+ " </tr>\n",
2368
+ " <tr>\n",
2369
+ " <td>30</td>\n",
2370
+ " <td>0.745439</td>\n",
2371
+ " </tr>\n",
2372
+ " <tr>\n",
2373
+ " <td>40</td>\n",
2374
+ " <td>0.714947</td>\n",
2375
+ " </tr>\n",
2376
+ " <tr>\n",
2377
+ " <td>50</td>\n",
2378
+ " <td>0.736302</td>\n",
2379
+ " </tr>\n",
2380
+ " <tr>\n",
2381
+ " <td>60</td>\n",
2382
+ " <td>0.717740</td>\n",
2383
+ " </tr>\n",
2384
+ " </tbody>\n",
2385
+ "</table><p>"
2386
+ ]
2387
+ },
2388
+ "metadata": {}
2389
+ }
2390
+ ],
2391
+ "source": [
2392
+ "def collate(batch):\n",
2393
+ " all_conversations = []\n",
2394
+ " for ex in batch:\n",
2395
+ " # Ensure required keys exist before trying to access them\n",
2396
+ " if \"video link\" not in ex or \"text prompt\" not in ex or \"conversations\" not in ex or len(ex[\"conversations\"]) < 2:\n",
2397
+ " print(f\"Skipping example due to missing or incomplete data: {ex.get('id', 'N/A')}\")\n",
2398
+ " continue\n",
2399
+ "\n",
2400
+ " video_path = ex[\"video link\"]\n",
2401
+ " question = ex[\"text prompt\"]\n",
2402
+ " answer = ex[\"conversations\"][1][\"value\"]\n",
2403
+ "\n",
2404
+ " # Create a single conversation (list of message dictionaries) for this example\n",
2405
+ " conversation = [\n",
2406
+ " {\"role\":\"user\",\"content\":[\n",
2407
+ " {\"type\":\"video\",\"path\":video_path},\n",
2408
+ " {\"type\":\"text\",\"text\":question}]},\n",
2409
+ " {\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":answer}]}\n",
2410
+ " ]\n",
2411
+ " all_conversations.append(conversation)\n",
2412
+ "\n",
2413
+ " if not all_conversations:\n",
2414
+ " # Return an empty dictionary if no valid conversations were constructed\n",
2415
+ " return {\"input_ids\": torch.tensor([]), \"attention_mask\": torch.tensor([]), \"labels\": torch.tensor([])}\n",
2416
+ "\n",
2417
+ " toks = tok.apply_chat_template(\n",
2418
+ " all_conversations, # Pass the list of conversations (List[List[Dict]])\n",
2419
+ " tokenize=True,\n",
2420
+ " padding=True,\n",
2421
+ " return_dict=True,\n",
2422
+ " return_tensors=\"pt\"\n",
2423
+ " )\n",
2424
+ " return {\"input_ids\": toks[\"input_ids\"],\n",
2425
+ " \"attention_mask\": toks[\"attention_mask\"],\n",
2426
+ " \"labels\": toks[\"input_ids\"]}\n",
2427
+ "\n",
2428
+ "args = TrainingArguments(\n",
2429
+ " your_model_folder, per_device_train_batch_size=4,\n",
2430
+ " gradient_accumulation_steps=8, num_train_epochs=1, fp16=True,\n",
2431
+ " learning_rate=2e-4, lr_scheduler_type=\"cosine\", warmup_ratio=0.03,\n",
2432
+ " logging_steps=10, save_total_limit=2,\n",
2433
+ " remove_unused_columns=False # Add this to prevent column removal by Trainer\n",
2434
+ ")\n",
2435
+ "\n",
2436
+ "Trainer(model=model, train_dataset=train_ds,\n",
2437
+ " data_collator=collate, args=args).train()\n",
2438
+ "model.save_pretrained(your_model_folder)\n"
2439
+ ]
2440
+ },
2441
+ {
2442
+ "cell_type": "code",
2443
+ "execution_count": null,
2444
+ "metadata": {
2445
+ "colab": {
2446
+ "base_uri": "https://localhost:8080/",
2447
+ "height": 248,
2448
+ "referenced_widgets": [
2449
+ "65d0a085c32e410bae5e889086673183",
2450
+ "5c5e7f4c4c274435b7c8200fed3c2af4",
2451
+ "7a94948e9d5a48ceb88b5ed26c1566bd",
2452
+ "226e267c66cc4232bf11b4c62d25fab4",
2453
+ "45b1a2a5225e4db2bb65e19da9129b64",
2454
+ "1b51f45b0f2746188d372442a8aafa11",
2455
+ "3ecd7dd20188419bbcd0855404fe228d",
2456
+ "b92ac54e7848482d932d731474ab26a2",
2457
+ "b699399a76b94dbea7e04d5e852d4f29",
2458
+ "cf8687b565a644b59bcab7ea1c3e16b3",
2459
+ "5c61a55db945430b80dd2ce7f0df5ac8",
2460
+ "bb8062a9db0c42c4b8c6f88061130c57",
2461
+ "87ceff8f62d9468da6cf505d0d6aae93",
2462
+ "ec7db76cac3b4e8a81784c440a14c247",
2463
+ "525399528bc54c0b928537fcb81bf4eb",
2464
+ "da3ca8489cb34c779476dfbcfcfd52c3",
2465
+ "88e8e360823b4901a04adafb0e352b5b",
2466
+ "231903c76fd241b89d104300433975cb",
2467
+ "ff5f0355efe1428c956308173060969c",
2468
+ "2a6a5d92c0a348c0aaca8bbf664912bb",
2469
+ "94379112ee5e43e898351005014e0202",
2470
+ "774cdebff3ef4b69bc62b97c5caa3e98",
2471
+ "21945612ba4c40ec943d33f77794bfd7",
2472
+ "30b0859dacf5452fb61beb704183d0e5",
2473
+ "7be39816f81c410eb3899ebf3d565578",
2474
+ "8810aaf657834f168d798e47d170bea3",
2475
+ "387acec5474a4d9393ad0d048d2ff6d9",
2476
+ "5a1bd3d9d6d64dee95d789bc30d82ae3",
2477
+ "dc023689144140f99298e9559860c5e6",
2478
+ "ffbd616e705f4b16b8df7f4589286f56",
2479
+ "0527cdbce0a24dae825cb7a95fe45d81",
2480
+ "030a44142d4a4815a15fa1a9cd0b4f3b",
2481
+ "ad4de7ddc58a4b02bb34e99ed6a484bf",
2482
+ "a854a0c760be4f85a2646f20c56a7d11",
2483
+ "b2188da2c959467b9333be65d3c4f263",
2484
+ "12f6065989064957b3b8a3f877b149e7",
2485
+ "350b69b057e346f4adaf3c90ece3dcda",
2486
+ "39421f248cfc4dd1938c7e51408dd96d",
2487
+ "14d03b195ef44c2cba7f058b61260e33",
2488
+ "7a545fb3a497431ca0662fe48a5243ea",
2489
+ "97580f89e83d43fe8a712a92bdeb6d11",
2490
+ "81697acb646149bb865855b5d4fd4250",
2491
+ "c353da6828f54a148da7440cf22c4fcf",
2492
+ "e2d9018b108048b78fb8da3b3e338f52",
2493
+ "6ea62c47df6d4e1cab0a39edadd7cb9f",
2494
+ "02ba170612d54afda9aba4b69b6c46b9",
2495
+ "99099eb02ff04ad98d79e5a8d6d222f3",
2496
+ "a1be81293007477bacc8c028df29e477",
2497
+ "c28169a69b00452d9b68a81823f6bce7",
2498
+ "8eceb5299c7748d694928f6ce7f4b99c",
2499
+ "fa2520ffe9c94bfe835a2d3df4b17bf7",
2500
+ "58628974056e4a099ac9efe67cbdba9e",
2501
+ "421512854f39478ba5fb9a05a524fa9e",
2502
+ "b0feb8aa77164ab2ab6e300b69acd58a",
2503
+ "5f2a971e42314282b3581bff7af699a3"
2504
+ ]
2505
+ },
2506
+ "id": "CrLdgBpda4oE",
2507
+ "outputId": "efcc2d40-db3f-4174-c3da-5f38b0566ba8"
2508
+ },
2509
+ "outputs": [
2510
+ {
2511
+ "output_type": "stream",
2512
+ "name": "stderr",
2513
+ "text": [
2514
+ "`torch_dtype` is deprecated! Use `dtype` instead!\n"
2515
+ ]
2516
+ },
2517
+ {
2518
+ "output_type": "display_data",
2519
+ "data": {
2520
+ "text/plain": [
2521
+ "Loading weights: 0%| | 0/489 [00:00<?, ?it/s]"
2522
+ ],
2523
+ "application/vnd.jupyter.widget-view+json": {
2524
+ "version_major": 2,
2525
+ "version_minor": 0,
2526
+ "model_id": "65d0a085c32e410bae5e889086673183"
2527
+ }
2528
+ },
2529
+ "metadata": {}
2530
+ },
2531
+ {
2532
+ "output_type": "display_data",
2533
+ "data": {
2534
+ "text/plain": [
2535
+ "README.md: 0.00B [00:00, ?B/s]"
2536
+ ],
2537
+ "application/vnd.jupyter.widget-view+json": {
2538
+ "version_major": 2,
2539
+ "version_minor": 0,
2540
+ "model_id": "bb8062a9db0c42c4b8c6f88061130c57"
2541
+ }
2542
+ },
2543
+ "metadata": {}
2544
+ },
2545
+ {
2546
+ "output_type": "display_data",
2547
+ "data": {
2548
+ "text/plain": [
2549
+ "Processing Files (0 / 0) : | | 0.00B / 0.00B "
2550
+ ],
2551
+ "application/vnd.jupyter.widget-view+json": {
2552
+ "version_major": 2,
2553
+ "version_minor": 0,
2554
+ "model_id": "21945612ba4c40ec943d33f77794bfd7"
2555
+ }
2556
+ },
2557
+ "metadata": {}
2558
+ },
2559
+ {
2560
+ "output_type": "display_data",
2561
+ "data": {
2562
+ "text/plain": [
2563
+ "New Data Upload : | | 0.00B / 0.00B "
2564
+ ],
2565
+ "application/vnd.jupyter.widget-view+json": {
2566
+ "version_major": 2,
2567
+ "version_minor": 0,
2568
+ "model_id": "a854a0c760be4f85a2646f20c56a7d11"
2569
+ }
2570
+ },
2571
+ "metadata": {}
2572
+ },
2573
+ {
2574
+ "output_type": "display_data",
2575
+ "data": {
2576
+ "text/plain": [
2577
+ " ...adapter_model.safetensors: 3%|3 | 639kB / 20.0MB "
2578
+ ],
2579
+ "application/vnd.jupyter.widget-view+json": {
2580
+ "version_major": 2,
2581
+ "version_minor": 0,
2582
+ "model_id": "6ea62c47df6d4e1cab0a39edadd7cb9f"
2583
+ }
2584
+ },
2585
+ "metadata": {}
2586
+ },
2587
+ {
2588
+ "output_type": "execute_result",
2589
+ "data": {
2590
+ "text/plain": [
2591
+ "CommitInfo(commit_url='https://huggingface.co/mfarre/smolvlm2-vide-qlora-adapter/commit/3d9f416b721ba01ca0e2fa978114f705b053191a', commit_message='Upload model', commit_description='', oid='3d9f416b721ba01ca0e2fa978114f705b053191a', pr_url=None, repo_url=RepoUrl('https://huggingface.co/mfarre/smolvlm2-vide-qlora-adapter', endpoint='https://huggingface.co', repo_type='model', repo_id='mfarre/smolvlm2-vide-qlora-adapter'), pr_revision=None, pr_num=None)"
2592
+ ],
2593
+ "application/vnd.google.colaboratory.intrinsic+json": {
2594
+ "type": "string"
2595
+ }
2596
+ },
2597
+ "metadata": {},
2598
+ "execution_count": 24
2599
+ }
2600
+ ],
2601
+ "source": [
2602
+ "# We can load the adapter that way:\n",
2603
+ "your_model_repo = '<yourUsername>/smolvlm2-vide-qlora-adapter'\n",
2604
+ "\n",
2605
+ "base = AutoModelForImageTextToText.from_pretrained(\n",
2606
+ " model_id, dtype=torch.bfloat16, device_map=\"auto\"\n",
2607
+ ")\n",
2608
+ "model = PeftModel.from_pretrained(base, your_model_folder)\n",
2609
+ "model.push_to_hub(your_model_repo)"
2610
+ ]
2611
+ },
2612
+ {
2613
+ "cell_type": "code",
2614
+ "execution_count": null,
2615
+ "metadata": {
2616
+ "colab": {
2617
+ "base_uri": "https://localhost:8080/",
2618
+ "height": 67,
2619
+ "referenced_widgets": [
2620
+ "32cb4fc987524bc69615856d8acdee96",
2621
+ "11e39b2c0d434dfb935710ac875c33a2",
2622
+ "8418f06fd5a04839bf17b546ccdbdcd4",
2623
+ "f71d21bc26534b44a6727f44681b9c53",
2624
+ "dde158b75b004efabcc569de95b27460",
2625
+ "a62a9c739fe74c76ac7983a8aa29c8b7",
2626
+ "d63299b6b0fd45d8ae9a6f8d6edaccc4",
2627
+ "b1522a6c30b04fb09c641198fbdaf264",
2628
+ "aa08ee015e18497185351224134c7118",
2629
+ "286a97ab27b14a6ba538bd1dc281a94d",
2630
+ "ed1925fe4fca4181812953459d9027c7"
2631
+ ]
2632
+ },
2633
+ "id": "iseid1NabDUa",
2634
+ "outputId": "45a922fa-2bd8-4eb7-99b6-872b0e6e2454"
2635
+ },
2636
+ "outputs": [
2637
+ {
2638
+ "output_type": "display_data",
2639
+ "data": {
2640
+ "text/plain": [
2641
+ "MewNUHRGOm0.mp4: 0%| | 0.00/6.84M [00:00<?, ?B/s]"
2642
+ ],
2643
+ "application/vnd.jupyter.widget-view+json": {
2644
+ "version_major": 2,
2645
+ "version_minor": 0,
2646
+ "model_id": "32cb4fc987524bc69615856d8acdee96"
2647
+ }
2648
+ },
2649
+ "metadata": {}
2650
+ },
2651
+ {
2652
+ "output_type": "stream",
2653
+ "name": "stdout",
2654
+ "text": [
2655
+ "A group of people are working in a control room, possibly preparing for a space mission.\n"
2656
+ ]
2657
+ }
2658
+ ],
2659
+ "source": [
2660
+ "# Let's test it:\n",
2661
+ "\n",
2662
+ "# We load the processor from the base model\n",
2663
+ "processor = AutoProcessor.from_pretrained(model_id)\n",
2664
+ "\n",
2665
+ "# We load a video\n",
2666
+ "sample_video = hf_hub_download(\n",
2667
+ " repo_id=\"vlmbook/videos\",\n",
2668
+ " repo_type=\"dataset\",\n",
2669
+ " filename=\"MewNUHRGOm0.mp4\",\n",
2670
+ ")\n",
2671
+ "\n",
2672
+ "# Auxiliary function to run inference\n",
2673
+ "def ask_video(video_path: str, prompt: str, num_frames: int = 8) -> str:\n",
2674
+ " messages = [{\n",
2675
+ " \"role\": \"user\",\n",
2676
+ " \"content\": [\n",
2677
+ " {\"type\": \"video\", \"path\": video_path},\n",
2678
+ " {\"type\": \"text\", \"text\": prompt},\n",
2679
+ " ],\n",
2680
+ " }]\n",
2681
+ "\n",
2682
+ " inputs = processor.apply_chat_template(\n",
2683
+ " messages,\n",
2684
+ " tokenize=True,\n",
2685
+ " add_generation_prompt=True,\n",
2686
+ " return_dict=True,\n",
2687
+ " return_tensors=\"pt\",\n",
2688
+ " do_sample_frames=True,\n",
2689
+ " num_frames=num_frames,\n",
2690
+ " )\n",
2691
+ " inputs = {k: (v.to(model.device) if torch.is_tensor(v) else v) for k, v in inputs.items()}\n",
2692
+ " if \"pixel_values_videos\" in inputs and torch.is_tensor(inputs[\"pixel_values_videos\"]):\n",
2693
+ " inputs[\"pixel_values_videos\"] = inputs[\"pixel_values_videos\"].to(dtype=dtype)\n",
2694
+ "\n",
2695
+ " out = model.generate(\n",
2696
+ " **inputs,\n",
2697
+ " max_new_tokens=128,\n",
2698
+ " do_sample=False,\n",
2699
+ " )\n",
2700
+ "\n",
2701
+ " prompt_len = inputs[\"input_ids\"].shape[-1]\n",
2702
+ " return processor.batch_decode(out[:, prompt_len:], skip_special_tokens=True)[0].strip()\n",
2703
+ "\n",
2704
+ "\n",
2705
+ "print(ask_video(sample_video, \"What is happening here?\", num_frames=8))"
2706
+ ]
2707
+ }
2708
+ ],
2709
+ "metadata": {
2710
+ "accelerator": "GPU",
2711
+ "colab": {
2712
+ "gpuType": "H100",
2713
+ "provenance": [],
2714
+ "machine_shape": "hm"
2715
+ },
2716
+ "kernelspec": {
2717
+ "display_name": "Python 3",
2718
+ "name": "python3"
2719
+ },
2720
+ "language_info": {
2721
+ "name": "python"
2722
+ }
2723
+ },
2724
+ "nbformat": 4,
2725
+ "nbformat_minor": 0
2726
+ }