Update data_loader.py
Browse files- data_loader.py +787 -831
data_loader.py
CHANGED
|
@@ -1,832 +1,788 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
import
|
| 11 |
-
import
|
| 12 |
-
from
|
| 13 |
-
import
|
| 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 |
-
self.
|
| 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 |
-
padding = torch.full((
|
| 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 |
-
dataset = PostTrainDataset(
|
| 790 |
-
mix_name=mix_name,
|
| 791 |
-
tokenizer=tokenizer,
|
| 792 |
-
max_length=max_length,
|
| 793 |
-
max_samples=max_samples,
|
| 794 |
-
split=split
|
| 795 |
-
)
|
| 796 |
-
return DataLoader(
|
| 797 |
-
dataset,
|
| 798 |
-
batch_size=batch_size,
|
| 799 |
-
shuffle=shuffle,
|
| 800 |
-
num_workers=num_workers,
|
| 801 |
-
collate_fn=collate_fn_v2,
|
| 802 |
-
pin_memory=True,
|
| 803 |
-
drop_last=False # 保留最后一个batch
|
| 804 |
-
)
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
def create_preference_dataloader(
|
| 808 |
-
dataset_name: str = 'hh_rlhf',
|
| 809 |
-
tokenizer=None,
|
| 810 |
-
batch_size: int = 8,
|
| 811 |
-
num_workers: int = 4,
|
| 812 |
-
max_length: int = 1024,
|
| 813 |
-
max_samples: Optional[int] = None,
|
| 814 |
-
split: str = 'train',
|
| 815 |
-
shuffle: bool = True
|
| 816 |
-
):
|
| 817 |
-
"""创建偏好数据加载器"""
|
| 818 |
-
dataset = PreferenceDataset(
|
| 819 |
-
dataset_name=dataset_name,
|
| 820 |
-
tokenizer=tokenizer,
|
| 821 |
-
max_length=max_length,
|
| 822 |
-
max_samples=max_samples,
|
| 823 |
-
split=split
|
| 824 |
-
)
|
| 825 |
-
return DataLoader(
|
| 826 |
-
dataset,
|
| 827 |
-
batch_size=batch_size,
|
| 828 |
-
shuffle=shuffle,
|
| 829 |
-
num_workers=num_workers,
|
| 830 |
-
collate_fn=collate_fn_v2,
|
| 831 |
-
pin_memory=True
|
| 832 |
)
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
from torch.utils.data import Dataset, DataLoader, IterableDataset
|
| 4 |
+
from datasets import load_dataset, concatenate_datasets, interleave_datasets
|
| 5 |
+
from typing import Dict, List, Optional, Any, Union
|
| 6 |
+
import random
|
| 7 |
+
import numpy as np
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
import warnings
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import requests
|
| 12 |
+
from io import BytesIO
|
| 13 |
+
from torchvision import transforms
|
| 14 |
+
import logging
|
| 15 |
+
|
| 16 |
+
# 设置日志
|
| 17 |
+
logging.basicConfig(level=logging.INFO)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 21 |
+
|
| 22 |
+
from data_config import (
|
| 23 |
+
PRETRAIN_DATASETS,
|
| 24 |
+
POSTTRAIN_DATASETS,
|
| 25 |
+
TEST_DATASETS,
|
| 26 |
+
PRETRAIN_MIX,
|
| 27 |
+
POSTTRAIN_MIX,
|
| 28 |
+
PREPROCESSING_CONFIG,
|
| 29 |
+
DATASET_CACHE_DIR,
|
| 30 |
+
HF_CACHE_DIR
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# 图像变换
|
| 34 |
+
image_transform = transforms.Compose([
|
| 35 |
+
transforms.Resize((224, 224)),
|
| 36 |
+
transforms.ToTensor(),
|
| 37 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 38 |
+
])
|
| 39 |
+
|
| 40 |
+
class PreTrainDataset(IterableDataset):
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
mix_name: str = 'default',
|
| 44 |
+
tokenizer=None,
|
| 45 |
+
max_length: int = 2048,
|
| 46 |
+
streaming: bool = True,
|
| 47 |
+
seed: int = 42,
|
| 48 |
+
max_samples: Optional[int] = None
|
| 49 |
+
):
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
if tokenizer is None:
|
| 53 |
+
raise ValueError("tokenizer cannot be None")
|
| 54 |
+
|
| 55 |
+
self.tokenizer = tokenizer
|
| 56 |
+
self.max_length = max_length
|
| 57 |
+
self.streaming = streaming
|
| 58 |
+
self.seed = seed
|
| 59 |
+
self.max_samples = max_samples
|
| 60 |
+
self.samples_generated = 0
|
| 61 |
+
|
| 62 |
+
# 获取混合配置
|
| 63 |
+
if mix_name not in PRETRAIN_MIX:
|
| 64 |
+
raise ValueError(f"Unknown mix: {mix_name}. Available: {list(PRETRAIN_MIX.keys())}")
|
| 65 |
+
|
| 66 |
+
mix_config = PRETRAIN_MIX[mix_name]
|
| 67 |
+
dataset_names = mix_config.get('datasets', [])
|
| 68 |
+
weights = mix_config.get('weights', [])
|
| 69 |
+
|
| 70 |
+
if not dataset_names:
|
| 71 |
+
raise ValueError(f"No datasets found in mix: {mix_name}")
|
| 72 |
+
|
| 73 |
+
logger.info(f"Loading pretrain mix: {mix_name}")
|
| 74 |
+
logger.info(f" Datasets: {dataset_names}")
|
| 75 |
+
logger.info(f" Weights: {weights}")
|
| 76 |
+
|
| 77 |
+
# 加载数据集
|
| 78 |
+
self.datasets = []
|
| 79 |
+
self.probabilities = []
|
| 80 |
+
|
| 81 |
+
for name, weight in zip(dataset_names, weights):
|
| 82 |
+
if name not in PRETRAIN_DATASETS:
|
| 83 |
+
logger.warning(f"Dataset {name} not found in PRETRAIN_DATASETS, skipping")
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
config = PRETRAIN_DATASETS[name]
|
| 87 |
+
try:
|
| 88 |
+
ds = self._load_dataset(config)
|
| 89 |
+
if ds is not None:
|
| 90 |
+
self.datasets.append((name, ds, config))
|
| 91 |
+
self.probabilities.append(weight)
|
| 92 |
+
logger.info(f" Successfully loaded {name}")
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logger.error(f"Error loading {name}: {e}")
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
if not self.datasets:
|
| 98 |
+
raise ValueError("No datasets loaded successfully")
|
| 99 |
+
|
| 100 |
+
# 归一化概率
|
| 101 |
+
total = sum(self.probabilities)
|
| 102 |
+
self.probabilities = [p / total for p in self.probabilities]
|
| 103 |
+
|
| 104 |
+
logger.info(f"Successfully loaded {len(self.datasets)} datasets")
|
| 105 |
+
|
| 106 |
+
def _load_dataset(self, config: Dict):
|
| 107 |
+
try:
|
| 108 |
+
load_kwargs = {
|
| 109 |
+
'path': config['hf_path'],
|
| 110 |
+
'split': config.get('split', 'train'),
|
| 111 |
+
'streaming': config.get('streaming', self.streaming),
|
| 112 |
+
'cache_dir': HF_CACHE_DIR,
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
if 'config' in config:
|
| 116 |
+
load_kwargs['name'] = config['config']
|
| 117 |
+
|
| 118 |
+
ds = load_dataset(**load_kwargs)
|
| 119 |
+
return ds
|
| 120 |
+
except Exception as e:
|
| 121 |
+
logger.error(f"Failed to load {config.get('hf_path', 'unknown')}: {e}")
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
def _process_text_sample(self, sample: Dict, config: Dict) -> Optional[Dict]:
|
| 125 |
+
try:
|
| 126 |
+
text_field = config.get('text_field', 'text')
|
| 127 |
+
text = sample.get(text_field, '')
|
| 128 |
+
|
| 129 |
+
if not text or not isinstance(text, str):
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
text = text.strip()
|
| 133 |
+
if len(text) < 10:
|
| 134 |
+
return None
|
| 135 |
+
|
| 136 |
+
# Tokenize
|
| 137 |
+
encoding = self.tokenizer(
|
| 138 |
+
text,
|
| 139 |
+
max_length=self.max_length,
|
| 140 |
+
truncation=True,
|
| 141 |
+
padding='max_length',
|
| 142 |
+
return_tensors='pt'
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
return {
|
| 146 |
+
'input_ids': encoding['input_ids'].squeeze(0),
|
| 147 |
+
'attention_mask': encoding['attention_mask'].squeeze(0),
|
| 148 |
+
'type': 'text'
|
| 149 |
+
}
|
| 150 |
+
except Exception as e:
|
| 151 |
+
logger.debug(f"Error processing text sample: {e}")
|
| 152 |
+
return None
|
| 153 |
+
|
| 154 |
+
def _process_image_text_sample(self, sample: Dict, config: Dict) -> Optional[Dict]:
|
| 155 |
+
try:
|
| 156 |
+
text_field = config.get('text_field', 'caption')
|
| 157 |
+
image_field = config.get('image_field', 'image')
|
| 158 |
+
|
| 159 |
+
text = sample.get(text_field, '')
|
| 160 |
+
image = sample.get(image_field)
|
| 161 |
+
|
| 162 |
+
if not text or image is None:
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
# 处理图像
|
| 166 |
+
if isinstance(image, str):
|
| 167 |
+
try:
|
| 168 |
+
response = requests.get(image, timeout=5)
|
| 169 |
+
image = Image.open(BytesIO(response.content)).convert('RGB')
|
| 170 |
+
except Exception as img_error:
|
| 171 |
+
logger.debug(f"Failed to load image from URL: {img_error}")
|
| 172 |
+
return None
|
| 173 |
+
elif isinstance(image, Image.Image):
|
| 174 |
+
image = image.convert('RGB')
|
| 175 |
+
else:
|
| 176 |
+
return None
|
| 177 |
+
|
| 178 |
+
# 转换图像
|
| 179 |
+
image_tensor = image_transform(image)
|
| 180 |
+
|
| 181 |
+
# Tokenize文本
|
| 182 |
+
encoding = self.tokenizer(
|
| 183 |
+
text,
|
| 184 |
+
max_length=self.max_length,
|
| 185 |
+
truncation=True,
|
| 186 |
+
padding='max_length',
|
| 187 |
+
return_tensors='pt'
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
return {
|
| 191 |
+
'input_ids': encoding['input_ids'].squeeze(0),
|
| 192 |
+
'attention_mask': encoding['attention_mask'].squeeze(0),
|
| 193 |
+
'image': image_tensor,
|
| 194 |
+
'type': 'image_text'
|
| 195 |
+
}
|
| 196 |
+
except Exception as e:
|
| 197 |
+
logger.debug(f"Error processing image-text sample: {e}")
|
| 198 |
+
return None
|
| 199 |
+
|
| 200 |
+
def __iter__(self):
|
| 201 |
+
"""迭代器"""
|
| 202 |
+
worker_info = torch.utils.data.get_worker_info()
|
| 203 |
+
if worker_info is not None:
|
| 204 |
+
# 多worker时设置不同的随机种子
|
| 205 |
+
random.seed(self.seed + worker_info.id)
|
| 206 |
+
np.random.seed(self.seed + worker_info.id)
|
| 207 |
+
else:
|
| 208 |
+
random.seed(self.seed)
|
| 209 |
+
np.random.seed(self.seed)
|
| 210 |
+
|
| 211 |
+
# 创建数据集迭代器
|
| 212 |
+
iterators = [iter(ds) for _, ds, _ in self.datasets]
|
| 213 |
+
self.samples_generated = 0
|
| 214 |
+
|
| 215 |
+
while True:
|
| 216 |
+
# 检查是否达到最大样本数
|
| 217 |
+
if self.max_samples and self.samples_generated >= self.max_samples:
|
| 218 |
+
break
|
| 219 |
+
|
| 220 |
+
try:
|
| 221 |
+
# 根据概率选择数据集
|
| 222 |
+
idx = np.random.choice(len(self.datasets), p=self.probabilities)
|
| 223 |
+
name, _, config = self.datasets[idx]
|
| 224 |
+
|
| 225 |
+
# 从选中的数据集获取样本
|
| 226 |
+
sample = next(iterators[idx])
|
| 227 |
+
|
| 228 |
+
# 处理样本
|
| 229 |
+
processed = None
|
| 230 |
+
if config.get('type') in ['text', 'code']:
|
| 231 |
+
processed = self._process_text_sample(sample, config)
|
| 232 |
+
elif config.get('type') == 'image_text':
|
| 233 |
+
processed = self._process_image_text_sample(sample, config)
|
| 234 |
+
else:
|
| 235 |
+
logger.debug(f"Unknown type: {config.get('type')}")
|
| 236 |
+
continue
|
| 237 |
+
|
| 238 |
+
if processed is not None:
|
| 239 |
+
self.samples_generated += 1
|
| 240 |
+
yield processed
|
| 241 |
+
|
| 242 |
+
except StopIteration:
|
| 243 |
+
# 重新创建迭代器
|
| 244 |
+
try:
|
| 245 |
+
iterators[idx] = iter(self.datasets[idx][1])
|
| 246 |
+
except Exception as e:
|
| 247 |
+
logger.error(f"Failed to recreate iterator for dataset {idx}: {e}")
|
| 248 |
+
break
|
| 249 |
+
except Exception as e:
|
| 250 |
+
logger.debug(f"Error in iterator: {e}")
|
| 251 |
+
continue
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class PostTrainDataset(Dataset):
|
| 255 |
+
def __init__(
|
| 256 |
+
self,
|
| 257 |
+
mix_name: str = 'default',
|
| 258 |
+
tokenizer=None,
|
| 259 |
+
max_length: int = 2048,
|
| 260 |
+
max_samples: Optional[int] = None,
|
| 261 |
+
split: str = 'train'
|
| 262 |
+
):
|
| 263 |
+
super().__init__()
|
| 264 |
+
|
| 265 |
+
if tokenizer is None:
|
| 266 |
+
raise ValueError("tokenizer cannot be None")
|
| 267 |
+
|
| 268 |
+
self.tokenizer = tokenizer
|
| 269 |
+
self.max_length = max_length
|
| 270 |
+
self.split = split
|
| 271 |
+
|
| 272 |
+
# 获取混合配置
|
| 273 |
+
if mix_name not in POSTTRAIN_MIX:
|
| 274 |
+
raise ValueError(f"Unknown mix: {mix_name}. Available: {list(POSTTRAIN_MIX.keys())}")
|
| 275 |
+
|
| 276 |
+
mix_config = POSTTRAIN_MIX[mix_name]
|
| 277 |
+
dataset_names = mix_config.get('datasets', [])
|
| 278 |
+
weights = mix_config.get('weights', [])
|
| 279 |
+
|
| 280 |
+
if not dataset_names:
|
| 281 |
+
raise ValueError(f"No datasets found in mix: {mix_name}")
|
| 282 |
+
|
| 283 |
+
logger.info(f"Loading posttrain mix: {mix_name}")
|
| 284 |
+
logger.info(f" Datasets: {dataset_names}")
|
| 285 |
+
|
| 286 |
+
# 加载和合并数据集
|
| 287 |
+
all_datasets = []
|
| 288 |
+
|
| 289 |
+
for name in dataset_names:
|
| 290 |
+
if name not in POSTTRAIN_DATASETS:
|
| 291 |
+
logger.warning(f"Dataset {name} not found in POSTTRAIN_DATASETS")
|
| 292 |
+
continue
|
| 293 |
+
|
| 294 |
+
config = POSTTRAIN_DATASETS[name]
|
| 295 |
+
try:
|
| 296 |
+
load_kwargs = {
|
| 297 |
+
'path': config['hf_path'],
|
| 298 |
+
'split': split,
|
| 299 |
+
'streaming': config.get('streaming', False),
|
| 300 |
+
'cache_dir': HF_CACHE_DIR,
|
| 301 |
+
}
|
| 302 |
+
if 'data_files' in config:
|
| 303 |
+
load_kwargs['data_files'] = config['data_files']
|
| 304 |
+
if 'config' in config:
|
| 305 |
+
load_kwargs['name'] = config['config']
|
| 306 |
+
|
| 307 |
+
ds = load_dataset(**load_kwargs)
|
| 308 |
+
|
| 309 |
+
# 限制样本数
|
| 310 |
+
if config.get('max_samples'):
|
| 311 |
+
if hasattr(ds, 'take'):
|
| 312 |
+
ds = ds.take(config['max_samples'])
|
| 313 |
+
elif hasattr(ds, 'select'):
|
| 314 |
+
ds = ds.select(range(min(len(ds), config['max_samples'])))
|
| 315 |
+
|
| 316 |
+
# 添加数据集标识
|
| 317 |
+
def add_source(example):
|
| 318 |
+
example['_source'] = name
|
| 319 |
+
example['_config'] = config
|
| 320 |
+
return example
|
| 321 |
+
|
| 322 |
+
ds = ds.map(add_source)
|
| 323 |
+
all_datasets.append(ds)
|
| 324 |
+
|
| 325 |
+
ds_len = len(ds) if hasattr(ds, '__len__') else 'streaming'
|
| 326 |
+
logger.info(f" Loaded {name}: {ds_len} samples")
|
| 327 |
+
|
| 328 |
+
except Exception as e:
|
| 329 |
+
logger.error(f"Error loading {name}: {e}")
|
| 330 |
+
continue
|
| 331 |
+
|
| 332 |
+
# 合并数据集
|
| 333 |
+
if not all_datasets:
|
| 334 |
+
raise ValueError("No datasets loaded successfully")
|
| 335 |
+
|
| 336 |
+
if len(all_datasets) == 1:
|
| 337 |
+
self.dataset = all_datasets[0]
|
| 338 |
+
else:
|
| 339 |
+
# 交织数据集
|
| 340 |
+
probabilities = [w / sum(weights[:len(all_datasets)])
|
| 341 |
+
for w in weights[:len(all_datasets)]]
|
| 342 |
+
self.dataset = interleave_datasets(
|
| 343 |
+
all_datasets,
|
| 344 |
+
probabilities=probabilities,
|
| 345 |
+
seed=42,
|
| 346 |
+
stopping_strategy='all_exhausted'
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# 限制总样本数
|
| 350 |
+
if max_samples and hasattr(self.dataset, '__len__'):
|
| 351 |
+
actual_len = min(len(self.dataset), max_samples)
|
| 352 |
+
self.dataset = self.dataset.select(range(actual_len))
|
| 353 |
+
|
| 354 |
+
dataset_len = len(self.dataset) if hasattr(self.dataset, '__len__') else 'streaming'
|
| 355 |
+
logger.info(f"Total samples: {dataset_len}")
|
| 356 |
+
|
| 357 |
+
def _format_instruction(self, sample: Dict, config: Dict) -> str:
|
| 358 |
+
"""格式化instruction"""
|
| 359 |
+
try:
|
| 360 |
+
data_type = config.get('type', 'instruction')
|
| 361 |
+
|
| 362 |
+
if data_type == 'instruction':
|
| 363 |
+
instruction_field = config.get('instruction_field', 'instruction')
|
| 364 |
+
input_field = config.get('input_field', 'input')
|
| 365 |
+
context_field = config.get('context_field', None)
|
| 366 |
+
|
| 367 |
+
instruction = sample.get(instruction_field, '')
|
| 368 |
+
input_text = sample.get(input_field, '')
|
| 369 |
+
context = sample.get(context_field, '') if context_field else ''
|
| 370 |
+
|
| 371 |
+
# 构建prompt
|
| 372 |
+
prompt_parts = [f"Instruction: {instruction}"]
|
| 373 |
+
|
| 374 |
+
if context:
|
| 375 |
+
prompt_parts.append(f"Context: {context}")
|
| 376 |
+
|
| 377 |
+
if input_text:
|
| 378 |
+
prompt_parts.append(f"Input: {input_text}")
|
| 379 |
+
|
| 380 |
+
prompt_parts.append("Response:")
|
| 381 |
+
return "\n".join(prompt_parts)
|
| 382 |
+
|
| 383 |
+
elif data_type == 'conversation':
|
| 384 |
+
if 'conversations' in sample:
|
| 385 |
+
conversations = sample['conversations']
|
| 386 |
+
if isinstance(conversations, list) and len(conversations) > 0:
|
| 387 |
+
dialogue = []
|
| 388 |
+
for conv in conversations[:-1]:
|
| 389 |
+
role = conv.get('from', 'user')
|
| 390 |
+
content = conv.get('value', '')
|
| 391 |
+
dialogue.append(f"{role}: {content}")
|
| 392 |
+
return "\n".join(dialogue) + "\nassistant:"
|
| 393 |
+
|
| 394 |
+
elif 'messages' in sample:
|
| 395 |
+
# 标准消息格式
|
| 396 |
+
messages = sample['messages']
|
| 397 |
+
if isinstance(messages, list) and len(messages) > 0:
|
| 398 |
+
dialogue = []
|
| 399 |
+
for msg in messages[:-1]:
|
| 400 |
+
role = msg.get('role', 'user')
|
| 401 |
+
content = msg.get('content', '')
|
| 402 |
+
dialogue.append(f"{role}: {content}")
|
| 403 |
+
return "\n".join(dialogue) + "\nassistant:"
|
| 404 |
+
|
| 405 |
+
# 如果没有标准格式,尝试使用text字段
|
| 406 |
+
return sample.get('text', '')
|
| 407 |
+
|
| 408 |
+
elif data_type == 'code_instruction':
|
| 409 |
+
# 代码instruction格式
|
| 410 |
+
instruction_field = config.get('instruction_field', 'instruction')
|
| 411 |
+
instruction = sample.get(instruction_field, '')
|
| 412 |
+
return f"### Instruction:\n{instruction}\n### Response:"
|
| 413 |
+
|
| 414 |
+
elif data_type == 'multimodal_instruction':
|
| 415 |
+
# 多模态instruction
|
| 416 |
+
instruction_field = config.get('instruction_field', 'conversations')
|
| 417 |
+
conversations = sample.get(instruction_field, [])
|
| 418 |
+
if isinstance(conversations, list) and len(conversations) > 0:
|
| 419 |
+
# 提取对话历史(除了最后一条回复)
|
| 420 |
+
dialogue = []
|
| 421 |
+
for conv in conversations[:-1]:
|
| 422 |
+
role = conv.get('from', 'user')
|
| 423 |
+
content = conv.get('value', '')
|
| 424 |
+
dialogue.append(f"{role}: {content}")
|
| 425 |
+
return "\n".join(dialogue) + "\nassistant:"
|
| 426 |
+
return ""
|
| 427 |
+
|
| 428 |
+
else:
|
| 429 |
+
return sample.get(config.get('instruction_field', 'text'), '')
|
| 430 |
+
except Exception as e:
|
| 431 |
+
logger.debug(f"Error formatting instruction: {e}")
|
| 432 |
+
return ""
|
| 433 |
+
|
| 434 |
+
def _get_response(self, sample: Dict, config: Dict) -> str:
|
| 435 |
+
try:
|
| 436 |
+
data_type = config.get('type', 'instruction')
|
| 437 |
+
|
| 438 |
+
if data_type == 'instruction' or data_type == 'code_instruction':
|
| 439 |
+
response_field = config.get('response_field', 'output')
|
| 440 |
+
return sample.get(response_field, '')
|
| 441 |
+
|
| 442 |
+
elif data_type == 'conversation':
|
| 443 |
+
# 从对话中提取最后一条assistant的回复
|
| 444 |
+
if 'conversations' in sample:
|
| 445 |
+
conversations = sample['conversations']
|
| 446 |
+
if isinstance(conversations, list) and len(conversations) > 0:
|
| 447 |
+
return conversations[-1].get('value', '')
|
| 448 |
+
|
| 449 |
+
elif 'messages' in sample:
|
| 450 |
+
messages = sample['messages']
|
| 451 |
+
if isinstance(messages, list) and len(messages) > 0:
|
| 452 |
+
return messages[-1].get('content', '')
|
| 453 |
+
|
| 454 |
+
return ""
|
| 455 |
+
|
| 456 |
+
elif data_type == 'multimodal_instruction':
|
| 457 |
+
instruction_field = config.get('instruction_field', 'conversations')
|
| 458 |
+
conversations = sample.get(instruction_field, [])
|
| 459 |
+
if isinstance(conversations, list) and len(conversations) > 0:
|
| 460 |
+
return conversations[-1].get('value', '')
|
| 461 |
+
return ""
|
| 462 |
+
|
| 463 |
+
else:
|
| 464 |
+
response_field = config.get('response_field', 'output')
|
| 465 |
+
return sample.get(response_field, '')
|
| 466 |
+
except Exception as e:
|
| 467 |
+
logger.debug(f"Error getting response: {e}")
|
| 468 |
+
return ""
|
| 469 |
+
|
| 470 |
+
def __len__(self):
|
| 471 |
+
return len(self.dataset) if hasattr(self.dataset, '__len__') else 0
|
| 472 |
+
|
| 473 |
+
def __getitem__(self, idx):
|
| 474 |
+
try:
|
| 475 |
+
sample = self.dataset[idx]
|
| 476 |
+
|
| 477 |
+
# 获取配置
|
| 478 |
+
if '_config' not in sample:
|
| 479 |
+
logger.warning(f"Sample at index {idx} missing _config")
|
| 480 |
+
return None
|
| 481 |
+
|
| 482 |
+
config = sample['_config']
|
| 483 |
+
|
| 484 |
+
# 格式化 instruction 和 response
|
| 485 |
+
instruction_text = self._format_instruction(sample, config)
|
| 486 |
+
response_text = self._get_response(sample, config)
|
| 487 |
+
|
| 488 |
+
if not instruction_text or not response_text:
|
| 489 |
+
return None
|
| 490 |
+
|
| 491 |
+
pad_token_id = self.tokenizer.pad_token_id
|
| 492 |
+
if pad_token_id is None:
|
| 493 |
+
pad_token_id = self.tokenizer.eos_token_id
|
| 494 |
+
instruction_max_len = self.max_length // 2
|
| 495 |
+
|
| 496 |
+
# Tokenize 不做 padding,手动处理
|
| 497 |
+
instruction_enc = self.tokenizer(
|
| 498 |
+
instruction_text,
|
| 499 |
+
truncation=True,
|
| 500 |
+
max_length=instruction_max_len,
|
| 501 |
+
add_special_tokens=False,
|
| 502 |
+
return_tensors='pt'
|
| 503 |
+
)
|
| 504 |
+
instr_ids = instruction_enc['input_ids'].squeeze(0)
|
| 505 |
+
|
| 506 |
+
# Instruction 手动 Padding
|
| 507 |
+
instr_len = instr_ids.size(0)
|
| 508 |
+
if instr_len < instruction_max_len:
|
| 509 |
+
padding = torch.full((instruction_max_len - instr_len,), pad_token_id, dtype=torch.long)
|
| 510 |
+
instr_ids = torch.cat([instr_ids, padding])
|
| 511 |
+
|
| 512 |
+
instr_mask = torch.cat([torch.ones(instr_len, dtype=torch.long), torch.zeros(instruction_max_len - instr_len, dtype=torch.long)])
|
| 513 |
+
else:
|
| 514 |
+
instr_mask = torch.ones(instruction_max_len, dtype=torch.long)
|
| 515 |
+
|
| 516 |
+
response_max_len = self.max_length // 2
|
| 517 |
+
|
| 518 |
+
# Tokenize: 预留1个位置给EOS
|
| 519 |
+
response_enc = self.tokenizer(
|
| 520 |
+
response_text,
|
| 521 |
+
truncation=True,
|
| 522 |
+
max_length=response_max_len - 1,
|
| 523 |
+
add_special_tokens=False,
|
| 524 |
+
return_tensors='pt'
|
| 525 |
+
)
|
| 526 |
+
resp_ids = response_enc['input_ids'].squeeze(0)
|
| 527 |
+
|
| 528 |
+
eos_token = torch.tensor([self.tokenizer.eos_token_id], dtype=torch.long)
|
| 529 |
+
resp_ids = torch.cat([resp_ids, eos_token])
|
| 530 |
+
|
| 531 |
+
# Response 手动 Padding
|
| 532 |
+
curr_resp_len = resp_ids.size(0)
|
| 533 |
+
if curr_resp_len < response_max_len:
|
| 534 |
+
padding = torch.full((response_max_len - curr_resp_len,), pad_token_id, dtype=torch.long)
|
| 535 |
+
resp_ids = torch.cat([resp_ids, padding])
|
| 536 |
+
resp_mask = torch.cat([torch.ones(curr_resp_len, dtype=torch.long), torch.zeros(response_max_len - curr_resp_len, dtype=torch.long)])
|
| 537 |
+
else:
|
| 538 |
+
resp_mask = torch.ones(response_max_len, dtype=torch.long)
|
| 539 |
+
|
| 540 |
+
result = {
|
| 541 |
+
'instruction': instr_ids,
|
| 542 |
+
'response': resp_ids,
|
| 543 |
+
'instruction_mask': instr_mask,
|
| 544 |
+
'response_mask': resp_mask,
|
| 545 |
+
'task': sample.get('_source', 'unknown'),
|
| 546 |
+
'modality_data': None
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
if config.get('type') == 'multimodal_instruction' and 'image' in sample:
|
| 550 |
+
try:
|
| 551 |
+
image = sample['image']
|
| 552 |
+
if isinstance(image, Image.Image):
|
| 553 |
+
image = image.convert('RGB')
|
| 554 |
+
image_tensor = image_transform(image)
|
| 555 |
+
result['modality_data'] = {'image': image_tensor}
|
| 556 |
+
except Exception as e:
|
| 557 |
+
logger.debug(f"Error processing image: {e}")
|
| 558 |
+
|
| 559 |
+
return result
|
| 560 |
+
|
| 561 |
+
except Exception as e:
|
| 562 |
+
logger.debug(f"Error getting item at index {idx}: {e}")
|
| 563 |
+
import traceback
|
| 564 |
+
traceback.print_exc()
|
| 565 |
+
return None
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class PreferenceDataset(Dataset):
|
| 569 |
+
def __init__(
|
| 570 |
+
self,
|
| 571 |
+
dataset_name: str = 'hh_rlhf',
|
| 572 |
+
tokenizer=None,
|
| 573 |
+
max_length: int = 1024,
|
| 574 |
+
max_samples: Optional[int] = None,
|
| 575 |
+
split: str = 'train'
|
| 576 |
+
):
|
| 577 |
+
super().__init__()
|
| 578 |
+
|
| 579 |
+
if tokenizer is None:
|
| 580 |
+
raise ValueError("tokenizer cannot be None")
|
| 581 |
+
|
| 582 |
+
self.tokenizer = tokenizer
|
| 583 |
+
self.max_length = max_length
|
| 584 |
+
|
| 585 |
+
if dataset_name not in POSTTRAIN_DATASETS:
|
| 586 |
+
raise ValueError(f"Unknown dataset: {dataset_name}. Available: {list(POSTTRAIN_DATASETS.keys())}")
|
| 587 |
+
|
| 588 |
+
config = POSTTRAIN_DATASETS[dataset_name]
|
| 589 |
+
if config.get('type') != 'preference':
|
| 590 |
+
raise ValueError(f"{dataset_name} is not a preference dataset (type: {config.get('type')})")
|
| 591 |
+
|
| 592 |
+
logger.info(f"Loading preference dataset: {dataset_name}")
|
| 593 |
+
|
| 594 |
+
load_kwargs = {
|
| 595 |
+
'path': config['hf_path'],
|
| 596 |
+
'split': split,
|
| 597 |
+
'cache_dir': HF_CACHE_DIR,
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
if 'config' in config:
|
| 601 |
+
load_kwargs['name'] = config['config']
|
| 602 |
+
|
| 603 |
+
self.dataset = load_dataset(**load_kwargs)
|
| 604 |
+
|
| 605 |
+
self.chosen_field = config.get('chosen_field', 'chosen')
|
| 606 |
+
self.rejected_field = config.get('rejected_field', 'rejected')
|
| 607 |
+
|
| 608 |
+
if max_samples and len(self.dataset) > max_samples:
|
| 609 |
+
self.dataset = self.dataset.select(range(max_samples))
|
| 610 |
+
|
| 611 |
+
logger.info(f"Loaded {len(self.dataset)} preference pairs")
|
| 612 |
+
|
| 613 |
+
def __len__(self):
|
| 614 |
+
return len(self.dataset)
|
| 615 |
+
|
| 616 |
+
def __getitem__(self, idx):
|
| 617 |
+
try:
|
| 618 |
+
sample = self.dataset[idx]
|
| 619 |
+
|
| 620 |
+
chosen_text = sample.get(self.chosen_field, '')
|
| 621 |
+
rejected_text = sample.get(self.rejected_field, '')
|
| 622 |
+
|
| 623 |
+
if not chosen_text or not rejected_text:
|
| 624 |
+
return None
|
| 625 |
+
|
| 626 |
+
# Tokenize
|
| 627 |
+
chosen_enc = self.tokenizer(
|
| 628 |
+
chosen_text,
|
| 629 |
+
max_length=self.max_length,
|
| 630 |
+
truncation=True,
|
| 631 |
+
padding='max_length',
|
| 632 |
+
return_tensors='pt'
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
rejected_enc = self.tokenizer(
|
| 636 |
+
rejected_text,
|
| 637 |
+
max_length=self.max_length,
|
| 638 |
+
truncation=True,
|
| 639 |
+
padding='max_length',
|
| 640 |
+
return_tensors='pt'
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
return (
|
| 644 |
+
chosen_enc['input_ids'].squeeze(0),
|
| 645 |
+
rejected_enc['input_ids'].squeeze(0),
|
| 646 |
+
chosen_enc['attention_mask'].squeeze(0),
|
| 647 |
+
rejected_enc['attention_mask'].squeeze(0)
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
except Exception as e:
|
| 651 |
+
logger.debug(f"Error getting preference item at index {idx}: {e}")
|
| 652 |
+
return None
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def collate_fn_v2(batch):
|
| 656 |
+
batch = [item for item in batch if item is not None]
|
| 657 |
+
|
| 658 |
+
if not batch:
|
| 659 |
+
logger.warning("Empty batch after filtering None values")
|
| 660 |
+
# 返回一个空的占位batch而不是None
|
| 661 |
+
return {
|
| 662 |
+
'input_ids': torch.empty(0),
|
| 663 |
+
'attention_mask': torch.empty(0)
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
# 检查是否是preference数据
|
| 667 |
+
if isinstance(batch[0], tuple):
|
| 668 |
+
if len(batch[0]) == 4: # 包含attention_mask
|
| 669 |
+
chosen = torch.stack([item[0] for item in batch])
|
| 670 |
+
rejected = torch.stack([item[1] for item in batch])
|
| 671 |
+
chosen_mask = torch.stack([item[2] for item in batch])
|
| 672 |
+
rejected_mask = torch.stack([item[3] for item in batch])
|
| 673 |
+
return {
|
| 674 |
+
'chosen': chosen,
|
| 675 |
+
'rejected': rejected,
|
| 676 |
+
'chosen_mask': chosen_mask,
|
| 677 |
+
'rejected_mask': rejected_mask
|
| 678 |
+
}
|
| 679 |
+
else:
|
| 680 |
+
chosen = torch.stack([item[0] for item in batch])
|
| 681 |
+
rejected = torch.stack([item[1] for item in batch])
|
| 682 |
+
return {'chosen': chosen, 'rejected': rejected}
|
| 683 |
+
|
| 684 |
+
keys = batch[0].keys()
|
| 685 |
+
collated = {}
|
| 686 |
+
|
| 687 |
+
for key in keys:
|
| 688 |
+
if key in ['instruction', 'response', 'instruction_mask',
|
| 689 |
+
'response_mask', 'input_ids', 'attention_mask']:
|
| 690 |
+
tensors = [item[key] for item in batch if item.get(key) is not None]
|
| 691 |
+
if tensors:
|
| 692 |
+
collated[key] = torch.stack(tensors)
|
| 693 |
+
else:
|
| 694 |
+
collated[key] = None
|
| 695 |
+
elif key == 'modality_data':
|
| 696 |
+
# 处理多模态数据
|
| 697 |
+
modality_list = [item[key] for item in batch if item.get(key) is not None]
|
| 698 |
+
if modality_list and any(m is not None for m in modality_list):
|
| 699 |
+
# 收集图像
|
| 700 |
+
images = [m.get('image') for m in modality_list if m and 'image' in m]
|
| 701 |
+
if images:
|
| 702 |
+
collated[key] = {'image': torch.stack(images)}
|
| 703 |
+
else:
|
| 704 |
+
collated[key] = None
|
| 705 |
+
else:
|
| 706 |
+
collated[key] = None
|
| 707 |
+
else:
|
| 708 |
+
collated[key] = [item[key] for item in batch]
|
| 709 |
+
|
| 710 |
+
return collated
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def create_pretrain_dataloader(
|
| 714 |
+
mix_name: str = 'default',
|
| 715 |
+
tokenizer=None,
|
| 716 |
+
batch_size: int = 8,
|
| 717 |
+
num_workers: int = 4,
|
| 718 |
+
max_length: int = 2048,
|
| 719 |
+
max_samples: Optional[int] = None
|
| 720 |
+
):
|
| 721 |
+
dataset = PreTrainDataset(
|
| 722 |
+
mix_name=mix_name,
|
| 723 |
+
tokenizer=tokenizer,
|
| 724 |
+
max_length=max_length,
|
| 725 |
+
streaming=True,
|
| 726 |
+
max_samples=max_samples
|
| 727 |
+
)
|
| 728 |
+
return DataLoader(
|
| 729 |
+
dataset,
|
| 730 |
+
batch_size=batch_size,
|
| 731 |
+
num_workers=num_workers,
|
| 732 |
+
collate_fn=collate_fn_v2
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def create_posttrain_dataloader(
|
| 737 |
+
mix_name: str = 'default',
|
| 738 |
+
tokenizer=None,
|
| 739 |
+
batch_size: int = 8,
|
| 740 |
+
num_workers: int = 4,
|
| 741 |
+
max_length: int = 2048,
|
| 742 |
+
max_samples: Optional[int] = None,
|
| 743 |
+
split: str = 'train',
|
| 744 |
+
shuffle: bool = True
|
| 745 |
+
):
|
| 746 |
+
dataset = PostTrainDataset(
|
| 747 |
+
mix_name=mix_name,
|
| 748 |
+
tokenizer=tokenizer,
|
| 749 |
+
max_length=max_length,
|
| 750 |
+
max_samples=max_samples,
|
| 751 |
+
split=split
|
| 752 |
+
)
|
| 753 |
+
return DataLoader(
|
| 754 |
+
dataset,
|
| 755 |
+
batch_size=batch_size,
|
| 756 |
+
shuffle=shuffle,
|
| 757 |
+
num_workers=num_workers,
|
| 758 |
+
collate_fn=collate_fn_v2,
|
| 759 |
+
pin_memory=True,
|
| 760 |
+
drop_last=False
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def create_preference_dataloader(
|
| 765 |
+
dataset_name: str = 'hh_rlhf',
|
| 766 |
+
tokenizer=None,
|
| 767 |
+
batch_size: int = 8,
|
| 768 |
+
num_workers: int = 4,
|
| 769 |
+
max_length: int = 1024,
|
| 770 |
+
max_samples: Optional[int] = None,
|
| 771 |
+
split: str = 'train',
|
| 772 |
+
shuffle: bool = True
|
| 773 |
+
):
|
| 774 |
+
dataset = PreferenceDataset(
|
| 775 |
+
dataset_name=dataset_name,
|
| 776 |
+
tokenizer=tokenizer,
|
| 777 |
+
max_length=max_length,
|
| 778 |
+
max_samples=max_samples,
|
| 779 |
+
split=split
|
| 780 |
+
)
|
| 781 |
+
return DataLoader(
|
| 782 |
+
dataset,
|
| 783 |
+
batch_size=batch_size,
|
| 784 |
+
shuffle=shuffle,
|
| 785 |
+
num_workers=num_workers,
|
| 786 |
+
collate_fn=collate_fn_v2,
|
| 787 |
+
pin_memory=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 788 |
)
|