Spaces:
Running
Running
File size: 110,144 Bytes
cf7a8a2 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.6.40">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Single GPU Fine-tuning – Open-Source AI Cookbook</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { display: inline-block; text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script><script src="../site_libs/quarto-nav/quarto-nav.js"></script>
<script src="../site_libs/quarto-nav/headroom.min.js"></script>
<script src="../site_libs/clipboard/clipboard.min.js"></script>
<script src="../site_libs/quarto-search/autocomplete.umd.js"></script>
<script src="../site_libs/quarto-search/fuse.min.js"></script>
<script src="../site_libs/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="../">
<script src="../site_libs/quarto-html/quarto.js"></script>
<script src="../site_libs/quarto-html/popper.min.js"></script>
<script src="../site_libs/quarto-html/tippy.umd.min.js"></script>
<script src="../site_libs/quarto-html/anchor.min.js"></script>
<link href="../site_libs/quarto-html/tippy.css" rel="stylesheet">
<link href="../site_libs/quarto-html/quarto-syntax-highlighting-549806ee2085284f45b00abea8c6df48.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="../site_libs/bootstrap/bootstrap.min.js"></script>
<link href="../site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="../site_libs/bootstrap/bootstrap-2be10d9e998f81ff6e49e26833438aa5.min.css" rel="stylesheet" append-hash="true" id="quarto-bootstrap" data-mode="light">
<script id="quarto-search-options" type="application/json">{
"location": "sidebar",
"copy-button": false,
"collapse-after": 3,
"panel-placement": "start",
"type": "textbox",
"limit": 50,
"keyboard-shortcut": [
"f",
"/",
"s"
],
"show-item-context": false,
"language": {
"search-no-results-text": "No results",
"search-matching-documents-text": "matching documents",
"search-copy-link-title": "Copy link to search",
"search-hide-matches-text": "Hide additional matches",
"search-more-match-text": "more match in this document",
"search-more-matches-text": "more matches in this document",
"search-clear-button-title": "Clear",
"search-text-placeholder": "",
"search-detached-cancel-button-title": "Cancel",
"search-submit-button-title": "Submit",
"search-label": "Search"
}
}</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous"></script>
<script type="application/javascript">define('jquery', [],function() {return window.jQuery;})</script>
<link rel="stylesheet" href="../styles.css">
</head>
<body class="nav-sidebar docked">
<div id="quarto-search-results"></div>
<header id="quarto-header" class="headroom fixed-top">
<nav class="quarto-secondary-nav">
<div class="container-fluid d-flex">
<button type="button" class="quarto-btn-toggle btn" data-bs-toggle="collapse" role="button" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
<i class="bi bi-layout-text-sidebar-reverse"></i>
</button>
<nav class="quarto-page-breadcrumbs" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item">Open-Source AI Cookbook</li><li class="breadcrumb-item"><a href="../notebooks/automatic_embedding.html">Additional Techniques</a></li><li class="breadcrumb-item"><a href="../notebooks/single_gpu.html">Single GPU Optimization</a></li></ol></nav>
<a class="flex-grow-1" role="navigation" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
</a>
<button type="button" class="btn quarto-search-button" aria-label="Search" onclick="window.quartoOpenSearch();">
<i class="bi bi-search"></i>
</button>
</div>
</nav>
</header>
<!-- content -->
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
<nav id="quarto-sidebar" class="sidebar collapse collapse-horizontal quarto-sidebar-collapse-item sidebar-navigation docked overflow-auto">
<div class="pt-lg-2 mt-2 text-left sidebar-header">
<div class="sidebar-title mb-0 py-0">
<a href="../">Open-Source AI Cookbook</a>
</div>
</div>
<div class="mt-2 flex-shrink-0 align-items-center">
<div class="sidebar-search">
<div id="quarto-search" class="" title="Search"></div>
</div>
</div>
<div class="sidebar-menu-container">
<ul class="list-unstyled mt-1">
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" role="navigation" aria-expanded="true">
<span class="menu-text">About</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-1" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../index.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">About Quarto</span></a>
</div>
</li>
</ul>
</li>
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-2" role="navigation" aria-expanded="true">
<span class="menu-text">Open-Source AI Cookbook</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-2" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-2" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-3" role="navigation" aria-expanded="true">
<span class="menu-text">RAG Techniques</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-3" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-3" class="collapse list-unstyled sidebar-section depth2 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/rag_zephyr_langchain.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">RAG Zephyr & LangChain</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/advanced_rag.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">Advanced RAG</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/rag_evaluation.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">RAG Evaluation</span></a>
</div>
</li>
</ul>
</li>
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-4" role="navigation" aria-expanded="true">
<span class="menu-text">Additional Techniques</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-4" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-4" class="collapse list-unstyled sidebar-section depth2 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/automatic_embedding.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">Automatic Embedding</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/faiss.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">FAISS for Efficient Search</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/single_gpu.html" class="sidebar-item-text sidebar-link active">
<span class="menu-text">Single GPU Optimization</span></a>
</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</nav>
<div id="quarto-sidebar-glass" class="quarto-sidebar-collapse-item" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item"></div>
<!-- margin-sidebar -->
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
<nav id="TOC" role="doc-toc" class="toc-active">
<h2 id="toc-title">On this page</h2>
<ul>
<li><a href="#fine-tuning-a-code-llm-on-custom-code-on-a-single-gpu" id="toc-fine-tuning-a-code-llm-on-custom-code-on-a-single-gpu" class="nav-link active" data-scroll-target="#fine-tuning-a-code-llm-on-custom-code-on-a-single-gpu">Fine-tuning a Code LLM on Custom Code on a single GPU</a>
<ul class="collapse">
<li><a href="#dataset" id="toc-dataset" class="nav-link" data-scroll-target="#dataset">Dataset</a></li>
<li><a href="#model" id="toc-model" class="nav-link" data-scroll-target="#model">Model</a></li>
<li><a href="#prepare-the-data" id="toc-prepare-the-data" class="nav-link" data-scroll-target="#prepare-the-data">Prepare the data</a></li>
<li><a href="#prepare-the-model" id="toc-prepare-the-model" class="nav-link" data-scroll-target="#prepare-the-model">Prepare the model</a></li>
<li><a href="#train-the-model" id="toc-train-the-model" class="nav-link" data-scroll-target="#train-the-model">Train the model</a></li>
<li><a href="#inference" id="toc-inference" class="nav-link" data-scroll-target="#inference">Inference</a></li>
</ul></li>
</ul>
</nav>
</div>
<!-- main -->
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default"><nav class="quarto-page-breadcrumbs quarto-title-breadcrumbs d-none d-lg-block" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item">Open-Source AI Cookbook</li><li class="breadcrumb-item"><a href="../notebooks/automatic_embedding.html">Additional Techniques</a></li><li class="breadcrumb-item"><a href="../notebooks/single_gpu.html">Single GPU Optimization</a></li></ol></nav>
<div class="quarto-title">
<h1 class="title">Single GPU Fine-tuning</h1>
</div>
<div class="quarto-title-meta">
</div>
</header>
<section id="fine-tuning-a-code-llm-on-custom-code-on-a-single-gpu" class="level1">
<h1>Fine-tuning a Code LLM on Custom Code on a single GPU</h1>
<p><em>Authored by: <a href="https://github.com/MKhalusova">Maria Khalusova</a></em></p>
<p>Publicly available code LLMs such as Codex, StarCoder, and Code Llama are great at generating code that adheres to general programming principles and syntax, but they may not align with an organization’s internal conventions, or be aware of proprietary libraries.</p>
<p>In this notebook, we’ll see show how you can fine-tune a code LLM on private code bases to enhance its contextual awareness and improve a model’s usefulness to your organization’s needs. Since the code LLMs are quite large, fine-tuning them in a traditional manner can be resource-draining. Worry not! We will show how you can optimize fine-tuning to fit on a single GPU.</p>
<section id="dataset" class="level2">
<h2 class="anchored" data-anchor-id="dataset">Dataset</h2>
<p>For this example, we picked the top 10 Hugging Face public repositories on GitHub. We have excluded non-code files from the data, such as images, audio files, presentations, and so on. For Jupyter notebooks, we’ve kept only cells containing code. The resulting code is stored as a dataset that you can find on the Hugging Face Hub under <a href="https://huggingface.co/datasets/smangrul/hf-stack-v1"><code>smangrul/hf-stack-v1</code></a>. It contains repo id, file path, and file content.</p>
</section>
<section id="model" class="level2">
<h2 class="anchored" data-anchor-id="model">Model</h2>
<p>We’ll finetune <a href="https://huggingface.co/bigcode/starcoderbase-1b"><code>bigcode/starcoderbase-1b</code></a>, which is a 1B parameter model trained on 80+ programming languages. This is a gated model, so if you plan to run this notebook with this exact model, you’ll need to gain access to it on the model’s page. Log in to your Hugging Face account to do so:</p>
<div id="cell-1" class="cell">
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> huggingface_hub <span class="im">import</span> notebook_login</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>notebook_login()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>To get started, let’s install all the necessary libraries. As you can see, in addition to <code>transformers</code> and <code>datasets</code>, we’ll be using <code>peft</code>, <code>bitsandbytes</code>, and <code>flash-attn</code> to optimize the training.</p>
<p>By employing parameter-efficient training techniques, we can run this notebook on a single A100 High-RAM GPU.</p>
<div id="cell-3" class="cell">
<div class="sourceCode cell-code" id="cb2"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="op">!</span>pip install <span class="op">-</span>q transformers datasets peft bitsandbytes flash<span class="op">-</span>attn</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Let’s define some variables now. Feel free to play with these.</p>
<div id="cell-5" class="cell">
<div class="sourceCode cell-code" id="cb3"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>MODEL<span class="op">=</span><span class="st">"bigcode/starcoderbase-1b"</span> <span class="co"># Model checkpoint on the Hugging Face Hub</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>DATASET<span class="op">=</span><span class="st">"smangrul/hf-stack-v1"</span> <span class="co"># Dataset on the Hugging Face Hub</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>DATA_COLUMN<span class="op">=</span><span class="st">"content"</span> <span class="co"># Column name containing the code content</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>SEQ_LENGTH<span class="op">=</span><span class="dv">2048</span> <span class="co"># Sequence length</span></span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a><span class="co"># Training arguments</span></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a>MAX_STEPS<span class="op">=</span><span class="dv">2000</span> <span class="co"># max_steps</span></span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a>BATCH_SIZE<span class="op">=</span><span class="dv">16</span> <span class="co"># batch_size</span></span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a>GR_ACC_STEPS<span class="op">=</span><span class="dv">1</span> <span class="co"># gradient_accumulation_steps</span></span>
<span id="cb3-11"><a href="#cb3-11" aria-hidden="true" tabindex="-1"></a>LR<span class="op">=</span><span class="fl">5e-4</span> <span class="co"># learning_rate</span></span>
<span id="cb3-12"><a href="#cb3-12" aria-hidden="true" tabindex="-1"></a>LR_SCHEDULER_TYPE<span class="op">=</span><span class="st">"cosine"</span> <span class="co"># lr_scheduler_type</span></span>
<span id="cb3-13"><a href="#cb3-13" aria-hidden="true" tabindex="-1"></a>WEIGHT_DECAY<span class="op">=</span><span class="fl">0.01</span> <span class="co"># weight_decay</span></span>
<span id="cb3-14"><a href="#cb3-14" aria-hidden="true" tabindex="-1"></a>NUM_WARMUP_STEPS<span class="op">=</span><span class="dv">30</span> <span class="co"># num_warmup_steps</span></span>
<span id="cb3-15"><a href="#cb3-15" aria-hidden="true" tabindex="-1"></a>EVAL_FREQ<span class="op">=</span><span class="dv">100</span> <span class="co"># eval_freq</span></span>
<span id="cb3-16"><a href="#cb3-16" aria-hidden="true" tabindex="-1"></a>SAVE_FREQ<span class="op">=</span><span class="dv">100</span> <span class="co"># save_freq</span></span>
<span id="cb3-17"><a href="#cb3-17" aria-hidden="true" tabindex="-1"></a>LOG_FREQ<span class="op">=</span><span class="dv">25</span> <span class="co"># log_freq</span></span>
<span id="cb3-18"><a href="#cb3-18" aria-hidden="true" tabindex="-1"></a>OUTPUT_DIR<span class="op">=</span><span class="st">"peft-starcoder-lora-a100"</span> <span class="co"># output_dir</span></span>
<span id="cb3-19"><a href="#cb3-19" aria-hidden="true" tabindex="-1"></a>BF16<span class="op">=</span><span class="va">True</span> <span class="co"># bf16</span></span>
<span id="cb3-20"><a href="#cb3-20" aria-hidden="true" tabindex="-1"></a>FP16<span class="op">=</span><span class="va">False</span> <span class="co"># no_fp16</span></span>
<span id="cb3-21"><a href="#cb3-21" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-22"><a href="#cb3-22" aria-hidden="true" tabindex="-1"></a><span class="co"># FIM trasformations arguments</span></span>
<span id="cb3-23"><a href="#cb3-23" aria-hidden="true" tabindex="-1"></a>FIM_RATE<span class="op">=</span><span class="fl">0.5</span> <span class="co"># fim_rate</span></span>
<span id="cb3-24"><a href="#cb3-24" aria-hidden="true" tabindex="-1"></a>FIM_SPM_RATE<span class="op">=</span><span class="fl">0.5</span> <span class="co"># fim_spm_rate</span></span>
<span id="cb3-25"><a href="#cb3-25" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-26"><a href="#cb3-26" aria-hidden="true" tabindex="-1"></a><span class="co"># LORA</span></span>
<span id="cb3-27"><a href="#cb3-27" aria-hidden="true" tabindex="-1"></a>LORA_R<span class="op">=</span><span class="dv">8</span> <span class="co"># lora_r</span></span>
<span id="cb3-28"><a href="#cb3-28" aria-hidden="true" tabindex="-1"></a>LORA_ALPHA<span class="op">=</span><span class="dv">32</span> <span class="co"># lora_alpha</span></span>
<span id="cb3-29"><a href="#cb3-29" aria-hidden="true" tabindex="-1"></a>LORA_DROPOUT<span class="op">=</span><span class="fl">0.0</span> <span class="co"># lora_dropout</span></span>
<span id="cb3-30"><a href="#cb3-30" aria-hidden="true" tabindex="-1"></a>LORA_TARGET_MODULES<span class="op">=</span><span class="st">"c_proj,c_attn,q_attn,c_fc,c_proj"</span> <span class="co"># lora_target_modules</span></span>
<span id="cb3-31"><a href="#cb3-31" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-32"><a href="#cb3-32" aria-hidden="true" tabindex="-1"></a><span class="co"># bitsandbytes config</span></span>
<span id="cb3-33"><a href="#cb3-33" aria-hidden="true" tabindex="-1"></a>USE_NESTED_QUANT<span class="op">=</span><span class="va">True</span> <span class="co"># use_nested_quant</span></span>
<span id="cb3-34"><a href="#cb3-34" aria-hidden="true" tabindex="-1"></a>BNB_4BIT_COMPUTE_DTYPE<span class="op">=</span><span class="st">"bfloat16"</span><span class="co"># bnb_4bit_compute_dtype</span></span>
<span id="cb3-35"><a href="#cb3-35" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-36"><a href="#cb3-36" aria-hidden="true" tabindex="-1"></a>SEED<span class="op">=</span><span class="dv">0</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-6" class="cell">
<div class="sourceCode cell-code" id="cb4"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> transformers <span class="im">import</span> (</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a> AutoModelForCausalLM,</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a> AutoTokenizer,</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a> Trainer,</span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a> TrainingArguments,</span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a> logging,</span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a> set_seed,</span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a> BitsAndBytesConfig,</span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a>set_seed(SEED)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="prepare-the-data" class="level2">
<h2 class="anchored" data-anchor-id="prepare-the-data">Prepare the data</h2>
<p>Begin by loading the data. As the dataset is likely to be quite large, make sure to enable the streaming mode. Streaming allows us to load the data progressively as we iterate over the dataset instead of downloading the whole dataset at once.</p>
<p>We’ll reserve the first 4000 examples as the validation set, and everything else will be the training data.</p>
<div id="cell-9" class="cell">
<div class="sourceCode cell-code" id="cb5"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> datasets <span class="im">import</span> load_dataset</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> torch</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tqdm <span class="im">import</span> tqdm</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>dataset <span class="op">=</span> load_dataset(</span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a> DATASET,</span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a> data_dir<span class="op">=</span><span class="st">"data"</span>,</span>
<span id="cb5-9"><a href="#cb5-9" aria-hidden="true" tabindex="-1"></a> split<span class="op">=</span><span class="st">"train"</span>,</span>
<span id="cb5-10"><a href="#cb5-10" aria-hidden="true" tabindex="-1"></a> streaming<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb5-11"><a href="#cb5-11" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb5-12"><a href="#cb5-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-13"><a href="#cb5-13" aria-hidden="true" tabindex="-1"></a>valid_data <span class="op">=</span> dataset.take(<span class="dv">4000</span>)</span>
<span id="cb5-14"><a href="#cb5-14" aria-hidden="true" tabindex="-1"></a>train_data <span class="op">=</span> dataset.skip(<span class="dv">4000</span>)</span>
<span id="cb5-15"><a href="#cb5-15" aria-hidden="true" tabindex="-1"></a>train_data <span class="op">=</span> train_data.shuffle(buffer_size<span class="op">=</span><span class="dv">5000</span>, seed<span class="op">=</span>SEED)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>At this step, the dataset still contains raw data with code of arbitraty length. For training, we need inputs of fixed length. Let’s create an Iterable dataset that would return constant-length chunks of tokens from a stream of text files.</p>
<p>First, let’s estimate the average number of characters per token in the dataset, which will help us later estimate the number of tokens in the text buffer later. By default, we’ll only take 400 examples (<code>nb_examples</code>) from the dataset. Using only a subset of the entire dataset will reduce computational cost while still providing a reasonable estimate of the overall character-to-token ratio.</p>
<div id="cell-11" class="cell" data-outputid="cabf7fd0-a922-4371-cbc6-60ee99ef7469">
<div class="sourceCode cell-code" id="cb6"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>tokenizer <span class="op">=</span> AutoTokenizer.from_pretrained(MODEL, trust_remote_code<span class="op">=</span><span class="va">True</span>)</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> chars_token_ratio(dataset, tokenizer, data_column, nb_examples<span class="op">=</span><span class="dv">400</span>):</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a> <span class="co">"""</span></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a><span class="co"> Estimate the average number of characters per token in the dataset.</span></span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a><span class="co"> """</span></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a> total_characters, total_tokens <span class="op">=</span> <span class="dv">0</span>, <span class="dv">0</span></span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> _, example <span class="kw">in</span> tqdm(<span class="bu">zip</span>(<span class="bu">range</span>(nb_examples), <span class="bu">iter</span>(dataset)), total<span class="op">=</span>nb_examples):</span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a> total_characters <span class="op">+=</span> <span class="bu">len</span>(example[data_column])</span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true" tabindex="-1"></a> total_tokens <span class="op">+=</span> <span class="bu">len</span>(tokenizer(example[data_column]).tokens())</span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-13"><a href="#cb6-13" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> total_characters <span class="op">/</span> total_tokens</span>
<span id="cb6-14"><a href="#cb6-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-15"><a href="#cb6-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-16"><a href="#cb6-16" aria-hidden="true" tabindex="-1"></a>chars_per_token <span class="op">=</span> chars_token_ratio(train_data, tokenizer, DATA_COLUMN)</span>
<span id="cb6-17"><a href="#cb6-17" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"The character to token ratio of the dataset is: </span><span class="sc">{</span>chars_per_token<span class="sc">:.2f}</span><span class="ss">"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stderr">
<pre><code>100%|██████████| 400/400 [00:10<00:00, 39.87it/s] </code></pre>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>The character to token ratio of the dataset is: 2.43</code></pre>
</div>
<div class="cell-output cell-output-stderr">
<pre><code></code></pre>
</div>
</div>
<p>The character-to-token ratio can also be used as an indicator of the quality of text tokenization. For instance, a character-to-token ratio of 1.0 would mean that each character is represented with a token, which is not very meaningful. This would indicate poor tokenization. In standard English text, one token is typically equivalent to approximately four characters, meaning the character-to-token ratio is around 4.0. We can expect a lower ratio in the code dataset, but generally speaking, a number between 2.0 and 3.5 can be considered good enough.</p>
<p><strong>Optional FIM transformations</strong></p>
<p>Autoregressive language models typically generate sequences from left to right. By applying the FIM transformations, the model can also learn to infill text. Check out <a href="https://arxiv.org/pdf/2207.14255.pdf">“Efficient Training of Language Models to Fill in the Middle” paper</a> to learn more about the technique. We’ll define the FIM transformations here and will use them when creating the Iterable Dataset. However, if you want to omit transformations, feel free to set <code>fim_rate</code> to 0.</p>
<div id="cell-14" class="cell">
<div class="sourceCode cell-code" id="cb10"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> functools</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> numpy <span class="im">as</span> np</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a><span class="co"># Helper function to get token ids of the special tokens for prefix, suffix and middle for FIM transformations.</span></span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a><span class="at">@functools.lru_cache</span>(maxsize<span class="op">=</span><span class="va">None</span>)</span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> get_fim_token_ids(tokenizer):</span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a> <span class="cf">try</span>:</span>
<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a> FIM_PREFIX, FIM_MIDDLE, FIM_SUFFIX, FIM_PAD <span class="op">=</span> tokenizer.special_tokens_map[<span class="st">"additional_special_tokens"</span>][<span class="dv">1</span>:<span class="dv">5</span>]</span>
<span id="cb10-10"><a href="#cb10-10" aria-hidden="true" tabindex="-1"></a> suffix_tok_id, prefix_tok_id, middle_tok_id, pad_tok_id <span class="op">=</span> (</span>
<span id="cb10-11"><a href="#cb10-11" aria-hidden="true" tabindex="-1"></a> tokenizer.vocab[tok] <span class="cf">for</span> tok <span class="kw">in</span> [FIM_SUFFIX, FIM_PREFIX, FIM_MIDDLE, FIM_PAD]</span>
<span id="cb10-12"><a href="#cb10-12" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb10-13"><a href="#cb10-13" aria-hidden="true" tabindex="-1"></a> <span class="cf">except</span> <span class="pp">KeyError</span>:</span>
<span id="cb10-14"><a href="#cb10-14" aria-hidden="true" tabindex="-1"></a> suffix_tok_id, prefix_tok_id, middle_tok_id, pad_tok_id <span class="op">=</span> <span class="va">None</span>, <span class="va">None</span>, <span class="va">None</span>, <span class="va">None</span></span>
<span id="cb10-15"><a href="#cb10-15" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> suffix_tok_id, prefix_tok_id, middle_tok_id, pad_tok_id</span>
<span id="cb10-16"><a href="#cb10-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-17"><a href="#cb10-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-18"><a href="#cb10-18" aria-hidden="true" tabindex="-1"></a><span class="co">## Adapted from https://github.com/bigcode-project/Megatron-LM/blob/6c4bf908df8fd86b4977f54bf5b8bd4b521003d1/megatron/data/gpt_dataset.py</span></span>
<span id="cb10-19"><a href="#cb10-19" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> permute(</span>
<span id="cb10-20"><a href="#cb10-20" aria-hidden="true" tabindex="-1"></a> sample,</span>
<span id="cb10-21"><a href="#cb10-21" aria-hidden="true" tabindex="-1"></a> np_rng,</span>
<span id="cb10-22"><a href="#cb10-22" aria-hidden="true" tabindex="-1"></a> suffix_tok_id,</span>
<span id="cb10-23"><a href="#cb10-23" aria-hidden="true" tabindex="-1"></a> prefix_tok_id,</span>
<span id="cb10-24"><a href="#cb10-24" aria-hidden="true" tabindex="-1"></a> middle_tok_id,</span>
<span id="cb10-25"><a href="#cb10-25" aria-hidden="true" tabindex="-1"></a> pad_tok_id,</span>
<span id="cb10-26"><a href="#cb10-26" aria-hidden="true" tabindex="-1"></a> fim_rate<span class="op">=</span><span class="fl">0.5</span>,</span>
<span id="cb10-27"><a href="#cb10-27" aria-hidden="true" tabindex="-1"></a> fim_spm_rate<span class="op">=</span><span class="fl">0.5</span>,</span>
<span id="cb10-28"><a href="#cb10-28" aria-hidden="true" tabindex="-1"></a> truncate_or_pad<span class="op">=</span><span class="va">False</span>,</span>
<span id="cb10-29"><a href="#cb10-29" aria-hidden="true" tabindex="-1"></a>):</span>
<span id="cb10-30"><a href="#cb10-30" aria-hidden="true" tabindex="-1"></a> <span class="co">"""</span></span>
<span id="cb10-31"><a href="#cb10-31" aria-hidden="true" tabindex="-1"></a><span class="co"> Take in a sample (list of tokens) and perform a FIM transformation on it with a probability of fim_rate, using two FIM modes:</span></span>
<span id="cb10-32"><a href="#cb10-32" aria-hidden="true" tabindex="-1"></a><span class="co"> PSM and SPM (with a probability of fim_spm_rate).</span></span>
<span id="cb10-33"><a href="#cb10-33" aria-hidden="true" tabindex="-1"></a><span class="co"> """</span></span>
<span id="cb10-34"><a href="#cb10-34" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-35"><a href="#cb10-35" aria-hidden="true" tabindex="-1"></a> <span class="co"># The if condition will trigger with the probability of fim_rate</span></span>
<span id="cb10-36"><a href="#cb10-36" aria-hidden="true" tabindex="-1"></a> <span class="co"># This means FIM transformations will apply to samples with a probability of fim_rate</span></span>
<span id="cb10-37"><a href="#cb10-37" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> np_rng.binomial(<span class="dv">1</span>, fim_rate):</span>
<span id="cb10-38"><a href="#cb10-38" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-39"><a href="#cb10-39" aria-hidden="true" tabindex="-1"></a> <span class="co"># Split the sample into prefix, middle, and suffix, based on randomly generated indices stored in the boundaries list.</span></span>
<span id="cb10-40"><a href="#cb10-40" aria-hidden="true" tabindex="-1"></a> boundaries <span class="op">=</span> <span class="bu">list</span>(np_rng.randint(low<span class="op">=</span><span class="dv">0</span>, high<span class="op">=</span><span class="bu">len</span>(sample) <span class="op">+</span> <span class="dv">1</span>, size<span class="op">=</span><span class="dv">2</span>))</span>
<span id="cb10-41"><a href="#cb10-41" aria-hidden="true" tabindex="-1"></a> boundaries.sort()</span>
<span id="cb10-42"><a href="#cb10-42" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-43"><a href="#cb10-43" aria-hidden="true" tabindex="-1"></a> prefix <span class="op">=</span> np.array(sample[: boundaries[<span class="dv">0</span>]], dtype<span class="op">=</span>np.int64)</span>
<span id="cb10-44"><a href="#cb10-44" aria-hidden="true" tabindex="-1"></a> middle <span class="op">=</span> np.array(sample[boundaries[<span class="dv">0</span>] : boundaries[<span class="dv">1</span>]], dtype<span class="op">=</span>np.int64)</span>
<span id="cb10-45"><a href="#cb10-45" aria-hidden="true" tabindex="-1"></a> suffix <span class="op">=</span> np.array(sample[boundaries[<span class="dv">1</span>] :], dtype<span class="op">=</span>np.int64)</span>
<span id="cb10-46"><a href="#cb10-46" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-47"><a href="#cb10-47" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> truncate_or_pad:</span>
<span id="cb10-48"><a href="#cb10-48" aria-hidden="true" tabindex="-1"></a> <span class="co"># calculate the new total length of the sample, taking into account tokens indicating prefix, middle, and suffix</span></span>
<span id="cb10-49"><a href="#cb10-49" aria-hidden="true" tabindex="-1"></a> new_length <span class="op">=</span> suffix.shape[<span class="dv">0</span>] <span class="op">+</span> prefix.shape[<span class="dv">0</span>] <span class="op">+</span> middle.shape[<span class="dv">0</span>] <span class="op">+</span> <span class="dv">3</span></span>
<span id="cb10-50"><a href="#cb10-50" aria-hidden="true" tabindex="-1"></a> diff <span class="op">=</span> new_length <span class="op">-</span> <span class="bu">len</span>(sample)</span>
<span id="cb10-51"><a href="#cb10-51" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-52"><a href="#cb10-52" aria-hidden="true" tabindex="-1"></a> <span class="co"># trancate or pad if there's a difference in length between the new length and the original</span></span>
<span id="cb10-53"><a href="#cb10-53" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> diff <span class="op">></span> <span class="dv">0</span>:</span>
<span id="cb10-54"><a href="#cb10-54" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> suffix.shape[<span class="dv">0</span>] <span class="op"><=</span> diff:</span>
<span id="cb10-55"><a href="#cb10-55" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> sample, np_rng</span>
<span id="cb10-56"><a href="#cb10-56" aria-hidden="true" tabindex="-1"></a> suffix <span class="op">=</span> suffix[: suffix.shape[<span class="dv">0</span>] <span class="op">-</span> diff]</span>
<span id="cb10-57"><a href="#cb10-57" aria-hidden="true" tabindex="-1"></a> <span class="cf">elif</span> diff <span class="op"><</span> <span class="dv">0</span>:</span>
<span id="cb10-58"><a href="#cb10-58" aria-hidden="true" tabindex="-1"></a> suffix <span class="op">=</span> np.concatenate([suffix, np.full((<span class="op">-</span><span class="dv">1</span> <span class="op">*</span> diff), pad_tok_id)])</span>
<span id="cb10-59"><a href="#cb10-59" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-60"><a href="#cb10-60" aria-hidden="true" tabindex="-1"></a> <span class="co"># With the probability of fim_spm_rateapply SPM variant of FIM transformations</span></span>
<span id="cb10-61"><a href="#cb10-61" aria-hidden="true" tabindex="-1"></a> <span class="co"># SPM: suffix, prefix, middle</span></span>
<span id="cb10-62"><a href="#cb10-62" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> np_rng.binomial(<span class="dv">1</span>, fim_spm_rate):</span>
<span id="cb10-63"><a href="#cb10-63" aria-hidden="true" tabindex="-1"></a> new_sample <span class="op">=</span> np.concatenate(</span>
<span id="cb10-64"><a href="#cb10-64" aria-hidden="true" tabindex="-1"></a> [</span>
<span id="cb10-65"><a href="#cb10-65" aria-hidden="true" tabindex="-1"></a> [prefix_tok_id, suffix_tok_id],</span>
<span id="cb10-66"><a href="#cb10-66" aria-hidden="true" tabindex="-1"></a> suffix,</span>
<span id="cb10-67"><a href="#cb10-67" aria-hidden="true" tabindex="-1"></a> [middle_tok_id],</span>
<span id="cb10-68"><a href="#cb10-68" aria-hidden="true" tabindex="-1"></a> prefix,</span>
<span id="cb10-69"><a href="#cb10-69" aria-hidden="true" tabindex="-1"></a> middle,</span>
<span id="cb10-70"><a href="#cb10-70" aria-hidden="true" tabindex="-1"></a> ]</span>
<span id="cb10-71"><a href="#cb10-71" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb10-72"><a href="#cb10-72" aria-hidden="true" tabindex="-1"></a> <span class="co"># Otherwise, apply the PSM variant of FIM transformations</span></span>
<span id="cb10-73"><a href="#cb10-73" aria-hidden="true" tabindex="-1"></a> <span class="co"># PSM: prefix, suffix, middle</span></span>
<span id="cb10-74"><a href="#cb10-74" aria-hidden="true" tabindex="-1"></a> <span class="cf">else</span>:</span>
<span id="cb10-75"><a href="#cb10-75" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-76"><a href="#cb10-76" aria-hidden="true" tabindex="-1"></a> new_sample <span class="op">=</span> np.concatenate(</span>
<span id="cb10-77"><a href="#cb10-77" aria-hidden="true" tabindex="-1"></a> [</span>
<span id="cb10-78"><a href="#cb10-78" aria-hidden="true" tabindex="-1"></a> [prefix_tok_id],</span>
<span id="cb10-79"><a href="#cb10-79" aria-hidden="true" tabindex="-1"></a> prefix,</span>
<span id="cb10-80"><a href="#cb10-80" aria-hidden="true" tabindex="-1"></a> [suffix_tok_id],</span>
<span id="cb10-81"><a href="#cb10-81" aria-hidden="true" tabindex="-1"></a> suffix,</span>
<span id="cb10-82"><a href="#cb10-82" aria-hidden="true" tabindex="-1"></a> [middle_tok_id],</span>
<span id="cb10-83"><a href="#cb10-83" aria-hidden="true" tabindex="-1"></a> middle,</span>
<span id="cb10-84"><a href="#cb10-84" aria-hidden="true" tabindex="-1"></a> ]</span>
<span id="cb10-85"><a href="#cb10-85" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb10-86"><a href="#cb10-86" aria-hidden="true" tabindex="-1"></a> <span class="cf">else</span>:</span>
<span id="cb10-87"><a href="#cb10-87" aria-hidden="true" tabindex="-1"></a> <span class="co"># don't apply FIM transformations</span></span>
<span id="cb10-88"><a href="#cb10-88" aria-hidden="true" tabindex="-1"></a> new_sample <span class="op">=</span> sample</span>
<span id="cb10-89"><a href="#cb10-89" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-90"><a href="#cb10-90" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> <span class="bu">list</span>(new_sample), np_rng</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Let’s define the <code>ConstantLengthDataset</code>, an Iterable dataset that will return constant-length chunks of tokens. To do so, we’ll read a buffer of text from the original dataset until we hit the size limits and then apply tokenizer to convert the raw text into tokenized inputs. Optionally, we’ll perform FIM transformations on some sequences (the proportion of sequences affected is controlled by <code>fim_rate</code>).</p>
<p>Once defined, we can create instances of the <code>ConstantLengthDataset</code> from both training and validation data.</p>
<div id="cell-16" class="cell">
<div class="sourceCode cell-code" id="cb11"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> torch.utils.data <span class="im">import</span> IterableDataset</span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> torch.utils.data.dataloader <span class="im">import</span> DataLoader</span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> random</span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a><span class="co"># Create an Iterable dataset that returns constant-length chunks of tokens from a stream of text files.</span></span>
<span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> ConstantLengthDataset(IterableDataset):</span>
<span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a> <span class="co">"""</span></span>
<span id="cb11-9"><a href="#cb11-9" aria-hidden="true" tabindex="-1"></a><span class="co"> Iterable dataset that returns constant length chunks of tokens from stream of text files.</span></span>
<span id="cb11-10"><a href="#cb11-10" aria-hidden="true" tabindex="-1"></a><span class="co"> Args:</span></span>
<span id="cb11-11"><a href="#cb11-11" aria-hidden="true" tabindex="-1"></a><span class="co"> tokenizer (Tokenizer): The processor used for proccessing the data.</span></span>
<span id="cb11-12"><a href="#cb11-12" aria-hidden="true" tabindex="-1"></a><span class="co"> dataset (dataset.Dataset): Dataset with text files.</span></span>
<span id="cb11-13"><a href="#cb11-13" aria-hidden="true" tabindex="-1"></a><span class="co"> infinite (bool): If True the iterator is reset after dataset reaches end else stops.</span></span>
<span id="cb11-14"><a href="#cb11-14" aria-hidden="true" tabindex="-1"></a><span class="co"> seq_length (int): Length of token sequences to return.</span></span>
<span id="cb11-15"><a href="#cb11-15" aria-hidden="true" tabindex="-1"></a><span class="co"> num_of_sequences (int): Number of token sequences to keep in buffer.</span></span>
<span id="cb11-16"><a href="#cb11-16" aria-hidden="true" tabindex="-1"></a><span class="co"> chars_per_token (int): Number of characters per token used to estimate number of tokens in text buffer.</span></span>
<span id="cb11-17"><a href="#cb11-17" aria-hidden="true" tabindex="-1"></a><span class="co"> fim_rate (float): Rate (0.0 to 1.0) that sample will be permuted with FIM.</span></span>
<span id="cb11-18"><a href="#cb11-18" aria-hidden="true" tabindex="-1"></a><span class="co"> fim_spm_rate (float): Rate (0.0 to 1.0) of FIM permuations that will use SPM.</span></span>
<span id="cb11-19"><a href="#cb11-19" aria-hidden="true" tabindex="-1"></a><span class="co"> seed (int): Seed for random number generator.</span></span>
<span id="cb11-20"><a href="#cb11-20" aria-hidden="true" tabindex="-1"></a><span class="co"> """</span></span>
<span id="cb11-21"><a href="#cb11-21" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-22"><a href="#cb11-22" aria-hidden="true" tabindex="-1"></a> <span class="kw">def</span> <span class="fu">__init__</span>(</span>
<span id="cb11-23"><a href="#cb11-23" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>,</span>
<span id="cb11-24"><a href="#cb11-24" aria-hidden="true" tabindex="-1"></a> tokenizer,</span>
<span id="cb11-25"><a href="#cb11-25" aria-hidden="true" tabindex="-1"></a> dataset,</span>
<span id="cb11-26"><a href="#cb11-26" aria-hidden="true" tabindex="-1"></a> infinite<span class="op">=</span><span class="va">False</span>,</span>
<span id="cb11-27"><a href="#cb11-27" aria-hidden="true" tabindex="-1"></a> seq_length<span class="op">=</span><span class="dv">1024</span>,</span>
<span id="cb11-28"><a href="#cb11-28" aria-hidden="true" tabindex="-1"></a> num_of_sequences<span class="op">=</span><span class="dv">1024</span>,</span>
<span id="cb11-29"><a href="#cb11-29" aria-hidden="true" tabindex="-1"></a> chars_per_token<span class="op">=</span><span class="fl">3.6</span>,</span>
<span id="cb11-30"><a href="#cb11-30" aria-hidden="true" tabindex="-1"></a> content_field<span class="op">=</span><span class="st">"content"</span>,</span>
<span id="cb11-31"><a href="#cb11-31" aria-hidden="true" tabindex="-1"></a> fim_rate<span class="op">=</span><span class="fl">0.5</span>,</span>
<span id="cb11-32"><a href="#cb11-32" aria-hidden="true" tabindex="-1"></a> fim_spm_rate<span class="op">=</span><span class="fl">0.5</span>,</span>
<span id="cb11-33"><a href="#cb11-33" aria-hidden="true" tabindex="-1"></a> seed<span class="op">=</span><span class="dv">0</span>,</span>
<span id="cb11-34"><a href="#cb11-34" aria-hidden="true" tabindex="-1"></a> ):</span>
<span id="cb11-35"><a href="#cb11-35" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.tokenizer <span class="op">=</span> tokenizer</span>
<span id="cb11-36"><a href="#cb11-36" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.concat_token_id <span class="op">=</span> tokenizer.eos_token_id</span>
<span id="cb11-37"><a href="#cb11-37" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.dataset <span class="op">=</span> dataset</span>
<span id="cb11-38"><a href="#cb11-38" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.seq_length <span class="op">=</span> seq_length</span>
<span id="cb11-39"><a href="#cb11-39" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.infinite <span class="op">=</span> infinite</span>
<span id="cb11-40"><a href="#cb11-40" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.current_size <span class="op">=</span> <span class="dv">0</span></span>
<span id="cb11-41"><a href="#cb11-41" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.max_buffer_size <span class="op">=</span> seq_length <span class="op">*</span> chars_per_token <span class="op">*</span> num_of_sequences</span>
<span id="cb11-42"><a href="#cb11-42" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.content_field <span class="op">=</span> content_field</span>
<span id="cb11-43"><a href="#cb11-43" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.fim_rate <span class="op">=</span> fim_rate</span>
<span id="cb11-44"><a href="#cb11-44" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.fim_spm_rate <span class="op">=</span> fim_spm_rate</span>
<span id="cb11-45"><a href="#cb11-45" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.seed <span class="op">=</span> seed</span>
<span id="cb11-46"><a href="#cb11-46" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-47"><a href="#cb11-47" aria-hidden="true" tabindex="-1"></a> (</span>
<span id="cb11-48"><a href="#cb11-48" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.suffix_tok_id,</span>
<span id="cb11-49"><a href="#cb11-49" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.prefix_tok_id,</span>
<span id="cb11-50"><a href="#cb11-50" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.middle_tok_id,</span>
<span id="cb11-51"><a href="#cb11-51" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.pad_tok_id,</span>
<span id="cb11-52"><a href="#cb11-52" aria-hidden="true" tabindex="-1"></a> ) <span class="op">=</span> get_fim_token_ids(<span class="va">self</span>.tokenizer)</span>
<span id="cb11-53"><a href="#cb11-53" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="kw">not</span> <span class="va">self</span>.suffix_tok_id <span class="kw">and</span> <span class="va">self</span>.fim_rate <span class="op">></span> <span class="dv">0</span>:</span>
<span id="cb11-54"><a href="#cb11-54" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">"FIM is not supported by tokenizer, disabling FIM"</span>)</span>
<span id="cb11-55"><a href="#cb11-55" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.fim_rate <span class="op">=</span> <span class="dv">0</span></span>
<span id="cb11-56"><a href="#cb11-56" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-57"><a href="#cb11-57" aria-hidden="true" tabindex="-1"></a> <span class="kw">def</span> <span class="fu">__iter__</span>(<span class="va">self</span>):</span>
<span id="cb11-58"><a href="#cb11-58" aria-hidden="true" tabindex="-1"></a> iterator <span class="op">=</span> <span class="bu">iter</span>(<span class="va">self</span>.dataset)</span>
<span id="cb11-59"><a href="#cb11-59" aria-hidden="true" tabindex="-1"></a> more_examples <span class="op">=</span> <span class="va">True</span></span>
<span id="cb11-60"><a href="#cb11-60" aria-hidden="true" tabindex="-1"></a> np_rng <span class="op">=</span> np.random.RandomState(seed<span class="op">=</span><span class="va">self</span>.seed)</span>
<span id="cb11-61"><a href="#cb11-61" aria-hidden="true" tabindex="-1"></a> <span class="cf">while</span> more_examples:</span>
<span id="cb11-62"><a href="#cb11-62" aria-hidden="true" tabindex="-1"></a> <span class="bu">buffer</span>, buffer_len <span class="op">=</span> [], <span class="dv">0</span></span>
<span id="cb11-63"><a href="#cb11-63" aria-hidden="true" tabindex="-1"></a> <span class="cf">while</span> <span class="va">True</span>:</span>
<span id="cb11-64"><a href="#cb11-64" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> buffer_len <span class="op">>=</span> <span class="va">self</span>.max_buffer_size:</span>
<span id="cb11-65"><a href="#cb11-65" aria-hidden="true" tabindex="-1"></a> <span class="cf">break</span></span>
<span id="cb11-66"><a href="#cb11-66" aria-hidden="true" tabindex="-1"></a> <span class="cf">try</span>:</span>
<span id="cb11-67"><a href="#cb11-67" aria-hidden="true" tabindex="-1"></a> <span class="bu">buffer</span>.append(<span class="bu">next</span>(iterator)[<span class="va">self</span>.content_field])</span>
<span id="cb11-68"><a href="#cb11-68" aria-hidden="true" tabindex="-1"></a> buffer_len <span class="op">+=</span> <span class="bu">len</span>(<span class="bu">buffer</span>[<span class="op">-</span><span class="dv">1</span>])</span>
<span id="cb11-69"><a href="#cb11-69" aria-hidden="true" tabindex="-1"></a> <span class="cf">except</span> <span class="pp">StopIteration</span>:</span>
<span id="cb11-70"><a href="#cb11-70" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="va">self</span>.infinite:</span>
<span id="cb11-71"><a href="#cb11-71" aria-hidden="true" tabindex="-1"></a> iterator <span class="op">=</span> <span class="bu">iter</span>(<span class="va">self</span>.dataset)</span>
<span id="cb11-72"><a href="#cb11-72" aria-hidden="true" tabindex="-1"></a> <span class="cf">else</span>:</span>
<span id="cb11-73"><a href="#cb11-73" aria-hidden="true" tabindex="-1"></a> more_examples <span class="op">=</span> <span class="va">False</span></span>
<span id="cb11-74"><a href="#cb11-74" aria-hidden="true" tabindex="-1"></a> <span class="cf">break</span></span>
<span id="cb11-75"><a href="#cb11-75" aria-hidden="true" tabindex="-1"></a> tokenized_inputs <span class="op">=</span> <span class="va">self</span>.tokenizer(<span class="bu">buffer</span>, truncation<span class="op">=</span><span class="va">False</span>)[<span class="st">"input_ids"</span>]</span>
<span id="cb11-76"><a href="#cb11-76" aria-hidden="true" tabindex="-1"></a> all_token_ids <span class="op">=</span> []</span>
<span id="cb11-77"><a href="#cb11-77" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-78"><a href="#cb11-78" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> tokenized_input <span class="kw">in</span> tokenized_inputs:</span>
<span id="cb11-79"><a href="#cb11-79" aria-hidden="true" tabindex="-1"></a> <span class="co"># optionally do FIM permutations</span></span>
<span id="cb11-80"><a href="#cb11-80" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="va">self</span>.fim_rate <span class="op">></span> <span class="dv">0</span>:</span>
<span id="cb11-81"><a href="#cb11-81" aria-hidden="true" tabindex="-1"></a> tokenized_input, np_rng <span class="op">=</span> permute(</span>
<span id="cb11-82"><a href="#cb11-82" aria-hidden="true" tabindex="-1"></a> tokenized_input,</span>
<span id="cb11-83"><a href="#cb11-83" aria-hidden="true" tabindex="-1"></a> np_rng,</span>
<span id="cb11-84"><a href="#cb11-84" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.suffix_tok_id,</span>
<span id="cb11-85"><a href="#cb11-85" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.prefix_tok_id,</span>
<span id="cb11-86"><a href="#cb11-86" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.middle_tok_id,</span>
<span id="cb11-87"><a href="#cb11-87" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.pad_tok_id,</span>
<span id="cb11-88"><a href="#cb11-88" aria-hidden="true" tabindex="-1"></a> fim_rate<span class="op">=</span><span class="va">self</span>.fim_rate,</span>
<span id="cb11-89"><a href="#cb11-89" aria-hidden="true" tabindex="-1"></a> fim_spm_rate<span class="op">=</span><span class="va">self</span>.fim_spm_rate,</span>
<span id="cb11-90"><a href="#cb11-90" aria-hidden="true" tabindex="-1"></a> truncate_or_pad<span class="op">=</span><span class="va">False</span>,</span>
<span id="cb11-91"><a href="#cb11-91" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb11-92"><a href="#cb11-92" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-93"><a href="#cb11-93" aria-hidden="true" tabindex="-1"></a> all_token_ids.extend(tokenized_input <span class="op">+</span> [<span class="va">self</span>.concat_token_id])</span>
<span id="cb11-94"><a href="#cb11-94" aria-hidden="true" tabindex="-1"></a> examples <span class="op">=</span> []</span>
<span id="cb11-95"><a href="#cb11-95" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> i <span class="kw">in</span> <span class="bu">range</span>(<span class="dv">0</span>, <span class="bu">len</span>(all_token_ids), <span class="va">self</span>.seq_length):</span>
<span id="cb11-96"><a href="#cb11-96" aria-hidden="true" tabindex="-1"></a> input_ids <span class="op">=</span> all_token_ids[i : i <span class="op">+</span> <span class="va">self</span>.seq_length]</span>
<span id="cb11-97"><a href="#cb11-97" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="bu">len</span>(input_ids) <span class="op">==</span> <span class="va">self</span>.seq_length:</span>
<span id="cb11-98"><a href="#cb11-98" aria-hidden="true" tabindex="-1"></a> examples.append(input_ids)</span>
<span id="cb11-99"><a href="#cb11-99" aria-hidden="true" tabindex="-1"></a> random.shuffle(examples)</span>
<span id="cb11-100"><a href="#cb11-100" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> example <span class="kw">in</span> examples:</span>
<span id="cb11-101"><a href="#cb11-101" aria-hidden="true" tabindex="-1"></a> <span class="va">self</span>.current_size <span class="op">+=</span> <span class="dv">1</span></span>
<span id="cb11-102"><a href="#cb11-102" aria-hidden="true" tabindex="-1"></a> <span class="cf">yield</span> {</span>
<span id="cb11-103"><a href="#cb11-103" aria-hidden="true" tabindex="-1"></a> <span class="st">"input_ids"</span>: torch.LongTensor(example),</span>
<span id="cb11-104"><a href="#cb11-104" aria-hidden="true" tabindex="-1"></a> <span class="st">"labels"</span>: torch.LongTensor(example),</span>
<span id="cb11-105"><a href="#cb11-105" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb11-106"><a href="#cb11-106" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-107"><a href="#cb11-107" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-108"><a href="#cb11-108" aria-hidden="true" tabindex="-1"></a>train_dataset <span class="op">=</span> ConstantLengthDataset(</span>
<span id="cb11-109"><a href="#cb11-109" aria-hidden="true" tabindex="-1"></a> tokenizer,</span>
<span id="cb11-110"><a href="#cb11-110" aria-hidden="true" tabindex="-1"></a> train_data,</span>
<span id="cb11-111"><a href="#cb11-111" aria-hidden="true" tabindex="-1"></a> infinite<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb11-112"><a href="#cb11-112" aria-hidden="true" tabindex="-1"></a> seq_length<span class="op">=</span>SEQ_LENGTH,</span>
<span id="cb11-113"><a href="#cb11-113" aria-hidden="true" tabindex="-1"></a> chars_per_token<span class="op">=</span>chars_per_token,</span>
<span id="cb11-114"><a href="#cb11-114" aria-hidden="true" tabindex="-1"></a> content_field<span class="op">=</span>DATA_COLUMN,</span>
<span id="cb11-115"><a href="#cb11-115" aria-hidden="true" tabindex="-1"></a> fim_rate<span class="op">=</span>FIM_RATE,</span>
<span id="cb11-116"><a href="#cb11-116" aria-hidden="true" tabindex="-1"></a> fim_spm_rate<span class="op">=</span>FIM_SPM_RATE,</span>
<span id="cb11-117"><a href="#cb11-117" aria-hidden="true" tabindex="-1"></a> seed<span class="op">=</span>SEED,</span>
<span id="cb11-118"><a href="#cb11-118" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb11-119"><a href="#cb11-119" aria-hidden="true" tabindex="-1"></a>eval_dataset <span class="op">=</span> ConstantLengthDataset(</span>
<span id="cb11-120"><a href="#cb11-120" aria-hidden="true" tabindex="-1"></a> tokenizer,</span>
<span id="cb11-121"><a href="#cb11-121" aria-hidden="true" tabindex="-1"></a> valid_data,</span>
<span id="cb11-122"><a href="#cb11-122" aria-hidden="true" tabindex="-1"></a> infinite<span class="op">=</span><span class="va">False</span>,</span>
<span id="cb11-123"><a href="#cb11-123" aria-hidden="true" tabindex="-1"></a> seq_length<span class="op">=</span>SEQ_LENGTH,</span>
<span id="cb11-124"><a href="#cb11-124" aria-hidden="true" tabindex="-1"></a> chars_per_token<span class="op">=</span>chars_per_token,</span>
<span id="cb11-125"><a href="#cb11-125" aria-hidden="true" tabindex="-1"></a> content_field<span class="op">=</span>DATA_COLUMN,</span>
<span id="cb11-126"><a href="#cb11-126" aria-hidden="true" tabindex="-1"></a> fim_rate<span class="op">=</span>FIM_RATE,</span>
<span id="cb11-127"><a href="#cb11-127" aria-hidden="true" tabindex="-1"></a> fim_spm_rate<span class="op">=</span>FIM_SPM_RATE,</span>
<span id="cb11-128"><a href="#cb11-128" aria-hidden="true" tabindex="-1"></a> seed<span class="op">=</span>SEED,</span>
<span id="cb11-129"><a href="#cb11-129" aria-hidden="true" tabindex="-1"></a>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="prepare-the-model" class="level2">
<h2 class="anchored" data-anchor-id="prepare-the-model">Prepare the model</h2>
<p>Now that the data is prepared, it’s time to load the model! We’re going to load the quantized version of the model.</p>
<p>This will allow us to reduce memory usage, as quantization represents data with fewer bits. We’ll use the <code>bitsandbytes</code> library to quantize the model, as it has a nice integration with <code>transformers</code>. All we need to do is define a <code>bitsandbytes</code> config, and then use it when loading the model.</p>
<p>There are different variants of 4bit quantization, but generally, we recommend using NF4 quantization for better performance (<code>bnb_4bit_quant_type="nf4"</code>).</p>
<p>The <code>bnb_4bit_use_double_quant</code> option adds a second quantization after the first one to save an additional 0.4 bits per parameter.</p>
<p>To learn more about quantization, check out the <a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes">“Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA” blog post</a>.</p>
<p>Once defined, pass the config to the <code>from_pretrained</code> method to load the quantized version of the model.</p>
<div id="cell-19" class="cell">
<div class="sourceCode cell-code" id="cb12"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> peft <span class="im">import</span> LoraConfig, get_peft_model, prepare_model_for_kbit_training</span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> peft.tuners.lora <span class="im">import</span> LoraLayer</span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>load_in_8bit <span class="op">=</span> <span class="va">False</span></span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a><span class="co"># 4-bit quantization</span></span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>compute_dtype <span class="op">=</span> <span class="bu">getattr</span>(torch, BNB_4BIT_COMPUTE_DTYPE)</span>
<span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-9"><a href="#cb12-9" aria-hidden="true" tabindex="-1"></a>bnb_config <span class="op">=</span> BitsAndBytesConfig(</span>
<span id="cb12-10"><a href="#cb12-10" aria-hidden="true" tabindex="-1"></a> load_in_4bit<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb12-11"><a href="#cb12-11" aria-hidden="true" tabindex="-1"></a> bnb_4bit_quant_type<span class="op">=</span><span class="st">"nf4"</span>,</span>
<span id="cb12-12"><a href="#cb12-12" aria-hidden="true" tabindex="-1"></a> bnb_4bit_compute_dtype<span class="op">=</span>compute_dtype,</span>
<span id="cb12-13"><a href="#cb12-13" aria-hidden="true" tabindex="-1"></a> bnb_4bit_use_double_quant<span class="op">=</span>USE_NESTED_QUANT,</span>
<span id="cb12-14"><a href="#cb12-14" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb12-15"><a href="#cb12-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-16"><a href="#cb12-16" aria-hidden="true" tabindex="-1"></a>device_map <span class="op">=</span> {<span class="st">""</span>: <span class="dv">0</span>}</span>
<span id="cb12-17"><a href="#cb12-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-18"><a href="#cb12-18" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> AutoModelForCausalLM.from_pretrained(</span>
<span id="cb12-19"><a href="#cb12-19" aria-hidden="true" tabindex="-1"></a> MODEL,</span>
<span id="cb12-20"><a href="#cb12-20" aria-hidden="true" tabindex="-1"></a> load_in_8bit<span class="op">=</span>load_in_8bit,</span>
<span id="cb12-21"><a href="#cb12-21" aria-hidden="true" tabindex="-1"></a> quantization_config<span class="op">=</span>bnb_config,</span>
<span id="cb12-22"><a href="#cb12-22" aria-hidden="true" tabindex="-1"></a> device_map<span class="op">=</span>device_map,</span>
<span id="cb12-23"><a href="#cb12-23" aria-hidden="true" tabindex="-1"></a> use_cache<span class="op">=</span><span class="va">False</span>, <span class="co"># We will be using gradient checkpointing</span></span>
<span id="cb12-24"><a href="#cb12-24" aria-hidden="true" tabindex="-1"></a> trust_remote_code<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb12-25"><a href="#cb12-25" aria-hidden="true" tabindex="-1"></a> use_flash_attention_2<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb12-26"><a href="#cb12-26" aria-hidden="true" tabindex="-1"></a>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>When using a quantized model for training, you need to call the <code>prepare_model_for_kbit_training()</code> function to preprocess the quantized model for training.</p>
<div id="cell-21" class="cell">
<div class="sourceCode cell-code" id="cb13"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> prepare_model_for_kbit_training(model)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Now that the quantized model is ready, we can set up a LoRA configuration. LoRA makes fine-tuning more efficient by drastically reducing the number of trainable parameters.</p>
<p>To train a model using LoRA technique, we need to wrap the base model as a <code>PeftModel</code>. This involves definign LoRA configuration with <code>LoraConfig</code>, and wrapping the original model with <code>get_peft_model()</code> using the <code>LoraConfig</code>.</p>
<p>To learn more about LoRA and its parameters, refer to <a href="https://huggingface.co/docs/peft/conceptual_guides/lora">PEFT documentation</a>.</p>
<div id="cell-23" class="cell" data-outputid="63328c2b-e693-49b1-ce0a-3ca8722f852a">
<div class="sourceCode cell-code" id="cb14"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Set up lora</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>peft_config <span class="op">=</span> LoraConfig(</span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a> lora_alpha<span class="op">=</span>LORA_ALPHA,</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a> lora_dropout<span class="op">=</span>LORA_DROPOUT,</span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a> r<span class="op">=</span>LORA_R,</span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a> bias<span class="op">=</span><span class="st">"none"</span>,</span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a> task_type<span class="op">=</span><span class="st">"CAUSAL_LM"</span>,</span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a> target_modules<span class="op">=</span>LORA_TARGET_MODULES.split(<span class="st">","</span>),</span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-11"><a href="#cb14-11" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> get_peft_model(model, peft_config)</span>
<span id="cb14-12"><a href="#cb14-12" aria-hidden="true" tabindex="-1"></a>model.print_trainable_parameters()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>trainable params: 5,554,176 || all params: 1,142,761,472 || trainable%: 0.4860310866343243</code></pre>
</div>
</div>
<p>As you can see, by applying LoRA technique we will now need to train less than 1% of the parameters.</p>
</section>
<section id="train-the-model" class="level2">
<h2 class="anchored" data-anchor-id="train-the-model">Train the model</h2>
<p>Now that we have prepared the data, and optimized the model, we are ready to bring everything together to start the training.</p>
<p>To instantiate a <code>Trainer</code>, you need to define the training configuration. The most important is the <code>TrainingArguments</code>, which is a class that contains all the attributes to configure the training.</p>
<p>These are similar to any other kind of model training you may run, so we won’t go into detail here.</p>
<div id="cell-27" class="cell">
<div class="sourceCode cell-code" id="cb16"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>train_data.start_iteration <span class="op">=</span> <span class="dv">0</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>training_args <span class="op">=</span> TrainingArguments(</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a> output_dir<span class="op">=</span><span class="ss">f"Your_HF_username/</span><span class="sc">{</span>OUTPUT_DIR<span class="sc">}</span><span class="ss">"</span>,</span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a> dataloader_drop_last<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a> evaluation_strategy<span class="op">=</span><span class="st">"steps"</span>,</span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a> save_strategy<span class="op">=</span><span class="st">"steps"</span>,</span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a> max_steps<span class="op">=</span>MAX_STEPS,</span>
<span id="cb16-10"><a href="#cb16-10" aria-hidden="true" tabindex="-1"></a> eval_steps<span class="op">=</span>EVAL_FREQ,</span>
<span id="cb16-11"><a href="#cb16-11" aria-hidden="true" tabindex="-1"></a> save_steps<span class="op">=</span>SAVE_FREQ,</span>
<span id="cb16-12"><a href="#cb16-12" aria-hidden="true" tabindex="-1"></a> logging_steps<span class="op">=</span>LOG_FREQ,</span>
<span id="cb16-13"><a href="#cb16-13" aria-hidden="true" tabindex="-1"></a> per_device_train_batch_size<span class="op">=</span>BATCH_SIZE,</span>
<span id="cb16-14"><a href="#cb16-14" aria-hidden="true" tabindex="-1"></a> per_device_eval_batch_size<span class="op">=</span>BATCH_SIZE,</span>
<span id="cb16-15"><a href="#cb16-15" aria-hidden="true" tabindex="-1"></a> learning_rate<span class="op">=</span>LR,</span>
<span id="cb16-16"><a href="#cb16-16" aria-hidden="true" tabindex="-1"></a> lr_scheduler_type<span class="op">=</span>LR_SCHEDULER_TYPE,</span>
<span id="cb16-17"><a href="#cb16-17" aria-hidden="true" tabindex="-1"></a> warmup_steps<span class="op">=</span>NUM_WARMUP_STEPS,</span>
<span id="cb16-18"><a href="#cb16-18" aria-hidden="true" tabindex="-1"></a> gradient_accumulation_steps<span class="op">=</span>GR_ACC_STEPS,</span>
<span id="cb16-19"><a href="#cb16-19" aria-hidden="true" tabindex="-1"></a> gradient_checkpointing<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb16-20"><a href="#cb16-20" aria-hidden="true" tabindex="-1"></a> fp16<span class="op">=</span>FP16,</span>
<span id="cb16-21"><a href="#cb16-21" aria-hidden="true" tabindex="-1"></a> bf16<span class="op">=</span>BF16,</span>
<span id="cb16-22"><a href="#cb16-22" aria-hidden="true" tabindex="-1"></a> weight_decay<span class="op">=</span>WEIGHT_DECAY,</span>
<span id="cb16-23"><a href="#cb16-23" aria-hidden="true" tabindex="-1"></a> push_to_hub<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb16-24"><a href="#cb16-24" aria-hidden="true" tabindex="-1"></a> include_tokens_per_second<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb16-25"><a href="#cb16-25" aria-hidden="true" tabindex="-1"></a>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>As a final step, instantiate the <code>Trainer</code> and call the <code>train</code> method.</p>
<div id="cell-29" class="cell" data-outputid="61a5bdb2-b7d0-4aed-8290-4bf20c2ccd38">
<div class="sourceCode cell-code" id="cb17"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>trainer <span class="op">=</span> Trainer(</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a> model<span class="op">=</span>model, args<span class="op">=</span>training_args, train_dataset<span class="op">=</span>train_dataset, eval_dataset<span class="op">=</span>eval_dataset</span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">"Training..."</span>)</span>
<span id="cb17-6"><a href="#cb17-6" aria-hidden="true" tabindex="-1"></a>trainer.train()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Training...</code></pre>
</div>
<div class="cell-output cell-output-display">
<div>
<progress value="2000" max="2000" style="width:300px; height:20px; vertical-align: middle;"></progress>
[2000/2000 4:16:10, Epoch 1/9223372036854775807]
</div>
<table class="dataframe caption-top table table-sm table-striped small" data-quarto-postprocess="true" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th">Step</th>
<th data-quarto-table-cell-role="th">Training Loss</th>
<th data-quarto-table-cell-role="th">Validation Loss</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>100</td>
<td>5.524600</td>
<td>7.456872</td>
</tr>
<tr class="even">
<td>200</td>
<td>5.617800</td>
<td>7.262190</td>
</tr>
<tr class="odd">
<td>300</td>
<td>5.129100</td>
<td>6.410039</td>
</tr>
<tr class="even">
<td>400</td>
<td>5.052200</td>
<td>6.306774</td>
</tr>
<tr class="odd">
<td>500</td>
<td>5.202900</td>
<td>6.117062</td>
</tr>
<tr class="even">
<td>600</td>
<td>4.654100</td>
<td>6.018349</td>
</tr>
<tr class="odd">
<td>700</td>
<td>5.100200</td>
<td>6.000355</td>
</tr>
<tr class="even">
<td>800</td>
<td>5.049800</td>
<td>5.889457</td>
</tr>
<tr class="odd">
<td>900</td>
<td>4.541200</td>
<td>5.813823</td>
</tr>
<tr class="even">
<td>1000</td>
<td>5.000700</td>
<td>5.834208</td>
</tr>
<tr class="odd">
<td>1100</td>
<td>5.026500</td>
<td>5.781939</td>
</tr>
<tr class="even">
<td>1200</td>
<td>4.411800</td>
<td>5.720596</td>
</tr>
<tr class="odd">
<td>1300</td>
<td>4.782500</td>
<td>5.736376</td>
</tr>
<tr class="even">
<td>1400</td>
<td>4.980200</td>
<td>5.712276</td>
</tr>
<tr class="odd">
<td>1500</td>
<td>4.368700</td>
<td>5.689637</td>
</tr>
<tr class="even">
<td>1600</td>
<td>4.884700</td>
<td>5.675920</td>
</tr>
<tr class="odd">
<td>1700</td>
<td>4.914400</td>
<td>5.662421</td>
</tr>
<tr class="even">
<td>1800</td>
<td>4.248700</td>
<td>5.660122</td>
</tr>
<tr class="odd">
<td>1900</td>
<td>4.798400</td>
<td>5.664026</td>
</tr>
<tr class="even">
<td>2000</td>
<td>4.704200</td>
<td>5.655665</td>
</tr>
</tbody>
</table>
<p>
</p></div>
<div class="cell-output cell-output-display" data-execution_count="19">
<pre><code>TrainOutput(global_step=2000, training_loss=4.885598585128784, metrics={'train_runtime': 15380.3075, 'train_samples_per_second': 2.081, 'train_steps_per_second': 0.13, 'train_tokens_per_second': 4261.033, 'total_flos': 4.0317260660736e+17, 'train_loss': 4.885598585128784, 'epoch': 1.0})</code></pre>
</div>
</div>
<p>Finally, you can push the fine-tuned model to your Hub repository to share with your team.</p>
<div id="cell-31" class="cell">
<div class="sourceCode cell-code" id="cb20"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>trainer.push_to_hub()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="inference" class="level2">
<h2 class="anchored" data-anchor-id="inference">Inference</h2>
<p>Once the model is uploaded to Hub, we can use it for inference. To do so we first initialize the original base model and its tokenizer. Next, we need to merge the fine-duned weights with the base model.</p>
<div id="cell-33" class="cell">
<div class="sourceCode cell-code" id="cb21"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> peft <span class="im">import</span> PeftModel</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> torch</span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a><span class="co"># load the original model first</span></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a>tokenizer <span class="op">=</span> AutoTokenizer.from_pretrained(MODEL, trust_remote_code<span class="op">=</span><span class="va">True</span>)</span>
<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a>base_model <span class="op">=</span> AutoModelForCausalLM.from_pretrained(</span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a> MODEL,</span>
<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a> quantization_config<span class="op">=</span><span class="va">None</span>,</span>
<span id="cb21-9"><a href="#cb21-9" aria-hidden="true" tabindex="-1"></a> device_map<span class="op">=</span><span class="va">None</span>,</span>
<span id="cb21-10"><a href="#cb21-10" aria-hidden="true" tabindex="-1"></a> trust_remote_code<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb21-11"><a href="#cb21-11" aria-hidden="true" tabindex="-1"></a> torch_dtype<span class="op">=</span>torch.bfloat16,</span>
<span id="cb21-12"><a href="#cb21-12" aria-hidden="true" tabindex="-1"></a>).cuda()</span>
<span id="cb21-13"><a href="#cb21-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-14"><a href="#cb21-14" aria-hidden="true" tabindex="-1"></a><span class="co"># merge fine-tuned weights with the base model</span></span>
<span id="cb21-15"><a href="#cb21-15" aria-hidden="true" tabindex="-1"></a>peft_model_id <span class="op">=</span> <span class="ss">f"Your_HF_username/</span><span class="sc">{</span>OUTPUT_DIR<span class="sc">}</span><span class="ss">"</span></span>
<span id="cb21-16"><a href="#cb21-16" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> PeftModel.from_pretrained(base_model, peft_model_id)</span>
<span id="cb21-17"><a href="#cb21-17" aria-hidden="true" tabindex="-1"></a>model.merge_and_unload()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Now we can use the merged model for inference. For convenience, we’ll define a <code>get_code_completion</code> - feel free to experiment with text generation parameters!</p>
<div id="cell-35" class="cell">
<div class="sourceCode cell-code" id="cb22"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> get_code_completion(prefix, suffix):</span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a> text <span class="op">=</span> prompt <span class="op">=</span> <span class="ss">f"""<fim_prefix></span><span class="sc">{</span>prefix<span class="sc">}</span><span class="ss"><fim_suffix></span><span class="sc">{</span>suffix<span class="sc">}</span><span class="ss"><fim_middle>"""</span></span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a> model.<span class="bu">eval</span>()</span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a> outputs <span class="op">=</span> model.generate(</span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a> input_ids<span class="op">=</span>tokenizer(text, return_tensors<span class="op">=</span><span class="st">"pt"</span>).input_ids.cuda(),</span>
<span id="cb22-6"><a href="#cb22-6" aria-hidden="true" tabindex="-1"></a> max_new_tokens<span class="op">=</span><span class="dv">128</span>,</span>
<span id="cb22-7"><a href="#cb22-7" aria-hidden="true" tabindex="-1"></a> temperature<span class="op">=</span><span class="fl">0.2</span>,</span>
<span id="cb22-8"><a href="#cb22-8" aria-hidden="true" tabindex="-1"></a> top_k<span class="op">=</span><span class="dv">50</span>,</span>
<span id="cb22-9"><a href="#cb22-9" aria-hidden="true" tabindex="-1"></a> top_p<span class="op">=</span><span class="fl">0.95</span>,</span>
<span id="cb22-10"><a href="#cb22-10" aria-hidden="true" tabindex="-1"></a> do_sample<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb22-11"><a href="#cb22-11" aria-hidden="true" tabindex="-1"></a> repetition_penalty<span class="op">=</span><span class="fl">1.0</span>,</span>
<span id="cb22-12"><a href="#cb22-12" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb22-13"><a href="#cb22-13" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> tokenizer.batch_decode(outputs, skip_special_tokens<span class="op">=</span><span class="va">True</span>)[<span class="dv">0</span>]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Now all we need to do to get code completion is call the <code>get_code_complete</code> function and pass the first few lines that we want to be completed as a prefix, and an empty string as a suffix.</p>
<div id="cell-37" class="cell" data-outputid="41c411ad-b7dc-4277-f975-c173888234bb">
<div class="sourceCode cell-code" id="cb23"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a>prefix <span class="op">=</span> <span class="st">"""from peft import LoraConfig, TaskType, get_peft_model</span></span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a><span class="st">from transformers import AutoModelForCausalLM</span></span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a><span class="st">peft_config = LoraConfig(</span></span>
<span id="cb23-4"><a href="#cb23-4" aria-hidden="true" tabindex="-1"></a><span class="st">"""</span></span>
<span id="cb23-5"><a href="#cb23-5" aria-hidden="true" tabindex="-1"></a>suffix <span class="op">=</span><span class="st">""""""</span></span>
<span id="cb23-6"><a href="#cb23-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-7"><a href="#cb23-7" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(get_code_completion(prefix, suffix))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForCausalLM
peft_config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=8,
lora_alpha=32,
target_modules=["q_proj", "v_proj"],
lora_dropout=0.1,
bias="none",
modules_to_save=["q_proj", "v_proj"],
inference_mode=False,
)
model = AutoModelForCausalLM.from_pretrained("gpt2")
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()</code></pre>
</div>
</div>
<p>As someone who has just used the PEFT library earlier in this notebook, you can see that the generated result for creating a <code>LoraConfig</code> is rather good!</p>
<p>If you go back to the cell where we instantiate the model for inference, and comment out the lines where we merge the fine-tuned weights, you can see what the original model would’ve generated for the exact same prefix:</p>
<div id="cell-39" class="cell" data-outputid="c6d597a2-01da-4d25-a32f-3a551212c5b4">
<div class="sourceCode cell-code" id="cb25"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a>prefix <span class="op">=</span> <span class="st">"""from peft import LoraConfig, TaskType, get_peft_model</span></span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="st">from transformers import AutoModelForCausalLM</span></span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a><span class="st">peft_config = LoraConfig(</span></span>
<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a><span class="st">"""</span></span>
<span id="cb25-5"><a href="#cb25-5" aria-hidden="true" tabindex="-1"></a>suffix <span class="op">=</span><span class="st">""""""</span></span>
<span id="cb25-6"><a href="#cb25-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-7"><a href="#cb25-7" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(get_code_completion(prefix, suffix))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForCausalLM
peft_config = LoraConfig(
model_name_or_path="facebook/wav2vec2-base-960h",
num_labels=1,
num_features=1,
num_hidden_layers=1,
num_attention_heads=1,
num_hidden_layers_per_attention_head=1,
num_attention_heads_per_hidden_layer=1,
hidden_size=1024,
hidden_dropout_prob=0.1,
hidden_act="gelu",
hidden_act_dropout_prob=0.1,
hidden</code></pre>
</div>
</div>
<p>While it is Python syntax, you can see that the original model has no understanding of what a <code>LoraConfig</code> should be doing.</p>
<p>To learn how this kind of fine-tuning compares to full fine-tuning, and how to use a model like this as your copilot in VS Code via Inference Endpoints, or locally, check out the <a href="https://huggingface.co/blog/personal-copilot">“Personal Copilot: Train Your Own Coding Assistant” blog post</a>. This notebook complements the original blog post.</p>
</section>
</section>
</main> <!-- /main -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const onCopySuccess = function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
}
const getTextToCopy = function(trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
text: getTextToCopy
});
clipboard.on('success', onCopySuccess);
if (window.document.getElementById('quarto-embedded-source-code-modal')) {
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
text: getTextToCopy,
container: window.document.getElementById('quarto-embedded-source-code-modal')
});
clipboardModal.on('success', onCopySuccess);
}
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
gutterDiv.style.position = 'absolute';
const codeCell = window.document.getElementById(targetCell);
const gutter = codeCell.querySelector('.code-annotation-gutter');
gutter.appendChild(gutterDiv);
}
gutterDiv.style.top = top - 2 + "px";
gutterDiv.style.height = height + 4 + "px";
}
selectedAnnoteEl = annoteEl;
}
};
const unselectCodeLines = () => {
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
elementsIds.forEach((elId) => {
const div = window.document.getElementById(elId);
if (div) {
div.remove();
}
});
selectedAnnoteEl = undefined;
};
// Handle positioning of the toggle
window.addEventListener(
"resize",
throttle(() => {
elRect = undefined;
if (selectedAnnoteEl) {
selectCodeLines(selectedAnnoteEl);
}
}, 10)
);
function throttle(fn, ms) {
let throttle = false;
let timer;
return (...args) => {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
// Attach click handler to the DT
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
for (const annoteDlNode of annoteDls) {
annoteDlNode.addEventListener('click', (event) => {
const clickedEl = event.target;
if (clickedEl !== selectedAnnoteEl) {
unselectCodeLines();
const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active');
if (activeEl) {
activeEl.classList.remove('code-annotation-active');
}
selectCodeLines(clickedEl);
clickedEl.classList.add('code-annotation-active');
} else {
// Unselect the line
unselectCodeLines();
clickedEl.classList.remove('code-annotation-active');
}
});
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {
tippyHover(citeInfo.el, function() {
var popup = window.document.createElement('div');
citeInfo.cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
}
});
</script>
</div> <!-- /content -->
</body></html> |