Video-Text-to-Text
Transformers
Safetensors
English
Chinese
moss_vl
feature-extraction
MOSS-VL
realtime
streaming
video-understanding
bitsandbytes
NF4
quantized
custom_code
4-bit precision
Run this model with HF Jobs
Run OpenMOSS-Team/MOSS-VL-Realtime-NF4 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/OpenMOSS-Team/MOSS-VL-Realtime-NF4. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/OpenMOSS-Team/MOSS-VL-Realtime-NF4 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use OpenMOSS-Team/MOSS-VL-Realtime-NF4 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenMOSS-Team/MOSS-VL-Realtime-NF4 with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("OpenMOSS-Team/MOSS-VL-Realtime-NF4", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
fix: apply query RoPE when reusing cached vision KV; align processor with the 0708 standard
Browse filesFiles changed (5)
- modeling_moss_vl.py+6-5
- preprocessor_config.json+25-43
- processing_moss_vl.py+130-125
- video_preprocessor_config.json+29-47
- video_processing_moss_vl.py+194-117
643 unmodified lines6446456466476486493 unmodified lines653654655656657658659660661662663643 unmodified linesquery_states = query_states.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)query_states = self.q_norm(query_states)if cross_attention_states is not None:# Key and Value from vision cross_attention_stateskey_states = self.k_proj(cross_attention_states)3 unmodified lineskey_states = self.k_norm(key_states)value_states = value_states.view(batch_size, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)# Apply different RoPE for query (text position) and key (vision position)if query_position_embeddings is not None:cos, sin = query_position_embeddingsquery_states = apply_rotary_pos_emb_cross_attention(query_states, cos, sin)if vision_position_embeddings is not None:vision_cos, vision_sin = vision_position_embeddingskey_states = apply_rotary_pos_emb_cross_attention(key_states, vision_cos, vision_sin)643 unmodified lines6446456466476486496506516526536543 unmodified lines658659660661662663664643 unmodified linesquery_states = query_states.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)query_states = self.q_norm(query_states)# Every new query needs RoPE, including reads from the vision KV cache.if query_position_embeddings is not None:cos, sin = query_position_embeddingsquery_states = apply_rotary_pos_emb_cross_attention(query_states, cos, sin)if cross_attention_states is not None:# Key and Value from vision cross_attention_stateskey_states = self.k_proj(cross_attention_states)3 unmodified lineskey_states = self.k_norm(key_states)value_states = value_states.view(batch_size, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)# Rotate new keys once; cached keys already include vision RoPE.if vision_position_embeddings is not None:vision_cos, vision_sin = vision_position_embeddingskey_states = apply_rotary_pos_emb_cross_attention(key_states, vision_cos, vision_sin)
1234567891011121314151617181920212223242526272829303132333435363738394041424344{"auto_map": {"AutoImageProcessor": "processing_moss_vl.MossVLImageProcessorFast","AutoProcessor": "processing_moss_vl.MossVLProcessor"},"crop_size": null,"data_format": "channels_first","default_to_square": true,"device": null,"disable_grouping": null,"do_center_crop": null,"do_convert_rgb": true,"do_normalize": true,"do_pad": null,"do_rescale": true,"do_resize": true,"image_mean": [0.5,0.5,0.5],"image_processor_type": "MossVLImageProcessorFast","image_std": [0.5,0.5,0.5],"input_data_format": null,"max_pixels": null,"merge_size": 2,"min_pixels": null,"multi_image_max_pixels": 65536000,"pad_size": null,"patch_size": 16,"processor_class": "MossVLProcessor","resample": 3,"rescale_factor": 0.00392156862745098,"return_tensors": null,"size": {"longest_edge": 16777216,"shortest_edge": 4096},"temporal_patch_size": 1}1234567891011121314151617181920212223242526{"auto_map": {"AutoProcessor": "processing_moss_vl.MossVLProcessor","AutoImageProcessor": "processing_moss_vl.MossVLImageProcessorFast"},"size": {"longest_edge": 16777216,"shortest_edge": 4096},"multi_image_max_pixels": 201326592,"patch_size": 16,"temporal_patch_size": 1,"merge_size": 2,"image_mean": [0.5,0.5,0.5],"image_std": [0.5,0.5,0.5],"processor_class": "MossVLProcessor","image_processor_type": "MossVLImageProcessorFast"}
48 unmodified lines4950515253545514 unmodified lines707172737475762 unmodified lines7980818283848512 unmodified lines98991001011021031041051061071081091108 unmodified lines11912012112212312412538 unmodified lines16416516616716816917017117217317417511 unmodified lines1871881891901911921931941951961971981992002012022031 unmodified line205206207208209210211212213214215113 unmodified lines3293303313323333343353363373383393403413423433443453463473484 unmodified lines3533543553563573583597 unmodified lines36736836937037137237337437537637737837938038157 unmodified lines43944044144244344444523 unmodified lines46947047147247347447547647747847948010 unmodified lines4914924934944954964974984995004 unmodified lines50550650750850951051151251351451551651751851952052152252352452552652752852924 unmodified lines55455555655755855956010 unmodified lines57157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260331 unmodified lines6356366376386396406416426436442 unmodified lines64764864965065165265365465565665765865966066166266366466566666766813 unmodified lines6826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297301 unmodified line7327337347357367377387397407417427437447457467477487497507517527537547557567578 unmodified lines7667677687697707717727737747757767777787797807817827836 unmodified lines7907917927937947957967977987998008018028038048058068072 unmodified lines8108118128138148158162 unmodified lines8198208218228238248252 unmodified lines8288298308318328338345 unmodified lines8408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768775 unmodified lines8838848858868878888898908918928938948958968978988999009019029039049059069076 unmodified lines9149159169179189199209219229239249259269271 unmodified line9299309319329339349359369379389399409419423 unmodified lines9469479489499509519529539549559569576 unmodified lines9649659669679689699702 unmodified lines9739749759769779789799809819822 unmodified lines985986987988989990991992993994995996997998999100010011002100310042 unmodified lines10071008100910101011101210132 unmodified lines10161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491 unmodified line10511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410757 unmodified lines10831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110613 unmodified lines112011211122112311241125112648 unmodified lines"""# Multi-image batch total pixels limit (read from config)multi_image_max_pixels = Nonedef _preprocess(self,14 unmodified lines**kwargs,):"""Override _preprocess to use custom smart_resize with batch-level max_pixels.multi_image_max_pixels is treated as a batch-level total budget, proportionally allocatedto each image based on its original pixel count. min_pixels remains a per-imageconstraint. multi_image_max_pixels can be configured separately from longest_edge.2 unmodified linesmax_pixels = size["longest_edge"] # Per-image upper limit# Use multi_image_max_pixels if configured, otherwise fall back to longest_edgemulti_image_max_pixels = getattr(self, "multi_image_max_pixels", None) or max_pixels# Calculate total original pixels across all images in the batch# This is used to proportionally allocate max_pixels to each imagetotal_original_pixels = sum(img.shape[-2] * img.shape[-1] for img in images)12 unmodified linesproportional_max_pixels = int(multi_image_max_pixels * proportion)else:proportional_max_pixels = multi_image_max_pixels# Ensure proportional max_pixels is within [min_pixels, max_pixels] range# min_pixels: per-image lower limit (shortest_edge)# max_pixels: per-image upper limit (longest_edge)proportional_max_pixels = max(proportional_max_pixels, min_pixels)proportional_max_pixels = min(proportional_max_pixels, max_pixels)resized_height, resized_width = smart_resize(height,width,8 unmodified lines)resized_images_grouped[shape] = stacked_imagesresized_images = reorder_images(resized_images_grouped, grouped_images_index)# Warn if multi-image batch exceeds multi_image_max_pixels due to min_pixels constraintif len(images) > 1:total_resized_pixels = sum(img.shape[-2] * img.shape[-1] for img in resized_images)38 unmodified lines)# Reorder dimensions to group grid and patch information for subsequent flattening.# (batch, grid_t, grid_h, grid_w, merge_h, merge_w, channel, temp_patch_size, patch_h, patch_w)patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)flatten_patches = patches.reshape(batch_size,grid_t * grid_h * grid_w,channel * temporal_patch_size * patch_size * patch_size,)processed_images_grouped[shape] = flatten_patchesprocessed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size11 unmodified lines"""Convert various tensor types to numpy array.Supports torch.Tensor, tf.Tensor, jax.Array, np.ndarray, lists, and primitives.Args:x: Input value that can be a tensor from various frameworks or a Python primitiveReturns:np.ndarray: NumPy array representation of the input"""# Already numpyif isinstance(x, np.ndarray):return x# Torch tensor or TensorFlow tensor (both have .numpy() method)if hasattr(x, 'numpy'):# For torch tensors on CUDA, need to move to CPU first1 unmodified linereturn x.cpu().numpy()# For TensorFlow or already on CPUreturn x.numpy()# JAX arrays and other array-like objects that support __array__ protocolif hasattr(x, '__array__'):return np.asarray(x)# Python primitives (list, tuple, int, float)return np.array(x)113 unmodified linestokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")def __init__(self,image_processor=None,tokenizer=None,video_processor=None,chat_template=None,**kwargs):super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_tokenself.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_tokenself.image_token_id = (tokenizer.image_token_idif getattr(tokenizer, "image_token_id", None)4 unmodified linesif getattr(tokenizer, "video_token_id", None)else tokenizer.convert_tokens_to_ids(self.video_token))self.vision_start_token = ("<|vision_start|>" if not hasattr(tokenizer, "vision_start_token") else tokenizer.vision_start_token)7 unmodified linesself.time_start_token = "<|time_start|>"self.time_end_token = "<|time_end|>"# EOS token for labels generation (assistant's response should end with this)self.im_end_token = "<|im_end|>"self.im_end_token_id = tokenizer.convert_tokens_to_ids(self.im_end_token)# Vision-related token ids (all should be masked in labels)self.vision_start_token_id = tokenizer.convert_tokens_to_ids(self.vision_start_token)self.vision_end_token_id = tokenizer.convert_tokens_to_ids(self.vision_end_token)# Token ids that should always be masked in labels (e.g. <|image_pad|>)self.mask_token_ids = {self.image_token_id}57 unmodified linestokenizer_init_kwargs=self.tokenizer.init_kwargs,**kwargs,)# Step 1: Process images if providedif images is not None:images_kwargs = output_kwargs["images_kwargs"].copy()23 unmodified lines# Step 3: Process text with placeholder replacementif text is None or (isinstance(text, str) and len(text.strip()) == 0):raise ValueError("Text input is required for MossVL processor and cannot be empty.")if not isinstance(text, list):text = [text]text = text.copy() # Copy to avoid in-place modifications# Prepare labels_spans if provided# labels_spans format: List[List[List[int]]] - batch of samples, each sample has multiple spans# Each span is [start, end] (list, not tuple) so it can be modified in place10 unmodified lineshas_images = images is not None and "pixel_values" in image_inputshas_videos = videos is not None and "pixel_values_videos" in videos_inputsneeds_reorder = has_images and has_videosimage_pixel_values_list = []video_pixel_values_list = []# Step 3.0: Record the order of media in original text (before replacement)# This will be used later to correctly order pixel_values and grid_thwmedia_order_per_sample = []4 unmodified lineswhile pos < len(temp_text):img_pos = temp_text.find(self.image_placeholder, pos)vid_pos = temp_text.find(self.video_placeholder, pos)if img_pos == -1 and vid_pos == -1:breakif img_pos != -1 and (vid_pos == -1 or img_pos < vid_pos):media_order.append(("image", img_pos))pos = img_pos + len(self.image_placeholder)elif vid_pos != -1:media_order.append(("video", vid_pos))pos = vid_pos + len(self.video_placeholder)media_order_per_sample.append(media_order)# Step 3.0.1: Check if any sample has no media (empty samples need blank image)# If there are empty samples, we need to enter slow path to handle them properlyhas_empty_samples = any(len(order) == 0 for order in media_order_per_sample)if has_empty_samples:needs_reorder = True# Split pixel values for reordering if neededif needs_reorder:if has_images:24 unmodified linesvideo_pixel_values_list = _split_array_or_tensor(flat_video_values, split_indices)# Step 3.1: Replace placeholders (simple replacement, no expansion yet)# In MossVL, one image placeholder = one image token# One video placeholder = one video token (will be expanded later)10 unmodified lineselse:text[i] = text[i].replace(self.image_placeholder, self.image_token)text[i] = text[i].replace(self.video_placeholder, self.video_token)# Step 3.2: Validate token countsn_images_in_text = [t.count(self.image_token) for t in text]n_videos_in_text = [t.count(self.video_token) for t in text]# Count placeholders in texttotal_images_in_text = sum(n_images_in_text)total_videos_in_text = sum(n_videos_in_text)# Count actual images and videos providedtotal_images_provided = len(image_grid_thw) if image_grid_thw is not None else 0total_videos_provided = len(video_grid_thw) if video_grid_thw is not None else 0# Validate image countsif total_images_in_text != total_images_provided:raise ValueError("Number of image tokens does not match number of images provided. "f"Found {total_images_in_text} image tokens in text and {total_images_provided} images.")# Validate video countsif total_videos_in_text != total_videos_provided:raise ValueError("Number of video tokens does not match number of videos provided. "f"Found {total_videos_in_text} video tokens in text and {total_videos_provided} videos.")# Step 3.3: Expand video tokens with timestamps# Now expand each video token to multiple tokens (one per frame) with timestampsif video_grid_thw is not None:31 unmodified linesvideo_tokens.append(f"{self.time_start_token}{curr_time:.1f} seconds{self.time_end_token}{self.image_token}")# Wrap the entire video sequence with vision_start and vision_end tokensvideo_placeholder = f"{self.vision_start_token}{''.join(video_tokens)}{self.vision_end_token}"# Replace the video token with expanded sequence and update spans if neededif should_create_labels:text[i], labels_spans[i] = self._replace_and_update_spans(2 unmodified lineselse:text[i] = text[i].replace(self.video_token, video_placeholder, 1)index += 1# Step 4: Tokenize textreturn_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)# Request offset_mapping if we need to create labelsif should_create_labels:output_kwargs["text_kwargs"]["return_offsets_mapping"] = Truetext_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])# ignore check_special_mm_tokens nums in test and input ids.# self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])# Create labels if labels_spans was providedif should_create_labels:offset_mapping = text_inputs.pop("offset_mapping")13 unmodified lines# Step 5: Concatenate pixel_values and grid_thw in sequence order# Prepare outputoutput_data = {**text_inputs}if not needs_reorder:# Fast path: only one media type, no reordering neededfinal_pixel_values = []final_grid_thw = []if has_images:final_pixel_values.append(image_inputs["pixel_values"])final_grid_thw.extend(image_grid_thw)if has_videos:final_pixel_values.append(videos_inputs["pixel_values_videos"])final_grid_thw.extend(video_grid_thw)if final_pixel_values:output_data["pixel_values"] = np.concatenate(final_pixel_values, axis=0) if len(final_pixel_values) > 1 else final_pixel_values[0]if final_grid_thw:output_data["grid_thw"] = np.stack(final_grid_thw, axis=0)# Calculate media_nums_per_samplemedia_nums_per_sample = []for batch_idx in range(len(text)):media_order = media_order_per_sample[batch_idx]media_nums_per_sample.append(len(media_order) if len(media_order) > 0 else 1)# Don't add media_nums_per_sample to output_data yet# Will add it after BatchFeature to keep it as listelse:# Slow path: both images and videos exist, need reorderingfinal_pixel_values = []final_grid_thw = []media_nums_per_sample = []# Global indices to track position in flattened image/video arraysglobal_image_idx = 0global_video_idx = 0for batch_idx in range(len(text)):# Use the recorded media order from Step 3.0media_order = media_order_per_sample[batch_idx]if len(media_order) == 0:# If no media provided for this sample, add a blank imagemedia_nums_per_sample.append(1)1 unmodified linepatch_size = getattr(self.image_processor, "patch_size", None) or 16temporal_patch_size = getattr(self.image_processor, "temporal_patch_size", None) or 1merge_size = getattr(self.image_processor, "merge_size", None) or 2factor = patch_size * merge_sizeside = int(np.ceil(np.sqrt(min_pixels) / factor) * factor)grid_h = side // patch_sizegrid_w = side // patch_sizegrid_t = 1# Channel = 3 (RGB)channel = 3dim = channel * temporal_patch_size * patch_size * patch_sizenum_patches = grid_t * grid_h * grid_wblank_pixel_values = np.zeros((num_patches, dim), dtype=np.float32)blank_grid_thw = np.array([grid_t, grid_h, grid_w], dtype=np.int64)final_pixel_values.append(blank_pixel_values)final_grid_thw.append(blank_grid_thw)else:media_nums_per_sample.append(len(media_order))# Collect media data according to the recorded orderfor media_type, _ in media_order:if media_type == "image" and image_grid_thw is not None:8 unmodified linesfinal_pixel_values.append(video_pixel_values_list[global_video_idx])final_grid_thw.append(video_grid_thw[global_video_idx])global_video_idx += 1# Concatenate/stack to unified formatif final_pixel_values:output_data["pixel_values"] = _concat_array_or_tensor(final_pixel_values, axis=0)if final_grid_thw:output_data["grid_thw"] = _stack_array_or_tensor(final_grid_thw, axis=0)# Don't add media_nums_per_sample to output_data yet# Will add it after BatchFeature to keep it as list6 unmodified linesoutput_data.get("attention_mask", None))output_data["cross_attention_mask"] = cross_attention_mask# Add labels to output if createdif should_create_labels:output_data["labels"] = labels# BatchFeature will handle conversion to pt/tf/jax/np based on tensor_typebatch_feature = BatchFeature(data=output_data, tensor_type=return_tensors)# Add media_nums_per_sample after BatchFeature to keep it as list (not tensor)if media_nums_per_sample:batch_feature["media_nums_per_sample"] = media_nums_per_samplereturn batch_featuredef _create_cross_attention_mask(self, input_ids, grid_thw, media_nums_per_sample, attention_mask=None):2 unmodified linesVideo frames are treated as individual images.Mask values: True for masked, False for visible.Causal masking: text can see images that appear at or before the text position.Args:input_ids: List of token idsgrid_thw: Grid sizes for each media item2 unmodified lines"""batch_size = len(input_ids)max_text_len = max(len(ids) for ids in input_ids)# Calculate total frames per sample to find max_num_framestotal_frames_per_sample = []media_idx = 02 unmodified linesif num_media == 0:total_frames_per_sample.append(0)continuesample_frames = 0for _ in range(num_media):# grid_thw is (N, 3) where first dim is t (num_frames)5 unmodified linessample_frames += tmedia_idx += 1total_frames_per_sample.append(sample_frames)max_num_frames = max(total_frames_per_sample) if total_frames_per_sample else 0if max_num_frames == 0:return None# Vectorized implementation for speed# 1. Pad input_ids to create a tensor# We use -1 as pad value since token ids are positiveinput_ids_tensor = torch.full((batch_size, max_text_len), -1, dtype=torch.long)for b, ids in enumerate(input_ids):l = len(ids)input_ids_tensor[b, :l] = torch.tensor(ids, dtype=torch.long)# 2. Identify image tokensis_image_token = (input_ids_tensor == self.image_token_id)# 3. Compute cumulative image tokens (how many image tokens appeared up to position t)# shape: (batch_size, text_len)cum_image_tokens = is_image_token.cumsum(dim=1)# 4. Create frame indices# shape: (1, 1, max_num_frames)frame_indices = torch.arange(max_num_frames).reshape(1, 1, -1)# 5. Determine visibility based on causal relationship# Text at `t` sees frame `i` if `cum_image_tokens[t] > i`# Because if frame `i` is the (i+1)-th image token, it becomes visible when count reaches i+1# shape: (batch_size, text_len, max_num_frames)visible_mask = cum_image_tokens.unsqueeze(-1) > frame_indices# 6. Apply attention_mask if providedif attention_mask is not None:# Convert to tensor if needed5 unmodified linesfor b, mask_row in enumerate(attention_mask):l = len(mask_row)attn_mask_tensor[b, :l] = torch.tensor(mask_row, dtype=torch.long)# shape: (batch_size, text_len, 1)valid_text = (attn_mask_tensor.unsqueeze(-1) == 1)visible_mask = visible_mask & valid_text# 7. Mask out frames that don't exist for a sample# shape: (batch_size, 1, 1)total_frames_tensor = torch.tensor(total_frames_per_sample).reshape(batch_size, 1, 1)# shape: (batch_size, 1, max_num_frames)valid_frames = frame_indices < total_frames_tensorvisible_mask = visible_mask & valid_frames# 8. Create final mask (True for masked, False for visible)mask = ~visible_mask# 9. Add channel dimension: (batch_size, 1, text_len, max_num_frames)mask = mask.unsqueeze(1)return maskdef _replace_and_update_spans(6 unmodified lines) -> tuple:"""Replace occurrences of old_str with new_str and update spans accordingly.Args:text: The text to perform replacement onold_str: String to be replacednew_str: String to replace withspans: List of [start, end] spans to update (modified in place)replace_count: Maximum number of replacements (-1 for all)Returns:Tuple of (new_text, updated_spans)"""1 unmodified lineresult_text = textcount = 0search_start = 0while True:pos = result_text.find(old_str, search_start)if pos == -1:breakif replace_count != -1 and count >= replace_count:break# Update all spans that come after this positionfor span in spans:if span[0] > pos:3 unmodified lineselif span[1] > pos:# Span ends after replacement point (spans the replacement)span[1] += delta# Perform the replacementresult_text = result_text[:pos] + new_str + result_text[pos + len(old_str):]search_start = pos + len(new_str)count += 1return result_text, spansdef _create_labels_from_spans(6 unmodified lines) -> List[List[int]]:"""Create labels from spans and offset_mapping.Args:input_ids: Tokenized input idsoffset_mapping: Character offsets for each token from tokenizer (special tokens included)2 unmodified linesmask_token_ids: Set of token ids that should always be masked (set to ignore_index)in labels, regardless of whether they fall inside a span.Defaults to self.mask_token_ids if not provided.Returns:labels: List of label ids, same shape as input_idsNote:- Tokenizer's offset_mapping already includes correct offsets for special tokens in text- Only need to mask tokens inside <|vision_start|>...<|vision_end|>2 unmodified lines"""if mask_token_ids is None:mask_token_ids = self.mask_token_idsbatch_labels = []for batch_idx in range(len(input_ids)):ids = input_ids[batch_idx]offsets = offset_mapping[batch_idx]spans = labels_spans[batch_idx]labels = [ignore_index] * len(ids)# Process each span: find token range and set labelsfor span_start, span_end in spans:in_vision = False# Find tokens that overlap with this spanfor token_idx, (token_id, (char_start, char_end)) in enumerate(zip(ids, offsets)):# Skip tokens completely before this span2 unmodified lines# Stop when tokens are completely after this spanif char_start >= span_end:break# Token overlaps with span, process it# Track vision region: <|vision_start|> ... <|vision_end|>if token_id == self.vision_start_token_id:2 unmodified linesif token_id == self.vision_end_token_id:in_vision = Falsecontinue# Skip tokens inside vision regionif in_vision:continue# Always mask special tokens that should never have labelsif token_id in mask_token_ids:continue# Set label for this tokenlabels[token_idx] = token_idbatch_labels.append(labels)return batch_labelsdef _calculate_timestamps(self,frames_indices: Optional[Union[List[int], np.ndarray]],total_num_frames: int,video_fps: float,duration: float,merge_size: int = 1,actual_timestamps: Optional[List[float]] = None):"""Calculate timestamps for video frames.Args:frames_indices: Actual frame indices extracted (if available)total_num_frames: Total number of sampled frames1 unmodified lineduration: Video duration in secondsmerge_size: Temporal merge sizeactual_timestamps: Pre-calculated actual timestamps (for segments)Returns:List of timestamps (one per merged temporal patch)"""# If actual timestamps are provided (from segment), use them directlyif actual_timestamps is not None:timestamps = list(actual_timestamps)# Pad timestamps to be multiple of merge_sizeif len(timestamps) % merge_size != 0:timestamps.extend([timestamps[-1]] * (merge_size - len(timestamps) % merge_size))# Frames are merged by merge_size, so we average the timestamps within each temporal patchtimestamps = [(timestamps[i] + timestamps[i + merge_size - 1]) / 2for i in range(0, len(timestamps), merge_size)]return timestamps# Use frames_indices if available, otherwise generate uniformly sampled indicesif frames_indices is not None:if isinstance(frames_indices, np.ndarray):7 unmodified lineselse:# Uniformly sample frames across the video durationindices = np.linspace(0, duration * video_fps - 1, total_num_frames).astype(np.int32).tolist()# Pad indices to be multiple of merge_sizeif len(indices) % merge_size != 0:indices.extend([indices[-1]] * (merge_size - len(indices) % merge_size))# Convert frame indices to timestampstimestamps = [idx / video_fps for idx in indices]# Frames are merged by merge_size, so we average the timestamps within each temporal patchtimestamps = [(timestamps[i] + timestamps[i + merge_size - 1]) / 2for i in range(0, len(timestamps), merge_size)]return timestampsdef batch_decode(self, *args, **kwargs):"""This method forwards all its arguments to the tokenizer's batch_decode.Please refer to the docstring of this method for more information."""return self.tokenizer.batch_decode(*args, **kwargs)13 unmodified linesArgs:generated_outputs (`torch.Tensor` or `np.ndarray`):The output of the model `generate` function. The output is expected to be a tensorof shape `(batch_size, sequence_length)` or `(sequence_length,)`.skip_special_tokens (`bool`, *optional*, defaults to `True`):Whether or not to remove special tokens in the output.48 unmodified lines4950515253545514 unmodified lines707172737475762 unmodified lines7980818283848512 unmodified lines98991001011021031041051061071081091108 unmodified lines11912012112212312412538 unmodified lines16416516616716816917017117217317417517617717817918011 unmodified lines1921931941951961971981992002012022032042052062072081 unmodified line210211212213214215216217218219220113 unmodified lines3343353363373383393403413423433443453463473483493503513523534 unmodified lines3583593603613623633647 unmodified lines37237337437537637737837938038138238338438538657 unmodified lines44444544644744844945023 unmodified lines47447547647747847948048148248348448510 unmodified lines4964974984995005015025035045054 unmodified lines51051151251351451551651751851952052152252352452552652752852953053153253353424 unmodified lines55956056156256356456510 unmodified lines57657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760831 unmodified lines6406416426436446456466476486492 unmodified lines65265365465565665765865966066166266366466566666766866967067167267313 unmodified lines6876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347351 unmodified line7377387397407417427437447457467477487497507517527537547557567577587597607617628 unmodified lines7717727737747757767777787797807817827837847857867877886 unmodified lines7957967977987998008018028038048058068078088098108118122 unmodified lines8158168178188198208212 unmodified lines8248258268278288298302 unmodified lines8338348358368378388395 unmodified lines8458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818825 unmodified lines8888898908918928938948958968978988999009019029039049059069079089099109119126 unmodified lines9199209219229239249259269279289299309319321 unmodified line9349359369379389399409419429439449459469473 unmodified lines9519529539549559569579589599609619626 unmodified lines9699709719729739749752 unmodified lines9789799809819829839849859869872 unmodified lines99099199299399499599699799899910001001100210031004100510061007100810092 unmodified lines10121013101410151016101710182 unmodified lines10211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541 unmodified line10561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910807 unmodified lines10881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111113 unmodified lines112511261127112811291130113148 unmodified lines"""# Multi-image batch total pixels limit (read from config)multi_image_max_pixels = Nonedef _preprocess(self,14 unmodified lines**kwargs,):"""Override _preprocess to use custom smart_resize with batch-level max_pixels.multi_image_max_pixels is treated as a batch-level total budget, proportionally allocatedto each image based on its original pixel count. min_pixels remains a per-imageconstraint. multi_image_max_pixels can be configured separately from longest_edge.2 unmodified linesmax_pixels = size["longest_edge"] # Per-image upper limit# Use multi_image_max_pixels if configured, otherwise fall back to longest_edgemulti_image_max_pixels = getattr(self, "multi_image_max_pixels", None) or max_pixels# Calculate total original pixels across all images in the batch# This is used to proportionally allocate max_pixels to each imagetotal_original_pixels = sum(img.shape[-2] * img.shape[-1] for img in images)12 unmodified linesproportional_max_pixels = int(multi_image_max_pixels * proportion)else:proportional_max_pixels = multi_image_max_pixels# Ensure proportional max_pixels is within [min_pixels, max_pixels] range# min_pixels: per-image lower limit (shortest_edge)# max_pixels: per-image upper limit (longest_edge)proportional_max_pixels = max(proportional_max_pixels, min_pixels)proportional_max_pixels = min(proportional_max_pixels, max_pixels)resized_height, resized_width = smart_resize(height,width,8 unmodified lines)resized_images_grouped[shape] = stacked_imagesresized_images = reorder_images(resized_images_grouped, grouped_images_index)# Warn if multi-image batch exceeds multi_image_max_pixels due to min_pixels constraintif len(images) > 1:total_resized_pixels = sum(img.shape[-2] * img.shape[-1] for img in resized_images)38 unmodified lines)# Reorder dimensions to group grid and patch information for subsequent flattening.# (batch, grid_t, grid_h, grid_w, merge_h, merge_w, channel, temp_patch_size, patch_h, patch_w)# NPU ops support at most 8-D tensors; route the 10-D permute+reshape# through CPU there. CUDA handles 10-D natively — keep it on-device.patches_device = patches.deviceif patches_device.type == "npu":patches = patches.cpu()patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)flatten_patches = patches.reshape(batch_size,grid_t * grid_h * grid_w,channel * temporal_patch_size * patch_size * patch_size,).to(patches_device)processed_images_grouped[shape] = flatten_patchesprocessed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size11 unmodified lines"""Convert various tensor types to numpy array.Supports torch.Tensor, tf.Tensor, jax.Array, np.ndarray, lists, and primitives.Args:x: Input value that can be a tensor from various frameworks or a Python primitiveReturns:np.ndarray: NumPy array representation of the input"""# Already numpyif isinstance(x, np.ndarray):return x# Torch tensor or TensorFlow tensor (both have .numpy() method)if hasattr(x, 'numpy'):# For torch tensors on CUDA, need to move to CPU first1 unmodified linereturn x.cpu().numpy()# For TensorFlow or already on CPUreturn x.numpy()# JAX arrays and other array-like objects that support __array__ protocolif hasattr(x, '__array__'):return np.asarray(x)# Python primitives (list, tuple, int, float)return np.array(x)113 unmodified linestokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")def __init__(self,image_processor=None,tokenizer=None,video_processor=None,chat_template=None,**kwargs):super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_tokenself.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_tokenself.image_token_id = (tokenizer.image_token_idif getattr(tokenizer, "image_token_id", None)4 unmodified linesif getattr(tokenizer, "video_token_id", None)else tokenizer.convert_tokens_to_ids(self.video_token))self.vision_start_token = ("<|vision_start|>" if not hasattr(tokenizer, "vision_start_token") else tokenizer.vision_start_token)7 unmodified linesself.time_start_token = "<|time_start|>"self.time_end_token = "<|time_end|>"# EOS token for labels generation (assistant's response should end with this)self.im_end_token = "<|im_end|>"self.im_end_token_id = tokenizer.convert_tokens_to_ids(self.im_end_token)# Vision-related token ids (all should be masked in labels)self.vision_start_token_id = tokenizer.convert_tokens_to_ids(self.vision_start_token)self.vision_end_token_id = tokenizer.convert_tokens_to_ids(self.vision_end_token)# Token ids that should always be masked in labels (e.g. <|image_pad|>)self.mask_token_ids = {self.image_token_id}57 unmodified linestokenizer_init_kwargs=self.tokenizer.init_kwargs,**kwargs,)# Step 1: Process images if providedif images is not None:images_kwargs = output_kwargs["images_kwargs"].copy()23 unmodified lines# Step 3: Process text with placeholder replacementif text is None or (isinstance(text, str) and len(text.strip()) == 0):raise ValueError("Text input is required for MossVL processor and cannot be empty.")if not isinstance(text, list):text = [text]text = text.copy() # Copy to avoid in-place modifications# Prepare labels_spans if provided# labels_spans format: List[List[List[int]]] - batch of samples, each sample has multiple spans# Each span is [start, end] (list, not tuple) so it can be modified in place10 unmodified lineshas_images = images is not None and "pixel_values" in image_inputshas_videos = videos is not None and "pixel_values_videos" in videos_inputsneeds_reorder = has_images and has_videosimage_pixel_values_list = []video_pixel_values_list = []# Step 3.0: Record the order of media in original text (before replacement)# This will be used later to correctly order pixel_values and grid_thwmedia_order_per_sample = []4 unmodified lineswhile pos < len(temp_text):img_pos = temp_text.find(self.image_placeholder, pos)vid_pos = temp_text.find(self.video_placeholder, pos)if img_pos == -1 and vid_pos == -1:breakif img_pos != -1 and (vid_pos == -1 or img_pos < vid_pos):media_order.append(("image", img_pos))pos = img_pos + len(self.image_placeholder)elif vid_pos != -1:media_order.append(("video", vid_pos))pos = vid_pos + len(self.video_placeholder)media_order_per_sample.append(media_order)# Step 3.0.1: Check if any sample has no media (empty samples need blank image)# If there are empty samples, we need to enter slow path to handle them properlyhas_empty_samples = any(len(order) == 0 for order in media_order_per_sample)if has_empty_samples:needs_reorder = True# Split pixel values for reordering if neededif needs_reorder:if has_images:24 unmodified linesvideo_pixel_values_list = _split_array_or_tensor(flat_video_values, split_indices)# Step 3.1: Replace placeholders (simple replacement, no expansion yet)# In MossVL, one image placeholder = one image token# One video placeholder = one video token (will be expanded later)10 unmodified lineselse:text[i] = text[i].replace(self.image_placeholder, self.image_token)text[i] = text[i].replace(self.video_placeholder, self.video_token)# Step 3.2: Validate token countsn_images_in_text = [t.count(self.image_token) for t in text]n_videos_in_text = [t.count(self.video_token) for t in text]# Count placeholders in texttotal_images_in_text = sum(n_images_in_text)total_videos_in_text = sum(n_videos_in_text)# Count actual images and videos providedtotal_images_provided = len(image_grid_thw) if image_grid_thw is not None else 0total_videos_provided = len(video_grid_thw) if video_grid_thw is not None else 0# Validate image countsif total_images_in_text != total_images_provided:raise ValueError("Number of image tokens does not match number of images provided. "f"Found {total_images_in_text} image tokens in text and {total_images_provided} images.")# Validate video countsif total_videos_in_text != total_videos_provided:raise ValueError("Number of video tokens does not match number of videos provided. "f"Found {total_videos_in_text} video tokens in text and {total_videos_provided} videos.")# Step 3.3: Expand video tokens with timestamps# Now expand each video token to multiple tokens (one per frame) with timestampsif video_grid_thw is not None:31 unmodified linesvideo_tokens.append(f"{self.time_start_token}{curr_time:.1f} seconds{self.time_end_token}{self.image_token}")# Wrap the entire video sequence with vision_start and vision_end tokensvideo_placeholder = f"{self.vision_start_token}{''.join(video_tokens)}{self.vision_end_token}"# Replace the video token with expanded sequence and update spans if neededif should_create_labels:text[i], labels_spans[i] = self._replace_and_update_spans(2 unmodified lineselse:text[i] = text[i].replace(self.video_token, video_placeholder, 1)index += 1# Step 4: Tokenize textreturn_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)# Request offset_mapping if we need to create labelsif should_create_labels:output_kwargs["text_kwargs"]["return_offsets_mapping"] = Truetext_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])# ignore check_special_mm_tokens nums in test and input ids.# self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])# Create labels if labels_spans was providedif should_create_labels:offset_mapping = text_inputs.pop("offset_mapping")13 unmodified lines# Step 5: Concatenate pixel_values and grid_thw in sequence order# Prepare outputoutput_data = {**text_inputs}if not needs_reorder:# Fast path: only one media type, no reordering neededfinal_pixel_values = []final_grid_thw = []if has_images:final_pixel_values.append(image_inputs["pixel_values"])final_grid_thw.extend(image_grid_thw)if has_videos:final_pixel_values.append(videos_inputs["pixel_values_videos"])final_grid_thw.extend(video_grid_thw)if final_pixel_values:output_data["pixel_values"] = np.concatenate(final_pixel_values, axis=0) if len(final_pixel_values) > 1 else final_pixel_values[0]if final_grid_thw:output_data["grid_thw"] = np.stack(final_grid_thw, axis=0)# Calculate media_nums_per_samplemedia_nums_per_sample = []for batch_idx in range(len(text)):media_order = media_order_per_sample[batch_idx]media_nums_per_sample.append(len(media_order) if len(media_order) > 0 else 1)# Don't add media_nums_per_sample to output_data yet# Will add it after BatchFeature to keep it as listelse:# Slow path: both images and videos exist, need reorderingfinal_pixel_values = []final_grid_thw = []media_nums_per_sample = []# Global indices to track position in flattened image/video arraysglobal_image_idx = 0global_video_idx = 0for batch_idx in range(len(text)):# Use the recorded media order from Step 3.0media_order = media_order_per_sample[batch_idx]if len(media_order) == 0:# If no media provided for this sample, add a blank imagemedia_nums_per_sample.append(1)1 unmodified linepatch_size = getattr(self.image_processor, "patch_size", None) or 16temporal_patch_size = getattr(self.image_processor, "temporal_patch_size", None) or 1merge_size = getattr(self.image_processor, "merge_size", None) or 2factor = patch_size * merge_sizeside = int(np.ceil(np.sqrt(min_pixels) / factor) * factor)grid_h = side // patch_sizegrid_w = side // patch_sizegrid_t = 1# Channel = 3 (RGB)channel = 3dim = channel * temporal_patch_size * patch_size * patch_sizenum_patches = grid_t * grid_h * grid_wblank_pixel_values = np.zeros((num_patches, dim), dtype=np.float32)blank_grid_thw = np.array([grid_t, grid_h, grid_w], dtype=np.int64)final_pixel_values.append(blank_pixel_values)final_grid_thw.append(blank_grid_thw)else:media_nums_per_sample.append(len(media_order))# Collect media data according to the recorded orderfor media_type, _ in media_order:if media_type == "image" and image_grid_thw is not None:8 unmodified linesfinal_pixel_values.append(video_pixel_values_list[global_video_idx])final_grid_thw.append(video_grid_thw[global_video_idx])global_video_idx += 1# Concatenate/stack to unified formatif final_pixel_values:output_data["pixel_values"] = _concat_array_or_tensor(final_pixel_values, axis=0)if final_grid_thw:output_data["grid_thw"] = _stack_array_or_tensor(final_grid_thw, axis=0)# Don't add media_nums_per_sample to output_data yet# Will add it after BatchFeature to keep it as list6 unmodified linesoutput_data.get("attention_mask", None))output_data["cross_attention_mask"] = cross_attention_mask# Add labels to output if createdif should_create_labels:output_data["labels"] = labels# BatchFeature will handle conversion to pt/tf/jax/np based on tensor_typebatch_feature = BatchFeature(data=output_data, tensor_type=return_tensors)# Add media_nums_per_sample after BatchFeature to keep it as list (not tensor)if media_nums_per_sample:batch_feature["media_nums_per_sample"] = media_nums_per_samplereturn batch_featuredef _create_cross_attention_mask(self, input_ids, grid_thw, media_nums_per_sample, attention_mask=None):2 unmodified linesVideo frames are treated as individual images.Mask values: True for masked, False for visible.Causal masking: text can see images that appear at or before the text position.Args:input_ids: List of token idsgrid_thw: Grid sizes for each media item2 unmodified lines"""batch_size = len(input_ids)max_text_len = max(len(ids) for ids in input_ids)# Calculate total frames per sample to find max_num_framestotal_frames_per_sample = []media_idx = 02 unmodified linesif num_media == 0:total_frames_per_sample.append(0)continuesample_frames = 0for _ in range(num_media):# grid_thw is (N, 3) where first dim is t (num_frames)5 unmodified linessample_frames += tmedia_idx += 1total_frames_per_sample.append(sample_frames)max_num_frames = max(total_frames_per_sample) if total_frames_per_sample else 0if max_num_frames == 0:return None# Vectorized implementation for speed# 1. Pad input_ids to create a tensor# We use -1 as pad value since token ids are positiveinput_ids_tensor = torch.full((batch_size, max_text_len), -1, dtype=torch.long)for b, ids in enumerate(input_ids):l = len(ids)input_ids_tensor[b, :l] = torch.tensor(ids, dtype=torch.long)# 2. Identify image tokensis_image_token = (input_ids_tensor == self.image_token_id)# 3. Compute cumulative image tokens (how many image tokens appeared up to position t)# shape: (batch_size, text_len)cum_image_tokens = is_image_token.cumsum(dim=1)# 4. Create frame indices# shape: (1, 1, max_num_frames)frame_indices = torch.arange(max_num_frames).reshape(1, 1, -1)# 5. Determine visibility based on causal relationship# Text at `t` sees frame `i` if `cum_image_tokens[t] > i`# Because if frame `i` is the (i+1)-th image token, it becomes visible when count reaches i+1# shape: (batch_size, text_len, max_num_frames)visible_mask = cum_image_tokens.unsqueeze(-1) > frame_indices# 6. Apply attention_mask if providedif attention_mask is not None:# Convert to tensor if needed5 unmodified linesfor b, mask_row in enumerate(attention_mask):l = len(mask_row)attn_mask_tensor[b, :l] = torch.tensor(mask_row, dtype=torch.long)# shape: (batch_size, text_len, 1)valid_text = (attn_mask_tensor.unsqueeze(-1) == 1)visible_mask = visible_mask & valid_text# 7. Mask out frames that don't exist for a sample# shape: (batch_size, 1, 1)total_frames_tensor = torch.tensor(total_frames_per_sample).reshape(batch_size, 1, 1)# shape: (batch_size, 1, max_num_frames)valid_frames = frame_indices < total_frames_tensorvisible_mask = visible_mask & valid_frames# 8. Create final mask (True for masked, False for visible)mask = ~visible_mask# 9. Add channel dimension: (batch_size, 1, text_len, max_num_frames)mask = mask.unsqueeze(1)return maskdef _replace_and_update_spans(6 unmodified lines) -> tuple:"""Replace occurrences of old_str with new_str and update spans accordingly.Args:text: The text to perform replacement onold_str: String to be replacednew_str: String to replace withspans: List of [start, end] spans to update (modified in place)replace_count: Maximum number of replacements (-1 for all)Returns:Tuple of (new_text, updated_spans)"""1 unmodified lineresult_text = textcount = 0search_start = 0while True:pos = result_text.find(old_str, search_start)if pos == -1:breakif replace_count != -1 and count >= replace_count:break# Update all spans that come after this positionfor span in spans:if span[0] > pos:3 unmodified lineselif span[1] > pos:# Span ends after replacement point (spans the replacement)span[1] += delta# Perform the replacementresult_text = result_text[:pos] + new_str + result_text[pos + len(old_str):]search_start = pos + len(new_str)count += 1return result_text, spansdef _create_labels_from_spans(6 unmodified lines) -> List[List[int]]:"""Create labels from spans and offset_mapping.Args:input_ids: Tokenized input idsoffset_mapping: Character offsets for each token from tokenizer (special tokens included)2 unmodified linesmask_token_ids: Set of token ids that should always be masked (set to ignore_index)in labels, regardless of whether they fall inside a span.Defaults to self.mask_token_ids if not provided.Returns:labels: List of label ids, same shape as input_idsNote:- Tokenizer's offset_mapping already includes correct offsets for special tokens in text- Only need to mask tokens inside <|vision_start|>...<|vision_end|>2 unmodified lines"""if mask_token_ids is None:mask_token_ids = self.mask_token_idsbatch_labels = []for batch_idx in range(len(input_ids)):ids = input_ids[batch_idx]offsets = offset_mapping[batch_idx]spans = labels_spans[batch_idx]labels = [ignore_index] * len(ids)# Process each span: find token range and set labelsfor span_start, span_end in spans:in_vision = False# Find tokens that overlap with this spanfor token_idx, (token_id, (char_start, char_end)) in enumerate(zip(ids, offsets)):# Skip tokens completely before this span2 unmodified lines# Stop when tokens are completely after this spanif char_start >= span_end:break# Token overlaps with span, process it# Track vision region: <|vision_start|> ... <|vision_end|>if token_id == self.vision_start_token_id:2 unmodified linesif token_id == self.vision_end_token_id:in_vision = Falsecontinue# Skip tokens inside vision regionif in_vision:continue# Always mask special tokens that should never have labelsif token_id in mask_token_ids:continue# Set label for this tokenlabels[token_idx] = token_idbatch_labels.append(labels)return batch_labelsdef _calculate_timestamps(self,frames_indices: Optional[Union[List[int], np.ndarray]],total_num_frames: int,video_fps: float,duration: float,merge_size: int = 1,actual_timestamps: Optional[List[float]] = None):"""Calculate timestamps for video frames.Args:frames_indices: Actual frame indices extracted (if available)total_num_frames: Total number of sampled frames1 unmodified lineduration: Video duration in secondsmerge_size: Temporal merge sizeactual_timestamps: Pre-calculated actual timestamps (for segments)Returns:List of timestamps (one per merged temporal patch)"""# If actual timestamps are provided (from segment), use them directlyif actual_timestamps is not None:timestamps = list(actual_timestamps)# Pad timestamps to be multiple of merge_sizeif len(timestamps) % merge_size != 0:timestamps.extend([timestamps[-1]] * (merge_size - len(timestamps) % merge_size))# Frames are merged by merge_size, so we average the timestamps within each temporal patchtimestamps = [(timestamps[i] + timestamps[i + merge_size - 1]) / 2for i in range(0, len(timestamps), merge_size)]return timestamps# Use frames_indices if available, otherwise generate uniformly sampled indicesif frames_indices is not None:if isinstance(frames_indices, np.ndarray):7 unmodified lineselse:# Uniformly sample frames across the video durationindices = np.linspace(0, duration * video_fps - 1, total_num_frames).astype(np.int32).tolist()# Pad indices to be multiple of merge_sizeif len(indices) % merge_size != 0:indices.extend([indices[-1]] * (merge_size - len(indices) % merge_size))# Convert frame indices to timestampstimestamps = [idx / video_fps for idx in indices]# Frames are merged by merge_size, so we average the timestamps within each temporal patchtimestamps = [(timestamps[i] + timestamps[i + merge_size - 1]) / 2for i in range(0, len(timestamps), merge_size)]return timestampsdef batch_decode(self, *args, **kwargs):"""This method forwards all its arguments to the tokenizer's batch_decode.Please refer to the docstring of this method for more information."""return self.tokenizer.batch_decode(*args, **kwargs)13 unmodified linesArgs:generated_outputs (`torch.Tensor` or `np.ndarray`):The output of the model `generate` function. The output is expected to be a tensorof shape `(batch_size, sequence_length)` or `(sequence_length,)`.skip_special_tokens (`bool`, *optional*, defaults to `True`):Whether or not to remove special tokens in the output.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{"auto_map": {"AutoProcessor": "processing_moss_vl.MossVLProcessor","AutoVideoProcessor": "video_processing_moss_vl.MossVLVideoProcessor"},"crop_size": null,"data_format": "channels_first","default_to_square": true,"device": null,"do_center_crop": null,"do_convert_rgb": true,"do_normalize": true,"do_rescale": true,"do_resize": true,"do_sample_frames": true,"fps": null,"image_mean": [0.5,0.5,0.5],"image_std": [0.5,0.5,0.5],"input_data_format": null,"max_frames": 256,"merge_size": 2,"min_frames": 1,"num_extract_threads": 4,"num_frames": null,"pad_size": null,"patch_size": 16,"processor_class": "MossVLProcessor","resample": 3,"rescale_factor": 0.00392156862745098,"return_metadata": false,"size": {"longest_edge": 16777216,"shortest_edge": 4096},"temporal_patch_size": 1,"video_fps": 1.0,"video_max_pixels": 65536000,"video_metadata": null,"video_processor_type": "MossVLVideoProcessor"}123456789101112131415161718192021222324252627282930{"auto_map": {"AutoProcessor": "processing_moss_vl.MossVLProcessor","AutoVideoProcessor": "video_processing_moss_vl.MossVLVideoProcessor"},"size": {"longest_edge": 16777216,"shortest_edge": 4096},"video_max_pixels": 201326592,"patch_size": 16,"temporal_patch_size": 1,"merge_size": 2,"video_fps": 1.0,"min_frames": 1,"max_frames": 256,"num_extract_threads": 4,"image_mean": [0.5,0.5,0.5],"image_std": [0.5,0.5,0.5],"processor_class": "MossVLProcessor","video_processor_type": "MossVLVideoProcessor"}
13 unmodified lines14151617181920212223242523 unmodified lines4950515253545556575811 unmodified lines707172737475762 unmodified lines798081828384852 unmodified lines8889909192939495969798994 unmodified lines10410510610710810911011 unmodified lines1221231241251261271281291301311321331341351361371381399 unmodified lines1491501511521531541559 unmodified lines1651661671681691701711721731741751761774 unmodified lines1821831841851861871881891901911921939 unmodified lines2032042052062072087 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382395 unmodified lines2452462472482492502512522532542552567 unmodified lines2642652662672682692702712722732742752762772782792802812822834 unmodified lines28828929029129229329429529629729829910 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333343353363373389 unmodified lines3483493503513523533543553563573583593605 unmodified lines366367368369370371372373374375376377378379380381382383384385386387388389129 unmodified lines51952052152252352481 unmodified lines60660760860961061161261361461561661761813 unmodified lines6326336346356366376386396406416421 unmodified line64464564664764864965011 unmodified lines662663664665666667668669670671672673142 unmodified lines8168178188198208218228238248258268278288292 unmodified lines8328338348358368378388398408418428438448458468478488498508518524 unmodified lines8578588598608618628638648658668678688698708718728738748758768778788798808818824 unmodified lines88788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492513 unmodified lines9399409419429439449459469475 unmodified lines9539549559569579589599609619629639649659669679689699709719729739749756 unmodified lines9829839849859869879889899909919929939944 unmodified lines9991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810294 unmodified lines10341035103610371038103910401041104210431044104510461047104898 unmodified lines11471148114911501151115211531154115511561157115816 unmodified lines1175117611771178117911801181118211831184118511861187118811892 unmodified lines119211931194119511961197119811991200120112022 unmodified lines1205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124813 unmodified lines# limitations under the License."""video processor class for Moss-VL."""import jsonimport logging as system_loggingimport mathimport osimport reimport subprocessimport tracebackfrom functools import lru_cachefrom typing import Any, Dict, List, Optional, Union23 unmodified linesdef check_video_for_extra_streams_and_errors(video_path: str) -> dict:"""Check if video file has abnormal streams or errors reported by ffprobe.Args:video_path: Path to the video file.Returns:A dictionary containing:- 'has_extra_streams': bool, whether there are streams other than video and audio.11 unmodified lines'stream_details': [],'num_streams': 0}command = ["ffprobe","-v", "error",2 unmodified lines"-of", "json",video_path]try:process = subprocess.run(command,2 unmodified linescheck=False)result['ffprobe_successful'] = (process.returncode == 0)if process.stderr:result['ffprobe_output_error'] = process.stderrunsupported_codec_pattern = re.compile(r"Unsupported codec with id \d+ for input stream \d+")result['unsupported_codec_errors'] = unsupported_codec_pattern.findall(process.stderr)if process.stdout:ffprobe_data = json.loads(process.stdout)if 'streams' in ffprobe_data:4 unmodified linesresult['stream_details'].append({'index': stream_index, 'codec_type': stream_type})if stream_type not in ['video', 'audio']:result['has_extra_streams'] = Trueif 'format' in ffprobe_data and 'nb_streams' in ffprobe_data['format']:if result['num_streams'] == 0:result['num_streams'] = ffprobe_data['format']['nb_streams']11 unmodified linesexcept Exception as e:result['ffprobe_output_error'] = f"An unexpected error occurred: {e}"result['ffprobe_successful'] = Falsereturn resultdef remove_video_extra_stream_ffmpeg(input_video: str, output_video: str) -> bool:"""Remove extra streams from video using ffmpeg.Args:input_video: Path to input video.output_video: Path to output video.Returns:bool: True if successful, False otherwise."""9 unmodified lines"-movflags", "faststart",output_video,]try:subprocess.run(command_list, shell=False, check=True, capture_output=True)return True9 unmodified linesreturn Falsedef clean_video_streams(video_path: str) -> str:"""Clean video streams if extra streams are detected.Args:video_path: Path to the video file.Returns:str: Path to cleaned video (or original if no cleaning needed)."""4 unmodified linesfile_name_without_ext, file_ext = os.path.splitext(base_name)new_base_name = f"{file_name_without_ext}_fix{file_ext}"video_path_output = os.path.join(output_folder, new_base_name)process_flag = remove_video_extra_stream_ffmpeg(video_path, video_path_output)if not process_flag:logger.warning("Failed to remove extra streams with ffmpeg")return video_pathreturn video_path_outputreturn video_path9 unmodified linesmin_pts = torchcodec_metadata.begin_stream_seconds_from_contentif min_pts is None:min_pts = 0.0max_pts_candidates = []if torchcodec_metadata.num_frames_from_content and torchcodec_metadata.average_fps:7 unmodified linesmax_pts_candidates.append(torchcodec_metadata.duration_seconds - TORCHCODEC_TIMESTAMP_EPSILON)if max_pts_candidates:max_pts = max(min_pts, min(max_pts_candidates))return [max(min_pts, min(float(t), max_pts)) for t in timestamps]if min_pts > 0:return [max(min_pts, float(t)) for t in timestamps]return [float(t) for t in timestamps]def split_indices(indices: List[Union[int, float]], num_chunks: int) -> List[List[Union[int, float]]]:"""Split an index list into roughly equal chunks.Args:indices: List of indices to split.num_chunks: Number of chunks to create.Returns:List of index chunks."""chunk_size = len(indices) // num_chunkschunks = []for i in range(num_chunks - 1):5 unmodified linesdef decode_sequentially(indices: List[int], video_path: str, ffmpeg_threads: int = 0):"""Decode frames sequentially from a video.Args:indices: List of frame indices to decode.video_path: Path to the video file.ffmpeg_threads: Number of ffmpeg threads to use.Returns:FrameBatch from torchcodec."""7 unmodified linesdef decode_with_multithreading(indices: List[int], num_threads: int, video_path: str) -> dict:"""Decode frames using multithreading with joblib.Args:indices: List of frame indices to decode.num_threads: Number of threads to use.video_path: Path to the video file.Returns:dict: Contains 'data', 'duration_seconds', 'pts_seconds' tensors."""chunks = split_indices(indices, num_chunks=num_threads)results = Parallel(n_jobs=num_threads, prefer="threads", verbose=0)(delayed(decode_sequentially)(chunk, video_path) for chunk in chunks)return {"data": torch.cat([frame_batch.data for frame_batch in results], dim=0),"duration_seconds": torch.cat([frame_batch.duration_seconds for frame_batch in results], dim=0),4 unmodified linesdef decode_sequentially_timestamp(timestamp_list: List[float], video_path: str, ffmpeg_threads: int = 0):"""Decode frames sequentially from a video based on timestamps.Args:timestamp_list: List of timestamps (in seconds) to decode.video_path: Path to the video file.ffmpeg_threads: Number of ffmpeg threads to use.Returns:FrameBatch from torchcodec."""10 unmodified linesdef timestamp_decode_with_multithreading(timestamp_list: List[float], num_threads: int, video_path: str) -> dict:"""Decode frames using multithreading based on timestamps.Args:timestamp_list: List of timestamps (in seconds) to decode.num_threads: Number of threads to use.video_path: Path to the video file.Returns:dict: Contains 'data', 'duration_seconds', 'pts_seconds' tensors."""chunks = split_indices(timestamp_list, num_chunks=num_threads)results = Parallel(n_jobs=num_threads, prefer="threads", verbose=0)(delayed(decode_sequentially_timestamp)(chunk, video_path) for chunk in chunks)# Concatenate results from all threadsdata_list = [frame_batch.data for frame_batch in results]duration_list = [frame_batch.duration_seconds for frame_batch in results]pts_list = [frame_batch.pts_seconds for frame_batch in results]if not data_list:logger.warning("No frames were successfully decoded.")return {"data": torch.empty(0), "duration_seconds": torch.empty(0), "pts_seconds": torch.empty(0)}return {"data": torch.cat(data_list, dim=0),"duration_seconds": torch.cat(duration_list, dim=0),9 unmodified lines) -> Optional[dict]:"""Extract frames from video using torchcodec with multithreading.Args:video_path: Path to the video file.sample_frames_count: Number of frames to sample.num_threads: Number of threads to use for extraction.sampling_method: Sampling method, either "index" (uniform frame indices) or "timestamp" (uniform timestamps).Returns:dict: Contains 'data' (N, C, H, W), 'duration_seconds' (N,), 'pts_seconds' (N,) tensors.Returns None if extraction fails.5 unmodified linestotal_frames_in_video = metadata.num_frames_from_contenteffective_sample_count = min(sample_frames_count, total_frames_in_video)if effective_sample_count == 0:logger.error("Cannot extract frames: video has 0 frames or specified frame count is 0")return None# Generate uniform frame indicesframe_indices = np.linspace(0, total_frames_in_video - 1, effective_sample_count).astype(np.int32)# Ensure indices are valid and remove duplicatesframe_indices = np.unique(np.clip(frame_indices, 0, total_frames_in_video - 1))result = decode_with_multithreading(frame_indices.tolist(), num_threads=num_threads, video_path=video_path)# Add frame_indices to the result for later useresult["frame_indices"] = frame_indicesreturn resultexcept Exception:traceback.print_exc()return None129 unmodified linesreturn video_input["video_path"]return video_inputdef _get_video_duration_seconds(self, video_input: Union[str, Dict[str, Any]]) -> float:"""Get video duration in seconds for weighted frame-budget allocation."""video_path = cached_clean_video_streams(self._get_video_path_from_input(video_input))81 unmodified lines) -> int:"""Calculate the number of frames to sample using fps-based logic with min/max constraints.Logic:1. Calculate target_frames based on fps and video duration2. Apply min_frames and max_frames constraints3. Apply max_allowed_frames protection (rough cap from total video_max_pixels budget)4. Return the number of frames to sampleArgs:metadata (`VideoMetadata`):Metadata of the video containing information about total duration, fps and total number of frames.13 unmodified linesraise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")total_num_frames = metadata.total_num_frames# Use provided min/max or fall back to defaultseffective_min_frames = min_frames if min_frames is not None else self.min_frameseffective_max_frames = max_frames if max_frames is not None else self.max_frames# Rough per-video frame cap derived from the multi-video total budget# (exact allocation happens later in _preprocess via weighted distribution)per_frame_min_pixels = self.size.get("shortest_edge", None) if self.size else None1 unmodified lineif per_frame_min_pixels is not None and video_max_pixels is not None and per_frame_min_pixels > 0:max_allowed_frames = video_max_pixels // per_frame_min_pixelseffective_max_frames = min(effective_max_frames, max_allowed_frames)# Get video durationif hasattr(metadata, 'duration') and metadata.duration is not None:duration = metadata.duration11 unmodified lines# Use provided fps or defaulttarget_fps = fps if fps is not None else self.video_fps# Calculate target frames based on fps and durationif num_frames is None:# Calculate how many frames we should sample based on target fpstarget_total_frames = int(math.ceil(duration * target_fps - 1e-6))# Apply min/max constraintssample_frames = max(target_total_frames, effective_min_frames)sample_frames = min(sample_frames, effective_max_frames, total_num_frames)142 unmodified lines):"""Fetch video frames for a specific segment.Args:video_path: Path to the video filesegment: [start, end] for a segment (left-closed, right-open) or [time] for a single framemin_frames: Minimum frames for this segment (weighted). Defaults to self.min_frames. Must be >= 1.max_frames: Maximum frames for this segment (weighted). Defaults to self.max_frames. Must be >= 1.video_fps: Target frames per second for video sampling. If None, uses self.video_fps.Returns:Tuple of (video_tensor, video_metadata)"""2 unmodified linesmax_frames = max(1, max_frames if max_frames is not None else self.max_frames)# Use provided video_fps or fall back to self.video_fpstarget_video_fps = video_fps if video_fps is not None else self.video_fpsvideo_path = clean_video_streams(video_path)decoder = VideoDecoder(video_path, num_ffmpeg_threads=0)try:torchcodec_metadata = decoder.metadatavideo_fps = torchcodec_metadata.average_fps# Calculate durationduration = Noneif torchcodec_metadata.end_stream_seconds_from_content is not None and torchcodec_metadata.begin_stream_seconds_from_content is not None:duration = torchcodec_metadata.end_stream_seconds_from_content - torchcodec_metadata.begin_stream_seconds_from_contentif duration is None or duration <= 0:duration = torchcodec_metadata.duration_secondsif len(segment) == 1:# Single frame at specified timeactual_timestamps = self._clamp_timestamps_for_decoder([segment[0]], torchcodec_metadata)4 unmodified lines# Segment [start, end) - left-closed, right-open intervalstart_time, end_time = segmentsegment_duration = end_time - start_time# Calculate number of frames to sample for this segmenttarget_frames = int(math.ceil(segment_duration * target_video_fps))target_frames = max(target_frames, min_frames)target_frames = min(target_frames, max_frames)# Generate timestamps for uniform sampling within segmentif target_frames == 1:actual_timestamps = [start_time] # Use start_time for single frameelse:# Sample uniformly within [start, end), endpoint=False for left-closed right-openactual_timestamps = np.linspace(start_time, end_time, target_frames, endpoint=False).tolist()actual_timestamps = self._clamp_timestamps_for_decoder(actual_timestamps, torchcodec_metadata)# Use multithreading for extractionresult = timestamp_decode_with_multithreading(actual_timestamps, self.num_extract_threads, video_path)video_tensor = result["data"]sample_count = len(actual_timestamps)# Create VideoMetadatavideo_metadata = VideoMetadata(total_num_frames=sample_count,4 unmodified lineswidth=torchcodec_metadata.width,frames_indices=None)# Store actual timestamps as a custom attribute for _calculate_timestamps to usevideo_metadata.actual_timestamps = actual_timestampsreturn video_tensor, video_metadatafinally:del decoderdef fetch_videos(self,video_url_or_urls: Union[str, Dict[str, Any], List[Union[str, Dict[str, Any]]]],sample_indices_fn=None,video_fps: Optional[float] = None,min_frames: Optional[int] = None,max_frames: Optional[int] = None,):"""Override fetch_videos to use torchcodec for frame extraction.This method uses torchcodec with multithreading for efficient frame extraction.Frame count is calculated by the calculate_num_frames method(fps-based with min/max constraints).Args:video_url_or_urls: Can be one of:- str: Single video path- Dict: Video with segments {"video_path": str, "segments": List[List[float]]}- List[Union[str, Dict]]: List of video paths or segment dictssample_indices_fn: (Not used) Kept for compatibility with base class signature.video_fps: Target frames per second for video sampling. If None, uses self.video_fps.min_frames: Minimum number of frames to sample. If None, uses self.min_frames.max_frames: Maximum number of frames to sample. If None, uses self.max_frames.Returns:Tuple of (videos, metadata) where videos are torch.Tensors and metadata are VideoMetadata objects."""13 unmodified lineseffective_max_frames,)for x, allocated_max_frames in zip(video_url_or_urls, per_video_max_frames):result = self.fetch_videos(x,video_fps=effective_video_fps,min_frames=effective_min_frames,max_frames=allocated_max_frames,)5 unmodified linesall_videos.append(result[0])all_metadata.append(result[1])return all_videos, all_metadata# Handle dict with segments - returns lists (one per segment)if isinstance(video_url_or_urls, dict):video_path = video_url_or_urls["video_path"]segments = video_url_or_urls["segments"]return self._fetch_video_segments_batched(video_path,segments,min_frames=effective_min_frames,max_frames=effective_max_frames,video_fps=effective_video_fps,)# Single video pathvideo_path = video_url_or_urls# Clean video streams first (remove extra streams if needed)video_path = cached_clean_video_streams(video_path)6 unmodified linesduration = Noneif torchcodec_metadata.end_stream_seconds_from_content is not None and torchcodec_metadata.begin_stream_seconds_from_content is not None:duration = torchcodec_metadata.end_stream_seconds_from_content - torchcodec_metadata.begin_stream_seconds_from_contentif duration is None or duration <= 0:duration = torchcodec_metadata.duration_seconds# Use num_frames_from_content for accurate frame count (consistent with extraction)total_frames_in_video = torchcodec_metadata.num_frames_from_content# Create VideoMetadata object for sample_frames methodtemp_metadata = VideoMetadata(total_num_frames=total_frames_in_video,4 unmodified lineswidth=torchcodec_metadata.width,frames_indices=None)# Use calculate_num_frames method to get the number of frames to samplesample_frames_count = self.calculate_num_frames(temp_metadata,fps=effective_video_fps,min_frames=effective_min_frames,max_frames=effective_max_frames,)# Ensure sample count is valideffective_sample_count = min(sample_frames_count, total_frames_in_video)if effective_sample_count == 0:raise ValueError(f"Cannot extract frames: video has 0 frames or specified frame count is 0")# Generate uniform frame indicesframe_indices = np.linspace(0, total_frames_in_video - 1, effective_sample_count).astype(np.int32)# Ensure indices are valid and remove duplicatesframe_indices = np.unique(np.clip(frame_indices, 0, total_frames_in_video - 1))# Extract frames using multithreading (decoder is created inside each thread for thread safety)result = decode_with_multithreading(frame_indices.tolist(), num_threads=self.num_extract_threads, video_path=video_path)# Extract frame tensor (N, C, H, W)frames_tensor = result["data"]# Create final VideoMetadata objectvideo_metadata = VideoMetadata(total_num_frames=len(frame_indices),4 unmodified lineswidth=torchcodec_metadata.width,frames_indices=frame_indices)# Ensure frames are in (T, C, H, W) formatif frames_tensor.dim() == 4: # (N, C, H, W)video_tensor = frames_tensorelse:raise ValueError(f"Unexpected frame tensor shape: {frames_tensor.shape}")return video_tensor, video_metadataexcept Exception as e:logger.error(f"Error loading video {video_path}: {e}")traceback.print_exc()98 unmodified linesmerge_size,patch_size,)patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)flatten_patches = patches.reshape(batch_size,grid_t * grid_h * grid_w,channel * temporal_patch_size * patch_size * patch_size,)processed_videos_grouped[shape] = flatten_patchesprocessed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size16 unmodified lines) -> BatchFeature:"""Preprocess videos for the model.This method overrides the base class to handle two video input formats:1. String path: "path/to/video.mp4"2. Dict with segments: {"video_path": "...", "segment": [[start, end], [time], ...]}Args:videos: Video input(s) in one of the supported formats.**kwargs: Additional arguments passed to _preprocess.Returns:BatchFeature with pixel_values_videos, video_grid_thw, and optionally video_metadata."""2 unmodified linescaptured_kwargs=kwargs.keys(),valid_processor_keys=list(self.valid_kwargs.__annotations__.keys()) + ["return_tensors"],)# Set default kwargs from selffor kwarg_name in self.valid_kwargs.__annotations__:kwargs.setdefault(kwarg_name, getattr(self, kwarg_name, None))# Pop kwargs that are handled separatelyreturn_tensors = kwargs.pop("return_tensors", None)return_metadata = kwargs.pop("return_metadata", False)2 unmodified lineskwargs.pop("video_metadata", None) # We generate our own metadatakwargs.pop("do_sample_frames", None) # We handle sampling ourselveskwargs.pop("data_format", None) # Not used# Normalize input to list formatif not isinstance(videos, list):videos = [videos]# Get video processing params from kwargs (may be passed explicitly for per-batch configuration)video_fps = kwargs.pop("video_fps", None)min_frames = kwargs.pop("min_frames", None)max_frames = kwargs.pop("max_frames", None)# Use fetch_videos to handle both string and dict formatsvideo_tensors, video_metadata = self.fetch_videos(videos,video_fps=video_fps,min_frames=min_frames,max_frames=max_frames,)# Prepare video tensors using _prepare_input_videosprepared_videos = self._prepare_input_videos(videos=video_tensors,input_data_format=input_data_format,device=device,)# Process kwargs for _preprocesskwargs = self._further_process_kwargs(**kwargs)self._validate_preprocess_kwargs(**kwargs)# Call _preprocess with prepared videosresult = self._preprocess(videos=prepared_videos, return_tensors=return_tensors, **kwargs)# Add metadata if requestedif return_metadata:result["video_metadata"] = video_metadatareturn result__all__ = ["MossVLVideoProcessor"]13 unmodified lines14151617181920212223242526272823 unmodified lines5253545556575859606111 unmodified lines737475767778792 unmodified lines828384858687882 unmodified lines9192939495969798991001011024 unmodified lines10710810911011111211311 unmodified lines1251261271281291301311321331341351361371381391401411429 unmodified lines1521531541551561571589 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921931944 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282299 unmodified lines2392402412422432442452462477 unmodified lines2552562572582592602612622632642652662672682692702712722732742752762772782792802812822832845 unmodified lines2902912922932942952962972982993003017 unmodified lines3093103113123133143153163173183193203213223233243253263273284 unmodified lines33333433533633733833934034134234334410 unmodified lines3553563573583593603613623633643653663673683693703713723733743753763773783793803813823839 unmodified lines3933943953963973983994004014024034044055 unmodified lines411412413414415416417418419420421422423424425426427428429430431432433434129 unmodified lines56456556656756856957057157257357457557657757857958058158258358458558658758881 unmodified lines67067167267367467567667767867968068168213 unmodified lines6966976986997007017027037047057061 unmodified line70870971071171271371411 unmodified lines726727728729730731732733734735736737142 unmodified lines8808818828838848858868878888898908918928932 unmodified lines8968978988999009019029039049059069079089099109119129139149159164 unmodified lines9219229239249259269279289299309319329339349359369379389399409419429439449459464 unmodified lines95195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999013 unmodified lines100410051006100710081009101010111012101310145 unmodified lines102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710486 unmodified lines10551056105710581059106010611062106310641065106610674 unmodified lines10721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111024 unmodified lines11071108110911101111111211131114111511161117111811191120112198 unmodified lines1220122112221223122412251226122712281229123012311232123312341235123616 unmodified lines1253125412551256125712581259126012611262126312641265126612672 unmodified lines127012711272127312741275127612771278127912802 unmodified lines128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513 unmodified lines# limitations under the License."""video processor class for Moss-VL."""import fcntlimport hashlibimport jsonimport logging as system_loggingimport mathimport osimport reimport subprocessimport tempfileimport tracebackfrom functools import lru_cachefrom typing import Any, Dict, List, Optional, Union23 unmodified linesdef check_video_for_extra_streams_and_errors(video_path: str) -> dict:"""Check if video file has abnormal streams or errors reported by ffprobe.Args:video_path: Path to the video file.Returns:A dictionary containing:- 'has_extra_streams': bool, whether there are streams other than video and audio.11 unmodified lines'stream_details': [],'num_streams': 0}command = ["ffprobe","-v", "error",2 unmodified lines"-of", "json",video_path]try:process = subprocess.run(command,2 unmodified linescheck=False)result['ffprobe_successful'] = (process.returncode == 0)if process.stderr:result['ffprobe_output_error'] = process.stderrunsupported_codec_pattern = re.compile(r"Unsupported codec with id \d+ for input stream \d+")result['unsupported_codec_errors'] = unsupported_codec_pattern.findall(process.stderr)if process.stdout:ffprobe_data = json.loads(process.stdout)if 'streams' in ffprobe_data:4 unmodified linesresult['stream_details'].append({'index': stream_index, 'codec_type': stream_type})if stream_type not in ['video', 'audio']:result['has_extra_streams'] = Trueif 'format' in ffprobe_data and 'nb_streams' in ffprobe_data['format']:if result['num_streams'] == 0:result['num_streams'] = ffprobe_data['format']['nb_streams']11 unmodified linesexcept Exception as e:result['ffprobe_output_error'] = f"An unexpected error occurred: {e}"result['ffprobe_successful'] = Falsereturn resultdef remove_video_extra_stream_ffmpeg(input_video: str, output_video: str) -> bool:"""Remove extra streams from video using ffmpeg.Args:input_video: Path to input video.output_video: Path to output video.Returns:bool: True if successful, False otherwise."""9 unmodified lines"-movflags", "faststart",output_video,]try:subprocess.run(command_list, shell=False, check=True, capture_output=True)return True9 unmodified linesreturn Falsedef _video_clean_lock_path(video_path: str) -> str:lock_dir = os.path.join(tempfile.gettempdir(), "mossvl_video_clean_locks")os.makedirs(lock_dir, exist_ok=True)path_key = os.path.realpath(video_path).encode("utf-8")return os.path.join(lock_dir, f"{hashlib.sha256(path_key).hexdigest()}.lock")def _is_reusable_clean_video(video_path: str) -> bool:if not os.path.isfile(video_path) or os.path.getsize(video_path) <= 0:return Falseprobe = check_video_for_extra_streams_and_errors(video_path)return probe["ffprobe_successful"] and not probe["has_extra_streams"]def clean_video_streams(video_path: str) -> str:"""Clean video streams if extra streams are detected.Args:video_path: Path to the video file.Returns:str: Path to cleaned video (or original if no cleaning needed)."""4 unmodified linesfile_name_without_ext, file_ext = os.path.splitext(base_name)new_base_name = f"{file_name_without_ext}_fix{file_ext}"video_path_output = os.path.join(output_folder, new_base_name)try:with open(_video_clean_lock_path(video_path), "a") as lock_file:fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)if _is_reusable_clean_video(video_path_output):return video_path_outputtemp_fd, temp_output = tempfile.mkstemp(prefix=f".{file_name_without_ext}_fix.",suffix=file_ext,dir=output_folder,)os.close(temp_fd)try:if not remove_video_extra_stream_ffmpeg(video_path, temp_output):logger.warning("Failed to remove extra streams with ffmpeg")return video_pathos.replace(temp_output, video_path_output)return video_path_outputfinally:if os.path.exists(temp_output):os.unlink(temp_output)except OSError as exc:logger.warning(f"Failed to publish cleaned video for {video_path}: {exc}")return video_pathreturn video_path9 unmodified linesmin_pts = torchcodec_metadata.begin_stream_seconds_from_contentif min_pts is None:min_pts = 0.0# TorchCodec can reject timestamps exactly equal to the reported stream# begin due to tiny metadata/decoder precision differences.safe_min_pts = min_pts + TORCHCODEC_TIMESTAMP_EPSILONmax_pts_candidates = []if torchcodec_metadata.num_frames_from_content and torchcodec_metadata.average_fps:7 unmodified linesmax_pts_candidates.append(torchcodec_metadata.duration_seconds - TORCHCODEC_TIMESTAMP_EPSILON)if max_pts_candidates:max_pts = max(safe_min_pts, min(max_pts_candidates))return [max(safe_min_pts, min(float(t), max_pts)) for t in timestamps]if safe_min_pts > 0:return [max(safe_min_pts, float(t)) for t in timestamps]return [float(t) for t in timestamps]def split_indices(indices: List[Union[int, float]], num_chunks: int) -> List[List[Union[int, float]]]:"""Split an index list into roughly equal chunks.Args:indices: List of indices to split.num_chunks: Number of chunks to create.Returns:List of index chunks."""if len(indices) == 0:raise ValueError("indices must not be empty")if num_chunks <= 0:raise ValueError("num_chunks must be positive")num_chunks = min(num_chunks, len(indices))chunk_size = len(indices) // num_chunkschunks = []for i in range(num_chunks - 1):5 unmodified linesdef decode_sequentially(indices: List[int], video_path: str, ffmpeg_threads: int = 0):"""Decode frames sequentially from a video.Args:indices: List of frame indices to decode.video_path: Path to the video file.ffmpeg_threads: Number of ffmpeg threads to use.Returns:FrameBatch from torchcodec."""7 unmodified linesdef decode_with_multithreading(indices: List[int], num_threads: int, video_path: str) -> dict:"""Decode frames using multithreading with joblib.Args:indices: List of frame indices to decode.num_threads: Number of threads to use.video_path: Path to the video file.Returns:dict: Contains 'data', 'duration_seconds', 'pts_seconds' tensors."""chunks = split_indices(indices, num_chunks=num_threads)results = Parallel(n_jobs=len(chunks), prefer="threads", verbose=0)(delayed(decode_sequentially)(chunk, video_path) for chunk in chunks)return {"data": torch.cat([frame_batch.data for frame_batch in results], dim=0),"duration_seconds": torch.cat([frame_batch.duration_seconds for frame_batch in results], dim=0),4 unmodified linesdef decode_sequentially_timestamp(timestamp_list: List[float], video_path: str, ffmpeg_threads: int = 0):"""Decode frames sequentially from a video based on timestamps.Args:timestamp_list: List of timestamps (in seconds) to decode.video_path: Path to the video file.ffmpeg_threads: Number of ffmpeg threads to use.Returns:FrameBatch from torchcodec."""10 unmodified linesdef timestamp_decode_with_multithreading(timestamp_list: List[float], num_threads: int, video_path: str) -> dict:"""Decode frames using multithreading based on timestamps.Args:timestamp_list: List of timestamps (in seconds) to decode.num_threads: Number of threads to use.video_path: Path to the video file.Returns:dict: Contains 'data', 'duration_seconds', 'pts_seconds' tensors."""chunks = split_indices(timestamp_list, num_chunks=num_threads)results = Parallel(n_jobs=len(chunks), prefer="threads", verbose=0)(delayed(decode_sequentially_timestamp)(chunk, video_path) for chunk in chunks)# Concatenate results from all threadsdata_list = [frame_batch.data for frame_batch in results]duration_list = [frame_batch.duration_seconds for frame_batch in results]pts_list = [frame_batch.pts_seconds for frame_batch in results]if not data_list:logger.warning("No frames were successfully decoded.")return {"data": torch.empty(0), "duration_seconds": torch.empty(0), "pts_seconds": torch.empty(0)}return {"data": torch.cat(data_list, dim=0),"duration_seconds": torch.cat(duration_list, dim=0),9 unmodified lines) -> Optional[dict]:"""Extract frames from video using torchcodec with multithreading.Args:video_path: Path to the video file.sample_frames_count: Number of frames to sample.num_threads: Number of threads to use for extraction.sampling_method: Sampling method, either "index" (uniform frame indices) or "timestamp" (uniform timestamps).Returns:dict: Contains 'data' (N, C, H, W), 'duration_seconds' (N,), 'pts_seconds' (N,) tensors.Returns None if extraction fails.5 unmodified linestotal_frames_in_video = metadata.num_frames_from_contenteffective_sample_count = min(sample_frames_count, total_frames_in_video)if effective_sample_count == 0:logger.error("Cannot extract frames: video has 0 frames or specified frame count is 0")return None# Generate uniform frame indicesframe_indices = np.linspace(0, total_frames_in_video - 1, effective_sample_count).astype(np.int32)# Ensure indices are valid and remove duplicatesframe_indices = np.unique(np.clip(frame_indices, 0, total_frames_in_video - 1))result = decode_with_multithreading(frame_indices.tolist(), num_threads=num_threads, video_path=video_path)# Add frame_indices to the result for later useresult["frame_indices"] = frame_indicesreturn resultexcept Exception:traceback.print_exc()return None129 unmodified linesreturn video_input["video_path"]return video_inputdef _get_video_fps_from_input(self,video_input: Union[str, Dict[str, Any]],default_fps: Optional[float],) -> Optional[float]:if not isinstance(video_input, dict) or "fps" not in video_input:return default_fpsraw_fps = video_input["fps"]if raw_fps is None:return default_fpstry:fps = float(raw_fps)except (TypeError, ValueError) as exc:raise ValueError(f"Invalid video fps value: {raw_fps!r}") from excif fps <= 0:raise ValueError(f"Invalid video fps value: {raw_fps!r}; fps must be positive")return fpsdef _get_video_duration_seconds(self, video_input: Union[str, Dict[str, Any]]) -> float:"""Get video duration in seconds for weighted frame-budget allocation."""video_path = cached_clean_video_streams(self._get_video_path_from_input(video_input))81 unmodified lines) -> int:"""Calculate the number of frames to sample using fps-based logic with min/max constraints.Logic:1. Calculate target_frames based on fps and video duration2. Apply min_frames and max_frames constraints3. Apply max_allowed_frames protection (rough cap from total video_max_pixels budget)4. Return the number of frames to sampleArgs:metadata (`VideoMetadata`):Metadata of the video containing information about total duration, fps and total number of frames.13 unmodified linesraise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")total_num_frames = metadata.total_num_frames# Use provided min/max or fall back to defaultseffective_min_frames = min_frames if min_frames is not None else self.min_frameseffective_max_frames = max_frames if max_frames is not None else self.max_frames# Rough per-video frame cap derived from the multi-video total budget# (exact allocation happens later in _preprocess via weighted distribution)per_frame_min_pixels = self.size.get("shortest_edge", None) if self.size else None1 unmodified lineif per_frame_min_pixels is not None and video_max_pixels is not None and per_frame_min_pixels > 0:max_allowed_frames = video_max_pixels // per_frame_min_pixelseffective_max_frames = min(effective_max_frames, max_allowed_frames)# Get video durationif hasattr(metadata, 'duration') and metadata.duration is not None:duration = metadata.duration11 unmodified lines# Use provided fps or defaulttarget_fps = fps if fps is not None else self.video_fps# Calculate target frames based on fps and durationif num_frames is None:# Calculate how many frames we should sample based on target fpstarget_total_frames = int(math.ceil(duration * target_fps - 1e-6))# Apply min/max constraintssample_frames = max(target_total_frames, effective_min_frames)sample_frames = min(sample_frames, effective_max_frames, total_num_frames)142 unmodified lines):"""Fetch video frames for a specific segment.Args:video_path: Path to the video filesegment: [start, end] for a segment (left-closed, right-open) or [time] for a single framemin_frames: Minimum frames for this segment (weighted). Defaults to self.min_frames. Must be >= 1.max_frames: Maximum frames for this segment (weighted). Defaults to self.max_frames. Must be >= 1.video_fps: Target frames per second for video sampling. If None, uses self.video_fps.Returns:Tuple of (video_tensor, video_metadata)"""2 unmodified linesmax_frames = max(1, max_frames if max_frames is not None else self.max_frames)# Use provided video_fps or fall back to self.video_fpstarget_video_fps = video_fps if video_fps is not None else self.video_fpsvideo_path = cached_clean_video_streams(video_path)decoder = VideoDecoder(video_path, num_ffmpeg_threads=0)try:torchcodec_metadata = decoder.metadatavideo_fps = torchcodec_metadata.average_fps# Calculate durationduration = Noneif torchcodec_metadata.end_stream_seconds_from_content is not None and torchcodec_metadata.begin_stream_seconds_from_content is not None:duration = torchcodec_metadata.end_stream_seconds_from_content - torchcodec_metadata.begin_stream_seconds_from_contentif duration is None or duration <= 0:duration = torchcodec_metadata.duration_secondsif len(segment) == 1:# Single frame at specified timeactual_timestamps = self._clamp_timestamps_for_decoder([segment[0]], torchcodec_metadata)4 unmodified lines# Segment [start, end) - left-closed, right-open intervalstart_time, end_time = segmentsegment_duration = end_time - start_time# Calculate number of frames to sample for this segmenttarget_frames = int(math.ceil(segment_duration * target_video_fps))target_frames = max(target_frames, min_frames)target_frames = min(target_frames, max_frames)# Generate timestamps for uniform sampling within segmentif target_frames == 1:actual_timestamps = [start_time] # Use start_time for single frameelse:# Sample uniformly within [start, end), endpoint=False for left-closed right-openactual_timestamps = np.linspace(start_time, end_time, target_frames, endpoint=False).tolist()actual_timestamps = self._clamp_timestamps_for_decoder(actual_timestamps, torchcodec_metadata)# Use multithreading for extractionresult = timestamp_decode_with_multithreading(actual_timestamps, self.num_extract_threads, video_path)video_tensor = result["data"]sample_count = len(actual_timestamps)# Create VideoMetadatavideo_metadata = VideoMetadata(total_num_frames=sample_count,4 unmodified lineswidth=torchcodec_metadata.width,frames_indices=None)# Store actual timestamps as a custom attribute for _calculate_timestamps to usevideo_metadata.actual_timestamps = actual_timestampsreturn video_tensor, video_metadatafinally:del decoderdef fetch_videos(self,video_url_or_urls: Union[str, Dict[str, Any], List[Union[str, Dict[str, Any]]]],sample_indices_fn=None,video_fps: Optional[float] = None,min_frames: Optional[int] = None,max_frames: Optional[int] = None,):"""Override fetch_videos to use torchcodec for frame extraction.This method uses torchcodec with multithreading for efficient frame extraction.Frame count is calculated by the calculate_num_frames method(fps-based with min/max constraints).Args:video_url_or_urls: Can be one of:- str: Single video path- Dict: Video descriptor with ``video_path`` and optional ``fps`` /``segments`` (``segment`` is accepted as an alias)- List[Union[str, Dict]]: List of video paths or descriptorssample_indices_fn: (Not used) Kept for compatibility with base class signature.video_fps: Target frames per second for video sampling. If None, uses self.video_fps.min_frames: Minimum number of frames to sample. If None, uses self.min_frames.max_frames: Maximum number of frames to sample. If None, uses self.max_frames.Returns:Tuple of (videos, metadata) where videos are torch.Tensors and metadata are VideoMetadata objects."""13 unmodified lineseffective_max_frames,)for x, allocated_max_frames in zip(video_url_or_urls, per_video_max_frames):explicit_video_fps = self._get_video_fps_from_input(x, None)item_video_fps = explicit_video_fps if explicit_video_fps is not None else effective_video_fpsresult = self.fetch_videos(x,video_fps=item_video_fps,min_frames=effective_min_frames,max_frames=allocated_max_frames,)5 unmodified linesall_videos.append(result[0])all_metadata.append(result[1])return all_videos, all_metadata# Dict inputs may override FPS and optionally select segments. Without# segments, the dict describes a full video.if isinstance(video_url_or_urls, dict):video_path = video_url_or_urls["video_path"]input_video_fps = self._get_video_fps_from_input(video_url_or_urls, effective_video_fps)segments = video_url_or_urls.get("segments", video_url_or_urls.get("segment"))if segments is not None:return self._fetch_video_segments_batched(video_path,segments,min_frames=effective_min_frames,max_frames=effective_max_frames,video_fps=input_video_fps,)video_url_or_urls = video_patheffective_video_fps = input_video_fps# Single video pathvideo_path = video_url_or_urls# Clean video streams first (remove extra streams if needed)video_path = cached_clean_video_streams(video_path)6 unmodified linesduration = Noneif torchcodec_metadata.end_stream_seconds_from_content is not None and torchcodec_metadata.begin_stream_seconds_from_content is not None:duration = torchcodec_metadata.end_stream_seconds_from_content - torchcodec_metadata.begin_stream_seconds_from_contentif duration is None or duration <= 0:duration = torchcodec_metadata.duration_seconds# Use num_frames_from_content for accurate frame count (consistent with extraction)total_frames_in_video = torchcodec_metadata.num_frames_from_content# Create VideoMetadata object for sample_frames methodtemp_metadata = VideoMetadata(total_num_frames=total_frames_in_video,4 unmodified lineswidth=torchcodec_metadata.width,frames_indices=None)# Use calculate_num_frames method to get the number of frames to samplesample_frames_count = self.calculate_num_frames(temp_metadata,fps=effective_video_fps,min_frames=effective_min_frames,max_frames=effective_max_frames,)# Ensure sample count is valideffective_sample_count = min(sample_frames_count, total_frames_in_video)if effective_sample_count == 0:raise ValueError(f"Cannot extract frames: video has 0 frames or specified frame count is 0")# Generate uniform frame indicesframe_indices = np.linspace(0, total_frames_in_video - 1, effective_sample_count).astype(np.int32)# Ensure indices are valid and remove duplicatesframe_indices = np.unique(np.clip(frame_indices, 0, total_frames_in_video - 1))# Extract frames using multithreading (decoder is created inside each thread for thread safety)result = decode_with_multithreading(frame_indices.tolist(), num_threads=self.num_extract_threads, video_path=video_path)# Extract frame tensor (N, C, H, W)frames_tensor = result["data"]# Create final VideoMetadata objectvideo_metadata = VideoMetadata(total_num_frames=len(frame_indices),4 unmodified lineswidth=torchcodec_metadata.width,frames_indices=frame_indices)# Ensure frames are in (T, C, H, W) formatif frames_tensor.dim() == 4: # (N, C, H, W)video_tensor = frames_tensorelse:raise ValueError(f"Unexpected frame tensor shape: {frames_tensor.shape}")return video_tensor, video_metadataexcept Exception as e:logger.error(f"Error loading video {video_path}: {e}")traceback.print_exc()98 unmodified linesmerge_size,patch_size,)patches_device = patches.device# NPU: max 8D tensors — route the 10D permute+reshape through CPU.# CUDA handles 10D natively — keep it on-device.if patches_device.type == "npu":patches = patches.cpu()patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)flatten_patches = patches.reshape(batch_size,grid_t * grid_h * grid_w,channel * temporal_patch_size * patch_size * patch_size,).to(patches_device)processed_videos_grouped[shape] = flatten_patchesprocessed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size16 unmodified lines) -> BatchFeature:"""Preprocess videos for the model.This method overrides the base class to handle two video input formats:1. String path: "path/to/video.mp4"2. Dict descriptor with ``video_path`` and optional ``fps`` / ``segments``Args:videos: Video input(s) in one of the supported formats.**kwargs: Additional arguments passed to _preprocess.Returns:BatchFeature with pixel_values_videos, video_grid_thw, and optionally video_metadata."""2 unmodified linescaptured_kwargs=kwargs.keys(),valid_processor_keys=list(self.valid_kwargs.__annotations__.keys()) + ["return_tensors"],)# Set default kwargs from selffor kwarg_name in self.valid_kwargs.__annotations__:kwargs.setdefault(kwarg_name, getattr(self, kwarg_name, None))# Pop kwargs that are handled separatelyreturn_tensors = kwargs.pop("return_tensors", None)return_metadata = kwargs.pop("return_metadata", False)2 unmodified lineskwargs.pop("video_metadata", None) # We generate our own metadatakwargs.pop("do_sample_frames", None) # We handle sampling ourselveskwargs.pop("data_format", None) # Not used# Normalize input to list formatif not isinstance(videos, list):videos = [videos]# Get video processing params from kwargs (may be passed explicitly for per-batch configuration)video_fps = kwargs.pop("video_fps", None)min_frames = kwargs.pop("min_frames", None)max_frames = kwargs.pop("max_frames", None)# Use fetch_videos to handle both string and dict formatsvideo_tensors, video_metadata = self.fetch_videos(videos,video_fps=video_fps,min_frames=min_frames,max_frames=max_frames,)# Prepare video tensors using _prepare_input_videosprepared_videos = self._prepare_input_videos(videos=video_tensors,input_data_format=input_data_format,device=device,)# Process kwargs for _preprocesskwargs = self._further_process_kwargs(**kwargs)self._validate_preprocess_kwargs(**kwargs)# Call _preprocess with prepared videosresult = self._preprocess(videos=prepared_videos, return_tensors=return_tensors, **kwargs)# Add metadata if requestedif return_metadata:result["video_metadata"] = video_metadatareturn result__all__ = ["MossVLVideoProcessor"]
modeling_moss_vl.py+6-5
preprocessor_config.json+25-43
processing_moss_vl.py+130-125
video_preprocessor_config.json+29-47
video_processing_moss_vl.py+194-117