-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrain_qwen_gp.py
More file actions
2035 lines (1716 loc) · 83.7 KB
/
Copy pathtrain_qwen_gp.py
File metadata and controls
2035 lines (1716 loc) · 83.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import ast
import math
import yaml
import warnings
from datetime import datetime
from dataclasses import dataclass, field
from collections import defaultdict
from typing import Any, Callable, Optional, Union, Sized, Dict, Tuple, List, Literal, Type
import numpy as np
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import datasets
from PIL import Image
from trl import ModelConfig, ScriptArguments, TrlParser, get_peft_config
from trl.models import unwrap_model_for_generation
from transformers import (
TrainingArguments,
Trainer,
GenerationConfig,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import (
is_safetensors_available,
is_peft_available
)
if is_safetensors_available():
import safetensors.torch
from peft import PeftConfig, get_peft_model, PeftModel
from accelerate.utils import is_peft_model, set_seed
from qwen_vl_utils import process_vision_info
from transformers_gp.models.qwen2_5_vl import (
Qwen2_5_VL_GP_ForConditionalGeneration,
Qwen2_5_VL_GP_Processor,
Qwen2_5_VL_GPConfig,
)
from transformers.trainer import (
logger,
TRAINING_ARGS_NAME,
CONFIG_NAME,
ADAPTER_WEIGHTS_NAME,
ADAPTER_SAFE_WEIGHTS_NAME,
WEIGHTS_NAME,
WEIGHTS_INDEX_NAME,
SAFE_WEIGHTS_NAME,
SAFE_WEIGHTS_INDEX_NAME,
FSDP_MODEL_NAME,
)
from utils.warppers import debug_calls
from utils.utils import (
norm_bboxes,
extract_one_bbox_from_str,
cal_paired_ious,
print_rank0
)
from utils.client import LLMClient
# ---------- Datasets ----------
QUERY_KEY = "query"
IMG_PATH_KEY = "img_path"
ANSWER_KEY = "answer"
NORMED_BBOXES_KEY = "normed_bboxes"
SCORE_FUNCS_KEY = "score_funcs"
REMAIN_KEYS = [
QUERY_KEY,
IMG_PATH_KEY,
NORMED_BBOXES_KEY,
ANSWER_KEY,
SCORE_FUNCS_KEY,
]
MAPPER_REGISTRY = {}
FILTER_REGISTRY = {}
def register_mappers():
def wrapper(func):
name = func.__name__.replace("_dataset_mapper", "")
MAPPER_REGISTRY[name] = func
return func
return wrapper
def register_filters():
def wrapper(func):
name = func.__name__.replace("_dataset_filter", "")
FILTER_REGISTRY[name] = func
return func
return wrapper
@register_mappers()
def cot_train_dataset_mapper(one_data, **kwargs):
query = one_data['question']
if 'prompt' in kwargs:
query = kwargs['prompt'].format(query)
answer = one_data['answer']
image = one_data['image']
dataset = one_data['dataset']
img_path = os.path.join(kwargs['img_dir'], "cot", dataset, image)
bboxes = one_data['bboxs']
# normed_bboxes = norm_bboxes(bboxes, height, width, bbox_type=kwargs['bbox_type'])
return {
QUERY_KEY: query,
ANSWER_KEY: answer,
IMG_PATH_KEY: img_path,
NORMED_BBOXES_KEY: bboxes,
SCORE_FUNCS_KEY: kwargs['score_funcs']
}
@register_mappers()
def cot_train_fullmask_dataset_mapper(one_data, **kwargs):
query = one_data['question']
if 'prompt' in kwargs:
query = kwargs['prompt'].format(query)
answer = one_data['answer']
image = one_data['image']
dataset = one_data['dataset']
img_path = os.path.join(kwargs['img_dir'], "cot", dataset, image)
normed_bboxes = [[0.0, 0.0, 1.0, 1.0]]
return {
QUERY_KEY: query,
ANSWER_KEY: answer,
IMG_PATH_KEY: img_path,
NORMED_BBOXES_KEY: normed_bboxes,
SCORE_FUNCS_KEY: kwargs['score_funcs']
}
@register_mappers()
def norm_bboxes_dataset_mapper(one_data, **kwargs):
bboxes = one_data.pop(NORMED_BBOXES_KEY)
if 'width' in one_data:
width = one_data['width']
height = one_data['height']
else:
img_path = one_data[IMG_PATH_KEY]
img_pil = Image.open(img_path)
width, height = img_pil.size
img_pil.close()
normed_bboxes = norm_bboxes(bboxes, height, width, bbox_type=kwargs['bbox_type'])
one_data[NORMED_BBOXES_KEY] = normed_bboxes
return one_data
@register_filters()
def image_exist_dataset_filter(one_data, **kwargs):
img_path = one_data[IMG_PATH_KEY]
try:
img = Image.open(img_path)
img.close() # Close the image to free resources
return True # Image exists and is valid
except (FileNotFoundError, OSError) as e:
print_rank0(f"Image not found or invalid: {img_path}. Error: {e}")
return False
except Exception as e:
print_rank0(f"Unexpected error while checking image: {img_path}. Error: {e}")
return False
@register_filters()
def inputs_seq_length_dataset_filter(one_data, **kwargs):
processor = kwargs['processor']
max_input_seq_length = kwargs.get('max_input_seq_length', None)
max_input_remain_seq_length = kwargs.get('max_input_remain_seq_length', None)
if max_input_seq_length is None and max_input_remain_seq_length is None:
return True
img_path = one_data[IMG_PATH_KEY]
query = one_data[QUERY_KEY]
normed_bboxes = [one_data[NORMED_BBOXES_KEY]] if max_input_remain_seq_length is not None else None
messages = [[{"role": "user", "content": [{"type": "image", "image": img_path}, {"type": "text", "text": query}]}]]
text = processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
text=text,
images=image_inputs,
videos=video_inputs,
normed_bboxes=normed_bboxes,
padding=True,
return_tensors="pt",
)
seq_length = inputs.input_ids.shape[1]
if max_input_seq_length is not None and seq_length > max_input_seq_length:
# print_rank0(f"Input sequence length {seq_length} exceeds max limit {max_input_seq_length}. Filtering out.")
return False
if max_input_remain_seq_length is not None:
ref_token_masks = inputs.ref_token_masks[0]
reduced_num = ref_token_masks.numel() - ref_token_masks.sum().item()
remain_seq_length = seq_length - reduced_num
if remain_seq_length > max_input_remain_seq_length:
# print_rank0(f"Remaining sequence length {remain_seq_length} exceeds max limit {max_input_remain_seq_length}. Filtering out.")
return False
return True
# ---------- Loss ----------
LOSS_REGISTRY = {}
def register_loss(loss_class):
"""
Decorator to register a loss class in the LOSS
registry. The class should inherit from torch.nn.Module.
"""
name = loss_class.__name__
if name in LOSS_REGISTRY:
raise ValueError(f"Loss class '{name}' is already registered.")
LOSS_REGISTRY[name] = loss_class
return loss_class
@register_loss
class DiceLoss(nn.Module):
def __init__(self, epsilon: float = 1e-6, **kwargs):
super().__init__()
self.epsilon = epsilon
def forward(self,
image_token_mask_logits: List[torch.Tensor],
ref_token_masks: List[torch.Tensor]
) -> torch.Tensor:
if not isinstance(image_token_mask_logits, list) or not isinstance(ref_token_masks, list):
raise TypeError("Inputs must be lists of tensors.")
if len(image_token_mask_logits) != len(ref_token_masks):
raise ValueError(f"Input lists must have the same length, but got "
f"{len(image_token_mask_logits)} and {len(ref_token_masks)}")
if len(image_token_mask_logits) == 0:
# Handle empty batch case if necessary, e.g., return 0 loss or raise error
return torch.tensor(0.0, device=image_token_mask_logits[0].device if image_token_mask_logits else None)
# Or raise ValueError("Input lists cannot be empty") depending on desired behavior
batch_size = len(image_token_mask_logits)
total_dice_loss = 0.0
for i in range(batch_size):
pred_mask_1d = image_token_mask_logits[i].flatten().sigmoid() # Shape: (N_b,) float
# Flatten the ground truth mask and convert to float
# Ensure it's on the same device as the prediction
gt_mask_1d = ref_token_masks[i].flatten().to(pred_mask_1d.device, dtype=torch.float) # Shape: (N_b,) float
# Calculate Dice components
intersection = (pred_mask_1d * gt_mask_1d).sum()
pred_sum = pred_mask_1d.sum()
gt_sum = gt_mask_1d.sum() # Already float
# Calculate Dice coefficient for this sample
dice_coefficient = (2.0 * intersection + self.epsilon) / (pred_sum + gt_sum + self.epsilon)
# Calculate Dice loss for this sample
dice_loss_sample = 1.0 - dice_coefficient
# Accumulate loss
total_dice_loss += dice_loss_sample
# Average loss over the batch
average_dice_loss = total_dice_loss / batch_size
return average_dice_loss
@register_loss
class BCELoss(nn.Module):
def ___init__(self, **kwargs):
super(BCELoss, self).__init__()
def forward(self,
image_token_mask_logits: List[torch.Tensor],
ref_token_masks: List[torch.Tensor]
) -> torch.Tensor:
batch_size = len(image_token_mask_logits)
total_bce_loss = 0.0
for i in range(batch_size):
pred_mask_1d = image_token_mask_logits[i].flatten()
# Flatten the ground truth mask and convert to float
gt_mask_1d = ref_token_masks[i].flatten().to(pred_mask_1d.device)
# Calculate BCE loss
bce_loss = F.binary_cross_entropy_with_logits(
pred_mask_1d.float(),
gt_mask_1d.float(),
)
# Accumulate loss
total_bce_loss += bce_loss
# Average loss over the batch
average_bce_loss = total_bce_loss / batch_size
return average_bce_loss
@register_loss
class MaskLoss(nn.Module):
def __init__(self,
dice_weight: float = 0.5,
bce_weight: float = 0.5,
epsilon: float = 1e-6,
**kwargs):
super().__init__()
self.dice_loss = DiceLoss(epsilon=epsilon)
self.bce_loss = BCELoss()
self.dice_weight = dice_weight
self.bce_weight = bce_weight
def forward(self, image_token_mask_logits: List[torch.Tensor],
ref_token_masks: List[torch.Tensor]
) -> torch.Tensor:
"""
Combines Dice Loss and BCE Loss for image token masks.
Args:
image_token_mask_logits (List[torch.Tensor]): List of predicted masks (1D tensors).
ref_token_masks (List[torch.Tensor]): List of ground truth masks (2D tensors).
Returns:
torch.Tensor: Combined loss value.
"""
dice_loss = self.dice_loss(image_token_mask_logits, ref_token_masks)
bce_loss = self.bce_loss(image_token_mask_logits, ref_token_masks)
return self.dice_weight * dice_loss + self.bce_weight * bce_loss
# ---------- Dataset & Collator & Sampler ----------
class GPDataset(torch.utils.data.Dataset):
"""
A PyTorch Dataset that loads and combines multiple datasets
based on a YAML configuration file. It handles sampling
and applies specified mapping functions.
"""
@classmethod
def _load_config(cls, config_path: str) -> Dict[str, Any]:
"""Loads configuration from a YAML file."""
print_rank0(f"Loading configuration from: {config_path}")
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
if config is None or 'datasets' not in config:
raise ValueError("YAML config is empty or missing 'datasets' key.")
print_rank0("Configuration loaded successfully.")
return config
except FileNotFoundError:
print_rank0(f"Error: Configuration file not found at {config_path}")
raise
except yaml.YAMLError as e:
print_rank0(f"Error: Could not parse YAML configuration: {e}")
raise
except Exception as e:
print_rank0(f"An unexpected error occurred during config loading: {e}")
raise
@classmethod
def _apply_sampling(cls, dataset: datasets.Dataset, strategy: Optional[str], seed: Optional[int] = None) -> datasets.Dataset:
"""Applies sampling strategy to a dataset."""
if not strategy:
print_rank0("No sampling strategy specified, using full dataset.")
return dataset
try:
parts = strategy.split(':')
if len(parts) != 2:
raise ValueError(f"Invalid sampling strategy format: '{strategy}'. Expected 'type:value'.")
strat_type, strat_value = parts[0].lower(), parts[1]
num_samples = int(strat_value)
total_size = len(dataset)
if num_samples <= 0:
raise ValueError(f"Sampling value must be positive, got: {num_samples} [{strategy}]")
# Ensure sample size isn't larger than dataset, prevents errors in select/slice
num_samples = min(num_samples, total_size)
print_rank0(f"Applying sampling: {strategy} ({num_samples} samples) to dataset of size {total_size}")
if strat_type == "first":
return dataset.select(range(num_samples))
elif strat_type == "end":
# Ensure we don't request more than available from the end
start_index = max(0, total_size - num_samples)
return dataset.select(range(start_index, total_size))
elif strat_type == "random":
if seed is None:
print_rank0("Warning: Random sampling without a fixed seed. Results may not be reproducible.")
shuffled_dataset = dataset.shuffle(seed=seed)
return shuffled_dataset.select(range(num_samples))
else:
print_rank0(f"Warning: Unknown sampling strategy type: '{strat_type}'. Using full dataset.")
return dataset
except ValueError as e:
print_rank0(f"Error parsing sampling strategy '{strategy}': {e}. Using full dataset.")
return dataset
except Exception as e:
print_rank0(f"An unexpected error occurred during sampling: {e}. Using full dataset.")
return dataset
@classmethod
def _all_processed_datasets(cls, config, processor, args):
all_processed_datasets: Dict[str, datasets.Dataset] = {}
for i, dataset_config in enumerate(config['datasets']):
print_rank0(f"\nProcessing dataset entry {i+1}/{len(config['datasets'])}...")
json_path = dataset_config.get('json_path')
base_name = '.'.join(os.path.basename(json_path).split('.')[:-1])
dataset_name = dataset_config.get('dataset_name', base_name)
if not json_path:
print_rank0(f"Warning: Skipping dataset entry {i+1} due to missing 'json_path'.")
continue
sampling_strategy = dataset_config.get('sampling_strategy', None)
mapper_name = dataset_config.get('mapper')
bbox_type = dataset_config.get('bbox_type')
img_dir = dataset_config.get('img_dir', args.img_dir)
additional_mappers = dataset_config.get('additional_mappers', [])
score_funcs = dataset_config.get('score_funcs', [])
prompt = dataset_config.get('prompt', None)
max_input_seq_length = dataset_config.get('max_input_seq_length', args.max_input_seq_length)
max_input_remain_seq_length = dataset_config.get('max_input_remain_seq_length', args.max_input_remain_seq_length)
for score_func in score_funcs:
assert score_func in SCORE_REGISTRY, f"Score function '{score_func}' not registered. Available: {list(SCORE_REGISTRY.keys())}"
try:
print_rank0(f"Loading raw data from: {json_path}")
# Assuming JSON Lines format, common with `datasets`
raw_dataset = datasets.load_dataset('json', data_files=json_path, split='train')
print_rank0(f"Loaded {len(raw_dataset)} examples raw.")
# Apply sampling
sampled_dataset = cls._apply_sampling(raw_dataset, sampling_strategy, args.sampling_seed)
if len(sampled_dataset) == 0:
print_rank0("Dataset is empty after sampling, skipping.")
continue
print_rank0(f"Dataset size after sampling: {len(sampled_dataset)}")
# Apply mapping
mapper_func = MAPPER_REGISTRY[mapper_name]
print_rank0(f"Applying mapper: '{mapper_name}'")
# Prepare arguments for the mapper function
mapper_kwargs = {
'img_dir': img_dir,
'score_funcs': score_funcs,
}
if prompt is not None:
mapper_kwargs['prompt'] = prompt
print_rank0(f"Mapper arguments: {mapper_kwargs}")
processed_dataset = sampled_dataset.map(
mapper_func,
num_proc=8,
fn_kwargs=mapper_kwargs,
)
processed_dataset = processed_dataset.remove_columns(
[col for col in processed_dataset.column_names if col not in REMAIN_KEYS]
)
# Filtering
print_rank0("Applying dataset filter: 'image_exist_dataset_filter'")
processed_dataset = processed_dataset.filter(
image_exist_dataset_filter,
num_proc=8,
fn_kwargs={}
)
print_rank0(f"Processed dataset size after image_exist_dataset_filter: {len(processed_dataset)}")
# Additional filtering
if max_input_seq_length is not None or max_input_remain_seq_length is not None:
processed_dataset = processed_dataset.filter(
inputs_seq_length_dataset_filter,
num_proc=8,
fn_kwargs={
'processor': processor,
'max_input_seq_length': max_input_seq_length,
'max_input_remain_seq_length': max_input_remain_seq_length,
}
)
print_rank0(f"Processed dataset size after inputs_seq_length_dataset_filter: {len(processed_dataset)}")
# Additional mapping
for additional_mapper in additional_mappers:
mapper_func = MAPPER_REGISTRY[additional_mapper]
print_rank0(f"Applying additional mapper: '{additional_mapper}'")
processed_dataset = processed_dataset.map(
mapper_func,
num_proc=8,
fn_kwargs={
'bbox_type': bbox_type,
}
)
print_rank0(f"Processed dataset size: {len(processed_dataset)}")
if len(processed_dataset) == 0:
print_rank0(f"Warning: Processed dataset {dataset_name} is empty after mapping. Skipping.")
continue
# Store the processed dataset
if dataset_name in all_processed_datasets:
dataset_name_with_uuid = f"{dataset_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
print_rank0(f"Warning: Dataset name '{dataset_name}' already exists. Renaming to '{dataset_name_with_uuid}'")
all_processed_datasets[dataset_name_with_uuid] = processed_dataset
else:
all_processed_datasets[dataset_name] = processed_dataset
except FileNotFoundError:
print_rank0(f"Error: Data file not found for dataset entry {i+1}: {json_path}. Skipping.")
except Exception as e:
print_rank0(f"Error processing dataset entry {i+1} ({json_path}): {e}. Skipping.")
return all_processed_datasets
def __init__(self, config_path: str, processor: Qwen2_5_VL_GP_Processor, script_args: Optional[Any] = None):
"""
Initializes the GPDataset.
Args:
config_path (str): Path to the YAML configuration file.
processor (Qwen2_5_VL_GP_Processor): Processor for handling text and vision data.
script_args (Any, optional): Additional arguments passed from the script
(e.g., training args, could contain seed). Defaults to None.
"""
super().__init__()
self.args = script_args
self.config = self._load_config(config_path)
self.processor = processor
all_processed_datasets = self._all_processed_datasets(self.config, self.processor, self.args)
# Combine all processed datasets
if all_processed_datasets:
print_rank0(f"\nConcatenating {len(all_processed_datasets)} processed dataset(s)...")
# Note: Concatenation works best if all datasets have the exact same features/columns.
# The `map` function should ensure consistent output structure.
# Consider using `features=...` argument in `concatenate_datasets` if schemas might differ slightly
# and you know how to resolve them.
self.final_dataset = datasets.concatenate_datasets(list(all_processed_datasets.values()))
if len(self.final_dataset) == 0:
raise ValueError("Final dataset is empty after concatenation.")
print_rank0(f"Final combined dataset size: {len(self.final_dataset)}")
# Optionally print final features/columns
print_rank0(f"Final dataset features: {self.final_dataset.features}")
else:
# print_rank0("No datasets were successfully processed.")
raise ValueError("No datasets were successfully processed. Please check your configuration.")
self.final_dataset = None
def __len__(self) -> int:
"""Returns the total number of samples in the combined dataset."""
return len(self.final_dataset) if self.final_dataset else 0
def __getitem__(self, index: int) -> Dict[str, Any]:
"""Retrieves a single sample from the combined dataset."""
if self.final_dataset is None:
raise IndexError("Dataset is not initialized or is empty.")
if not 0 <= index < len(self.final_dataset):
raise IndexError(f"Index {index} out of bounds for dataset of size {len(self.final_dataset)}")
# `datasets` objects behave like lists/dicts for access
return self.final_dataset[index]
@classmethod
def get_processed_dataset_dict(cls, config_path: str, processor: Qwen2_5_VL_GP_Processor, script_args: Optional[Any] = None) -> Dict[str, datasets.Dataset]:
"""
Class method to get processed datasets based on the YAML configuration.
Args:
config_path (str): Path to the YAML configuration file.
script_args (Any, optional): Additional arguments passed from the script
(e.g., training args). Defaults to None.
Returns:
Dict[str, datasets.Dataset]: Dictionary of processed datasets.
"""
config = cls._load_config(config_path)
all_processed_datasets = cls._all_processed_datasets(config, processor, script_args)
return all_processed_datasets
class GPCollator:
def __init__(self, processor, is_sft):
self.processor = processor
self.is_sft = is_sft
self.im_start_id = self.processor.tokenizer.encode("<|im_start|>")[0]
def _prepare_labels_from_input_ids(self, input_ids):
B, L = input_ids.shape
labels = input_ids.clone()
mask = input_ids == self.im_start_id
flipped_mask = mask.flip(dims=(1,)) # Reverse the mask to find the last <|im_start|> token
first_idx_in_flipped = torch.argmax(flipped_mask.int(), dim=1)
last_pos = (L - 1) - first_idx_in_flipped
mask_until_idx = last_pos + 3
mask_until_idx = torch.clamp(mask_until_idx, max=L)
arange_l = torch.arange(L, device=input_ids.device).expand(B, -1)
modification_mask = arange_l < mask_until_idx.unsqueeze(1)
labels[modification_mask] = -100 # ignore index of CrossEntropyLoss
return labels
def __call__(self, features):
messages = []
normed_bboxes = []
answers = []
querys = []
score_funcs = []
for feature in features:
query = feature[QUERY_KEY]
answer = feature[ANSWER_KEY]
img_path = feature[IMG_PATH_KEY]
if self.is_sft:
messages.append([{"role": "user", "content": [{"type": "image", "image": img_path}, {"type": "text", "text": query}]}, {"role": "assistant", "content": [{"type": "text", "text": answer}]}])
else:
messages.append([{"role": "user", "content": [{"type": "image", "image": img_path}, {"type": "text", "text": query}]}])
normed_bboxes.append(feature[NORMED_BBOXES_KEY])
querys.append(query)
answers.append(answer)
score_funcs.append(feature[SCORE_FUNCS_KEY])
text = self.processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=(not self.is_sft)
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = self.processor(
text=text,
normed_bboxes=normed_bboxes,
images=image_inputs,
videos=video_inputs,
padding=True,
return_tensors="pt",
)
if self.is_sft:
labels = self._prepare_labels_from_input_ids(inputs.input_ids)
inputs["labels"] = labels
inputs[QUERY_KEY] = querys
inputs[ANSWER_KEY] = answers
inputs[SCORE_FUNCS_KEY] = score_funcs
return inputs
class RepeatRandomSampler(torch.utils.data.Sampler):
"""
Sampler that repeats the indices of a dataset in a structured manner.
Args:
data_source (`Sized`):
Dataset to sample from.
mini_repeat_count (`int`):
Number of times to repeat each index per batch.
batch_size (`int`, *optional*, defaults to `1`):
Number of unique indices per batch.
repeat_count (`int`, *optional*, defaults to `1`):
Number of times to repeat the full sampling process.
seed (`int` or `None`, *optional*, defaults to `None`):
Random seed for reproducibility.
"""
def __init__(
self,
data_source: Sized,
mini_repeat_count: int,
batch_size: int = 1,
repeat_count: int = 1,
seed: Optional[int] = None,
):
self.data_source = data_source
self.mini_repeat_count = mini_repeat_count
self.batch_size = batch_size
self.repeat_count = repeat_count
self.num_samples = len(data_source)
self.seed = seed
self.generator = torch.Generator()
if seed is not None:
self.generator.manual_seed(seed)
def __iter__(self):
indexes = torch.randperm(self.num_samples, generator=self.generator).tolist()
indexes = [indexes[i : i + self.batch_size] for i in range(0, len(indexes), self.batch_size)]
indexes = [chunk for chunk in indexes if len(chunk) == self.batch_size]
for chunk in indexes:
for _ in range(self.repeat_count):
for index in chunk:
for _ in range(self.mini_repeat_count):
yield index
def __len__(self) -> int:
return self.num_samples * self.mini_repeat_count * self.repeat_count
# ---------- Client & Score Functions ----------
SCORE_REGISTRY = {}
def register_score():
def wrapper(func):
name = func.__name__.replace("_score", "")
SCORE_REGISTRY[name] = func
return func
return wrapper
@register_score()
def llm_score(query, completion, answer, args):
client = LLMClient(base_url=args.client_base_url, api_key=args.client_api_key, model_name=args.client_model_name)
return client.score(query, completion, answer)
@register_score()
def precision_match_or_llm_score(query, completion, answer, args):
"""
This score function first checks if the completion matches the answer.
If it does, it returns the LLM score; otherwise, it returns 0.
"""
client = LLMClient(base_url=args.client_base_url, api_key=args.client_api_key, model_name=args.client_model_name)
scores = []
for one_query, one_completion, one_answer in zip(query, completion, answer):
if one_completion.strip().lower() == one_answer.strip().lower():
scores.append(1.0)
else:
scores.append(client.score([one_query], [one_completion], [one_answer])[0])
return scores
@register_score()
def precision_match_score(query, completion, answer, args):
"""
This score function checks if the completion matches the answer.
Returns 1.0 if they match, otherwise returns 0.0.
"""
scores = []
for one_query, one_completion, one_answer in zip(query, completion, answer):
if one_completion.strip().lower() == one_answer.strip().lower():
scores.append(1.0)
else:
scores.append(0.0)
return scores
@register_score()
def one_box_iou_score(query, completion, answer, args):
pred_bboxes = [extract_one_bbox_from_str(one_str) for one_str in completion]
gt_bboxes = [ast.literal_eval(one_answer) for one_answer in answer]
ious = cal_paired_ious(np.array(pred_bboxes), np.array(gt_bboxes))
return ious.tolist()
@register_score()
def one_box_format_score(query, completion, answer, args):
bbox_pattern = r'\[(\d+),\s*(\d+),\s*(\d+),\s*(\d+)\]'
# Score=1 only if there exists only one bbox in the completion and it matches the pattern
scores = []
for one_completion in completion:
matches = re.findall(bbox_pattern, one_completion)
if len(matches) == 1:
scores.append(1.0) # Correct format
else:
scores.append(0.0)
return scores
@register_score()
def single_choice_score(query, completion, answer, args):
patterns = [
r'(?:(?:the|my|the correct)\s+)?(?:answer|choice|option)\s*(?:is)?\s*[::]?\s*([A-Z])',
r'\(([A-Z])\)',
r'\b([A-Z])[\.\)]',
r'^([A-Z])\b',
r'\b([A-Z])\b'
]
scores = []
for one_completion, one_answer in zip(completion, answer):
one_answer = one_answer.strip().upper()
extracted_completion = None
for pattern in patterns:
match = re.search(pattern, one_completion, re.IGNORECASE)
if match:
extracted_completion = match.group(1).strip().upper()
break
if extracted_completion and extracted_completion == one_answer:
scores.append(1.0)
else:
scores.append(0.0)
return scores
# ---------- Parameter Scheduler ----------
class BaseScheduler:
def __init__(self, min_value: float, max_value: float, total_steps: int):
if total_steps < 1:
raise ValueError("total_steps must be at least 1.")
self.min_value = min_value
self.max_value = max_value
self.total_steps = total_steps
def get_value(self, current_step: int) -> float:
raise NotImplementedError("This method should be implemented by subclasses.")
def __repr__(self):
return (f"{self.__class__.__name__}("
f"min_value={self.min_value}, "
f"max_value={self.max_value}, "
f"total_steps={self.total_steps})")
SCHEDULER_REGISTRY = {}
def register_scheduler(name: Optional[str] = None):
def _decorator(cls: Type['BaseScheduler']) -> Type['BaseScheduler']:
if name is not None:
key = name
else:
# 'LinearScheduler' -> 'linear_scheduler'
key = re.sub(r'(?<!^)(?=[A-Z])', '_', cls.__name__).lower()
if key in SCHEDULER_REGISTRY:
raise ValueError(f"Error: Scheduler '{key}' is already registered. ")
SCHEDULER_REGISTRY[key] = cls
return cls
return _decorator
def create_scheduler(
scheduler_name: str,
min_value: float,
max_value: float,
total_steps: int
) -> BaseScheduler:
if scheduler_name not in SCHEDULER_REGISTRY:
raise ValueError(f"Scheduler '{scheduler_name}' is not registered. Available: {list(SCHEDULER_REGISTRY.keys())}")
return SCHEDULER_REGISTRY[scheduler_name](min_value, max_value, total_steps)
@register_scheduler("linear")
class LinearScheduler(BaseScheduler):
def get_value(self, current_step: int) -> float:
current_step = min(current_step, self.total_steps - 1)
if self.total_steps == 1:
return self.min_value
progress = current_step / (self.total_steps - 1)
return self.max_value - (self.max_value - self.min_value) * progress
@register_scheduler("cosine")
class CosineAnnealingScheduler(BaseScheduler):
def get_value(self, current_step: int) -> float:
current_step = min(current_step, self.total_steps - 1)
if self.total_steps == 1:
return self.min_value
cosine_progress = 0.5 * (1 + math.cos(math.pi * current_step / (self.total_steps - 1)))
return self.min_value + (self.max_value - self.min_value) * cosine_progress
@register_scheduler("exponential")
class ExponentialScheduler(BaseScheduler):
def __init__(self, min_value: float, max_value: float, total_steps: int):
super().__init__(min_value, max_value, total_steps)
if self.total_steps == 1 or self.max_value == 0:
self.gamma = 0
else:
epsilon = 1e-9
safe_min_value = max(self.min_value, epsilon)
self.gamma = (safe_min_value / self.max_value) ** (1 / (self.total_steps - 1))
def get_value(self, current_step: int) -> float:
current_step = min(current_step, self.total_steps - 1)
value = self.max_value * (self.gamma ** current_step)
return max(value, self.min_value)
# ---------- Trainer ----------
def convert_to_left_padding(
input_ids: torch.LongTensor,
inputs_embeds: Optional[torch.FloatTensor],
attention_mask: torch.LongTensor,
position_ids: Optional[torch.LongTensor],
completion_mask: torch.LongTensor,
max_seq_length: Optional[int] = None,
) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor], torch.LongTensor, Optional[torch.LongTensor], torch.LongTensor]:
B = input_ids.shape[0]
C = inputs_embeds.shape[2] if inputs_embeds is not None else 0 # Embedding dimension
P = position_ids.shape[0] if position_ids is not None else 0 # First dimension of position_ids (e.g., 3)
# max_completion_length = completion_mask.shape[1] # Length of completion mask
valid_completion_lens = completion_mask.sum(dim=1).long()
device = input_ids.device # Use device of one of the inputs
# 1. Calculate original effective lengths (number of non-padding tokens)
original_effective_lengths = attention_mask.sum(dim=1).long() # Ensure long type for consistency
# 2. Determine the length to keep for each sequence after applying max_seq_length
if max_seq_length is not None:
# Ensure max_seq_length is a tensor for broadcasting
original_max_lengths = original_effective_lengths.max().item() # Get the maximum original length
if max_seq_length < original_max_lengths:
warnings.warn(
f"max_seq_length ({max_seq_length}) is less than the maximum original effective length "
f"({original_max_lengths}). Sequences will be truncated."
)
valid_completion_lens -= (original_max_lengths - max_seq_length)
if torch.all(valid_completion_lens < 0):
warnings.warn(
"All sequences will be truncated to zero length. Consider increasing max_seq_length."
)
elif torch.any(valid_completion_lens < 0):
warnings.warn(
"Some sequences will be truncated to zero length. Consider increasing max_seq_length."
)
# valid_completion_lens = torch.maximum(valid_completion_lens, torch.zeros_like(valid_completion_lens))
max_len_tensor = torch.tensor(max_seq_length, device=device, dtype=torch.long)
lengths_to_keep = torch.minimum(original_effective_lengths, max_len_tensor)
else:
lengths_to_keep = original_effective_lengths
if max_seq_length == 0:
lengths_to_keep = torch.zeros_like(original_effective_lengths)
if lengths_to_keep.numel() > 0: # Check if lengths_to_keep is not empty
output_L = lengths_to_keep.max().item()
else:
output_L = 0
new_input_ids = torch.zeros((B, output_L), dtype=input_ids.dtype, device=device)
if inputs_embeds is not None:
new_inputs_embeds = torch.zeros((B, output_L, C), dtype=inputs_embeds.dtype, device=device)
else:
new_inputs_embeds = None
new_attention_mask = torch.zeros((B, output_L), dtype=attention_mask.dtype, device=device)
if position_ids is not None:
new_position_ids = torch.zeros((P, B, output_L), dtype=position_ids.dtype, device=device)
else:
new_position_ids = None
new_completion_mask = torch.zeros((B, output_L), dtype=completion_mask.dtype, device=device)
# 5. Fill the new tensors
for i in range(B):
# Number of tokens to keep for sequence i (after potential truncation)
len_to_keep_i = lengths_to_keep[i].item()
if len_to_keep_i == 0: # If sequence becomes empty, skip copying
continue
num_left_pads = output_L - len_to_keep_i
num_completion_len = valid_completion_lens[i].item()
# Create a boolean mask for valid tokens in the original sequence i
# Assuming attention_mask[i] is 1D and has L_orig elements
original_valid_token_mask_i = attention_mask[i].bool()
# --- input_ids ---
original_valid_ids_i = input_ids[i][original_valid_token_mask_i]
ids_to_copy = original_valid_ids_i[:len_to_keep_i] # Take last 'len_to_keep_i' valid tokens
new_input_ids[i, num_left_pads:] = ids_to_copy
# --- inputs_embeds ---
if new_inputs_embeds is not None:
original_valid_embeds_i = inputs_embeds[i][original_valid_token_mask_i, :]
embeds_to_copy = original_valid_embeds_i[:len_to_keep_i, :]
new_inputs_embeds[i, num_left_pads:, :] = embeds_to_copy
# --- attention_mask ---
# The new attention mask is '1' for all kept tokens
new_attention_mask[i, num_left_pads:] = 1
# --- position_ids ---
if new_position_ids is not None:
# position_ids[:, i] gives shape (P, L_orig)
original_valid_pos_ids_i = position_ids[:, i][:, original_valid_token_mask_i] # Shape (P, num_original_valid)
pos_ids_to_copy = original_valid_pos_ids_i[:, :len_to_keep_i] # Shape (P, len_to_keep_i)
new_position_ids[:, i, num_left_pads:] = pos_ids_to_copy
# --- completion_mask ---