<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kartikeya on Medium]]></title>
        <description><![CDATA[Stories by Kartikeya on Medium]]></description>
        <link>https://medium.com/@kartikeyasaraswat67?source=rss-e0536b8dbd20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ULe0Qdg3zP75xgxPTuq69w.jpeg</url>
            <title>Stories by Kartikeya on Medium</title>
            <link>https://medium.com/@kartikeyasaraswat67?source=rss-e0536b8dbd20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:13:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kartikeyasaraswat67/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Video Scene Graph Generation Using VLMs]]></title>
            <link>https://pub.towardsai.net/video-scene-graph-generation-using-vlms-d469e506797d?source=rss-e0536b8dbd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/d469e506797d</guid>
            <category><![CDATA[vision-language-model]]></category>
            <category><![CDATA[scene-graph]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Kartikeya]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 11:16:11 GMT</pubDate>
            <atom:updated>2026-07-05T11:26:11.585Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to turn any video into a structured, machine-readable description of “objects/people and actions between them”: without hand-defining a single object class or predicate rule.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMdfvAHx5b3_LRKr2n3HUQ.png" /><figcaption>An example showing object and action relationship in a scene graph</figcaption></figure><blockquote>What a scene graph is, and why you’d want one</blockquote><p>A scene graph is a topological structure that represents a scene described in text, images, or video. Nodes encode object categories or attributes; edges encode pair-wise relations. A scene graph can also be described as a compact, structured representation of a scene as a set of (subject, predicate, object) triples:</p><p><em>(host, interviewing, guest)<br>(chef, plating, dish)<br>(person_1, arguing_with, person_2)</em></p><p>Each triple is a directed edge in a graph whose nodes are entities (people, animals, objects) and whose edges are the relationships or actions between them. The power of this representation is that it’s something you can <em>reason over programmatically</em>: you can count how many distinct interactions occur, ask whether any human is acting on any other human, find the single most salient action, measure how densely connected the scene is, or match one scene’s structure against another’s. None of that is straightforward from a pixel array or a sentence.</p><p>In the case of videos, instead of processing raw pixels, models use evolving graphs to map how actions unfold over time, enabling computers to understand long-form videos, actions, and complex spatial interactions.</p><blockquote>Limitations of Existing Methods</blockquote><p>Scene graph generation (SGG) has been studied for years, but conventionally, it has required <strong>a fixed vocabulary</strong>. Foundational datasets like Visual Genome ship with a closed set of object classes and predicate labels, and models are trained to pick from that set. This has an issue; if the video contains a concept the ontology did not anticipate, the model simply cannot express it.</p><blockquote>VLMs generate open-vocabulary triplets directly</blockquote><p>Modern Vision Language Models are capable of generating an open-vocabulary format. We describe the required format in a prompt, and the model produces entities and predicates in natural language, drawn from its understanding of the visual linguistic cues.</p><p>The rest of this post walks through a complete implementation built around Qwen2.5-VL, an open-source VLM.</p><h4>Scene Graph Generation Pipeline</h4><blockquote>Step 1: Necessary Imports</blockquote><pre>import os<br>import re<br>import cv2<br>import json<br>import glob<br>import math<br>import hashlib<br>from collections import defaultdict, Counter<br>from dataclasses import dataclass, field, asdict<br>from typing import Optional, Protocol<br>from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor<br>import torch<br>from qwen_vl_utils import process_vision_info<br>from PIL import Image<br><br>import numpy as np<br>import networkx as nx</pre><blockquote>Step 1: Keyframe Selection</blockquote><pre>def select_keyframes(video_path: str,<br>                     max_frames: int = 8,<br>                     min_gap_sec: int = 1,<br>                     hist_threshold: int = 0.35) -&gt; list[tuple[int, float, np.ndarray]]:<br><br>cap = cv2.VideoCapture(video_path)<br>if not cap.isOpened():<br>   raise IOError(f&quot;Cannot open video: {video_path}&quot;)<br>fps = cap.get(cv2.CAP_PROP_FPS) or 30.0<br>total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)<br><br>keyframes = []<br>prev_hist = None<br>last_kept_t = -1e9<br>idx = 0<br># stride: don&#39;t inspect every single frame for very long videos<br>stride = max(1, int(fps // 3)<br><br>while True:<br>  ok, frame = cap.read()<br>  if not ok:<br>    break<br>  if idx % stride != 0<br>    idx += 1<br>    continue<br>  t = idx / fps<br>  small = cv2.resize(frame, (160, 90))<br>  hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)<br>  hist = cv2.calcHist([hsv], [0, 1], None, [50, 60], [0, 180, 0, 256])<br>  cv2.normalize(hist, hist)<br>  <br>  take = False<br>  if prev_hist is None:<br>    take = True<br>  else:<br>    diff = cv2.compareHist(prev_hist, hist, cv2.HISTCMP_BHATTACHARYYA)<br>    if diff &gt; hist_threshold and (t - last_kept_t) &gt;= min_gap_sec:<br>      take = True<br>  if take:<br>    keyframes.append((idx, t, frame.copy()))<br>    prev_hist = hist<br>    last_kept_t = t<br>  idx += 1<br><br>cap.release()<br><br>if len(keyframes) &gt; max_frames:<br>  pick = np.linspace(0, len(keyframes) - 1, max_frames).astype(int)<br>  keyframes = [keyframes[i] for i in pick]<br># if too few (static video), pad with uniform samples<br>if len(keyframes) &lt; 2 and total &gt; 0:<br>  cap = cv2.VideoCapture(video_path)<br>  for f in np.linspace(0, total - 1, min(max_frames, 3)).astype(int):<br>    cap.set(cv2.CAP_PROP_POS_FRAMES, int(f))<br>    ok, fr = cap.read()<br>    if ok:<br>      keyframes.append((int(f), f / fps, fr))<br>  cap.release()<br><br>return keyframes</pre><blockquote>Step3: Extracting Triplets Using VLM</blockquote><pre>class QwenVLBackend:<br><br>  def __init__(self, model_name: str = &quot;Qwen/Qwen2.5-VL-7B-Instruct&quot;,<br>               device: str = &quot;cuda&quot;, max_pixels: int = 768 * 28 * 28,<br>               use_flash_attn: bool = True):<br>   <br>    kwargs = dict(torch_dtype=&quot;auto&quot;, device_map=device)<br>    if use_flash_attn:<br>      try:<br>        kwargs[&quot;attn_implementation&quot;] = &quot;flash_attention_2&quot;<br>        kwargs[&quot;torch_dtype&quot;] = torch.bfloat16<br>      except Exception:<br>        pass<br>    <br>    self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(model_name, **kwargs)<br>    self.processor = AutoProcessor.from_pretrained(model_name, max_pixels=max_pixels)<br>    self.torch = torch<br>  <br>  def generate(self, frames_bgr, prompt, max_new_tokens=512):<br>    <br>    pil_images = [Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)) for f in frames_bgr]<br>    messages = [{<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: [<br>         {&quot;type&quot;: &quot;video&quot;, &quot;video&quot;: pil_images},<br>         {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: prompt},<br>      ],<br>    }]<br>    text = self.processor.apply_chat_template(<br>           messages, tokenize=False, add_generation_prompt=True)<br>    image_inputs, video_inputs = process_vision_info(messages)<br>    inputs = self.processor(text=[text], images=image_inputs,<br>                            videos=video_inputs, padding=True,<br>                            return_tensors=&quot;pt&quot;).to(self.model.device)<br>    <br>    with self.torch.no_grad():<br>      out = self.model.generate(**inputs, max_new_tokens=max_new_tokens,<br>                                do_sample=False)<br>    trimmed = [o[len(i):] for i, o in zip(inputs.input_ids, out)]<br>    <br>    return self.processor.batch_decode(<br>           trimmed, skip_special_tokens=True,<br>           clean_up_tokenization_spaces=True)[0]<br>  <br>SCENE_GRAPH_PROMPT = &quot;&quot;&quot;You are analyzing keyframes sampled in order from one short video.<br><br>Identify the MOST IMPORTANT entities (people, animals, key objects) and the<br>meaningful interactions or actions between them across these frames.<br><br>Rules:<br>- Return ONLY the salient relationships that describe what is happening.<br>- Use concrete action/semantic predicates (e.g. interviewing, hugging, holding,<br>  pointing_at, laughing_at, presenting, cooking, dancing_with, arguing_with).<br>- DO NOT use vague spatial predicates like &quot;near&quot;, &quot;next to&quot;, &quot;beside&quot;, &quot;above&quot;.<br>- Refer to recurring people consistently (person_1, person_2, host, guest...).<br>- At most 8 triples total for the whole video.<br><br>Return STRICT JSON only, no prose, in exactly this schema:<br>{&quot;entities&quot;: [&quot;...&quot;, &quot;...&quot;],<br> &quot;triples&quot;: [{&quot;subject&quot;: &quot;...&quot;, &quot;predicate&quot;: &quot;...&quot;, &quot;object&quot;: &quot;...&quot;, &quot;salience&quot;: 0.0-1.0}],<br> &quot;scene_summary&quot;: &quot;one short sentence&quot;}&quot;&quot;&quot;</pre><blockquote>Step 4: Robust Json Parsing to extract clean triplets</blockquote><pre>def _extract_json(text:str) -&gt; Optional[dict]:<br>  <br>  text = re.sub(r&quot;```(?:json)?&quot;, &quot;&quot;, text).strip(&quot;` \n&quot;)<br>  <br>  start = text.find(&quot;{&quot;)<br>  if start == -1:<br>    return None<br>  depth = 0:<br>  for i in range(start, len(text)):<br>    if text[i] == &quot;{&quot;:<br>      depth += 1  <br>    elif text[i] == &quot;}&quot;:<br>      depth -= -1<br>      if depth == 0:<br>        blob = text[start:i+1]<br>        try:<br>          return json.loads(blob)<br>        except json.JSONDecodeError:<br>          blob2 = re.sub(r&quot;,\s*([}\]])&quot;, r&quot;\1&quot;, blob)<br>          try:<br>            return json.loads(blob2)<br>          except json.JSONDecodeError:<br>            return None<br>  return None</pre><blockquote>Step 5: Build a Scene Graph using Networkx</blockquote><pre>@dataclass<br>class VLMTriple:<br>    subject: str<br>    predicate: str<br>    object: str<br>    salience: float = 0.5<br><br>def _norm_entity(name: str) -&gt; str:<br>    return re.sub(r&quot;\s+&quot;, &quot;_&quot;, name.strip().lower())<br><br>def build_scene_graph(video_path:str, vlm, max_frames:int = 8) -&gt; dict:<br><br>  kfs = select_keyframes(video_path, max_frames=max_frames)<br>  frames = [f for _, _, f in kfs]<br>  if not frames:<br>    raise RuntimeError(f&quot;No frames extracted from {video_path}&quot;)<br>  <br>  raw = vlm.generate(frames, SCENE_GRAPH_PROMPT, max_new_tokens=512)<br>  parsed = _extract_json(raw) or {}<br>  triples_in = parsed.get(&quot;triples&quot;, []) if isinstance(parsed, dict) else []<br>  <br>  triples: list[VLMTriple] = []<br>  for t in triples_in:<br>    try:<br>      s = _norm_entity(str(t[&quot;subject&quot;]))<br>      p = _norm_entity(str(t[&quot;predicate&quot;]))<br>      o = _norm_entity(str(t[&quot;object&quot;]))<br>      if not s or not o or not p:<br>        continue<br>      sal = float(t.get(&quot;salience&quot;, 0.5))<br>      triples.append(VLMTriple(s, p, o, max(0.0, min(1.0, sal))))<br>    except (KeyError, TypeError, ValueError):<br>      continue<br>   <br>  G = nx.MultiDiGraph()<br>  ent_mentions = Counter()<br>  for tr in triples:<br>    ent_mentions[tr.subject] += 1<br>    ent_mentions[tr.object] += 1<br>  for ent, c in ent_mentions.items():<br>    is_person = any(k in ent for k in (&quot;person&quot;, &quot;host&quot;, &quot;guest&quot;, &quot;man&quot;,<br>                                       &quot;woman&quot;, &quot;people&quot;, &quot;player&quot;, &quot;child&quot;)<br>    G.add_node(ent, label=ent, mentions=c, is_person=is_person)<br>  <br>  for tr in triples:<br>    G.add_edge(tr.subject, tr.object, key=tr.predicate, predicate=tr.predicate,<br>               salience=tr.salience)<br>  return {<br>        &quot;graph&quot;: G,<br>        &quot;triples&quot;: [asdict(t) for t in triples],<br>        &quot;entities&quot;: parsed.get(&quot;entities&quot;, []),<br>        &quot;summary&quot;: parsed.get(&quot;scene_summary&quot;, &quot;&quot;),<br>        &quot;n_keyframes&quot;: len(frames),<br>        &quot;raw_response&quot;: raw,<br>    }<br></pre><pre>def draw_scene_graph(G: nx.MultiDiGraph, title: str = &quot;&quot;,<br>                     save_path: str | None = None, figsize=(10, 7)):<br>    if G.number_of_nodes() == 0:<br>        print(f&quot;[{title}] empty graph&quot;)<br>        return<br>    pos = nx.spring_layout(G, k=1.5, seed=42)<br>    is_person = nx.get_node_attributes(G, &quot;is_person&quot;)<br>    colors = [&quot;#ff6b6b&quot; if is_person.get(n) else &quot;#4dabf7&quot; for n in G.nodes]<br>    mentions = nx.get_node_attributes(G, &quot;mentions&quot;)<br>    sizes = [800 + 500 * mentions.get(n, 1) for n in G.nodes]<br><br>    plt.figure(figsize=figsize)<br>    nx.draw_networkx_nodes(G, pos, node_size=sizes, node_color=colors, alpha=0.9)<br>    nx.draw_networkx_labels(G, pos, {n: n for n in G.nodes},<br>                            font_size=9, font_weight=&quot;bold&quot;)<br>    for u, v, k, d in G.edges(keys=True, data=True):<br>        w = 1 + 4 * d.get(&quot;salience&quot;, 0.5)<br>        nx.draw_networkx_edges(G, pos, edgelist=[(u, v)], width=w, alpha=0.55,<br>                               edge_color=&quot;#495057&quot;, arrowsize=18,<br>                               connectionstyle=&quot;arc3,rad=0.1&quot;)<br>    elabels = {(u, v): d[&quot;predicate&quot;] for u, v, k, d in G.edges(keys=True, data=True)}<br>    nx.draw_networkx_edge_labels(G, pos, elabels, font_size=8)<br>    plt.title(title, fontsize=13, fontweight=&quot;bold&quot;)<br>    plt.axis(&quot;off&quot;)<br>    plt.tight_layout()<br>    if save_path:<br>        plt.savefig(save_path, dpi=130, bbox_inches=&quot;tight&quot;)<br>        plt.close()<br>        print(f&quot;saved -&gt; {save_path}&quot;)<br>    else:<br>        plt.close()</pre><h4>Where this is actually useful</h4><blockquote>Semantic Video Search and Retrieval</blockquote><p>A scene graph lets you query relationships, e.g., “Find clips where a person is handing something to another person” or “where someone is pointing at a screen”.</p><blockquote>Visual question answering and multimodal reasoning</blockquote><p>When a system needs to answer “why did the person react that way?”, a structured graph of the entities and their interactions is a better structure than a flat caption. The graph can be traversed, and relationships can be composed, supporting multi-hop questions (“who did the thing that caused the other person to laugh?”) that a single sentence can’t reliably answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d469e506797d" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/video-scene-graph-generation-using-vlms-d469e506797d">Video Scene Graph Generation Using VLMs</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning BLIP2 for Prompt-instructed Video Classification]]></title>
            <link>https://pub.towardsai.net/fine-tuning-blip2-for-prompt-instructed-video-classification-e1a3aaf40c34?source=rss-e0536b8dbd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a3aaf40c34</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[vision-language-model]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Kartikeya]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 18:31:01 GMT</pubDate>
            <atom:updated>2026-04-26T18:31:01.358Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5UvfSgbQGJQ7T9f62lpbg.png" /><figcaption>Generated Using Gemini’s Nano Banana Pro</figcaption></figure><p>Video understanding remains one of the most challenging frontiers in computer vision. Unlike static images, videos exhibit rich temporal dynamics, including human actions, object interactions, and scene transitions. Conventional video classification methods rely on architectures such as 3D CNNs and Video Transformers (Timesformer, ViViT). These methods, while effective, cannot incorporate natural-language guidance into the classification process.</p><p>Simultaneously, the rapid progress in Vision-Language Models (VLMs) — such as CLIP, BLIP, BLIP-2, and Flamingo — has demonstrated that jointly learning visual and linguistic representations yields powerful, generalizable features. BLIP-2 (Bootstrapped Language-Image Pre-training 2) introduced an efficient architecture, the Querying Transformer (Q-Former), that bridges a frozen image encoder and a frozen large language model, achieving state-of-the-art performance on image-text tasks with minimal trainable parameters.</p><p>However, BLIP-2 was designed for static images. Extending it to video understanding and further conditioning it on natural-language prompts (instructions) opens the door to a flexible, instruction-driven video classification paradigm — where the model not only sees the video but is also told <em>what to look for</em>.</p><blockquote><em>In this article, we’ll walk through a complete, generic pipeline for fine-tuning a </em><em>BLIP2 model for video classification.</em></blockquote><h4>What is BLIP2?</h4><p>The BLIP-2 model was proposed in <a href="https://huggingface.co/papers/2301.12597">BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models</a> by Junnan Li, Dongxu Li, Silvio Savarese, and Steven Hoi. BLIP-2 leverages frozen pre-trained image encoders and large language models (LLMs) by training a lightweight, 12-layer Transformer encoder in between them, achieving state-of-the-art performance on various vision-language tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fJWcS2ruiVZ7gJNQ.png" /><figcaption>Image from original BLIP2 Paper</figcaption></figure><p>This work presents a method to fine-tune BLIP-2 for prompt-instructed video classification by:</p><ul><li>Extending the BLIP-2 vision encoder to handle video inputs (temporal frame sequences)</li><li>Leveraging the pretrained Q-Former for visual feature aggregation</li><li>Conditioning classification on a natural language prompt via a cross-attention fusion mechanism</li><li>Training only a small set of parameters (Q-Former + fusion layers + classifier) while keeping the vision encoder frozen</li></ul><blockquote>InstructBLIP demonstrated that conditioning the Q-Former on task-specific instructions significantly improves performance across diverse vision-language tasks. Our work takes a similar approach but applies it specifically to video classification, where temporal reasoning is critical and the instruction guides spatial-temporal feature aggregation.</blockquote><h4>Python Implementation</h4><p><strong>Import Libraries</strong></p><pre>import os<br>import av<br>import numpy as np<br>import torch<br>import torch.nn as nn<br>from torch.utils.data import Dataset, DataLoader<br>from datasets import Dataset as HFDataset, DatasetDict<br>from transformers import (<br>    Blip2Processor,<br>    BatchEncoding,<br>    TrainingArguments,<br>    Trainer,<br>    EarlyStoppingCallback,<br>)<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import (<br>    accuracy_score,<br>    f1_score,<br>    classification_report,<br>    confusion_matrix,<br>)<br>from typing import Any, Callable, Optional<br>import logging<br>import pandas as pd<br>from dataclasses import dataclass<br>from transformers import (<br>    Blip2Config,<br>    Blip2ForConditionalGeneration,<br>    Blip2QFormerModel,<br>    Blip2VisionModel,<br>)<br>from transformers.modeling_outputs import BaseModelOutputWithPooling</pre><p><strong>Training Hyperparameters</strong></p><pre>MODEL_NAME = &quot;Salesforce/blip2-opt-2.7b&quot;<br>NUM_FRAMES = 8          <br>BATCH_SIZE = 8<br>NUM_EPOCHS = 100<br>LEARNING_RATE = 1e-4<br>WEIGHT_DECAY = 0.01<br>WARMUP_RATIO = 0.1<br>OUTPUT_DIR = &quot;./videoblip_classification_output&quot;<br>RANDOM_SEED = 42<br>IMG_SIZE = 224</pre><p><strong>Read Video</strong></p><pre>def read_video_pyav(filepath: str, num_frames: int = 8) -&gt; np.ndarray:<br><br>    &quot;&quot;&quot;<br>    Read a video file and uniformly sample `num_frames` frames.<br><br>    :returns: np.ndarray of shape (num_frames, height, width, 3), dtype uint8<br><br>    &quot;&quot;&quot;<br>    container = av.open(filepath)<br>    stream = container.streams.video[0]<br>    total_frames = stream.frames<br>    if total_frames == 0:<br>       <br>        frames = [f.to_ndarray(format=&quot;rgb24&quot;) for f in container.decode(video=0)]<br>        total_frames = len(frames)<br>        indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)<br>        return np.stack([frames[i] for i in indices])<br><br>    indices = set(np.linspace(0, total_frames - 1, num_frames, dtype=int).tolist())<br><br>    frames = []<br>    for i, frame in enumerate(container.decode(video=0)):<br>        if i in indices:<br>            frames.append(frame.to_ndarray(format=&quot;rgb24&quot;))<br>        if len(frames) == num_frames:<br>            break<br><br>    container.close()<br><br>    while len(frames) &lt; num_frames:<br>        frames.append(frames[-1])  <br><br>    return np.stack(frames)</pre><p><strong>Function to Process Video and Prompt Jointly</strong></p><pre>def process(<br>        processor: Blip2Processor,<br>        video: np.ndarray | None = None,<br>        text: str | list[str] | None = None,<br>)-&gt; BatchEncoding:<br>    <br>    if video is not None:<br>        video_list = [frame for frame in video]<br>        <br>    inputs = processor(images=video_list, text=text, return_tensors=&quot;pt&quot;)<br><br>    if video is not None:<br>        if isinstance(inputs[&#39;pixel_values&#39;], list):<br>            pixel_values = torch.stack(inputs[&#39;pixel_values&#39;])<br>        else:<br>            pixel_values = inputs[&#39;pixel_values&#39;]<br>        num_frames = video.shape[0]<br>        c, h, w = pixel_values.shape[1:]<br>        inputs[&quot;pixel_values&quot;] = pixel_values.view(num_frames, c, h, w).permute(1, 0, 2, 3)<br>    <br>    return inputs</pre><p><strong>Customized BLIP2 Model for Videos</strong></p><pre>@dataclass<br>class VideoClassificationOutput:<br><br>    loss: Optional[torch.FloatTensor] = None<br>    logits: Optional[torch.FloatTensor] = None<br>    hidden_states: Optional[tuple] = None<br>    attentions: Optional[tuple] = None<br><br><br>class VideoBlipVisionModel(Blip2VisionModel):<br><br>    &quot;&quot;&quot;Video-aware BLIP2 vision model.&quot;&quot;&quot;<br><br>    def forward(<br>        self,<br>        pixel_values: torch.FloatTensor | None = None,<br>        output_attentions: bool | None = None,<br>        output_hidden_states: bool | None = None,<br>        return_dict: bool | None = None,<br>    )-&gt; tuple | BaseModelOutputWithPooling:<br>        if pixel_values is None:<br>            raise ValueError(&quot;You have to specify pixel_values&quot;)<br><br>        batch, _, time, _, _ = pixel_values.size()<br>        flat_pixel_values = pixel_values.permute(0, 2, 1, 3, 4).flatten(end_dim=1)<br><br>        vision_outputs: BaseModelOutputWithPooling = super().forward(<br>            pixel_values=flat_pixel_values,<br>            output_attentions=output_attentions,<br>            output_hidden_states=output_hidden_states,<br>            return_dict=True,<br>        )<br><br>        seq_len = vision_outputs.last_hidden_state.size(1)<br><br>        last_hidden_state = vision_outputs.last_hidden_state.view(<br>            batch, time * seq_len, -1<br>        )<br>        pooler_output = vision_outputs.pooler_output.view(batch, time, -1)<br><br>        hidden_states = (<br>            tuple(<br>                hidden.view(batch, time * seq_len, -1)<br>                for hidden in vision_outputs.hidden_states<br>            )<br>            if vision_outputs.hidden_states is not None<br>            else None<br>        )<br><br>        attentions = (<br>            tuple(<br>                hidden.view(batch, time, -1, seq_len, seq_len)<br>                for hidden in vision_outputs.attentions<br>            )<br>            if vision_outputs.attentions is not None<br>            else None<br>        )<br><br>        if return_dict:<br>            return BaseModelOutputWithPooling(<br>                last_hidden_state=last_hidden_state,<br>                pooler_output=pooler_output,<br>                hidden_states=hidden_states,<br>                attentions=attentions,<br>            )<br>        <br>        return (last_hidden_state, pooler_output, hidden_states, attentions)<br><br><br>class VideoBlipForClassification(Blip2ForConditionalGeneration):<br><br>    &quot;&quot;&quot;<br>    Prompt-conditioned VideoBLIP classifier.<br><br>    Inputs:<br>        - pixel_values: (B, C, T, H, W)<br>        - input_ids: (B, L)<br>        - attention_mask: (B, L)<br><br>    The prompt is fed into Q-Former along with query tokens and video features.<br><br>    &quot;&quot;&quot;<br><br>    def __init__(self, config: Blip2Config, num_classes: int) -&gt; None:<br>        <br>        super(Blip2ForConditionalGeneration, self).__init__(config)<br><br>        self.num_classes = num_classes<br><br>        self.vision_model = VideoBlipVisionModel(config.vision_config)  <br><br>        self.query_tokens = nn.Parameter(<br>            torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size)<br>        )<br>        self.qformer = Blip2QFormerModel(config.qformer_config)<br><br>        qformer_hidden = config.qformer_config.hidden_size<br><br>        self.classifier = nn.Sequential(<br>            nn.LayerNorm(qformer_hidden),<br>            nn.Linear(qformer_hidden, qformer_hidden),<br>            nn.GELU(),<br>            nn.Dropout(0.1),<br>            nn.Linear(qformer_hidden, num_classes),<br>        )<br><br>        self.language_projection = None<br>        self.language_model = None<br><br>        self.post_init()<br>    <br>    @classmethod<br>    def from_pretrained_videoblip(<br>        cls,<br>        pretrained_model_name_or_path: str,<br>        num_classes: int,<br>        freeze_vision: bool = True,<br>        freeze_qformer: bool = False,<br>        **kwargs,<br>    ) -&gt; &quot;VideoBlipForClassification&quot;:<br>        config = Blip2Config.from_pretrained(pretrained_model_name_or_path)<br>        model = cls(config, num_classes=num_classes)<br><br>        pretrained = Blip2ForConditionalGeneration.from_pretrained(<br>            pretrained_model_name_or_path, **kwargs<br>        )<br><br>        msg = model.vision_model.load_state_dict(<br>            pretrained.vision_model.state_dict(), strict=False<br>        )<br>        print(f&quot;Vision model load info: {msg}&quot;)<br>        model.qformer.load_state_dict(pretrained.qformer.state_dict())<br>        model.query_tokens.data.copy_(pretrained.query_tokens.data)<br><br>        if freeze_vision:<br>            for param in model.vision_model.parameters():<br>                param.requires_grad = False<br>            print(&quot;Vision encoder frozen.&quot;)<br>        if freeze_qformer:<br>            for param in model.qformer.parameters():<br>                param.requires_grad = False<br>            model.query_tokens.requires_grad = False<br>            print(&quot;Q-Former frozen.&quot;)<br><br>        del pretrained<br>        return model<br>    <br>    def forward(<br>        self,<br>        pixel_values: torch.FloatTensor,<br>        labels: Optional[torch.LongTensor] = None,<br>        output_attentions: Optional[bool] = None,<br>        output_hidden_states: Optional[bool] = None,<br>        return_dict: bool = True, <br>    ) -&gt; VideoClassificationOutput:<br>        <br>        return_dict = return_dict if return_dict is not None else self.config.use_return_dict<br><br>        vision_outputs = self.vision_model(<br>            pixel_values=pixel_values,<br>            output_attentions=output_attentions,<br>            output_hidden_states=output_hidden_states,<br>            return_dict=True,<br>        )<br><br>        frame_embeds = vision_outputs.last_hidden_state<br>        frame_attention_mask = torch.ones(<br>            frame_embeds.size()[:-1], dtype=torch.long, device=frame_embeds.device<br>        )<br><br>        query_tokens = self.query_tokens.expand(frame_embeds.size(0), -1, -1)<br>        query_outputs = self.qformer(<br>            query_embeds=query_tokens,<br>            encoder_hidden_states=frame_embeds,<br>            encoder_attention_mask=frame_attention_mask,<br>            return_dict=return_dict,<br>        )<br>        query_output = query_outputs[0] if not return_dict else query_outputs.last_hidden_state<br>        pooled_query_output = query_output.mean(dim=1)<br>        logits = self.classifier(pooled_query_output)<br><br>        loss = None<br>        if labels is not None:<br>            loss_fct = nn.CrossEntropyLoss()<br>            loss = loss_fct(logits.view(-1, self.num_classes), labels.view(-1))<br>        <br>        if not return_dict:<br>            output = (logits,)<br>            if output_hidden_states:<br>                output = output + (query_outputs.hidden_states,)<br>            if output_attentions:<br>                output = output + (query_outputs.attentions,)<br>            return ((loss,) + output) if loss is not None else output<br><br>        return VideoClassificationOutput(<br>            loss=loss,<br>            logits=logits,<br>            hidden_states=query_outputs.hidden_states,<br>            attentions=query_outputs.attentions,<br>        )</pre><p><strong>Data Preparation</strong></p><pre>def collate_fn(batch: list[dict]) -&gt; dict:<br>    pixel_values = torch.stack([torch.tensor(item[&#39;pixel_values&#39;]) for item in batch])  # (B, C, T, H, W)<br>    labels = torch.tensor([item[&#39;labels&#39;] for item in batch])  # (B,)<br>    return {&#39;pixel_values&#39;: pixel_values, &#39;labels&#39;: labels}<br><br>processor = Blip2Processor.from_pretrained(MODEL_NAME)<br><br>def create_dataset(data: DatasetDict, processor: Blip2Processor) -&gt; DatasetDict:<br>    <br>    def process_example(example: dict) -&gt; dict:<br>        video_path = example[&#39;video&#39;]<br>        label = example[&#39;label&#39;]<br>        video_frames = read_video_pyav(video_path, num_frames=NUM_FRAMES) # (T, H, W, C) numpy array<br>        # Pass the numpy array directly<br>        inputs = process(processor, video=video_frames, text=PROMPT)<br>        return {<br>            &#39;pixel_values&#39;: inputs[&#39;pixel_values&#39;],  # (C, T, H, W)<br>            &#39;labels&#39;: label<br>        }<br>    num_cpus = os.cpu_count()<br>    return data.map(process_example, batched=False, num_proc=num_cpus)<br><br>train_dataset = create_dataset(data[&#39;train&#39;], processor)<br>val_dataset = create_dataset(data[&#39;validation&#39;], processor)<br>test_dataset = create_dataset(data[&#39;test&#39;], processor)</pre><p><strong>Training</strong></p><pre>def compute_metrics(eval_pred):<br>    predictions, labels = eval_pred<br>    if isinstance(predictions, tuple):<br>        predictions = predictions[0]<br>    pred_ids = np.argmax(predictions, axis=-1)<br>    return {<br>        &quot;accuracy&quot;: accuracy_score(labels, pred_ids),<br>        &quot;f1&quot;: f1_score(labels, pred_ids, average=&quot;weighted&quot;),<br>    }<br><br>class VideoBlipTrainer(Trainer):<br>    <br>    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):<br>        labels = inputs.pop(&quot;labels&quot;, None)<br>        <br>        # When return_outputs is True, the trainer expects a tuple (loss, model_outputs...).<br>        # We should ask the model to return a tuple by setting return_dict=False.<br>        outputs = model(<br>            pixel_values=inputs[&quot;pixel_values&quot;],<br>            labels=labels,<br>            return_dict=not return_outputs, # Return a dict for training, a tuple for evaluation<br>        )<br><br>        if return_outputs:<br>            # For evaluation, outputs is a tuple (loss, logits, ...)<br>            loss = outputs[0]<br>            return (loss, outputs)<br>        else:<br>            # For training, outputs is the VideoClassificationOutput object<br>            loss = outputs.loss<br>            return loss<br><br>model = VideoBlipForClassification.from_pretrained_videoblip(<br>    MODEL_NAME,<br>    num_classes=NUM_CLASSES,<br>    freeze_vision=True,<br>    freeze_qformer=False,<br>)<br><br>training_args = TrainingArguments(<br>    run_name=&quot;VideoBlip-Classification&quot;,<br>    output_dir=OUTPUT_DIR,<br>    num_train_epochs=NUM_EPOCHS,<br>    per_device_train_batch_size=BATCH_SIZE,<br>    per_device_eval_batch_size=BATCH_SIZE,<br>    gradient_accumulation_steps=8,<br>    learning_rate=LEARNING_RATE,<br>    eval_strategy=&quot;epoch&quot;,<br>    save_strategy=&quot;epoch&quot;,<br>    load_best_model_at_end=True,<br>    metric_for_best_model=&quot;f1&quot;,<br>    greater_is_better=True,<br>    save_total_limit=2,<br>    remove_unused_columns=False,<br>    fp16=torch.cuda.is_available(),<br>    logging_steps=10,<br>    report_to=&quot;wandb&quot;,<br>)<br><br>trainer = VideoBlipTrainer(<br>    model=model,<br>    args=raining_args,<br>    train_dataset=train_dataset,<br>    eval_dataset=val_dataset,<br>    data_collator=collate_fn,<br>    compute_metrics=compute_metrics,<br>    callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],<br>)</pre><p><strong>References</strong></p><ul><li><a href="https://huggingface.co/docs/transformers/index">https://huggingface.co/docs/transformers/index</a></li><li><a href="https://huggingface.co/papers/2301.12597">https://huggingface.co/papers/2301.12597</a></li><li><a href="https://github.com/salesforce/LAVIS/tree/main/projects/blip2">https://github.com/salesforce/LAVIS/tree/main/projects/blip2</a></li><li><a href="https://github.com/huggingface/transformers/tree/main/src/transformers/models">https://github.com/huggingface/transformers/tree/main/src/transformers/models</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a3aaf40c34" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/fine-tuning-blip2-for-prompt-instructed-video-classification-e1a3aaf40c34">Fine-tuning BLIP2 for Prompt-instructed Video Classification</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Fine-tune Vision Transformers Using PEFT for Video Classification?]]></title>
            <link>https://pub.towardsai.net/how-to-fine-tune-vision-transformers-using-peft-for-video-classification-8425d5a6b1ab?source=rss-e0536b8dbd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/8425d5a6b1ab</guid>
            <category><![CDATA[peft]]></category>
            <category><![CDATA[vision-language-model]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[video-classification]]></category>
            <dc:creator><![CDATA[Kartikeya]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 11:22:21 GMT</pubDate>
            <atom:updated>2026-01-16T05:40:57.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Fine-tune Vision Transformers (ViT) for Video Classification with PEFT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0K0sFLINUBLfvnPXlHvKA.png" /><figcaption>Generated Using Gemini’s Nano Banana Pro</figcaption></figure><p>Vision Transformers (ViTs) and their variants, such as <em>Timesformer </em>and <em>ViViT</em>, pretrained on video understanding tasks, have set new benchmarks in computer vision. However, their enormous size (hundreds of millions or billions of parameters) makes full fine-tuning incredibly expensive, requiring large amounts of vRAM and training time. <strong>Parameter-Efficient Fine-Tuning (PEFT)</strong> techniques allow us to adapt these massive models to new tasks by training only a tiny fraction of their parameters.</p><p>The idea is to add a randomly initialized classification head on top of a pre-trained encoder and fine-tune the model as a whole on a labeled dataset using <strong>PEFT </strong>methods for efficient training.</p><blockquote>In this article, we’ll walk through a complete, generic pipeline for fine-tuning a Timesformer model for video classification using <strong>LoRA (Low-Rank Adaptation)</strong> and <strong>QLoRA</strong> (which adds 4-bit quantization for even greater memory savings). We will utilize <strong>PyTorchVideo </strong>for loading and processing video data, the<strong> peft </strong>library for defining LoRA configurations, and<strong> Transformers </strong>for loading and fine-tuning our vision backbone.</blockquote><h4><strong>The Core Idea: What is PEFT?</strong></h4><p>PEFT, or Parameter-Efficient Fine-Tuning, is a set of techniques that adapt large pre-trained models, such as language models (LLMs), for new tasks by training only a small subset of parameters, rather than the entire model.</p><p>The <a href="https://github.com/huggingface/peft">PEFT</a> library integrates popular PEFT techniques, such as LoRA, Prefix Tuning, AdaLoRA, Prompt Tuning, Multi-Task Prompt Tuning, and LoHa, with Transformers and Accelerate. This provides easy access to cutting-edge large language models with efficient and scalable fine-tuning.</p><h4><strong>LoRA</strong></h4><p>The architecture of the model using LoRA is depicted below, with the left side illustrating LoRA integrated into our Timesformer Model (for simplicity, we have shown a transformer encoder) and the right side detailing the specific structure of LoRA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*zdN-0-0hyK35Rl7IK9pmBw.png" /><figcaption>LoRA Integration in a Transformer Encoder</figcaption></figure><blockquote>In this tutorial, we inject LoRA in the following layers of our Timesformer Model :</blockquote><blockquote><strong>Target Modules </strong>: “‘dense’, ‘temporal_dense’, ‘qkv’</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEo3CLK0GOLpcyj4FE1Zcw.png" /><figcaption>Decomposing Weight Matrix into a lower rank representaion using LoRA</figcaption></figure><h3>Step-by-Step Guide to Fine-Tuning -</h3><h4>Install the Dependencies</h4><pre>pip install transformers peft bitsandbytes accelerate evaluate scikit-learn<br>pip install pytorchvideo</pre><h4>Dataset Preparation</h4><blockquote>For the training dataset transformations, we use a combination of uniform temporal subsampling, pixel normalization, random cropping, and random horizontal flipping. For the validation and evaluation dataset transformations, we maintain the transformation chain unchanged, except for random cropping and horizontal flipping. To learn more about the details of these transformations, refer to the <a href="https://www.google.com/url?q=https%3A%2F%2Fpytorchvideo.org">official PyTorch Video</a> documentation.</blockquote><blockquote>We will use the image_processor associated with the pre-trained model to obtain the following information:</blockquote><ul><li>Image mean and standard deviation: to normalize the video frame pixels.</li><li>Spatial resolution: to resize the video frames.</li></ul><pre>import pandas as pd<br>import torch<br>import logging<br>from pathlib import Path<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder<br>from pytorchvideo.data.labeled_video_dataset import LabeledVideoDataset<br>from pytorchvideo.data.clip_sampling import make_clip_sampler<br>from pytorchvideo.transforms import (<br>    ApplyTransformToKey, Normalize, RandomShortSideScale, UniformTemporalSubsample<br>)<br>from torchvision.transforms import Compose, Lambda, RandomCrop, RandomHorizontalFlip, Resize<br><br>logger = logging.getLogger(__name__)<br><br>def get_transforms(image_processor, num_frames, train=True):<br>    mean = image_processor.image_mean<br>    std = image_processor.image_std<br>    size = image_processor.size[&quot;shortest_edge&quot;]<br>    <br>    if train:<br>        return Compose([<br>            ApplyTransformToKey(key=&quot;video&quot;, transform=Compose([<br>                UniformTemporalSubsample(num_frames),<br>                Lambda(lambda x: x / 255.0),<br>                Normalize(mean=mean, std=std),<br>                RandomShortSideScale(min_size=256, max_size=320),<br>                RandomCrop((size, size)),<br>                RandomHorizontalFlip(p=0.5),<br>            ])),<br>        ])<br>    else:<br>        return Compose([<br>            ApplyTransformToKey(key=&quot;video&quot;, transform=Compose([<br>                UniformTemporalSubsample(num_frames),<br>                Lambda(lambda x: x / 255.0),<br>                Normalize(mean=mean, std=std),<br>                Resize((size, size)),<br>            ])),<br>        ])<br><br>def prepare_dataset(csv_path, video_root, label_col, video_col, clip_duration, num_frames, processor):<br>    &quot;&quot;&quot;<br>    Loader that handles N-classes automatically.<br>    &quot;&quot;&quot;<br>    # 1. Load Data<br>    df = pd.read_csv(csv_path)<br>    <br>    # 2. Encode Labels Dynamically<br>    le = LabelEncoder()<br>    df[&#39;encoded_label&#39;] = le.fit_transform(df[label_col].astype(str))<br>    <br>    # Create mappings for the Model Config later<br>    classes = list(le.classes_)<br>    label2id = {label: int(id) for id, label in enumerate(classes)}<br>    id2label = {int(id): label for id, label in enumerate(classes)}<br>    <br>    print(f&quot;Found {len(classes)} classes: {classes}&quot;)<br><br>    # 3. Split Data (Stratified)<br>    train_df, val_df = train_test_split(df, test_size=0.2, stratify=df[&#39;encoded_label&#39;], random_state=42)<br>    val_df, test_df = train_test_split(val_df, test_size=0.5, stratify=val_df[&#39;encoded_label&#39;], random_state=42)<br><br>    # 4. Helper to build path list<br>    def get_labeled_paths(d):<br>        paths = []<br>        for _, row in d.iterrows():<br>            # Resolve path: Root + Filename<br>            fname = Path(str(row[video_col])).name<br>            full_path = Path(video_root) / fname<br>            <br>            if full_path.exists():<br>                paths.append((str(full_path), {&quot;label&quot;: int(row[&#39;encoded_label&#39;])}))<br>        return paths<br><br>    # 5. Create PyTorchVideo Datasets<br>    train_ds = LabeledVideoDataset(<br>        get_labeled_paths(train_df),<br>        make_clip_sampler(&quot;random&quot;, clip_duration),<br>        transform=get_transforms(processor, num_frames, train=True),<br>        decode_audio=False<br>    )<br>    val_ds = LabeledVideoDataset(<br>        get_labeled_paths(val_df),<br>        make_clip_sampler(&quot;uniform&quot;, clip_duration),<br>        transform=get_transforms(processor, num_frames, train=False),<br>        decode_audio=False<br>    )<br>    test_ds = LabeledVideoDataset(<br>        get_labeled_paths(test_df),<br>        make_clip_sampler(&quot;uniform&quot;, clip_duration),<br>        transform=get_transforms(processor, num_frames, train=False),<br>        decode_audio=False<br>    )<br>    <br>    return train_ds, val_ds, test_ds, label2id, id2label</pre><h4>Model and Training Configuration</h4><pre>class Config:<br>    # Model Defaults<br>    MODEL_CHECKPOINT = &quot;facebook/timesformer-base-finetuned-k400&quot;<br>    <br>    # Preprocessing<br>    NUM_FRAMES = 8<br>    CLIP_DURATION = 8.0<br>   <br>    # Training<br>    BATCH_SIZE = 8<br>    GRAD_ACCUMULATION = 4<br>    EPOCHS = 10<br>    LR = 5e-5<br>    <br>    # PEFT Defaults<br>    LORA_R = 16<br>    LORA_ALPHA = 32<br>    LORA_DROPOUT = 0.1</pre><h4>Load Timesformer with PEFT Config (LoRA/QLoRA)</h4><pre>import torch<br>from transformers import TimesformerForVideoClassification, BitsAndBytesConfig<br>from peft import LoraConfig, get_peft_model<br><br>def find_linear_names(model, use_4bit=False):<br>    cls = torch.nn.Linear<br>    if use_4bit:<br>        import bitsandbytes as bnb<br>        cls = bnb.nn.Linear4bit<br>        <br>    lora_module_names = set()<br>    for name, module in model.named_modules():<br>        if isinstance(module, cls):<br>            names = name.split(&#39;.&#39;)<br>            lora_module_names.add(names[-1])<br>            <br>    if &#39;classifier&#39; in lora_module_names: lora_module_names.remove(&#39;classifier&#39;)<br>    return list(lora_module_names)<br><br>def get_model(method, model_ckpt, label2id, id2label, config):<br>    num_labels = len(label2id)<br>    print(f&quot;Initializing {method.upper()} model for {num_labels} classes.&quot;)<br>    <br>    # 1. QLoRA<br>    if method == &quot;qlora&quot;:<br>        bnb_config = BitsAndBytesConfig(<br>            load_in_4bit=True,<br>            bnb_4bit_use_double_quant=True,<br>            bnb_4bit_quant_type=&quot;nf4&quot;,<br>            bnb_4bit_compute_dtype=torch.bfloat16<br>        )<br>        model = TimesformerForVideoClassification.from_pretrained(<br>            model_ckpt, <br>            num_labels=num_labels, label2id=label2id, id2label=id2label,<br>            quantization_config=bnb_config,<br>            ignore_mismatched_sizes=True<br>        )<br>        target_modules = find_linear_names(model, use_4bit=True)<br>        <br>        peft_config = LoraConfig(<br>            r=config.LORA_R, lora_alpha=config.LORA_ALPHA,<br>            target_modules=target_modules, lora_dropout=config.LORA_DROPOUT,<br>            bias=&quot;none&quot;, modules_to_save=[&quot;classifier&quot;]<br>        )<br>        model = get_peft_model(model, peft_config)<br><br>    # 2. LoRA / DoRA<br>    elif method in [&quot;lora&quot;, &quot;dora&quot;]:<br>        model = TimesformerForVideoClassification.from_pretrained(<br>            model_ckpt, <br>            num_labels=num_labels, label2id=label2id, id2label=id2label,<br>            ignore_mismatched_sizes=True<br>        )<br>        target_modules = find_linear_names(model)<br>        peft_config = LoraConfig(<br>            r=config.LORA_R, lora_alpha=config.LORA_ALPHA,<br>            target_modules=target_modules, lora_dropout=config.LORA_DROPOUT,<br>            bias=&quot;none&quot;, modules_to_save=[&quot;classifier&quot;],<br>            use_dora=(method == &quot;dora&quot;)<br>        )<br>        model = get_peft_model(model, peft_config)<br><br>    # 3. Full Fine-Tuning<br>    else:<br>        model = TimesformerForVideoClassification.from_pretrained(<br>            model_ckpt, <br>            num_labels=num_labels, label2id=label2id, id2label=id2label,<br>            ignore_mismatched_sizes=True<br>        )<br>    return model</pre><h4>Train the Model Using HuggingFace Trainer</h4><blockquote>We will leverage <a href="https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fdocs%2Ftransformers%2Fmain_classes%2Ftrainer">Trainer</a> from Transformers for training the model. To instantiate a Trainer, we will need to define the training configuration and an evaluation metric. The most important is the <a href="https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Ftransformers%2Fmain_classes%2Ftrainer.html%23transformers.TrainingArguments">TrainingArguments</a> class, which has all the attributes to configure the training. It needs an output folder name to save the model’s checkpoints.</blockquote><blockquote>Most of the training arguments are relatively self-explanatory, but one that is particularly important here is remove_unused_columns=False. This one will drop any features not used by the model’s call function. By default, it is True because it is usually ideal to drop unused feature columns, making it easier to unpack inputs into the model’s call function. Nevertheless, in our case, we need the unused features (‘video’ in particular) in order to create pixel_values (which is an important key our model expects in its inputs).</blockquote><pre>import argparse<br>import os<br>import torch<br>import numpy as np<br>import evaluate<br>from transformers import AutoImageProcessor, TrainingArguments, Trainer, EarlyStoppingCallback<br>from config import Config<br>from src.dataset import prepare_dataset<br>from src.model import get_model<br><br>class CustomTrainer(Trainer):<br>    def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None):<br>        model.eval()<br>        inputs = self._prepare_inputs(inputs)<br>        with torch.no_grad():<br>            outputs = model(**inputs)<br>            loss = outputs.loss<br>            logits = outputs.logits<br>        return (loss, logits, inputs.get(&quot;labels&quot;))<br><br>def compute_metrics(eval_pred):<br>    metric_acc = evaluate.load(&quot;accuracy&quot;)<br>    preds = np.argmax(eval_pred.predictions, axis=-1)<br>    return {<br>        &quot;accuracy&quot;: metric_acc.compute(predictions=preds, references=eval_pred.label_ids)[&quot;accuracy&quot;],<br>    }<br><br>def collate_fn(examples):<br>    pixel_values = torch.stack([ex[&quot;video&quot;].permute(1, 0, 2, 3) for ex in examples])<br>    labels = torch.tensor([ex[&quot;label&quot;] for ex in examples])<br>    return {&quot;pixel_values&quot;: pixel_values, &quot;labels&quot;: labels}<br><br>def main():<br>    parser = argparse.ArgumentParser(description=&quot;Video Classifier&quot;)<br>    parser.add_argument(&quot;--csv_path&quot;, type=str, required=True)<br>    parser.add_argument(&quot;--video_root&quot;, type=str, required=True)<br>    parser.add_argument(&quot;--label_col&quot;, type=str, required=True, help=&quot;Column name for labels&quot;)<br>    parser.add_argument(&quot;--video_col&quot;, type=str, default=&quot;videoPath&quot;, help=&quot;Column name for filenames&quot;)<br>    parser.add_argument(&quot;--method&quot;, type=str, default=&quot;lora&quot;, choices=[&quot;lora&quot;, &quot;qlora&quot;, &quot;dora&quot;, &quot;full&quot;])<br>    parser.add_argument(&quot;--output_dir&quot;, type=str, default=&quot;./output&quot;)<br>    args = parser.parse_args()<br><br>    # 1. Processor<br>    processor = AutoImageProcessor.from_pretrained(Config.MODEL_CHECKPOINT)<br><br>    # 2. Data Preparation<br>    print(f&quot;Analyzing {args.csv_path} for labels in column &#39;{args.label_col}&#39;...&quot;)<br>    train_ds, val_ds, test_ds, label2id, id2label = prepare_dataset(<br>        args.csv_path, args.video_root, args.label_col, args.video_col,<br>        Config.CLIP_DURATION, Config.NUM_FRAMES, processor<br>    )<br>    print(f&quot;Data Loaded: Train={len(train_ds)}, Val={len(val_ds)}, Classes={len(label2id)}&quot;)<br><br>    # 3. Model<br>    model = get_model(args.method, Config.MODEL_CHECKPOINT, label2id, id2label, Config)<br><br>    # 4. Configure Trainer<br>    training_args = TrainingArguments(<br>        output_dir=args.output_dir,<br>        remove_unused_columns=False,<br>        eval_strategy=&quot;epoch&quot;,<br>        save_strategy=&quot;epoch&quot;,<br>        learning_rate=Config.LR,<br>        per_device_train_batch_size=Config.BATCH_SIZE,<br>        per_device_eval_batch_size=Config.BATCH_SIZE,<br>        gradient_accumulation_steps=Config.GRAD_ACCUMULATION,<br>        warmup_ratio=0.1,<br>        logging_steps=10,<br>        load_best_model_at_end=True,<br>        metric_for_best_model=&quot;accuracy&quot;,<br>        num_train_epochs=Config.EPOCHS,<br>        report_to=&quot;wandb&quot;,<br>    )<br><br>    trainer = CustomTrainer(<br>        model=model, args=training_args, train_dataset=train_ds, eval_dataset=val_ds,<br>        data_collator=collate_fn, compute_metrics=compute_metrics,<br>        callbacks=[EarlyStoppingCallback(early_stopping_patience=5)]<br>    )<br><br>    print(&quot;Starting Training...&quot;)<br>    trainer.train()<br>    trainer.save_model(os.path.join(args.output_dir, &quot;best_model&quot;))<br>    print(trainer.evaluate(test_ds))<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>References:</h4><ul><li><a href="https://github.com/huggingface/peft">https://github.com/huggingface/peft</a></li><li><a href="https://pytorchvideo.org/">https://pytorchvideo.org/</a></li><li><a href="https://huggingface.co/docs/transformers/index">https://huggingface.co/docs/transformers/index</a></li><li><a href="https://huggingface.co/blog/fine-tune-vit">https://huggingface.co/blog/fine-tune-vit</a></li><li><a href="https://huggingface.co/docs/transformers/tasks/video_classification">https://huggingface.co/docs/transformers/tasks/video_classification</a></li><li><a href="https://huggingface.co/docs/transformers/en/model_doc/timesformer">https://huggingface.co/docs/transformers/en/model_doc/timesformer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8425d5a6b1ab" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-to-fine-tune-vision-transformers-using-peft-for-video-classification-8425d5a6b1ab">How to Fine-tune Vision Transformers Using PEFT for Video Classification?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>