Views
No views yet

1from longva.model.builder import load_pretrained_model
2from longva.mm_utils import tokenizer_image_token, process_images
3from longva.constants import IMAGE_TOKEN_INDEX
4from PIL import Image
5from decord import VideoReader, cpu
6import torch
7import numpy as np
8# fix seed
9torch.manual_seed(0)
10
11model_path = "lmms-lab/LongVA-7B-DPO"
12image_path = "local_demo/assets/lmms-eval.png"
13video_path = "local_demo/assets/dc_demo.mp4"
14max_frames_num = 16 # you can change this to several thousands so long you GPU memory can handle it :)
15gen_kwargs = {"do_sample": True, "temperature": 0.5, "top_p": None, "num_beams": 1, "use_cache": True, "max_new_tokens": 1024}
16tokenizer, model, image_processor, _ = load_pretrained_model(model_path, None, "llava_qwen", device_map="cuda:0")
17
18#image input
19prompt = "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<image>\nDescribe the image in details.<|im_end|>\n<|im_start|>assistant\n"
20input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(model.device)
21image = Image.open(image_path).convert("RGB")
22images_tensor = process_images([image], image_processor, model.config).to(model.device, dtype=torch.float16)
23with torch.inference_mode():
24 output_ids = model.generate(input_ids, images=images_tensor, image_sizes=[image.size], modalities=["image"], **gen_kwargs)
25outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
26print(outputs)
27print("-"*50)
28
29#video input
30prompt = "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<image>\nGive a detailed caption of the video as if I am blind.<|im_end|>\n<|im_start|>assistant\n"
31input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(model.device)
32vr = VideoReader(video_path, ctx=cpu(0))
33total_frame_num = len(vr)
34uniform_sampled_frames = np.linspace(0, total_frame_num - 1, max_frames_num, dtype=int)
35frame_idx = uniform_sampled_frames.tolist()
36frames = vr.get_batch(frame_idx).asnumpy()
37video_tensor = image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(model.device, dtype=torch.float16)
38with torch.inference_mode():
39 output_ids = model.generate(input_ids, images=[video_tensor], modalities=["video"], **gen_kwargs)
40outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
41print(outputs)