File size: 44,404 Bytes
edfb009 |
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 |
{
"cells": [
{
"cell_type": "markdown",
"id": "695a0d97-6b1d-4448-b16c-3ba95bb60c30",
"metadata": {},
"source": [
"# If these install, restart the kernal so it has access to the recently installed files"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "22de09b1-3c40-4195-8b5a-926d5391313f",
"metadata": {},
"outputs": [],
"source": [
"!pip3 install --user transformers datasets evaluate rouge_score\n",
"!pip3 install --user datasets\n",
"!pip install --user transformers[torch]\n",
"!pip install --user accelerate -U\n",
"!pip install --user wandb"
]
},
{
"cell_type": "markdown",
"id": "e1687d09-6b14-47fb-9819-dbed0d8ae3b3",
"metadata": {},
"source": [
"# Logging into huggingface hub"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f2f10d5e-9655-4554-abb0-511044640854",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "85b2b1cf7e174dc4b50a3ff3a768b282",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from huggingface_hub import notebook_login\n",
"\n",
"notebook_login()"
]
},
{
"cell_type": "markdown",
"id": "05b9e8c7-b52d-4a1f-8464-fb5f7e78e579",
"metadata": {},
"source": [
"# Naming the WANDB project and notebook"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "6b4bad30-76c7-49dc-b563-a27ed9465eee",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[34m\u001b[1mwandb\u001b[0m: \u001b[33mWARNING\u001b[0m WANDB_NOTEBOOK_NAME should be a path to a notebook file, couldn't find ./TermProject.\n",
"\u001b[34m\u001b[1mwandb\u001b[0m: Currently logged in as: \u001b[33mtah6k\u001b[0m (\u001b[33mcheaptrix\u001b[0m). Use \u001b[1m`wandb login --relogin`\u001b[0m to force relogin\n"
]
},
{
"data": {
"text/html": [
"wandb version 0.16.6 is available! To upgrade, please run:\n",
" $ pip install wandb --upgrade"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Tracking run with wandb version 0.16.2"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Run data is saved locally in <code>/scratch/user/u.th161689/AI_NLP/TermProject/wandb/run-20240403_223123-2h8q76y0</code>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Syncing run <strong><a href='https://wandb.ai/cheaptrix/California_bills_summary/runs/2h8q76y0' target=\"_blank\">swift-planet-1</a></strong> to <a href='https://wandb.ai/cheaptrix/California_bills_summary' target=\"_blank\">Weights & Biases</a> (<a href='https://wandb.me/run' target=\"_blank\">docs</a>)<br/>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
" View project at <a href='https://wandb.ai/cheaptrix/California_bills_summary' target=\"_blank\">https://wandb.ai/cheaptrix/California_bills_summary</a>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
" View run at <a href='https://wandb.ai/cheaptrix/California_bills_summary/runs/2h8q76y0' target=\"_blank\">https://wandb.ai/cheaptrix/California_bills_summary/runs/2h8q76y0</a>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<button onClick=\"this.nextSibling.style.display='block';this.style.display='none';\">Display W&B run</button><iframe src='https://wandb.ai/cheaptrix/California_bills_summary/runs/2h8q76y0?jupyter=true' style='border:none;width:100%;height:420px;display:none;'></iframe>"
],
"text/plain": [
"<wandb.sdk.wandb_run.Run at 0x14c5f8617710>"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Must set the global variable WANDB_NOTEBOOK_NAME to the name of the notebook\n",
"import os\n",
"import wandb\n",
"# Name is found through the os incase the name changes\n",
"# WANDB_NOTEBOOK_NAME = os.path.basename(os.getcwd())\n",
"notebook_name = str(os.path.basename(os.getcwd()))\n",
"os.environ[\"WANDB_NOTEBOOK_NAME\"] = \"./\" + notebook_name\n",
"os.environ[\"WANDB_PROJECT\"] = \"California_bills_summary\"\n",
"wandb.init(project='California_bills_summary') "
]
},
{
"cell_type": "markdown",
"id": "69fbba70-2fb2-47c9-abc9-1824a3ab10d7",
"metadata": {},
"source": [
"# Importing and loading the California Bills dataset"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "fd3b62f1-5bd2-44ff-87f3-1d48ccb74459",
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset\n",
"\n",
"billsum = load_dataset(\"billsum\", split=\"ca_test\")"
]
},
{
"cell_type": "markdown",
"id": "2c87b4f7-bdbd-4869-8975-609373000ab0",
"metadata": {},
"source": [
"# Splitting the data to training and testing split"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "9f08c14e-820e-497d-a979-6332bce67bc1",
"metadata": {},
"outputs": [],
"source": [
"billsum = billsum.train_test_split(test_size=0.2)"
]
},
{
"cell_type": "markdown",
"id": "9949be74-ed88-49a8-8465-8290af7abe6f",
"metadata": {},
"source": [
"# Example of data within the training set"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "2f7551a5-631d-4de3-afb7-99d923d18ccd",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'text': \"The people of the State of California do enact as follows:\\n\\n\\nSECTION 1.\\nThe Legislature finds and declares as follows:\\n(a) On February 27, 2014, the President of the United States launched the My Brother’s Keeper initiative to address persistent opportunity gaps faced by boys and young men of color and to ensure that all young people can reach their full potential.\\n(b) The My Brother’s Keeper Task Force recognizes that challenges facing boys and young men of color affect others as well and that it is important to break down barriers wherever they exist and to identify means of creating ladders of opportunity for all.\\n(c) The My Brother’s Keeper Task Force was established to develop a coordinated federal effort to significantly improve the expected life outcomes for boys and young men of color, including Black Americans, Hispanic Americans, and Native Americans, and to improve their contributions to the nation’s prosperity, so that all youth have an equal opportunity at achieving the American dream.\\n(d) The My Brother’s Keeper Task Force noted that significant diversity exists within and among boys and men of color as a segment of the population. Differences of language status, income, disability, sexual orientation, and many other factors influence the identity and experience of these young people, just as with any other population.\\n(e) My Brother’s Keeper is focused on the following milestones: (1) getting a healthy start and entering school ready to learn; (2) reading at grade level by third grade; (3) graduating from high school ready for college and career; (4) completing postsecondary education or training; (5) successfully entering the workforce; and (6) keeping kids on track and giving them second chances.\\n(f) The My Brother’s Keeper Task Force Report to the President (May 2014) cites numerous areas in which boys and men of color consistently experience disproportionately negative outcomes. These areas include living in poverty, living without a male parent in the household, high school dropout rates, unemployment, death by homicide, and imprisonment.\\n(g) The My Brother’s Keeper Task Force has identified initial recommendations and areas of opportunity at each of these key milestones or “focus areas.” The task force has also identified several cross-cutting areas of opportunity that span all focus areas.\\n(h) The recommendations in the My Brother’s Keeper Task Force Report to the President inform and influence California policy and California’s compliance with those recommendations makes the state more competitive for federal funding and strengthens its economic competitiveness.\\n(i) Our state’s future prosperity and health depend on all Californians having a fair chance to thrive and succeed. One of the best investments we can make is to be certain we do everything possible to help young people become healthy, productive adults. As California becomes more diverse, we must nurture and harness the talents, skills, and hopes of young people of color — boys and young men in particular.\\n(j) The Department of Finance projects California’s population of boys and men of color will increasingly represent a growing percentage of the state's male population, reaching close to 80 percent for boys and men of color compared to 20 percent for non-Hispanic white males by 2050.\\n(k) The Assembly Select Committee on the Status of Boys and Men of Color in California has recognized that boys and young men of color are in jeopardy, and this poses a serious threat to California’s economic strength and competitiveness.\\n(l) The Assembly Select Committee on the Status of Boys and Men of Color’s policy framework emphasizes the following issues: (1) health and safety; (2) education; (3) juvenile justice; (4) employment and wealth; and (5) youth development. Related issues that have been recommended for expansion of the committee’s work include higher education, immigration, and housing.\\n(m) Community and youth leaders from across the state have taken a significant interest in partnering with government and systems leaders through the Alliance for Boys and Men of Color in order to improve the health and success of our state’s young people of color.\\nSEC. 2.\\nChapter 3.4 (commencing with Section 8265) is added to Division 1 of Title 2 of the Government Code, to read:\\nCHAPTER 3.4. Interagency Task Force on the Status of Boys and Men of Color\\n8265.\\n(a) (1) There is in state government the Interagency Task Force on the Status of Boys and Men of Color, which shall serve as a support mechanism for department, agency, and systems leaders by taking coordinated action in meeting the myriad of challenges facing boys and men of color, and assisting the respective departments and agencies in more successfully improving life outcomes for this population.\\n(2) It is the intent of the Legislature that the task force include participation from a core set of department, agency, and systems leaders with discretion and responsibility for policy areas of primary importance to the fulfillment of the Final Report and Policy Platform for State Action (2012–18) of the Assembly Select Committee on the Status of Boys and Men in California.\\n(b) The task force shall be comprised of the following 20 members:\\n(1) One Member of the Senate, appointed by the Senate Committee on Rules, and one Member of the Assembly, appointed by the Speaker of the Assembly, as ex officio, nonvoting members, and to the extent that participation is not incompatible with their position as Members of the Legislature.\\n(2) The Superintendent of Public Instruction, or his or her designee.\\n(3) The President of the University of California, or his or her designee.\\n(4) The Chancellor of the California State University, or his or her designee.\\n(5) The Chancellor of the California Community Colleges, or his or her designee.\\n(6) The Secretary of California Health and Human Services, or his or her designee.\\n(7) The State Public Health Officer, or his or her designee.\\n(8) The Deputy Director of the Office of Health Equity, or his or her designee.\\n(9) The Secretary of Business, Consumer Services, and Housing, or his or her designee.\\n(10) The Secretary of Labor and Workforce Development, or his or her designee.\\n(11) The Director of Employment Development, or his or her designee.\\n(12) The Executive Director of the California Workforce Investment Board, or his or her designee.\\n(13) The Chair of the California Workforce Investment Board, or his or her designee.\\n(14) The Secretary of Transportation, or his or her designee.\\n(15) The Director of Finance, or his or her designee.\\n(16) The Attorney General, or his or her designee.\\n(17) The Secretary of the Department of Corrections and Rehabilitation, or his or her designee.\\n(18) The Chair of the Board of State and Community Corrections, or his or her designee.\\n(19) The Chief Justice of California, or his or her designee.\\n(c) The task force shall elect one of its members to serve as chair of the task force. Desirable qualifications for the position of chair shall include, but not be limited to, all of the following:\\n(1) He or she should possess a broad and deep understanding of the issues facing boys and men of color.\\n(2) He or she should be a political appointee with a senior leadership role either leading a department or agency or managing a significant and pertinent body of work.\\n(3) He or she should have a demonstrated strong and positive working relationship with the members of the Legislature and the Governor.\\n(d) All members of the task force shall hold office until the appointment of their successors.\\n8266.\\nMeetings of the task force shall be subject to the Bagley-Keene Open Meetings Act (Article 9 (commencing with Section 11120) of Chapter 1 of Part 1 of Division 3).\\n8267.\\nThe task force shall have the powers and authority necessary to carry out the duties imposed upon it by this chapter, including, but not limited to, all of the following:\\n(a) To employ any administrative, technical, or other personnel necessary for the performance of its powers and duties.\\n(b) To hold hearings, make and sign any agreements, and to do or perform any acts that may be necessary, desirable, or proper to carry out the purposes of this chapter.\\n(c) To cooperate with, and secure the cooperation of, any department, division, board, bureau, commission, or other agency of the state to facilitate the task force properly to carry out its powers and duties.\\n(d) To appoint advisers or advisory committees from time to time when the task force determines that the experience or expertise of the advisers or advisory committees is needed for projects of the task force. Section 11009 shall apply to these advisers or advisory committees.\\n(e) To accept any federal funds granted, by act of Congress or by executive order, for all or any of the purposes of this chapter.\\n(f) To accept any gifts, donations, grants, or bequests for all or any of the purposes of this chapter.\\n8268.\\n(a) Within six months after the effective date of this chapter, the task force shall complete all of the following requirements:\\n(1) Assess existing department and agency programs that align with the priorities outlined in the May 2014 My Brother’s Keeper Task Force Report to the President. Based on this assessment, the task force shall identify state opportunities to partner and coordinate with the work of the federal My Brother’s Keeper Task Force.\\n(2) Assess the Governor’s Budget to identify those areas in which the budget priorities are in alignment with the objectives of the task force.\\n(3) Review the action plan of the Final Report and Policy Platform for State Action (2012–18) of the Assembly Select Committee on the Status of Boys and Men of Color in California, and identify ambitious state goals for boys and men of color, as well as barriers to achieving desired results.\\n(b) Upon completion of the requirements in subdivision (a), the long-term, ongoing responsibilities of the task force shall include all of the following:\\n(1) Assessing state policies, regulations, and programs with respect to boys and men of color, and the development of proven and promising strategies to enhance positive outcomes and eliminate or mitigate negative outcomes.\\n(2) Preparing population and agency-specific data on boys and men of color in California. The task force shall aggregate the data and make it publicly available in a manner that does not reveal personally identifiable information or otherwise conflict with federal or state privacy laws.\\n(3) Serving as a liaison to departments and agencies by ensuring engagement and partnership with other public, nonprofit, and philanthropic entities among the various member agencies and with the task force as a whole, and recommend ways to strengthen partnerships with external leaders advancing strategies relevant to boys and men of color.\\n(c) The first meeting of the task force shall be convened on or before January 31, 2016. Subsequently, the task force shall convene on no less than a quarterly basis to assess progress on its ongoing responsibilities pursuant to subdivision (b), and to provide support and ensure coordination across agencies.\\n(d) (1) Notwithstanding Section 10231.5, the task force shall prepare and submit to the Legislature an annual report on department and agency findings pursuant to this section. The task force shall also report these findings at the Assembly Select Committee on the Status of Boys and Men of Color in California’s annual hearing on the status of advancing the committee priorities and policies.\\n(2) A report submitted pursuant to this subdivision shall be submitted in compliance with Section 9795.\\n8269.\\nWith respect to its duties under Section 8268, the task force shall be an advisory body only, and there shall be no right or obligation on the part of the state, or the parties meeting and conferring, to implement the findings of the task force without further legislation that specifically authorizes that the evaluations, determinations, and findings of the task force be implemented.\\n8269.5\\nThe Boys and Men of Color Task Force Fund is hereby created as a fund in the State Treasury to carry out this chapter in support of the task force, upon appropriation by the Legislature. Subject to the approval of the Department of Finance, all moneys collected or received by the task force from gifts, bequests, or donations shall be deposited in the State Treasury to the credit of the Boys and Men of Color Task Force Fund in accordance with the terms of the gift or donation from which the moneys are derived and in accordance with Sections 8647, 11005, 11005.1, and 16302 of the Government Code.\\n8269.7.\\nThis chapter shall remain in effect only until January 1, 2026, and as of that date is repealed.\",\n",
" 'summary': 'The California Constitution prohibits a person from being deprived of life, liberty, or property without due process of law, or from being denied equal protection of the laws. The United States Constitution prohibits a state from denying to any person within its jurisdiction the equal protection of the laws. Existing law establishes various advisory boards and commissions in state government with specified duties and responsibilities.\\nThe federal My Brother’s Keeper Initiative, launched by the President of the United States in February 2014, required the establishment of the My Brother’s Keeper Task Force, an interagency effort to improve the expected educational and life outcomes for and address the persistent opportunity gaps faced by boys and young men of color in the United States.\\nThis bill would establish until January 1, 2026, the Interagency Task Force on the Status of Boys and Men of Color, a multiagency advisory body that would serve as a support mechanism for department agency and systems leaders by taking coordinated action in meeting the myriad of challenges facing boys and men of color in California, and assisting the respective departments and agencies in more successfully improving life outcomes for this population. The membership of the task force would include members of the Legislature, as well as representatives of specified agencies, departments, and private entities. The bill would set forth the initial and ongoing responsibilities of the task force, including, among others, an assessment of state program alignment with the objectives of the My Brother’s Keeper program, review the action plan of a specified final report of the Assembly Select Committee on the Status of Boys and Men of Color in California, and an assessment of the development of strategies to enhance positive outcomes and eliminate or mitigate negative outcomes for boys and men of color in the state. The bill would establish the Boys and Men of Color Task Force Fund, which would be subject to appropriation by the Legislature, to carry out the bill’s requirements in support of the task force, upon appropriation by the Legislature. The bill would authorize the task force to accept federal funds, gifts, donations, grants, or bequests for all or any of its purposes.',\n",
" 'title': 'An act to add and repeal Chapter 3.4 (commencing with Section 8265) to Division 1 of Title 2 of the Government Code, relating to state government.'}"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"billsum[\"train\"][0]"
]
},
{
"cell_type": "markdown",
"id": "7c2e2c67-3d0b-4d4b-b3b6-e6d9afb60c8a",
"metadata": {},
"source": [
"# Load T5 tokenizer to process text and summary"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "b3d4454e-e7f3-4020-9ecc-4c692c6da5c6",
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"checkpoint = \"google-t5/t5-small\"\n",
"tokenizer = AutoTokenizer.from_pretrained(checkpoint)"
]
},
{
"cell_type": "markdown",
"id": "15e4537b-4a72-434a-8af7-1cef702581d0",
"metadata": {},
"source": [
"# Perprocessing Function"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "2feec165-87ed-4258-a332-14c3b7dd9867",
"metadata": {},
"outputs": [],
"source": [
"prefix = \"summarize: \"\n",
"\n",
"\n",
"def preprocess_function(examples):\n",
" inputs = [prefix + doc for doc in examples[\"text\"]]\n",
" model_inputs = tokenizer(inputs, max_length=1024, truncation=True)\n",
"\n",
" labels = tokenizer(text_target=examples[\"summary\"], max_length=128, truncation=True)\n",
"\n",
" model_inputs[\"labels\"] = labels[\"input_ids\"]\n",
" return model_inputs"
]
},
{
"cell_type": "markdown",
"id": "814f0888-e5c0-4841-9084-ed4f6762ecdd",
"metadata": {},
"source": [
"# Tokenize the dataset using the map function"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "65c755b9-33ae-4d95-b0d2-b7b7950f4f71",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "24949b7ce3e54b5689d7d42a928d1d49",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Map: 0%| | 0/989 [00:00<?, ? examples/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8d68949efc8c4ef68bbbffeaac9f1aae",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Map: 0%| | 0/248 [00:00<?, ? examples/s]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"tokenized_billsum = billsum.map(preprocess_function, batched=True)"
]
},
{
"cell_type": "markdown",
"id": "294ec0e7-5120-4c13-9517-6e4407dd12e7",
"metadata": {},
"source": [
"# Creating a batch of examples using DataCollatorForSeq2Seq with dynamic padding"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "a1e9d07d-7cbf-46c2-87c6-9ebc97fcbfcf",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2024-04-03 22:31:45.588933: I tensorflow/core/util/port.cc:111] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
"2024-04-03 22:31:45.622854: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
"2024-04-03 22:31:45.622885: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
"2024-04-03 22:31:45.622911: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
"2024-04-03 22:31:45.629431: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
"To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
"2024-04-03 22:31:46.665693: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n"
]
}
],
"source": [
"from transformers import DataCollatorForSeq2Seq\n",
"\n",
"data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)"
]
},
{
"cell_type": "markdown",
"id": "bd435fc8-af8b-419b-b41b-384f6b412119",
"metadata": {},
"source": [
"# Importing the evaluator"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "bc7159a1-3997-47bd-8d17-48c2e09f7ace",
"metadata": {},
"outputs": [],
"source": [
"import evaluate\n",
"\n",
"rouge = evaluate.load(\"rouge\")"
]
},
{
"cell_type": "markdown",
"id": "11f1979d-91e3-414f-b76b-36034e97b8b0",
"metadata": {},
"source": [
"# Function that passes predictions and labels to compute to calculate the Rouge metric."
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "e301045f-eb8d-4c2d-b2f5-59acf2f053b0",
"metadata": {},
"outputs": [],
"source": [
"def compute_metrics(eval_pred):\n",
" predictions, labels = eval_pred\n",
" decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)\n",
" labels = np.where(labels != -100, labels, tokenizer.pad_token_id)\n",
" decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)\n",
"\n",
" result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)\n",
"\n",
" prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]\n",
" result[\"gen_len\"] = np.mean(prediction_lens)\n",
"\n",
" return {k: round(v, 4) for k, v in result.items()}"
]
},
{
"cell_type": "markdown",
"id": "e3833f68-20da-4343-88c6-4b5c144bfb7c",
"metadata": {},
"source": [
"# Training - Loading T5 with AutoModelForSeq2SeqLM"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "8a9100fb-4ebe-469d-a1a3-b0a00c54528a",
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer\n",
"\n",
"model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)"
]
},
{
"cell_type": "markdown",
"id": "9722c5f5-a9ed-44d1-b677-9fe558890218",
"metadata": {},
"source": [
"# Defining the training hyperparameters"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "e9d5eb20-6e52-44c7-aa09-5ad6c09576d9",
"metadata": {},
"outputs": [],
"source": [
"training_args = Seq2SeqTrainingArguments(\n",
" output_dir=\"California_bills_summary\",\n",
" evaluation_strategy=\"epoch\",\n",
" learning_rate=2e-5,\n",
" per_device_train_batch_size=16,\n",
" per_device_eval_batch_size=16,\n",
" weight_decay=0.01,\n",
" save_total_limit=3,\n",
" num_train_epochs=4,\n",
" predict_with_generate=True,\n",
" fp16=True,\n",
" push_to_hub=True,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "aa5635ee-8d6a-45ce-8976-90df52eacd8a",
"metadata": {},
"source": [
"# Passing the arguments, model, dataset, tokenizer, data collator, and compute_metrics function to Seq2SeqTrainer for training"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "3476e539-1f86-41b2-beec-f9441406a692",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/u.th161689/.local/lib/python3.11/site-packages/accelerate/accelerator.py:432: FutureWarning: Passing the following arguments to `Accelerator` is deprecated and will be removed in version 1.0 of Accelerate: dict_keys(['dispatch_batches', 'split_batches']). Please pass an `accelerate.DataLoaderConfiguration` instead: \n",
"dataloader_config = DataLoaderConfiguration(dispatch_batches=None, split_batches=False)\n",
" warnings.warn(\n",
"Detected kernel version 4.18.0, which is below the recommended minimum of 5.5.0; this can cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher.\n"
]
}
],
"source": [
"trainer = Seq2SeqTrainer(\n",
" model=model,\n",
" args=training_args,\n",
" train_dataset=tokenized_billsum[\"train\"],\n",
" eval_dataset=tokenized_billsum[\"test\"],\n",
" tokenizer=tokenizer,\n",
" data_collator=data_collator,\n",
" compute_metrics=compute_metrics,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "91c564a2-6a8c-4073-ac83-aa45b2ae28fa",
"metadata": {},
"source": [
"# Fine-tuning the model"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "d3f06124-0e43-4cf6-9af8-af0b42fa1b78",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"You're using a T5TokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.\n"
]
},
{
"data": {
"text/html": [
"\n",
" <div>\n",
" \n",
" <progress value='248' max='248' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
" [248/248 03:49, Epoch 4/4]\n",
" </div>\n",
" <table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: left;\">\n",
" <th>Epoch</th>\n",
" <th>Training Loss</th>\n",
" <th>Validation Loss</th>\n",
" <th>Rouge1</th>\n",
" <th>Rouge2</th>\n",
" <th>Rougel</th>\n",
" <th>Rougelsum</th>\n",
" <th>Gen Len</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <td>1</td>\n",
" <td>No log</td>\n",
" <td>2.797509</td>\n",
" <td>0.125500</td>\n",
" <td>0.036400</td>\n",
" <td>0.106700</td>\n",
" <td>0.106400</td>\n",
" <td>19.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <td>2</td>\n",
" <td>No log</td>\n",
" <td>2.585288</td>\n",
" <td>0.135400</td>\n",
" <td>0.046000</td>\n",
" <td>0.112500</td>\n",
" <td>0.112200</td>\n",
" <td>19.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <td>3</td>\n",
" <td>No log</td>\n",
" <td>2.522834</td>\n",
" <td>0.139200</td>\n",
" <td>0.049100</td>\n",
" <td>0.114500</td>\n",
" <td>0.114200</td>\n",
" <td>19.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <td>4</td>\n",
" <td>No log</td>\n",
" <td>2.506120</td>\n",
" <td>0.141300</td>\n",
" <td>0.050300</td>\n",
" <td>0.116300</td>\n",
" <td>0.116100</td>\n",
" <td>19.000000</td>\n",
" </tr>\n",
" </tbody>\n",
"</table><p>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/opt/conda/lib/python3.11/site-packages/transformers/generation/utils.py:1355: UserWarning: Using the model-agnostic default `max_length` (=20) to control the generation length. We recommend setting `max_new_tokens` to control the maximum length of the generation.\n",
" warnings.warn(\n"
]
},
{
"data": {
"text/plain": [
"TrainOutput(global_step=248, training_loss=3.0278184952274447, metrics={'train_runtime': 230.4959, 'train_samples_per_second': 17.163, 'train_steps_per_second': 1.076, 'total_flos': 1070824333246464.0, 'train_loss': 3.0278184952274447, 'epoch': 4.0})"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Training needs numpy\n",
"import numpy as np\n",
"\n",
"# Fine-tuning the model\n",
"trainer.train()"
]
},
{
"cell_type": "markdown",
"id": "166d4903-8809-4a77-9f43-45316cbccc91",
"metadata": {},
"source": [
"# Interface"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "4b5fd53a-df64-4273-bc9a-b0e02c212f0b",
"metadata": {},
"outputs": [],
"source": [
"text = \"summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. It'll lower the deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes.\""
]
},
{
"cell_type": "markdown",
"id": "a0635a21-fde7-4d8e-92f0-9058131afd85",
"metadata": {},
"source": [
"# SAVING THE MODEL"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "afe34cd8-eccb-4cea-abfb-7775173be6b9",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7afa4227cddf46b580032efb5050b6f2",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Upload 3 LFS files: 0%| | 0/3 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "c95787eebc7b42e8851e256c1b23e57e",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"events.out.tfevents.1712201512.fc100.155086.0: 0%| | 0.00/7.81k [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "84de531b675141bc8b471214b9a308c1",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"model.safetensors: 0%| | 0.00/242M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "5d8b263ec643440fbddf787a0bab59a5",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"training_args.bin: 0%| | 0.00/4.86k [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"trainer.save_model(\"./California_bills_summary\")"
]
},
{
"cell_type": "markdown",
"id": "a14d26cd-ac89-4e11-a884-0550f8ff39c6",
"metadata": {},
"source": [
"# PUSHING MODEL TO PERSONAL HUGGINFACE HUB"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "90908ffc-9dac-451c-a0ff-edaae4312aed",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"CommitInfo(commit_url='https://huggingface.co/cheaptrix/California_bills_summary/commit/5a2db3aecf4f224ab11b75fc9c3dedbc4fa0a570', commit_message='cheaptrix/California_bills_summary', commit_description='', oid='5a2db3aecf4f224ab11b75fc9c3dedbc4fa0a570', pr_url=None, pr_revision=None, pr_num=None)"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"trainer.push_to_hub(\"cheaptrix/California_bills_summary\")"
]
},
{
"cell_type": "markdown",
"id": "484d784c-2700-4e2e-8c09-99293468487d",
"metadata": {},
"source": [
"# Creating a pipeline with the transformers module"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "7298e9e4-4a53-4494-8f8a-0a69dbb55d52",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ade2d9311d3249fcb6e33fa5da4a6fa4",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"config.json: 0%| | 0.00/1.51k [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "3d89a35f912c441fa40514f6966d87af",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"model.safetensors: 0%| | 0.00/242M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7e37b930e95c4f6e8dbf65dd78dc7360",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"generation_config.json: 0%| | 0.00/112 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "c63f4905c41041038fac2b6f0860655f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"tokenizer_config.json: 0%| | 0.00/20.7k [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "beaf7c005393433f8987a5d8a612c2a3",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"tokenizer.json: 0%| | 0.00/2.42M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "96071911ee5f42978d9d2164510bba13",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"special_tokens_map.json: 0%| | 0.00/2.54k [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Your max_length is set to 200, but your input_length is only 103. Since this is a summarization task, where outputs shorter than the input are typically wanted, you might consider decreasing max_length manually, e.g. summarizer('...', max_length=51)\n"
]
},
{
"data": {
"text/plain": [
"[{'summary_text': \"the Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs . it's the most aggressive action on tackling the climate crisis in American history . no one making under $400,000 per year will pay a penny more in taxes .\"}]"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from transformers import pipeline\n",
"\n",
"summarizer = pipeline(\"summarization\", model=\"cheaptrix/California_bills_summary\")\n",
"summarizer(text)\n",
"# [{\"summary_text\": \"The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country.\"}]"
]
},
{
"cell_type": "markdown",
"id": "08a1e990-420c-4c2b-becf-69d096865a10",
"metadata": {},
"source": [
"# Manaul pipeline"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "6d46a243-bfbc-4304-ae5b-db48c045e517",
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\"cheaptrix/California_bills_summary\")\n",
"inputs = tokenizer(text, return_tensors=\"pt\").input_ids"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "ff9ffe5e-24a8-4baa-abd9-b72dbf4ecc93",
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForSeq2SeqLM\n",
"\n",
"model = AutoModelForSeq2SeqLM.from_pretrained(\"cheaptrix/California_bills_summary\")\n",
"outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "24aa0a58-781f-4883-90e2-8a7818192fab",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"the Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in American history. it'll ask the ultra-wealthy and corporations to pay their fair share.\""
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tokenizer.decode(outputs[0], skip_special_tokens=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3320e679-fd4d-4d23-ab05-5184b579af21",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|