Views
No views yet
transformers library. Ensure trust_remote_code=True is set for proper model loading. For video input, you will typically provide a list of image frames (PIL Images).decord to easily load video frames. Install it via pip install decord.1from transformers import AutoModelForCausalLM, AutoTokenizer, AutoProcessor
2from PIL import Image
3import torch
4import numpy as np
5from decord import VideoReader, cpu # For video loading
6
7# Load model and processor
8model_id = "VITA-MLLM/Sparrow-Llama3-V-2_5" # Replace with the actual model ID if different
9model = AutoModelForCausalLM.from_pretrained(
10 model_id,
11 torch_dtype=torch.bfloat16, # Use bfloat16 for better performance/memory
12 device_map="auto",
13 trust_remote_code=True
14)
15tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
16processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
17
18# --- Example: Load video frames ---
19video_path = "path/to/your/video.mp4" # <--- IMPORTANT: Replace with your video file path!
20video_frames = []
21try:
22 vr = VideoReader(video_path, ctx=cpu(0))
23 # Sample a maximum of 32 frames uniformly for demonstration
24 total_frames = len(vr)
25 num_frames_to_sample = min(total_frames, 32)
26 frame_indices = np.linspace(0, total_frames - 1, num_frames_to_sample, dtype=int)
27
28 video_frames = [Image.fromarray(vr[i].asnumpy()) for i in frame_indices]
29 print(f"Loaded {len(video_frames)} frames from {video_path}")
30except Exception as e:
31 print(f"Could not load video from {video_path}: {e}")
32 print("Using placeholder images for demonstration. Please provide a valid video file.")
33 video_frames = [Image.new("RGB", (224, 224), color="blue")] * 4 # Fallback to placeholder images
34
35
36# --- Prepare prompt with video frames ---
37# The <video> tag is specific to MiniCPM-V models for indicating video/image input.
38# It should be repeated for each image frame provided.
39messages = [
40 {"role": "user", "content": "<video>" * len(video_frames) + "
41Describe this video in detail."}
42]
43
44# Apply chat template and tokenize inputs
45inputs = processor.apply_chat_template(
46 messages,
47 video=video_frames, # Pass the list of PIL Images here
48 tokenize=True,
49 add_generation_prompt=True,
50 return_tensors="pt"
51)
52
53# Move inputs to appropriate device (e.g., GPU)
54inputs = {k: v.to(model.device) for k, v in inputs.items()}
55
56# --- Generate response ---
57with torch.no_grad():
58 generated_ids = model.generate(
59 input_ids=inputs["input_ids"],
60 attention_mask=inputs["attention_mask"],
61 image_pixel_values=inputs["image_pixel_values"], # Essential for vision inputs
62 max_new_tokens=256, # Adjust as needed
63 do_sample=True,
64 temperature=0.7,
65 top_p=0.9,
66 )
67
68# Decode and print the output
69response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
70# Clean up any potential chat template artifacts at the beginning/end
71response = response.split('<|start_header_id|>assistant<|end_header_id|>')[-1].strip()
72
73print("
74Generated Response:")
75print(response)
76