zzhowe1207 commited on
Commit
3510c51
·
verified ·
1 Parent(s): 5a2b198

Upload rl_code/verl/utils/dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. rl_code/verl/utils/dataset.py +311 -0
rl_code/verl/utils/dataset.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ import os
17
+ from collections import defaultdict
18
+ from io import BytesIO
19
+ from typing import Any, Dict, List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ from datasets import load_dataset
24
+ from jinja2 import Template
25
+ from PIL import Image
26
+ from PIL.Image import Image as ImageObject
27
+ from qwen_vl_utils.vision_process import fetch_video
28
+ from torch.utils.data import Dataset
29
+ from transformers import PreTrainedTokenizer, ProcessorMixin
30
+
31
+ from ..models.transformers.qwen2_vl import get_rope_index
32
+ from . import torch_functional as VF
33
+
34
+
35
+ def collate_fn(features: List[Dict[str, Any]]) -> Dict[str, Any]:
36
+ tensors = defaultdict(list)
37
+ non_tensors = defaultdict(list)
38
+ for feature in features:
39
+ for key, value in feature.items():
40
+ if isinstance(value, torch.Tensor):
41
+ tensors[key].append(value)
42
+ else:
43
+ non_tensors[key].append(value)
44
+
45
+ for key, value in tensors.items():
46
+ tensors[key] = torch.stack(value, dim=0)
47
+
48
+ for key, value in non_tensors.items():
49
+ non_tensors[key] = np.array(value, dtype=object)
50
+
51
+ return {**tensors, **non_tensors}
52
+
53
+
54
+ def process_image(
55
+ image: Union[Dict[str, Any], ImageObject, str], min_pixels: Optional[int], max_pixels: Optional[int]
56
+ ) -> ImageObject:
57
+ if isinstance(image, str):
58
+ image = Image.open(image)
59
+ elif isinstance(image, dict):
60
+ image = Image.open(BytesIO(image["bytes"]))
61
+ elif isinstance(image, bytes):
62
+ image = Image.open(BytesIO(image))
63
+
64
+ image.load() # avoid "Too many open files" errors
65
+ if max_pixels is not None and (image.width * image.height) > max_pixels:
66
+ resize_factor = math.sqrt(max_pixels / (image.width * image.height))
67
+ width, height = int(image.width * resize_factor), int(image.height * resize_factor)
68
+ image = image.resize((width, height))
69
+
70
+ if min_pixels is not None and (image.width * image.height) < min_pixels:
71
+ resize_factor = math.sqrt(min_pixels / (image.width * image.height))
72
+ width, height = int(image.width * resize_factor), int(image.height * resize_factor)
73
+ image = image.resize((width, height))
74
+
75
+ if image.mode != "RGB":
76
+ image = image.convert("RGB")
77
+
78
+ return image
79
+
80
+
81
+ def process_video(
82
+ video: str, min_pixels: Optional[int], max_pixels: Optional[int], video_fps: float, return_fps: bool = False
83
+ ) -> Union[List[ImageObject], Tuple[List[ImageObject], List[float]]]:
84
+ vision_info = {"video": video, "min_pixels": min_pixels, "max_pixels": max_pixels, "fps": video_fps}
85
+ return fetch_video(vision_info, return_video_sample_fps=return_fps)
86
+
87
+
88
+ class RLHFDataset(Dataset):
89
+ """
90
+ We assume the dataset contains a column that contains prompts and other information
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ data_path: str,
96
+ tokenizer: PreTrainedTokenizer,
97
+ processor: Optional[ProcessorMixin],
98
+ prompt_key: str = "prompt",
99
+ answer_key: str = "answer",
100
+ image_key: str = "images",
101
+ video_key: str = "videos",
102
+ image_dir: Optional[str] = None,
103
+ video_fps: float = 2.0,
104
+ max_prompt_length: int = 1024,
105
+ truncation: str = "error",
106
+ format_prompt: Optional[str] = None,
107
+ min_pixels: Optional[int] = None,
108
+ max_pixels: Optional[int] = None,
109
+ filter_overlong_prompts: bool = True,
110
+ filter_overlong_prompts_workers: int = 16,
111
+ ):
112
+ self.tokenizer = tokenizer
113
+ self.processor = processor
114
+ self.prompt_key = prompt_key
115
+ self.answer_key = answer_key
116
+ self.image_key = image_key
117
+ self.video_key = video_key
118
+ self.image_dir = image_dir
119
+ self.video_fps = video_fps
120
+ self.max_prompt_length = max_prompt_length
121
+ self.truncation = truncation
122
+ self.min_pixels = min_pixels
123
+ self.max_pixels = max_pixels
124
+
125
+ if "@" in data_path:
126
+ data_path, data_split = data_path.split("@")
127
+ else:
128
+ data_split = "train"
129
+
130
+ if os.path.isdir(data_path):
131
+ # Check if it's a HuggingFace dataset directory (contains train/, validation/, etc.)
132
+ subdirs = [d for d in os.listdir(data_path) if os.path.isdir(os.path.join(data_path, d))]
133
+ if any(split_name in subdirs for split_name in ['train', 'validation', 'test']):
134
+ # This is a HuggingFace dataset directory, load it directly
135
+ from datasets import load_from_disk
136
+ full_dataset = load_from_disk(data_path)
137
+ self.dataset = full_dataset[data_split]
138
+ else:
139
+ # when we use dataset builder, we should always refer to the train split
140
+ file_type = os.path.splitext(os.listdir(data_path)[0])[-1][1:].replace("jsonl", "json")
141
+ self.dataset = load_dataset(file_type, data_dir=data_path, split=data_split)
142
+ elif os.path.isfile(data_path):
143
+ file_type = os.path.splitext(data_path)[-1][1:].replace("jsonl", "json")
144
+ self.dataset = load_dataset(file_type, data_files=data_path, split=data_split)
145
+ else:
146
+ # load remote dataset from huggingface hub
147
+ self.dataset = load_dataset(data_path, split=data_split)
148
+
149
+ self.format_prompt = None
150
+ if format_prompt:
151
+ with open(format_prompt, encoding="utf-8") as f:
152
+ self.format_prompt = f.read()
153
+
154
+ if filter_overlong_prompts:
155
+ self.dataset = self.dataset.filter(
156
+ self._filter_overlong_prompts,
157
+ desc="Filtering overlong prompts",
158
+ num_proc=filter_overlong_prompts_workers,
159
+ )
160
+
161
+ def _build_messages(self, example: Dict[str, Any]) -> List[Dict[str, Any]]:
162
+ prompt_str: str = example[self.prompt_key]
163
+ if self.format_prompt:
164
+ format_prompt = Template(self.format_prompt.strip())
165
+ prompt_str = format_prompt.render(content=prompt_str)
166
+
167
+ if self.image_key in example:
168
+ # https://huggingface.co/docs/transformers/en/tasks/image_text_to_text
169
+ content_list = []
170
+ for i, content in enumerate(prompt_str.split("<image>")):
171
+ if i != 0:
172
+ content_list.append({"type": "image"})
173
+
174
+ if content:
175
+ content_list.append({"type": "text", "text": content})
176
+
177
+ return [{"role": "user", "content": content_list}]
178
+ elif self.video_key in example:
179
+ content_list = []
180
+ for i, content in enumerate(prompt_str.split("<video>")):
181
+ if i != 0:
182
+ content_list.append({"type": "video"})
183
+
184
+ if content:
185
+ content_list.append({"type": "text", "text": content})
186
+
187
+ return [{"role": "user", "content": content_list}]
188
+ else:
189
+ return [{"role": "user", "content": prompt_str}]
190
+
191
+ def _filter_overlong_prompts(self, example: Dict[str, Any]) -> bool:
192
+ messages = self._build_messages(example)
193
+ if self.image_key in example:
194
+ prompt = self.processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
195
+ images = example[self.image_key]
196
+ if self.image_dir is not None and len(images) != 0 and isinstance(images[0], str): # image paths
197
+ images = [os.path.join(self.image_dir, image) for image in images]
198
+
199
+ processed_images = [] if len(images) != 0 else None # text-only data
200
+ for image in images:
201
+ processed_images.append(process_image(image, self.min_pixels, self.max_pixels))
202
+
203
+ model_inputs = self.processor(processed_images, [prompt], add_special_tokens=False, return_tensors="pt")
204
+ return model_inputs["input_ids"].size(-1) <= self.max_prompt_length
205
+ elif self.video_key in example:
206
+ prompt = self.processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
207
+ videos = example[self.video_key]
208
+ if self.image_dir is not None and len(videos) != 0 and isinstance(videos[0], str): # video paths
209
+ videos = [os.path.join(self.image_dir, video) for video in videos]
210
+
211
+ processed_videos = [] if len(videos) != 0 else None # text-only data
212
+ for video in videos:
213
+ processed_videos.append(process_video(video, self.min_pixels, self.max_pixels, self.video_fps))
214
+
215
+ model_inputs = self.processor(
216
+ videos=processed_videos, text=[prompt], add_special_tokens=False, return_tensors="pt"
217
+ )
218
+ return model_inputs["input_ids"].size(-1) <= self.max_prompt_length
219
+ else:
220
+ input_ids = self.tokenizer.apply_chat_template(messages, add_generation_prompt=True)
221
+ return len(input_ids) <= self.max_prompt_length
222
+
223
+ def __len__(self):
224
+ return len(self.dataset)
225
+
226
+ def __getitem__(self, index):
227
+ example: dict = self.dataset[index]
228
+ messages = self._build_messages(example)
229
+ example.pop(self.prompt_key, None)
230
+
231
+ if self.image_key in example:
232
+ prompt = self.processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
233
+ images = example.pop(self.image_key)
234
+ if self.image_dir is not None and len(images) != 0 and isinstance(images[0], str): # image paths
235
+ images = [os.path.join(self.image_dir, image) for image in images]
236
+
237
+ processed_images = [] if len(images) != 0 else None # text-only data
238
+ for image in images:
239
+ processed_images.append(process_image(image, self.min_pixels, self.max_pixels))
240
+
241
+ model_inputs = self.processor(processed_images, [prompt], add_special_tokens=False, return_tensors="pt")
242
+ input_ids = model_inputs.pop("input_ids")[0]
243
+ attention_mask = model_inputs.pop("attention_mask")[0]
244
+ example["multi_modal_data"] = {"images": images}
245
+ elif self.video_key in example:
246
+ prompt = self.processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
247
+ videos = example.pop(self.video_key)
248
+ if self.image_dir is not None and len(videos) != 0 and isinstance(videos[0], str): # video paths
249
+ videos = [os.path.join(self.image_dir, video) for video in videos]
250
+
251
+ processed_videos = [] if len(videos) != 0 else None # text-only data
252
+ video_fps_list = []
253
+ for video in videos:
254
+ processed_video, video_fps = process_video(
255
+ video, self.min_pixels, self.max_pixels, self.video_fps, return_fps=True
256
+ )
257
+ processed_videos.append(processed_video)
258
+ video_fps_list.append(video_fps)
259
+
260
+ model_inputs = self.processor(
261
+ videos=processed_videos, text=[prompt], add_special_tokens=False, return_tensors="pt"
262
+ )
263
+ if "second_per_grid_ts" in self.processor.model_input_names:
264
+ model_inputs["second_per_grid_ts"] = [2.0 / video_sample_fps for video_sample_fps in video_fps_list]
265
+
266
+ input_ids = model_inputs.pop("input_ids")[0]
267
+ attention_mask = model_inputs.pop("attention_mask")[0]
268
+ example["multi_modal_data"] = {"videos": videos}
269
+ else:
270
+ prompt = self.tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
271
+ model_inputs = self.tokenizer([prompt], add_special_tokens=False, return_tensors="pt")
272
+ input_ids = model_inputs.pop("input_ids")[0]
273
+ attention_mask = model_inputs.pop("attention_mask")[0]
274
+
275
+ if self.processor is not None and "Qwen2VLImageProcessor" in self.processor.image_processor.__class__.__name__:
276
+ # qwen2vl mrope
277
+ position_ids = get_rope_index(
278
+ self.processor,
279
+ input_ids=input_ids,
280
+ image_grid_thw=model_inputs.get("image_grid_thw", None),
281
+ video_grid_thw=model_inputs.get("video_grid_thw", None),
282
+ second_per_grid_ts=model_inputs.get("second_per_grid_ts", None),
283
+ attention_mask=attention_mask,
284
+ ) # (3, seq_length)
285
+ else:
286
+ position_ids = torch.clip(attention_mask.cumsum(dim=0) - 1, min=0, max=None) # (seq_length,)
287
+
288
+ input_ids, attention_mask, position_ids = VF.postprocess_data(
289
+ input_ids=input_ids,
290
+ attention_mask=attention_mask,
291
+ position_ids=position_ids,
292
+ max_length=self.max_prompt_length,
293
+ pad_token_id=self.tokenizer.pad_token_id,
294
+ left_pad=True,
295
+ truncation=self.truncation,
296
+ )
297
+ raw_prompt_ids = self.tokenizer.encode(prompt, add_special_tokens=False)
298
+ if len(raw_prompt_ids) > self.max_prompt_length:
299
+ if self.truncation == "left":
300
+ raw_prompt_ids = raw_prompt_ids[-self.max_prompt_length :]
301
+ elif self.truncation == "right":
302
+ raw_prompt_ids = raw_prompt_ids[: self.max_prompt_length]
303
+ elif self.truncation == "error":
304
+ raise RuntimeError(f"Prompt length {len(raw_prompt_ids)} is longer than {self.max_prompt_length}.")
305
+
306
+ example["input_ids"] = input_ids
307
+ example["attention_mask"] = attention_mask
308
+ example["position_ids"] = position_ids
309
+ example["raw_prompt_ids"] = raw_prompt_ids
310
+ example["ground_truth"] = example.pop(self.answer_key)
311
+ return example