Views
No views yet
[!Important] This is the Base model. The instruct model is at LiveCC-7B-Instruct.


pip install qwen-vl-utils livecc-utils liger_kerneltransformers and the above utils:1import functools, torch, os, tqdm
2from liger_kernel.transformers import apply_liger_kernel_to_qwen2_vl
3apply_liger_kernel_to_qwen2_vl() # important. our model is trained with this. keep consistency
4from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, LogitsProcessor, logging
5from livecc_utils import prepare_multiturn_multimodal_inputs_for_generation, get_smart_resized_clip, get_smart_resized_video_reader
6from qwen_vl_utils import process_vision_info
7
8class LiveCCDemoInfer:
9 fps = 2
10 initial_fps_frames = 6
11 streaming_fps_frames = 2
12 initial_time_interval = initial_fps_frames / fps
13 streaming_time_interval = streaming_fps_frames / fps
14 frame_time_interval = 1 / fps
15 def __init__(self, model_path: str = None, device_id: int = 0):
16 self.model = Qwen2VLForConditionalGeneration.from_pretrained(
17 model_path, torch_dtype="auto",
18 device_map=f'cuda:{device_id}',
19 attn_implementation='flash_attention_2'
20 )
21 self.processor = AutoProcessor.from_pretrained(model_path, use_fast=False)
22 self.model.prepare_inputs_for_generation = functools.partial(prepare_multiturn_multimodal_inputs_for_generation, self.model)
23 message = {
24 "role": "user",
25 "content": [
26 {"type": "text", "text": 'livecc'},
27 ]
28 }
29 texts = self.processor.apply_chat_template([message], tokenize=False)
30 self.system_prompt_offset = texts.index('<|im_start|>user')
31 self._cached_video_readers_with_hw = {}
32
33
34 def live_cc(
35 self,
36 query: str,
37 state: dict,
38 max_pixels: int = 384 * 28 * 28,
39 default_query: str = 'Please describe the video.',
40 do_sample: bool = True,
41 repetition_penalty: float = 1.05,
42 **kwargs,
43 ):
44 """
45 state: dict, (maybe) with keys:
46 video_path: str, video path
47 video_timestamp: float, current video timestamp
48 last_timestamp: float, last processed video timestamp
49 last_video_pts_index: int, last processed video frame index
50 video_pts: np.ndarray, video pts
51 last_history: list, last processed history
52 past_key_values: llm past_key_values
53 past_ids: past generated ids
54 """
55 # 1. preparation: video_reader, and last processing info
56 video_timestamp, last_timestamp = state.get('video_timestamp', 0), state.get('last_timestamp', -1 / self.fps)
57 video_path = state['video_path']
58 if video_path not in self._cached_video_readers_with_hw:
59 self._cached_video_readers_with_hw[video_path] = get_smart_resized_video_reader(video_path, max_pixels)
60 video_reader = self._cached_video_readers_with_hw[video_path][0]
61 video_reader.get_frame_timestamp(0)
62 state['video_pts'] = torch.from_numpy(video_reader._frame_pts[:, 1])
63 state['last_video_pts_index'] = -1
64 video_pts = state['video_pts']
65 if last_timestamp + self.frame_time_interval > video_pts[-1]:
66 state['video_end'] = True
67 return
68 video_reader, resized_height, resized_width = self._cached_video_readers_with_hw[video_path]
69 last_video_pts_index = state['last_video_pts_index']
70
71 # 2. which frames will be processed
72 initialized = last_timestamp >= 0
73 if not initialized:
74 video_timestamp = max(video_timestamp, self.initial_time_interval)
75 if video_timestamp <= last_timestamp + self.frame_time_interval:
76 return
77 timestamps = torch.arange(last_timestamp + self.frame_time_interval, video_timestamp, self.frame_time_interval) # add compensation
78
79 # 3. fetch frames in required timestamps
80 clip, clip_timestamps, clip_idxs = get_smart_resized_clip(video_reader, resized_height, resized_width, timestamps, video_pts, video_pts_index_from=last_video_pts_index+1)
81 state['last_video_pts_index'] = clip_idxs[-1]
82 state['last_timestamp'] = clip_timestamps[-1]
83
84 # 4. organize to interleave frames
85 interleave_clips, interleave_timestamps = [], []
86 if not initialized:
87 interleave_clips.append(clip[:self.initial_fps_frames])
88 interleave_timestamps.append(clip_timestamps[:self.initial_fps_frames])
89 clip = clip[self.initial_fps_frames:]
90 clip_timestamps = clip_timestamps[self.initial_fps_frames:]
91 if len(clip) > 0:
92 interleave_clips.extend(list(clip.split(self.streaming_fps_frames)))
93 interleave_timestamps.extend(list(clip_timestamps.split(self.streaming_fps_frames)))
94
95 # 5. make conversation and send to model
96 for clip, timestamps in zip(interleave_clips, interleave_timestamps):
97 start_timestamp, stop_timestamp = timestamps[0].item(), timestamps[-1].item() + self.frame_time_interval
98 message = {
99 "role": "user",
100 "content": [
101 {"type": "text", "text": f'Time={start_timestamp:.1f}-{stop_timestamp:.1f}s'},
102 {"type": "video", "video": clip}
103 ]
104 }
105 if not query and not state.get('query', None):
106 query = default_query
107 print(f'No query provided, use default_query={default_query}')
108 if query and state.get('query', None) != query:
109 message['content'].append({"type": "text", "text": query})
110 state['query'] = query
111 texts = self.processor.apply_chat_template([message], tokenize=False, add_generation_prompt=True, return_tensors='pt')
112 past_ids = state.get('past_ids', None)
113 if past_ids is not None:
114 texts = '<|im_end|>\n' + texts[self.system_prompt_offset:]
115 inputs = self.processor(
116 text=texts,
117 images=None,
118 videos=[clip],
119 return_tensors="pt",
120 return_attention_mask=False
121 )
122 inputs.to('cuda')
123 if past_ids is not None:
124 inputs['input_ids'] = torch.cat([past_ids, inputs.input_ids], dim=1)
125 outputs = self.model.generate(
126 **inputs, past_key_values=state.get('past_key_values', None),
127 return_dict_in_generate=True, do_sample=do_sample,
128 repetition_penalty=repetition_penalty,
129 )
130 state['past_key_values'] = outputs.past_key_values
131 state['past_ids'] = outputs.sequences[:, :-1]
132 yield (start_timestamp, stop_timestamp), self.processor.decode(outputs.sequences[0, inputs.input_ids.size(1):], skip_special_tokens=True), state
133
134model_path = 'chenjoya/LiveCC-7B-Base'
135# download a test video at: https://github.com/showlab/livecc/blob/main/demo/sources/howto_fix_laptop_mute_1080p.mp4
136video_path = "demo/sources/howto_fix_laptop_mute_1080p.mp4"
137query = "Please describe the video."
138
139infer = LiveCCDemoInfer(model_path=model_path)
140state = {'video_path': video_path}
141commentaries = []
142t = 0
143for t in range(31):
144 state['video_timestamp'] = t
145 for (start_t, stop_t), response, state in infer.live_cc(
146 query=query, state=state,
147 max_pixels = 384 * 28 * 28, repetition_penalty=1.05,
148 streaming_eos_base_threshold=0.0, streaming_eos_threshold_step=0
149 ):
150 print(f'{start_t}s-{stop_t}s: {response}')
151 commentaries.append([start_t, stop_t, response])
152 if state.get('video_end', False):
153 break
154 t += 1@article{livecc,
author = {Joya Chen and Ziyun Zeng and Yiqi Lin and Wei Li and Zejun Ma and Mike Zheng Shou},
title = {LiveCC: Learning Video LLM with Streaming Speech Transcription at Scale},
journal = {arXiv preprint arXiv:2504.16030}
year = {2025},
}