├── .gitignore ├── LICENSE.txt ├── README.md ├── assets ├── LF_LLM-269M_model_diagram.png ├── hellaswag_acc.png ├── nvidia-smi_sample_train_output.txt ├── open_source_models.numbers ├── pretraining_log.txt ├── puzzle_fox.jpg ├── some_open_source_models.png ├── train_val_loss.png └── training_metrics_over_steps.png ├── env_my_llm.yml ├── notebooks ├── .gitattributes ├── hf_sampling.ipynb ├── metric_graphs.ipynb ├── notes.ipynb └── parameters_tuning.ipynb ├── pretrain.py ├── run_pre_training_e2e.sh ├── run_pre_training_e2e_debug.sh └── src ├── __init__.py ├── attention.py ├── data_processing ├── __init__.py ├── data_downloader.py └── training_data_loader.py ├── ffn.py ├── global_cache.py ├── model.py ├── model_assessment ├── __init__.py ├── hellaswag.py ├── hf_sampling.py ├── sampling.py └── validation.py ├── model_configs ├── __init__.py └── my_llm_config.py ├── model_utils ├── adamw_opt.py ├── checkpoint_utils.py ├── debugging.py └── weight_init.py ├── params.py ├── rope.py ├── transformer_block.py └── utils ├── __init__.py ├── handle_ddp.py ├── logger.py ├── rand_idx_seq_gen.py └── root.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Store temp data (e.g. training datasets) 2 | /temp_data/* 3 | !temp_data/.gitkeep 4 | !temp_data/temp_data.py 5 | 6 | .DS_Store 7 | 8 | # Byte-compiled / optimized / DLL files 9 | __pycache__/ 10 | *.py[cod] 11 | *$py.class 12 | 13 | # C extensions 14 | *.so 15 | 16 | # Distribution / packaging 17 | .Python 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | share/python-wheels/ 31 | *.egg-info/ 32 | .installed.cfg 33 | *.egg 34 | MANIFEST 35 | 36 | # PyInstaller 37 | # Usually these files are written by a python script from a template 38 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 39 | *.manifest 40 | *.spec 41 | 42 | # Installer logs 43 | pip-log.txt 44 | pip-delete-this-directory.txt 45 | 46 | # Unit test / coverage reports 47 | htmlcov/ 48 | .tox/ 49 | .nox/ 50 | .coverage 51 | .coverage.* 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | *.cover 56 | *.py,cover 57 | .hypothesis/ 58 | .pytest_cache/ 59 | cover/ 60 | 61 | # Translations 62 | *.mo 63 | *.pot 64 | 65 | # Django stuff: 66 | *.log 67 | local_settings.py 68 | db.sqlite3 69 | db.sqlite3-journal 70 | 71 | # Flask stuff: 72 | instance/ 73 | .webassets-cache 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | .pybuilder/ 83 | target/ 84 | 85 | # Jupyter Notebook 86 | .ipynb_checkpoints 87 | 88 | # IPython 89 | profile_default/ 90 | ipython_config.py 91 | 92 | # pyenv 93 | # For a library or package, you might want to ignore these files since the code is 94 | # intended to run in multiple environments; otherwise, check them in: 95 | # .python-version 96 | 97 | # pipenv 98 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 99 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 100 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 101 | # install all needed dependencies. 102 | #Pipfile.lock 103 | 104 | # poetry 105 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 106 | # This is especially recommended for binary packages to ensure reproducibility, and is more 107 | # commonly ignored for libraries. 108 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 109 | #poetry.lock 110 | 111 | # pdm 112 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 113 | #pdm.lock 114 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 115 | # in version control. 116 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 117 | .pdm.toml 118 | .pdm-python 119 | .pdm-build/ 120 | 121 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 122 | __pypackages__/ 123 | 124 | # Celery stuff 125 | celerybeat-schedule 126 | celerybeat.pid 127 | 128 | # SageMath parsed files 129 | *.sage.py 130 | 131 | # Environments 132 | .env 133 | .venv 134 | env/ 135 | venv/ 136 | ENV/ 137 | env.bak/ 138 | venv.bak/ 139 | 140 | # Spyder project settings 141 | .spyderproject 142 | .spyproject 143 | 144 | # Rope project settings 145 | .ropeproject 146 | 147 | # mkdocs documentation 148 | /site 149 | 150 | # mypy 151 | .mypy_cache/ 152 | .dmypy.json 153 | dmypy.json 154 | 155 | # Pyre type checker 156 | .pyre/ 157 | 158 | # pytype static type analyzer 159 | .pytype/ 160 | 161 | # Cython debug symbols 162 | cython_debug/ 163 | 164 | # PyCharm 165 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 166 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 167 | # and can be added to the global gitignore or merged into this file. For a more nuclear 168 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 169 | #.idea/ 170 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | # LF_LLM-269M 4 | 5 |
6 |
7 | 8 | MyLLM is a deep-learning personal project where I built a modern LLM (`LF_LLM-269M`) from the ground up. I focused on developing the core components required for pre-training an LLM, including writing the model-architecture code, handling large datasets, training the model efficiently, and evaluating its performance. 9 | 10 | Below I'll talk about the structure of this project, design choices, training, and results. You can find the pretrained model on Huggingface ([LF_LLM-269M on Huggingface 🤗](https://huggingface.co/LF-Luis/LF_LLM-269M)). 11 | 12 | # Directory Structure 13 | Directory structure of various components implemented to build `LF_LLM-269M`. 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 36 | 37 | 49 | 50 | 66 | 67 | 82 | 83 | 93 | 94 | 108 | 109 | 117 | 118 |
Component Code
Model Code
22 | Literal code for building every
23 | layer of the model, and notebook
24 | used to figure some of this. 25 |
 26 | └── src
 27 |     ├── model.py
 28 |     ├── global_cache.py
 29 |     ├── transformer_block.py
 30 |     ├── attention.py
 31 |     ├── rope.py
 32 |     ├── ffn.py
 33 |     └── notebooks
 34 |         └── notes.ipynb
 35 | 
Model Config
38 | Config data type, actual and debug
39 | configs, and helper notebook used
40 | to figure out config values. 41 |
 42 | └── src
 43 |     ├── params.py
 44 |     ├── model_configs
 45 |         └── my_llm_config.py
 46 |     └── notebooks
 47 |         └── parameters_tuning.ipynb
 48 | 
Model Training
51 | Code to pretrain model, compute
52 | validation loss, scheduled AdamW
53 | wrapper, weight initialization
54 | scheme, and distributed training handler. 55 |
 56 | └── src
 57 |     ├── pretrain.py
 58 |     ├── model_assessment
 59 |         └── validation.py
 60 |     ├── model_utils
 61 |         ├── adamw_opt.py
 62 |         └── weight_init.py
 63 |     └── utils
 64 |         └── handle_ddp.py
 65 | 
Training Data
68 | Code to download, tokenize, and
69 | shard 10 Billion Tokens (BT)
70 | worth of training data. And
71 | also randomly shuffle and
72 | load shards to memory while
73 | running distributed training. 74 |
 75 | └── src
 76 |     ├── data_processing
 77 |         ├── data_downloader.py
 78 |         └── training_data_loader.py
 79 |     └── utils
 80 |         └── rand_idx_seq_gen.py
 81 | 
Model Assessment
84 | Code to autoregressively sample
85 | from the LF_LLM-269M model and
86 | run HellaSwag evaluation. 87 |
 88 | └── src
 89 |     └── model_assessment
 90 |         ├── sampling.py
 91 |         └── hellaswag.py
 92 | 
Training Helpers
95 | Helper code to log, manage files,
96 | checkpoint, and graph metrics. 97 |
 98 | └── src
 99 |     ├── utils
100 |         ├── logger.py
101 |         └── root.py
102 |     ├── model_utils
103 |         ├── debugging.py
104 |         └── checkpoint_utils.py
105 |     └── notebooks
106 |         └── metric_graphs.ipynb
107 | 
Temp Storage
110 | Temp storage where datasets,
111 | logs, checkpoints are stored
112 | for easy access as model is
113 | being trained/evaluated. 114 |
115 | └── temp_data/*
116 | 
119 | 120 | # How To Reproduce 121 | You can debug training on a Mac (or most unix/linux-machine) by using `./run_pre_training_e2e_debug.sh`. 122 | 123 | To actually train the model I used NVIDIA GPUs (went with 8xA100s because of cost). To run training end-to-end (downloading all datasets needed, training, running evals, etc) you can simply run `./run_pre_training_e2e.sh`. I used [VESSL AI's](https://vessl.ai) Workspaces to setup my training infra, using their `PyTorch 2.3.1 (CUDA 12.1)` image. 124 | 125 | [hf_sampling.ipynb](./notebooks/hf_sampling.ipynb) has steps to download the model (`LF_LLM-269M`) from Huggingface and sample it (see the long text response example in there about the *The Industrial Revolution* and *Climate change*). 126 | 127 | # LF_LLM-269M 128 | 129 | ### Model Architecture 130 | I went with the following model architecture, inspired by examples seen in GPT-2/3, Llama 3.2, OpenELM, MolmoE, OLMo, etc. 131 | 132 | From the bottom up on the diagram below, I used OpenAI's fast `tiktoken` library and leveraged their `r50k_base` BPE tokenizer, which has a vocab size of 50,257 —- sufficient for the small model I aimed to pre-train. As is common now, I went with pre-layer normalization, using RMSNorm due to its efficiency (compared to LayerNorm) while still providing stable normalization for the small training dataset and model. 133 | 134 | In the Transformer Block, I used regular causal multi-head attention (powered by PyTorch's `F.scaled_dot_product_attention`, which, according to my setup, should have been using `FlashAttention2`). There was no clear advantage to using GQA or other variants for this small model. Instead of using fixed or learned positional embeddings, I implemented RoPE to conserve model capacity (i.e., not something else the model has to optimize) and maintain the model's contextual understanding capacity (keeping the window size at 2,048). I applied a small dropout after this to avoid overfitting in the learned representations of the attention mechanism. With more data and a deeper model, I wouldn't have used dropout, but here the opposite was true. 135 | 136 | In the Feed Forward Network, I opted for SwiGLU, as it has become very popular with modern LLMs due to its efficiency and improved expressiveness through its gating mechanism. I added another small dropout after the activation because, at that point, the hidden state has quadrupled in size, and I wanted to avoid overfitting given the limited training data (relative to production LLMs, i.e., mine: 10BT vs. theirs: 1–9TT or larger). I effectively wanted to force the model to learn redundant representations that come out of the activation layer. 137 | 138 | As is common, I added residual connections from the start of a Transformer Block to after the attention mechanism, and then from there to the end of that Transformer Block. This gives the deep model a fighting chance by allowing deeper layers to learn useful representations due to improved gradient flow. 139 | 140 | After the data passes through various Transformer Blocks, the model ends with another RMS Normalization layer and, finally, a learned Linear Layer (with no bias). The Linear Layer at the end shares weights with the Token Embedding Layer located at the start of the model. This is done to reduce the model size while also acting as a regularization and generalization technique. 141 | 142 |
143 | 144 | ### Model and Training Parameters 145 | Due to my limited GPU resources (I don't want to spend resources searching for the best parameters), and because this is a learning project, I'll base my parameters around the parameters used by open source LLMs. It's not a perfect approach by any means, and choosing parameters can be an entire project of its own, but for now this is fine. 146 | 147 | Below is a summary table I created to help me tune my parameters (more info in [parameters_tuning.ipynb](./notebooks/parameters_tuning.ipynb)). 148 | 149 | ![Summary table](./assets/some_open_source_models.png) 150 | 151 | For `LF_LLM-269M`, I chose the following parameters. See [my_llm_config.py](./src/model_configs/my_llm_config.py) for all configs. 152 | 153 | | Parameter | Value | 154 | |-----------|-------| 155 | | n_vocab | 50_257 | 156 | | n_ctx | 2_048 | 157 | | n_embd | 1_024 | 158 | | n_head | 16 | 159 | | n_layer | 16 | 160 | | Pos-Emb | RoPE | 161 | | Attn | MHA | 162 | | FFN-Act | SwiGLU | 163 | | FFN-Mult | 4x | 164 | | Norm | RMSNorm | 165 | | Weight-tying | Yes | 166 | | | | 167 | | Train Token Count | 10B | 168 | | token_batch_size | ~0.5M | 169 | | max_lr | 0.0021 | 170 | | Adam beta 1 | 0.9 | 171 | | Adam beta 2 | 0.95 | 172 | | epsilon | 1e-8 | 173 | | clip_grad_max_norm | 1.0 | 174 | | weight_decay_rate | 0.1 | 175 | | Optimizer | AdamW | 176 | | LR schedule | (1) Linear warmup for 119 Million Tokens (MT)
(2) Cosine decay to 10% max_lr until end | 177 | 178 | 179 | ### Pre-Training Data 180 | For pre-training data I looked at [Dolma](https://allenai.org/dolma) and [RedPajama-v2](https://www.together.ai/blog/redpajama-data-v2), but [build-nanogpt](https://github.com/karpathy/build-nanogpt) showed me that a smaller, more refined dataset is enough for a small project like this so I ended up using the [Fineweb-Edu (sample-10BT)](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu) dataset. 181 | 182 | # Training LF_LLM-269M 183 | 184 | Training was done on 8 rented NVIDIA-A100-SXM4-80GB, hosted on [VESSL AI's](https://vessl.ai), I used their `PyTorch 2.3.1 (CUDA 12.1)` image for this project. 185 | 186 | The model trained on the 10 Billion Tokens (BT) of data for about 8 hours and 47 mins (from `20:28 2024-12-06 - 05:15 2024-12-07 UTC`). Each training step processed over 0.52 Million Tokens (MT) at around ~1698 ms (1.698 secs) per step. The throughput was around ~308,800 tokens processed per second. Fine detail of pretraining can be found in the logs: [pretraining_log.txt](./assets/pretraining_log.txt). 187 | 188 | # Results 189 | 190 | Compared to the table of open source models in Model and Training Parameters above where models are trained with trillions of tokens, `LF_LLM-269M` was trained with only 10 billion tokens (yes, different tokenizers, but it's a fair comparison). Even with this short training run, the results look pretty good. 191 | 192 | Both training and validation loss decreased with the same shape, showing that at a high level overfitting is not a major concern. Perplexity reached values of around 16.5, meaning the model is fairly confident in its predictions having narrowed down the choices effectively. 193 | 194 | The LR scheduler behaved as expected, the time per training step and throughput are consistent throughout the entire training loop, and gradient norm stayed fairly constant. 195 | 196 | ![Training Metrics](./assets/training_metrics_over_steps.png) 197 | ![Train Val Loss](./assets/train_val_loss.png) 198 | ![HellaSwag Acc](./assets/hellaswag_acc.png) 199 | 200 | To get a better sense of the model's sentence completion capabilities, I ran some prompts before the model even trained (so total random noise) and after the model had completed training and it's showing that it's making some sense: 201 | 202 | | 📝 Prompt | ❌ Sentence Completion at Step 0 | ✅ Sentence Completion after Last Step | 203 | |-------------------|----------------------------------------------|------------| 204 | | "*HTML stands for*" | " *campaigns desserts sawradio AUTH sort Pythononto unforeseen rainfall rainfall Host awaits solubleheaded Fever estimate genders proponentMAR*" | " *HyperText Markup Language. For more information about the browser, see:<\|endoftext\|>A few months ago*" | 205 | | "*If animals could talk, my pet would probably say*" | " *undertake undertake distortion intest Gylassotide acids Yankee neoconcept Coming Coming launcherimpl Sussex Sussexinea minim Ding*" | "*hello or I would say Hi. I am excited to have my pet respond to the sound I*" | 206 | | "*The clever fox built the strange machine with just a feather, a pebble, and a tiny twig*" | " *intrusion complying Resist master Yad induced derogatory Magic damageced amusing 290Sn},{" muddy universal prospect prospect prospect Rey*" | "*; by the time it was ready, it was a great working machine. After watching him carefully,*" | 207 | 208 | [hf_sampling.ipynb](./notebooks/hf_sampling.ipynb) has longer response examples. 209 | 210 |
211 | Resources/References 212 | 213 | - [Molomo (MolmoE)](https://huggingface.co/allenai/MolmoE-1B-0924) 214 | - [apple/corenet](https://github.com/apple/corenet/tree/main) 215 | - [allenai/OLMo](https://github.com/allenai/OLMo) 216 | - [mosaicml/llm-foundry](https://github.com/mosaicml/llm-foundry) 217 | - [google-research/tuning_playbook](https://github.com/google-research/tuning_playbook) 218 | - [karpathy/build-nanogpt](https://github.com/karpathy/build-nanogpt/tree/master) 219 | - more to add... 220 | 221 |
222 | 223 | ----- 224 | 225 | ### Why is the icon above a fox? 226 | I asked ChatGPT for a mascot to represent this project, and it suggested a "puzzle fox." I'd never heard of that before, but it explained that it aligns with the project because various puzzle pieces were cleverly put together — clever like a fox 😅. 227 | 228 | ----- 229 | 230 | ## License 231 | GNU GPLv3 ([LICENSE.txt](./LICENSE.txt)) 232 | -------------------------------------------------------------------------------- /assets/LF_LLM-269M_model_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/assets/LF_LLM-269M_model_diagram.png -------------------------------------------------------------------------------- /assets/hellaswag_acc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/assets/hellaswag_acc.png -------------------------------------------------------------------------------- /assets/nvidia-smi_sample_train_output.txt: -------------------------------------------------------------------------------- 1 | Every 1.0s: nvidia-smi 2 | 3 | Fri Dec 6 20:34:35 2024 4 | +---------------------------------------------------------------------------------------+ 5 | | NVIDIA-SMI 535.183.01 Driver Version: 535.183.01 CUDA Version: 12.2 | 6 | |-----------------------------------------+----------------------+----------------------+ 7 | | GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC | 8 | | Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. | 9 | | | | MIG M. | 10 | |=========================================+======================+======================| 11 | | 0 NVIDIA A100-SXM4-80GB Off | 00000000:06:00.0 Off | Off | 12 | | N/A 65C P0 381W / 400W | 72338MiB / 81920MiB | 99% Default | 13 | | | | Disabled | 14 | +-----------------------------------------+----------------------+----------------------+ 15 | | 1 NVIDIA A100-SXM4-80GB Off | 00000000:0C:00.0 Off | Off | 16 | | N/A 61C P0 397W / 400W | 72482MiB / 81920MiB | 99% Default | 17 | | | | Disabled | 18 | +-----------------------------------------+----------------------+----------------------+ 19 | | 2 NVIDIA A100-SXM4-80GB Off | 00000000:10:00.0 Off | Off | 20 | | N/A 63C P0 327W / 400W | 72488MiB / 81920MiB | 98% Default | 21 | | | | Disabled | 22 | +-----------------------------------------+----------------------+----------------------+ 23 | | 3 NVIDIA A100-SXM4-80GB Off | 00000000:16:00.0 Off | Off | 24 | | N/A 62C P0 331W / 400W | 72480MiB / 81920MiB | 100% Default | 25 | | | | Disabled | 26 | +-----------------------------------------+----------------------+----------------------+ 27 | | 4 NVIDIA A100-SXM4-80GB Off | 00000000:19:00.0 Off | Off | 28 | | N/A 65C P0 382W / 400W | 72480MiB / 81920MiB | 100% Default | 29 | | | | Disabled | 30 | +-----------------------------------------+----------------------+----------------------+ 31 | | 5 NVIDIA A100-SXM4-80GB Off | 00000000:1B:00.0 Off | Off | 32 | | N/A 66C P0 412W / 400W | 72480MiB / 81920MiB | 100% Default | 33 | | | | Disabled | 34 | +-----------------------------------------+----------------------+----------------------+ 35 | | 6 NVIDIA A100-SXM4-80GB Off | 00000000:21:00.0 Off | Off | 36 | | N/A 70C P0 400W / 400W | 72486MiB / 81920MiB | 100% Default | 37 | | | | Disabled | 38 | +-----------------------------------------+----------------------+----------------------+ 39 | | 7 NVIDIA A100-SXM4-80GB Off | 00000000:24:00.0 Off | Off | 40 | | N/A 62C P0 389W / 400W | 72342MiB / 81920MiB | 100% Default | 41 | | | | Disabled | 42 | +-----------------------------------------+----------------------+----------------------+ 43 | 44 | +---------------------------------------------------------------------------------------+ 45 | | Processes: | 46 | | GPU GI CI PID Type Process name GPU Memory | 47 | | ID ID Usage | 48 | |=======================================================================================| 49 | +---------------------------------------------------------------------------------------+ 50 | -------------------------------------------------------------------------------- /assets/open_source_models.numbers: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/assets/open_source_models.numbers -------------------------------------------------------------------------------- /assets/puzzle_fox.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/assets/puzzle_fox.jpg -------------------------------------------------------------------------------- /assets/some_open_source_models.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/assets/some_open_source_models.png -------------------------------------------------------------------------------- /assets/train_val_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/assets/train_val_loss.png -------------------------------------------------------------------------------- /assets/training_metrics_over_steps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/assets/training_metrics_over_steps.png -------------------------------------------------------------------------------- /env_my_llm.yml: -------------------------------------------------------------------------------- 1 | # Create: mamba env create -f env_my_llm.yml 2 | # Activate: mamba activate my_llm 3 | # Update: mamba env update --file env_my_llm.yml 4 | # Update and prune: mamba env update --file env_my_llm.yml --prune 5 | name: my_llm 6 | channels: 7 | - conda-forge 8 | - defaults 9 | dependencies: 10 | # Utils 11 | - python>=3.9,<3.10 12 | - pip 13 | - jupyter 14 | - notebook 15 | - matplotlib 16 | - tqdm 17 | # ML 18 | - numpy 19 | - pytorch 20 | - einops 21 | - transformers 22 | - tiktoken 23 | - datasets -------------------------------------------------------------------------------- /notebooks/.gitattributes: -------------------------------------------------------------------------------- 1 | *.ipynb linguist-documentation -------------------------------------------------------------------------------- /notebooks/hf_sampling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import sys\n", 10 | "import os\n", 11 | "parent_directory = os.path.dirname(os.getcwd())\n", 12 | "sys.path.append(parent_directory)" 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": 3, 18 | "metadata": {}, 19 | "outputs": [], 20 | "source": [ 21 | "from dataclasses import fields\n", 22 | "from src.params import TParams\n", 23 | "from src.utils.handle_ddp import DDPHandler\n", 24 | "from src.model_assessment.hf_sampling import get_hf_model, hf_sample" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 4, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "import logging\n", 34 | "log = logging.getLogger(\"\")\n", 35 | "logging.basicConfig(level=logging.INFO)" 36 | ] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": {}, 41 | "source": [ 42 | "### How to sample pretrained LF_LLM-269M\n", 43 | "To download the model and load it into memory run:\n", 44 | "\n", 45 | "```python\n", 46 | "ddp = DDPHandler()\n", 47 | "model = get_hf_model(ddp)\n", 48 | "```\n", 49 | "\n", 50 | "To run sampling, use the following:\n", 51 | "\n", 52 | "```python\n", 53 | "tParams = TParams(**{f.name: None for f in fields(TParams)})\n", 54 | "tParams.sampling_top_k = 50 # Leave this at 50, unless experimenting\n", 55 | "tParams.sampling_tokens = 40 # Number of tokens to create\n", 56 | "tParams.sampling_batch = 2 # Number of generated outputs to create\n", 57 | "\n", 58 | "hf_sample(model, ddp, tParams, \"Let's talk about Rome, Rome is\")\n", 59 | "```" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 5, 65 | "metadata": {}, 66 | "outputs": [ 67 | { 68 | "name": "stderr", 69 | "output_type": "stream", 70 | "text": [ 71 | "INFO:src.utils.handle_ddp:Launching worker with config: \n", 72 | "local_rank: 0 | world_size: 1 | is_main: True \n", 73 | "assigned_device: cuda | device_type: cuda.\n", 74 | "INFO:src.utils.root:Creating dir: /home/MyLLM/temp_data/hf_model\n" 75 | ] 76 | }, 77 | { 78 | "data": { 79 | "application/vnd.jupyter.widget-view+json": { 80 | "model_id": "7059d50edf514453b9ce3c8a56cee21c", 81 | "version_major": 2, 82 | "version_minor": 0 83 | }, 84 | "text/plain": [ 85 | "pytorch_model.pth: 0%| | 0.00/3.84G [00:00One-Third of American Kids and Strenuous Activities Are Outdoors In Their Homes, Report Shows\n", 193 | "WASHINGTON (AP) – The recent spike in American children’s outdoor play – one of the nation’s top environmental stewards – also found families sitting in chairs and unstructured backyard play, said a new report published Monday by the Environmental Working Group (EWG).\n", 194 | "“Children and their parents play the equivalent of one-third of the American adult workforce,” said Michael C. Perry, senior author of the study, which is based on the largest-ever survey of outdoor play in the U.S.\n", 195 | "“Their participation is inextricably linked with outdoor activities, but there’s still a lot of variability within children and families,” said Perry, an environmental psychologist at the University of Houston’s College of Education. “In their own homes, parents may have some of the most creative and engaged outdoor experiences with little physical activity or technology. But they may be on a mission to make sure every American has access to healthy outdoor environments, not just for school trips, but for all children.”\n", 196 | "The survey, conducted for TIME magazine, also found that nearly half of all kids surveyed are outdoors, but at a price.\n", 197 | "On average, children spent on average 24 hours a week in unstructured, untended, outdoor play – which is defined as “doing activities outdoors, not indoors, without any formal education or training –” compared with 5.4 hours a week in unstructured, unplanned outdoor time.\n", 198 | "Among children ages\n" 199 | ] 200 | } 201 | ], 202 | "source": [ 203 | "tParams.sampling_tokens = 500\n", 204 | "tParams.sampling_batch = 1\n", 205 | "\n", 206 | "hf_sample(model, ddp, tParams, \"Climate change poses one of the most significant challenges of the 21st century, with wide-ranging impacts on ecosystems, economies, and communities worldwide. Driven primarily by the increase in greenhouse gas emissions from human activities, it has led to rising global temperatures, melting polar ice caps, and more frequent extreme weather events. Addressing this crisis requires a multifaceted approach, including international cooperation, innovative technological solutions, and behavioral changes. For instance, renewable energy sources such as solar and wind power offer a promising alternative to fossil fuels, but\")" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": null, 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [] 215 | } 216 | ], 217 | "metadata": { 218 | "kernelspec": { 219 | "display_name": "my_llm", 220 | "language": "python", 221 | "name": "python3" 222 | }, 223 | "language_info": { 224 | "codemirror_mode": { 225 | "name": "ipython", 226 | "version": 3 227 | }, 228 | "file_extension": ".py", 229 | "mimetype": "text/x-python", 230 | "name": "python", 231 | "nbconvert_exporter": "python", 232 | "pygments_lexer": "ipython3", 233 | "version": "3.9.20" 234 | } 235 | }, 236 | "nbformat": 4, 237 | "nbformat_minor": 4 238 | } 239 | -------------------------------------------------------------------------------- /notebooks/notes.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "Notebook that helped me figure out topics as I created my LLM, might remove since it's not really polished.." 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 2, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import sys\n", 17 | "import os\n", 18 | "parent_directory = os.path.dirname(os.getcwd())\n", 19 | "sys.path.append(parent_directory)" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "### Attention\n", 27 | "Given an input sequence of three tokens, with embedding dimension of 2:\n", 28 | "$$\n", 29 | "X = \\begin{bmatrix}\n", 30 | "x_{1,1} & x_{1,2} \\\\\n", 31 | "x_{2,1} & x_{2,2} \\\\\n", 32 | "x_{3,1} & x_{3,2}\n", 33 | "\\end{bmatrix}\n", 34 | "$$" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "metadata": {}, 40 | "source": [ 41 | "And Q, K, and V learnable weights:\n", 42 | "$$\n", 43 | "W_Q = \\begin{bmatrix}\n", 44 | "w^{q}_{1,1} & w^{q}_{1,2} \\\\\n", 45 | "w^{q}_{2,1} & w^{q}_{2,2}\n", 46 | "\\end{bmatrix}\n", 47 | "\\quad\n", 48 | "W_K = \\begin{bmatrix}\n", 49 | "w^{k}_{1,1} & w^{k}_{1,2} \\\\\n", 50 | "w^{k}_{2,1} & w^{k}_{2,2}\n", 51 | "\\end{bmatrix}\n", 52 | "\\quad\n", 53 | "W_V = \\begin{bmatrix}\n", 54 | "w^{v}_{1,1} & w^{v}_{1,2} \\\\\n", 55 | "w^{v}_{2,1} & w^{v}_{2,2}\n", 56 | "\\end{bmatrix}\n", 57 | "$$\n" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "$$\n", 65 | "Q = X \\times W_Q\n", 66 | "$$\n", 67 | "\n", 68 | "$$\n", 69 | "Q = \\begin{bmatrix}\n", 70 | "x_{1,1} & x_{1,2} \\\\\n", 71 | "x_{2,1} & x_{2,2} \\\\\n", 72 | "x_{3,1} & x_{3,2}\n", 73 | "\\end{bmatrix}\n", 74 | "\\times\n", 75 | "\\begin{bmatrix}\n", 76 | "w^{q}_{1,1} & w^{q}_{1,2} \\\\\n", 77 | "w^{q}_{2,1} & w^{q}_{2,2}\n", 78 | "\\end{bmatrix}\n", 79 | "=\n", 80 | "\\begin{bmatrix}\n", 81 | "x_{1,1}w^{q}_{1,1} + x_{1,2}w^{q}_{2,1} & x_{1,1}w^{q}_{1,2} + x_{1,2}w^{q}_{2,2} \\\\\n", 82 | "x_{2,1}w^{q}_{1,1} + x_{2,2}w^{q}_{2,1} & x_{2,1}w^{q}_{1,2} + x_{2,2}w^{q}_{2,2} \\\\\n", 83 | "x_{3,1}w^{q}_{1,1} + x_{3,2}w^{q}_{2,1} & x_{3,1}w^{q}_{1,2} + x_{3,2}w^{q}_{2,2}\n", 84 | "\\end{bmatrix}\n", 85 | "$$\n", 86 | "\n", 87 | "$$\n", 88 | "Q = \\begin{bmatrix}\n", 89 | "q_{1,1} & q_{1,2} \\\\\n", 90 | "q_{2,1} & q_{2,2} \\\\\n", 91 | "q_{3,1} & q_{3,2}\n", 92 | "\\end{bmatrix}\n", 93 | "$$\n" 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "$$\n", 101 | "K = X \\times W_K \\quad = \\quad \\begin{bmatrix}\n", 102 | "k_{1,1} & k_{1,2} \\\\\n", 103 | "k_{2,1} & k_{2,2} \\\\\n", 104 | "k_{3,1} & k_{3,2}\n", 105 | "\\end{bmatrix}\n", 106 | "$$\n", 107 | "\n", 108 | "$$\n", 109 | "V = X \\times W_V \\quad = \\quad \\begin{bmatrix}\n", 110 | "v_{1,1} & v_{1,2} \\\\\n", 111 | "v_{2,1} & v_{2,2} \\\\\n", 112 | "v_{3,1} & v_{3,2}\n", 113 | "\\end{bmatrix}\n", 114 | "$$\n" 115 | ] 116 | }, 117 | { 118 | "cell_type": "markdown", 119 | "metadata": {}, 120 | "source": [ 121 | "Attention Score:\n", 122 | "$$\n", 123 | "A\\_S = Q \\times K^T\n", 124 | "$$\n", 125 | "\n", 126 | "$$\n", 127 | "A\\_S = \\begin{bmatrix}\n", 128 | "q_{1,1} & q_{1,2} \\\\\n", 129 | "q_{2,1} & q_{2,2} \\\\\n", 130 | "q_{3,1} & q_{3,2}\n", 131 | "\\end{bmatrix}\n", 132 | "\\times\n", 133 | "\\begin{bmatrix}\n", 134 | "k_{1,1} & k_{2,1} & k_{3,1} \\\\\n", 135 | "k_{1,2} & k_{2,2} & k_{3,2}\n", 136 | "\\end{bmatrix}\n", 137 | "=\n", 138 | "\\begin{bmatrix}\n", 139 | "q_{1,1}k_{1,1} + q_{1,2}k_{1,2} & q_{1,1}k_{2,1} + q_{1,2}k_{2,2} & q_{1,1}k_{3,1} + q_{1,2}k_{3,2} \\\\\n", 140 | "q_{2,1}k_{1,1} + q_{2,2}k_{1,2} & q_{2,1}k_{2,1} + q_{2,2}k_{2,2} & q_{2,1}k_{3,1} + q_{2,2}k_{3,2} \\\\\n", 141 | "q_{3,1}k_{1,1} + q_{3,2}k_{1,2} & q_{3,1}k_{2,1} + q_{3,2}k_{2,2} & q_{3,1}k_{3,1} + q_{3,2}k_{3,2}\n", 142 | "\\end{bmatrix}\n", 143 | "$$\n", 144 | "\n", 145 | "$$\n", 146 | "A\\_S = \\begin{bmatrix}\n", 147 | "s_{1,1} & s_{1,2} & s_{1,3} \\\\\n", 148 | "s_{2,1} & s_{2,2} & s_{2,3} \\\\\n", 149 | "s_{3,1} & s_{3,2} & s_{3,3}\n", 150 | "\\end{bmatrix}\n", 151 | "$$" 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "metadata": {}, 157 | "source": [ 158 | "Scale and Normalize attention scores: \n", 159 | "(softmax is applied across the features dimension)\n", 160 | "$$\n", 161 | "\\text{Scaled, Normalized } A\\_S = \\text{softmax}\\left(\\frac{1}{\\sqrt{2}} \\begin{bmatrix}\n", 162 | "s_{1,1} & s_{1,2} & s_{1,3} \\\\\n", 163 | "s_{2,1} & s_{2,2} & s_{2,3} \\\\\n", 164 | "s_{3,1} & s_{3,2} & s_{3,3}\n", 165 | "\\end{bmatrix}\\right)\n", 166 | "$$\n" 167 | ] 168 | }, 169 | { 170 | "cell_type": "markdown", 171 | "metadata": {}, 172 | "source": [ 173 | "Attention Weights\n", 174 | "$$\n", 175 | "\\text{Attention Weights} = \\text{Scaled, Normalized } A\\_S\n", 176 | "$$\n", 177 | "\n", 178 | "$$\n", 179 | "\\text{Attention Weights} = \\begin{bmatrix}\n", 180 | "\\alpha_{1,1} & \\alpha_{1,2} & \\alpha_{1,3} \\\\\n", 181 | "\\alpha_{2,1} & \\alpha_{2,2} & \\alpha_{2,3} \\\\\n", 182 | "\\alpha_{3,1} & \\alpha_{3,2} & \\alpha_{3,3}\n", 183 | "\\end{bmatrix}\n", 184 | "$$\n" 185 | ] 186 | }, 187 | { 188 | "cell_type": "markdown", 189 | "metadata": {}, 190 | "source": [ 191 | "Attention Output:\n", 192 | "$$\n", 193 | "\\text{Attention Output} = \\text{Attention Weights} \\times V\n", 194 | "$$\n", 195 | "\n", 196 | "$$\n", 197 | "\\text{Attention Output} = \\begin{bmatrix}\n", 198 | "\\alpha_{1,1} & \\alpha_{1,2} & \\alpha_{1,3} \\\\\n", 199 | "\\alpha_{2,1} & \\alpha_{2,2} & \\alpha_{2,3} \\\\\n", 200 | "\\alpha_{3,1} & \\alpha_{3,2} & \\alpha_{3,3}\n", 201 | "\\end{bmatrix}\n", 202 | "\\times\n", 203 | "\\begin{bmatrix}\n", 204 | "v_{1,1} & v_{1,2} \\\\\n", 205 | "v_{2,1} & v_{2,2} \\\\\n", 206 | "v_{3,1} & v_{3,2}\n", 207 | "\\end{bmatrix}\n", 208 | "=\n", 209 | "\\begin{bmatrix}\n", 210 | "\\alpha_{1,1}v_{1,1} + \\alpha_{1,2}v_{2,1} + \\alpha_{1,3}v_{3,1} & \\alpha_{1,1}v_{1,2} + \\alpha_{1,2}v_{2,2} + \\alpha_{1,3}v_{3,2} \\\\\n", 211 | "\\alpha_{2,1}v_{1,1} + \\alpha_{2,2}v_{2,1} + \\alpha_{2,3}v_{3,1} & \\alpha_{2,1}v_{1,2} + \\alpha_{2,2}v_{2,2} + \\alpha_{2,3}v_{3,2} \\\\\n", 212 | "\\alpha_{3,1}v_{1,1} + \\alpha_{3,2}v_{2,1} + \\alpha_{3,3}v_{3,1} & \\alpha_{3,1}v_{1,2} + \\alpha_{3,2}v_{2,2} + \\alpha_{3,3}v_{3,2}\n", 213 | "\\end{bmatrix}\n", 214 | "$$\n" 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "metadata": {}, 220 | "source": [ 221 | "$$\n", 222 | "\\text{Attention Output} = O = \\begin{bmatrix}\n", 223 | "o_{1,1} & o_{1,2} \\\\\n", 224 | "o_{2,1} & o_{2,2} \\\\\n", 225 | "o_{3,1} & o_{3,2}\n", 226 | "\\end{bmatrix}\n", 227 | "$$\n" 228 | ] 229 | }, 230 | { 231 | "cell_type": "markdown", 232 | "metadata": {}, 233 | "source": [ 234 | "Multi-head attention\n", 235 | "$$\n", 236 | "\\text{MultiHead}(Q, K, V) = \\text{Concat}(\\text{head}_1, \\dots, \\text{head}_h) W^O\n", 237 | "$$\n", 238 | "\n", 239 | "$$\n", 240 | "\\text{head}_i = \\text{Attention}(Q W_Q^{(i)}, K W_K^{(i)}, V W_V^{(i)}) = \\text{softmax}\\left(\\frac{(Q W_Q^{(i)}) (K W_K^{(i)})^T}{\\sqrt{d_k}}\\right) (V W_V^{(i)})\n", 241 | "$$\n" 242 | ] 243 | }, 244 | { 245 | "cell_type": "markdown", 246 | "metadata": {}, 247 | "source": [ 248 | "example of mulit-head attention\n", 249 | "$$\n", 250 | "\\text{MultiHead}(Q, K, V) = \\text{Concat}(\\text{head}_1, \\text{head}_2, \\text{head}_3) W^O\n", 251 | "$$\n", 252 | "\n", 253 | "$$\n", 254 | "\\text{Concat}(\\text{head}_1, \\text{head}_2, \\text{head}_3) =\n", 255 | "\\begin{bmatrix}\n", 256 | "\\text{head}_1 & \\text{head}_2 & \\text{head}_3\n", 257 | "\\end{bmatrix}\n", 258 | "=\n", 259 | "\\begin{bmatrix}\n", 260 | "h_{1,1} & h_{1,2} & h_{1,3} & h_{1,4} & h_{1,5} & h_{1,6} \\\\\n", 261 | "h_{2,1} & h_{2,2} & h_{2,3} & h_{2,4} & h_{2,5} & h_{2,6} \\\\\n", 262 | "h_{3,1} & h_{3,2} & h_{3,3} & h_{3,4} & h_{3,5} & h_{3,6}\n", 263 | "\\end{bmatrix}\n", 264 | "$$\n", 265 | "\n", 266 | "$$\n", 267 | "\\text{Attention Output} = \\begin{bmatrix}\n", 268 | "h_{1,1} & h_{1,2} & h_{1,3} & h_{1,4} & h_{1,5} & h_{1,6} \\\\\n", 269 | "h_{2,1} & h_{2,2} & h_{2,3} & h_{2,4} & h_{2,5} & h_{2,6} \\\\\n", 270 | "h_{3,1} & h_{3,2} & h_{3,3} & h_{3,4} & h_{3,5} & h_{3,6}\n", 271 | "\\end{bmatrix}\n", 272 | "\\times\n", 273 | "\\begin{bmatrix}\n", 274 | "w_{1,1} & w_{1,2} & \\dots & w_{1,d_{model}} \\\\\n", 275 | "w_{2,1} & w_{2,2} & \\dots & w_{2,d_{model}} \\\\\n", 276 | "\\vdots & \\vdots & \\ddots & \\vdots \\\\\n", 277 | "w_{6,1} & w_{6,2} & \\dots & w_{6,d_{model}}\n", 278 | "\\end{bmatrix}\n", 279 | "$$\n", 280 | "\n", 281 | "$$\n", 282 | "=\n", 283 | "\\begin{bmatrix}\n", 284 | "o_{1,1} & o_{1,2} & \\dots & o_{1,d_{model}} \\\\\n", 285 | "o_{2,1} & o_{2,2} & \\dots & o_{2,d_{model}} \\\\\n", 286 | "o_{3,1} & o_{3,2} & \\dots & o_{3,d_{model}}\n", 287 | "\\end{bmatrix}\n", 288 | "$$\n" 289 | ] 290 | }, 291 | { 292 | "cell_type": "markdown", 293 | "metadata": {}, 294 | "source": [ 295 | "## Rotary Positional Embedding (RoPE)" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": 3, 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "'''\n", 305 | "RoPE (rotary positional embedding) -- spelled out.\n", 306 | "Rotate token embedding pairs before attending. This means that the positional embedding will no longer be a learned parameter (or fixed sinusoidal), it is just a transformation of a token's embedding. This encodes positional information intrinsically within the token's embedding.\n", 307 | "\n", 308 | "The rotation angle `theta_p` is set to `p * ω_k`, where `p` is the token's position in the sequence and `w_k` is a frequency associated with each pair of dimensions.\n", 309 | "`w_k` decreases exponentially with increasing dimension index, meaning lower-indexed pairs of dimensions rotate more than higher-indexed ones.\n", 310 | "This design allows RoPE to capture relative positional information across different dimensions in a smooth, continuous manner.\n", 311 | "'''\n", 312 | "\n", 313 | "import math\n", 314 | "import torch\n", 315 | "\n", 316 | "def rope_1d_slow(p, embedding):\n", 317 | " # p: index-position of token in sequence\n", 318 | " # embedding: embedding representation of token\n", 319 | "\n", 320 | " dim = len(embedding)\n", 321 | " assert dim % 2 == 0\n", 322 | "\n", 323 | " def w_k(k):\n", 324 | " return 1 / (10_000 ** (2*k/dim))\n", 325 | " \n", 326 | " def theta_p(k):\n", 327 | " # k: index-position of embedding-pair for tokem embedding\n", 328 | " return p * w_k(k)\n", 329 | " \n", 330 | " transformation = torch.zeros(dim//2, 2)\n", 331 | "\n", 332 | " for i in range(0, len(embedding), 2):\n", 333 | " x_i_0 = embedding[i]\n", 334 | " x_i_1 = embedding[i+1]\n", 335 | " theta_p_val = theta_p(i//2)\n", 336 | " cos = math.cos(theta_p_val)\n", 337 | " sin = math.sin(theta_p_val)\n", 338 | " rotation = torch.tensor([\n", 339 | " [cos, -1*sin],\n", 340 | " [sin, cos]\n", 341 | " ])\n", 342 | " x = torch.tensor([x_i_0, x_i_1])\n", 343 | " transformation[i//2, :] = torch.matmul(rotation, x)\n", 344 | "\n", 345 | " return transformation.view(-1)\n", 346 | "\n", 347 | "def rope_1d_faster(p, embedding):\n", 348 | " dim = len(embedding)\n", 349 | " assert dim % 2 == 0\n", 350 | "\n", 351 | " indices = torch.arange(0, dim // 2)\n", 352 | " w_k = 1 / (10_000 ** (2 * indices / dim))\n", 353 | " cosine = torch.cos(p * w_k)\n", 354 | " cosine = cosine.repeat_interleave(2)\n", 355 | " sine = torch.sin(p * w_k)\n", 356 | " sine = sine.repeat_interleave(2)\n", 357 | " \n", 358 | " x = embedding\n", 359 | " x_shifted = torch.empty(len(embedding), dtype=embedding.dtype)\n", 360 | " x_shifted[1::2], x_shifted[::2] = embedding[::2], -embedding[1::2]\n", 361 | "\n", 362 | " return x * cosine + x_shifted * sine\n", 363 | "\n", 364 | "def rope_multi_head_broadcasting(att_comp):\n", 365 | " # att_comp: attention component, either Q or K.\n", 366 | " # Perform RoPE on each attention head of att_comp\n", 367 | " # expected shape (Batch, Sequence, Head, Head Dimension).\n", 368 | " # Use broadcasting along the Batch and Sequence dimension to save memory.\n", 369 | " B, S, H, HD = att_comp.shape\n", 370 | " assert HD % 2 == 0\n", 371 | "\n", 372 | " ind_emb = torch.arange(0, HD // 2) # embedding-pairs indices\n", 373 | " w_k = 1 / (10_000 ** (2 * ind_emb / HD))\n", 374 | "\n", 375 | " # Expand w_k for each token in Sequence and perform `p * w_k`\n", 376 | " w_k = w_k.view(1, -1)\n", 377 | " w_k = w_k.repeat_interleave(S, 0)\n", 378 | " ind_tok = torch.arange(S).unsqueeze(1).repeat(1, w_k.shape[1]) # token indices\n", 379 | " w_k = w_k * ind_tok\n", 380 | "\n", 381 | " # Get cosine rot. values\n", 382 | " cosine = torch.cos(w_k)\n", 383 | " cosine = cosine.repeat_interleave(2, -1) # repeat for embedding pairs\n", 384 | " # reshape to B=1, S, H=1, HD\n", 385 | " cosine = cosine.view(1, S, 1, HD)\n", 386 | "\n", 387 | " # Get sine rot. values\n", 388 | " sine = torch.sin(w_k)\n", 389 | " sine = sine.repeat_interleave(2, -1) # repeat for embedding pairs\n", 390 | " sine = sine.repeat_interleave(H, 0) # repeat for all attn heads\n", 391 | " # reshape to B, S, H, HD\n", 392 | " sine = sine.view(1, S, H, HD)\n", 393 | " sine = sine.repeat_interleave(B, 0)\n", 394 | "\n", 395 | " x = att_comp\n", 396 | " x_shifted = torch.empty(att_comp.shape, dtype=att_comp.dtype)\n", 397 | " x_shifted[...,1::2], x_shifted[...,::2] = att_comp[...,::2], -att_comp[...,1::2]\n", 398 | "\n", 399 | " return x * cosine + x_shifted * sine" 400 | ] 401 | }, 402 | { 403 | "cell_type": "code", 404 | "execution_count": 4, 405 | "metadata": {}, 406 | "outputs": [ 407 | { 408 | "name": "stdout", 409 | "output_type": "stream", 410 | "text": [ 411 | "tensor([[[[ 0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000,\n", 412 | " 0.7000],\n", 413 | " [ 0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000,\n", 414 | " 0.7000]],\n", 415 | "\n", 416 | " [[-0.0841, 0.0540, 0.1691, 0.3185, 0.3950, 0.5040, 0.5993,\n", 417 | " 0.7006],\n", 418 | " [-0.0841, 0.0540, 0.1691, 0.3185, 0.3950, 0.5040, 0.5993,\n", 419 | " 0.7006]],\n", 420 | "\n", 421 | " [[-0.0909, -0.0416, 0.1364, 0.3338, 0.3899, 0.5079, 0.5986,\n", 422 | " 0.7012],\n", 423 | " [-0.0909, -0.0416, 0.1364, 0.3338, 0.3899, 0.5079, 0.5986,\n", 424 | " 0.7012]]],\n", 425 | "\n", 426 | "\n", 427 | " [[[ 0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000,\n", 428 | " 0.7000],\n", 429 | " [ 0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000,\n", 430 | " 0.7000]],\n", 431 | "\n", 432 | " [[-0.0841, 0.0540, 0.1691, 0.3185, 0.3950, 0.5040, 0.5993,\n", 433 | " 0.7006],\n", 434 | " [-0.0841, 0.0540, 0.1691, 0.3185, 0.3950, 0.5040, 0.5993,\n", 435 | " 0.7006]],\n", 436 | "\n", 437 | " [[-0.0909, -0.0416, 0.1364, 0.3338, 0.3899, 0.5079, 0.5986,\n", 438 | " 0.7012],\n", 439 | " [-0.0909, -0.0416, 0.1364, 0.3338, 0.3899, 0.5079, 0.5986,\n", 440 | " 0.7012]]]])\n" 441 | ] 442 | } 443 | ], 444 | "source": [ 445 | "# Full RoPE implementation\n", 446 | "B, S, H, HD = 2, 3, 2, 8\n", 447 | "q = torch.empty(B, S, H, HD)\n", 448 | "q[:,:,:,:] = torch.tensor([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])\n", 449 | "rope_multi_head_broadcasting_res = rope_multi_head_broadcasting(q)\n", 450 | "print(rope_multi_head_broadcasting_res)" 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": 5, 456 | "metadata": {}, 457 | "outputs": [ 458 | { 459 | "name": "stdout", 460 | "output_type": "stream", 461 | "text": [ 462 | "tensor([-0.0909, -0.0416, 0.1364, 0.3338, 0.3899, 0.5079, 0.5986, 0.7012])\n", 463 | "tensor([-0.0909, -0.0416, 0.1364, 0.3338, 0.3899, 0.5079, 0.5986, 0.7012])\n" 464 | ] 465 | } 466 | ], 467 | "source": [ 468 | "# Simpler RoPE implementations\n", 469 | "rope_1d_slow_res = rope_1d_slow(2, [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])\n", 470 | "print(rope_1d_slow(2, [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]))\n", 471 | "print(rope_1d_faster(2, torch.tensor([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])))" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "execution_count": 7, 477 | "metadata": {}, 478 | "outputs": [ 479 | { 480 | "name": "stdout", 481 | "output_type": "stream", 482 | "text": [ 483 | "False\n" 484 | ] 485 | } 486 | ], 487 | "source": [ 488 | "# sanity check that naive implementation\n", 489 | "print(torch.equal(rope_multi_head_broadcasting_res[0,2,0,:], rope_1d_slow_res))" 490 | ] 491 | }, 492 | { 493 | "cell_type": "code", 494 | "execution_count": 8, 495 | "metadata": {}, 496 | "outputs": [ 497 | { 498 | "name": "stdout", 499 | "output_type": "stream", 500 | "text": [ 501 | "tensor([[[[-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 502 | " 0.3000],\n", 503 | " [-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 504 | " 0.3000]],\n", 505 | "\n", 506 | " [[-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 507 | " 0.3000],\n", 508 | " [-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 509 | " 0.3000]],\n", 510 | "\n", 511 | " [[-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 512 | " 0.3000],\n", 513 | " [-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 514 | " 0.3000]]],\n", 515 | "\n", 516 | "\n", 517 | " [[[-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 518 | " 0.3000],\n", 519 | " [-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 520 | " 0.3000]],\n", 521 | "\n", 522 | " [[-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 523 | " 0.3000],\n", 524 | " [-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 525 | " 0.3000]],\n", 526 | "\n", 527 | " [[-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 528 | " 0.3000],\n", 529 | " [-0.4000, -0.5000, -0.6000, -0.7000, 0.0000, 0.1000, 0.2000,\n", 530 | " 0.3000]]]])\n" 531 | ] 532 | } 533 | ], 534 | "source": [ 535 | "def rotate_half(x):\n", 536 | " x1, x2 = x.chunk(2, dim=-1)\n", 537 | " return torch.cat((-x2, x1), dim=-1)\n", 538 | "\n", 539 | "B, S, H, HD = 2, 3, 2, 8\n", 540 | "q = torch.empty(B, S, H, HD)\n", 541 | "q[:,:,:,:] = torch.tensor([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])\n", 542 | "q = rotate_half(q)\n", 543 | "print(q)" 544 | ] 545 | } 546 | ], 547 | "metadata": { 548 | "language_info": { 549 | "name": "python" 550 | } 551 | }, 552 | "nbformat": 4, 553 | "nbformat_minor": 2 554 | } 555 | -------------------------------------------------------------------------------- /pretrain.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | import math 4 | import time 5 | from contextlib import nullcontext 6 | 7 | import torch 8 | 9 | from src.model import LLM 10 | from src.utils.logger import setup_logging 11 | from src.utils.handle_ddp import DDPHandler 12 | from src.utils.root import get_temp_data_abs_path 13 | from src.model_assessment.hellaswag import HellaSwag 14 | from src.model_assessment.sampling import multi_sample 15 | from src.model_assessment.validation import Validation 16 | from src.model_utils.adamw_opt import AdamWOptimizer 17 | from src.model_utils.checkpoint_utils import save_checkpoint 18 | from src.model_utils.debugging import get_model_size, log_training_metrics 19 | from src.model_configs.my_llm_config import get_llm_config, get_pre_train_sampling_prompts 20 | from src.data_processing.training_data_loader import TrainingDataLoader 21 | 22 | 23 | ''' 24 | Main script to pre-train MyLLM in 8xA100 GPUs. 25 | ''' 26 | 27 | if __name__ == "__main__": 28 | setup_logging() 29 | log = logging.getLogger(__name__) 30 | ddp = DDPHandler() 31 | 32 | # Set up all parameters 33 | hParams, tParams = get_llm_config() 34 | batch_size = tParams.batch_token_count / ddp.world_size / hParams.n_ctx 35 | micro_batch_size = int(batch_size / tParams.grad_acc_steps) 36 | assert batch_size % micro_batch_size == 0, f'Error, batch_size ({batch_size}) must be divisible by micro_batch_size ({micro_batch_size}).' 37 | sampling_prompts = get_pre_train_sampling_prompts() 38 | 39 | # Setup model and optimizer 40 | # Make sure to keep this order: move to device, compile, then DDP wrap 41 | model = LLM(hParams) 42 | model.to(ddp.assigned_device) 43 | if ddp.is_avail: 44 | model = torch.compile(model) 45 | model = ddp.wrap_model(model) # Only wraps if CUDA + GPU is available 46 | model.train() 47 | opt = AdamWOptimizer(tParams, ddp, ddp.get_actual_model(model)) 48 | torch.set_float32_matmul_precision('high') # Enable TF32 49 | 50 | if ddp.is_main: 51 | log.info(f'Model size (full): {get_model_size(ddp.get_actual_model(model)):,}') 52 | log.info(f'Model size: {math.ceil(get_model_size(ddp.get_actual_model(model)) / 1_000_000)}M') 53 | log.info(f'batch_size: {batch_size}') 54 | log.info(f'micro_batch_size: {micro_batch_size}') 55 | log.info(f'hParams: {hParams}') 56 | log.info(f'tParams: {tParams}') 57 | 58 | # Prep data loader 59 | data_loader = TrainingDataLoader( 60 | dataset_dir=os.path.join(get_temp_data_abs_path(), 'edu_fineweb10B'), 61 | ddp=ddp, 62 | batch_count=micro_batch_size, 63 | tokens_per_batch=hParams.n_ctx, 64 | ) 65 | 66 | # Setup model assessment 67 | val = Validation(model, data_loader, tParams, ddp) 68 | hSwag = HellaSwag(model, tParams, ddp) 69 | 70 | ddp.barrier() 71 | 72 | for step in range(tParams.tot_steps): 73 | ''' 74 | Training code. 75 | ''' 76 | train_start = time.time() 77 | opt.zero_grad() 78 | 79 | # Grad accumulation 80 | total_loss = 0. 81 | for micro_step in range(tParams.grad_acc_steps): 82 | input, output = data_loader.get_train_samples(micro_batch_size, hParams.n_ctx) 83 | 84 | # Disable DDP gradient sync until last micro step 85 | sync_context = nullcontext() 86 | if ddp.is_avail and micro_step < tParams.grad_acc_steps - 1: 87 | sync_context = model.no_sync() 88 | 89 | with sync_context: 90 | with torch.autocast(device_type=ddp.device_type, dtype=torch.bfloat16): 91 | _, loss = model(input, output) 92 | loss = loss / tParams.grad_acc_steps # Scale loss 93 | loss.backward() 94 | 95 | total_loss += loss.detach() 96 | 97 | grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), tParams.clip_grad_max_norm) 98 | 99 | debugging_lr = opt.step(step=step) 100 | 101 | ''' 102 | Log metrics and save checkpoints at certain intervals. 103 | Make sure to wait for GPU compute to be done before logging, and 104 | sync all distributed processes before checkpointing. 105 | ''' 106 | is_last_step = (step == (tParams.tot_steps - 1)) 107 | should_log = (step % tParams.logging_interval == 0) or is_last_step 108 | should_checkpoint = (step in tParams.checkpointing_steps) or is_last_step 109 | should_run_val = (step % tParams.validation_interval == 0) or is_last_step 110 | should_sample = (step % tParams.sampling_interval == 0) or is_last_step 111 | should_run_hs_eval = (step % tParams.eval_interval == 0) or is_last_step 112 | 113 | if ddp.is_avail and should_log: 114 | torch.cuda.synchronize() 115 | if should_checkpoint: 116 | ddp.barrier() 117 | 118 | train_end = time.time() 119 | 120 | if should_run_val: val.run_validation(step) 121 | if should_run_hs_eval: hSwag.run_eval(step) 122 | if should_sample: multi_sample(model, ddp, sampling_prompts, tParams) 123 | if should_log: 124 | log_training_metrics(log, ddp, tParams, train_start, train_end, step, 125 | total_loss, grad_norm, debugging_lr) 126 | if ddp.is_main and should_checkpoint: 127 | save_checkpoint(ddp.get_actual_model(model), opt.optimizer, step) 128 | 129 | if should_run_val or should_run_hs_eval or should_sample or should_checkpoint: 130 | ddp.barrier() 131 | 132 | ddp.barrier() 133 | ddp.end() 134 | -------------------------------------------------------------------------------- /run_pre_training_e2e.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # Script to run all pre-training end-to-end. 5 | # This script will first download training and validation data 6 | # and then start running the pre-training loop. 7 | 8 | export PYTHONPATH="${PYTHONPATH}:$PWD/src" 9 | 10 | if [[ "$(basename "$PWD")" != "MyLLM" ]]; then 11 | echo "Error: You are not in the 'MyLLM' project directory. Current directory is '$PWD'." 12 | exit 1 13 | fi 14 | 15 | # Create log file for script, training logic handles its own logging 16 | LOGFILE="$PWD/temp_data/logs/run_training_e2e_$(date +'%Y_%m_%d-%H_%M_%Z').log" 17 | mkdir -p "$(dirname "$LOGFILE")" && [ -f "$LOGFILE" ] || touch "$LOGFILE" 18 | : > "$LOGFILE" # Empty the log file 19 | log() { 20 | local timestamp=$(date '+%Y-%m-%d %H:%M:%S') 21 | echo "$timestamp $*" | tee -a "$LOGFILE" 22 | } 23 | 24 | log "LOGFILE: $LOGFILE" 25 | log "DEBUG_MODE is set to $DEBUG_MODE" 26 | 27 | if [ "$DEBUG_MODE" == "True" ]; then 28 | export LOG_LEVEL="DEBUG" 29 | else 30 | export LOG_LEVEL="INFO" 31 | fi 32 | log "Python log level set to $LOG_LEVEL" 33 | 34 | # Check if running on GPU-instance 35 | if command -v nvidia-smi &> /dev/null && nvidia-smi > /dev/null 2>&1; then 36 | log "Running on NVIDIA GPU-instance!" 37 | pip install transformers && pip install tiktoken && pip install --upgrade scipy && pip install --upgrade networkx && pip install datasets && pip install tqdm && pip install einops && pip install "numpy<2" 38 | fi 39 | 40 | # Download pretraining data 41 | if [ ! -d "$PWD/temp_data/edu_fineweb10B" ]; then 42 | log "Downloading Pre-Training dataset." 43 | python src/data_processing/data_downloader.py 44 | log "Done downloading Pre-Training dataset." 45 | else 46 | log "Skipping downloading Pre-Training dataset." 47 | fi 48 | 49 | # Start pretraining 50 | log "Start training MyLLM." 51 | if command -v nvidia-smi &> /dev/null && nvidia-smi > /dev/null 2>&1; then 52 | GPU_COUNT=$(nvidia-smi --list-gpus | wc -l) 53 | log "Number of GPUs: $GPU_COUNT" 54 | torchrun --standalone --nproc_per_node=$GPU_COUNT pretrain.py 55 | else 56 | python pretrain.py 57 | fi 58 | log "Done training MyLLM." 59 | -------------------------------------------------------------------------------- /run_pre_training_e2e_debug.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # Set true to debug on a Mac (or any other system). This will download 5 | # a very small subset of the data and train with smaller batches for less time. 6 | # This is mainly to quckly see if the code is working e2e. 7 | export DEBUG_MODE=True 8 | 9 | ./run_pre_training_e2e.sh 10 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/src/__init__.py -------------------------------------------------------------------------------- /src/attention.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from torch.nn import functional as F 4 | from einops import rearrange 5 | 6 | from src.params import HParams 7 | from src.rope import Rope 8 | from src.model_utils.weight_init import init_linear, init_linear_res_proj 9 | 10 | 11 | class Attention(nn.Module): 12 | ''' 13 | Casual, multi-head attention module. 14 | - Using Rotary Positional Embeddings (RoPE) since it can help small models by efficiently encoding relative positions, improving contextual understanding and token relationships even in limited contexts, like 2048 tokens. 15 | - Not using Grouped Query Attention (GQA) since we're training a small language model with a small sequence length. GQA primarily enhances efficiency in large models by reducing computational complexity, but its benefits mey be limited for models under 1B parameters. 16 | - Keeping bias term in linear layers to help the small model's capacity to learn and generalize. 17 | ''' 18 | 19 | def __init__(self, hParams: HParams): 20 | super().__init__() 21 | assert hParams.n_embd % hParams.n_head == 0, 'n_embd must be divisible by n_head' 22 | self.n_embd = hParams.n_embd 23 | self.n_head = hParams.n_head 24 | self.head_dim = self.n_embd // self.n_head # Dimension per head 25 | # self.attn_pdrop = hParams.attn_pdrop 26 | self.rope = Rope(hParams) 27 | self.qkv_proj = nn.Linear(self.n_embd, 3 * self.n_embd) # Project to Q, K, V 28 | self.out_proj = nn.Linear(self.n_embd, self.n_embd) # Output projection 29 | self._reset_parameters(hParams) 30 | 31 | def _reset_parameters(self, hParams: HParams): 32 | init_linear(self.qkv_proj, hParams) 33 | init_linear_res_proj(self.out_proj, hParams) 34 | 35 | def forward(self, x): 36 | batch_size, n_ctx, embed_dim = x.size() 37 | assert embed_dim == self.n_embd, ( 38 | f'Expected embedding dimension {self.n_embd}, got {embed_dim}' 39 | ) 40 | 41 | ''' 42 | # # (batch_size, n_ctx, 3 * n_embd) 43 | # qkv = self.qkv_proj(x) 44 | 45 | # # Reshape qkv to (batch_size, n_ctx, 3, n_head, head_dim) 46 | # qkv = qkv.view(batch_size, n_ctx, 3, self.n_head, self.head_dim) 47 | 48 | # # Permute to (batch_size, n_head, n_ctx, 3, head_dim) 49 | # qkv = qkv.permute(0, 3, 1, 2, 4) 50 | # .contiguous() 51 | 52 | qkv = self.qkv_proj(x).view(batch_size, n_ctx, 3, self.n_head, self.head_dim).permute(0, 3, 1, 2, 4) 53 | ''' 54 | 55 | # (batch_size, n_ctx, 3 * n_embd) 56 | qkv = self.qkv_proj(x) 57 | qkv = rearrange(qkv, 'b t (three h d) -> b h t three d', three=3, h=self.n_head) 58 | 59 | # Shape: (batch_size, n_head, n_ctx, head_dim) 60 | xq, xk, xv = qkv.unbind(dim=3) 61 | 62 | # Apply rotary embeddings 63 | xq = self.rope.apply_rotary(xq) 64 | xk = self.rope.apply_rotary(xk) 65 | 66 | y = F.scaled_dot_product_attention( 67 | xq, 68 | xk, 69 | xv, 70 | is_causal=True, 71 | # dropout_p=self.attn_pdrop, # can lead to underfitting and training instability, specially since dropout is being in multiple other places 72 | ) 73 | 74 | # Reshape the output back to (batch_size, n_ctx, embed_dim) 75 | y = y.transpose(1, 2).reshape(batch_size, n_ctx, embed_dim) 76 | return self.out_proj(y) 77 | 78 | 79 | if __name__ == '__main__': 80 | torch.manual_seed(123) 81 | if torch.cuda.is_available(): 82 | torch.cuda.manual_seed(123) 83 | 84 | hParams = HParams( 85 | n_vocab = 0., 86 | n_ctx = 4, 87 | n_embd = 8, 88 | n_head = 2, 89 | n_layer = 6, 90 | ) 91 | 92 | batch_size, n_ctx, embed_dim = 2, hParams.n_ctx, hParams.n_embd 93 | 94 | x = torch.tensor([ 95 | [[0.0975, 0.2956, 0.9027, 0.3112, 0.9167, 0.4139, 0.4362, 0.6996], 96 | [0.4265, 0.4958, 0.8463, 0.6671, 0.4801, 0.6904, 0.9355, 0.6260], 97 | [0.3534, 0.6638, 0.4563, 0.1091, 0.3069, 0.7274, 0.5164, 0.6845], 98 | [0.2073, 0.9727, 0.2913, 0.6066, 0.2557, 0.2588, 0.7239, 0.3604]], 99 | [[0.1829, 0.2956, 0.8646, 0.8010, 0.8044, 0.0733, 0.7355, 0.6248], 100 | [0.1638, 0.5158, 0.6000, 0.2299, 0.2890, 0.9078, 0.4596, 0.4947], 101 | [0.1836, 0.2010, 0.9603, 0.6861, 0.4209, 0.8046, 0.2621, 0.0638], 102 | [0.0036, 0.7032, 0.3051, 0.8070, 0.9271, 0.6647, 0.9296, 0.3848]] 103 | ]) 104 | 105 | expected_output = torch.tensor([ 106 | [[-0.0174, 0.0117, 0.0126, -0.0265, -0.0076, 0.0299, 0.0985, -0.0651], 107 | [-0.0026, 0.0103, 0.0168, 0.0157, -0.0218, 0.0313, 0.1209, -0.0648], 108 | [-0.0013, 0.0109, 0.0216, 0.0219, -0.0142, 0.0335, 0.1194, -0.0562], 109 | [ 0.0056, 0.0029, 0.0259, 0.0323, -0.0273, 0.0316, 0.1189, -0.0548]], 110 | [[ 0.0056, -0.0153, 0.0235, 0.0127, -0.0415, 0.0129, 0.0927, -0.0704], 111 | [-0.0026, 0.0063, 0.0185, 0.0115, -0.0270, 0.0305, 0.1077, -0.0593], 112 | [-0.0095, 0.0213, 0.0043, 0.0005, -0.0368, 0.0408, 0.1136, -0.0592], 113 | [-0.0026, 0.0143, 0.0096, 0.0121, -0.0440, 0.0393, 0.1219, -0.0608]] 114 | ]) 115 | 116 | casual_self_attention = Attention(hParams) 117 | output = casual_self_attention(x) 118 | output = torch.round(output * 10000) / 10000 119 | 120 | # print(f'x shape: {x.shape}') 121 | # print(f'x: {x}') 122 | # print(f'output shape: {output.shape}') 123 | # print(f'output: {output}') 124 | 125 | if torch.equal(output, expected_output): 126 | print('alls good') 127 | else: 128 | not_equal = output != expected_output 129 | different_indices = not_equal.nonzero(as_tuple=True) 130 | for idx in zip(*different_indices): 131 | print(f"Diff at index {idx}: output = {output[idx]}, expected_output = {expected_output[idx]}") 132 | -------------------------------------------------------------------------------- /src/data_processing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/src/data_processing/__init__.py -------------------------------------------------------------------------------- /src/data_processing/data_downloader.py: -------------------------------------------------------------------------------- 1 | import os 2 | import math 3 | import multiprocessing 4 | from datasets import load_dataset, Dataset 5 | import numpy as np 6 | from tqdm import tqdm 7 | import tiktoken 8 | from src.utils.root import create_temp_data_dir 9 | import time 10 | 11 | ''' 12 | Data downloader file to download and process large datasets from HF. 13 | This code can download (in parallel), tokenize data (in parallel) and store that data 14 | into multiple shards for usage later. 15 | 16 | Right now this code is only being used for the "HuggingFaceFW/fineweb-edu" "sample-10BT" 17 | dataset (~85GB), but it can be expanded as needed. 18 | https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu 19 | ''' 20 | 21 | DEBUG_STREAMING = False # Here streaming is used just for debugging, though it's more powerful than just for that. 22 | DEBUG_ENTRY_COUNT = 0 23 | NUM_PROC = NUM_PROC_FOR_DOWNLOAD = int(0.75 * os.cpu_count()) 24 | HF_DATA_FIELD = "text" 25 | HF_DATA_PATH = "HuggingFaceFW/fineweb-edu" 26 | HF_DATA_SUBSET_NAME = "sample-10BT" 27 | HF_DATA_SPLIT = "train" 28 | SHARD_STORAGE_DIR_NAME = "edu_fineweb10B" 29 | SHARD_FILE_PREFIX = "edufineweb" 30 | CHUNK_SIZE = 16 31 | SHARDS_COUNT = 100 32 | 33 | if os.getenv('DEBUG_MODE'): 34 | # Debug args -- downloads only 200 entries from FineWeb EDU 35 | DEBUG_STREAMING = True 36 | NUM_PROC_FOR_DOWNLOAD = None # If streaming, can't use parallel downloading of dataset 37 | DEBUG_ENTRY_COUNT = 200 38 | SHARDS_COUNT = 7 39 | 40 | 41 | # Using fast BPE tokenizer tiktoken 42 | tokenizer = tiktoken.get_encoding("r50k_base") 43 | eot_token = tokenizer._special_tokens['<|endoftext|>'] 44 | def tokenize_to_uint16(data_entry): 45 | # Tokenize 46 | text = data_entry[HF_DATA_FIELD] 47 | tokens = [eot_token] 48 | tokens.extend(tokenizer.encode_ordinary(text)) 49 | tokens = np.array(tokens) 50 | # Convert tokens to np.uint16 and return 51 | assert ( 52 | (0 <= tokens).all() and (tokens < 2**16).all() 53 | ), f'Error: Token values out of expected bounds. text: {text}. tokens: {tokens}' 54 | return tokens.astype(np.uint16) 55 | 56 | 57 | if __name__ == '__main__': 58 | # Env set needed due to py-3.8 and mac-os issues 59 | os.environ['LC_ALL'] = 'en_US.UTF-8' 60 | os.environ['LANG'] = 'en_US.UTF-8' 61 | start_time = time.time() 62 | 63 | shard_storage_dir = create_temp_data_dir(SHARD_STORAGE_DIR_NAME) 64 | 65 | # Load the dataset 66 | print(f'Storing shard data in: {shard_storage_dir}. Cached in: ~/.cache/huggingface/datasets/') 67 | dataset = load_dataset( 68 | HF_DATA_PATH, 69 | name=HF_DATA_SUBSET_NAME, 70 | split=HF_DATA_SPLIT, 71 | streaming=DEBUG_STREAMING, 72 | num_proc=NUM_PROC_FOR_DOWNLOAD, 73 | ) 74 | 75 | if DEBUG_STREAMING: 76 | # Convert a streamed subset of the data into a Dataset obj, which is expected in the code below 77 | dataset_small_iterable = dataset.take(DEBUG_ENTRY_COUNT) 78 | examples = list(dataset_small_iterable) 79 | dataset = Dataset.from_list(examples) 80 | 81 | # Shuffle dataset before processing 82 | dataset = dataset.shuffle(seed=42) 83 | 84 | dataset_count = len(dataset) 85 | dataset_per_shard = math.ceil(dataset_count / SHARDS_COUNT) 86 | print(f'NUM_PROC: {NUM_PROC}') 87 | 88 | # Store every dataset_per_shard dataset group into a shard 89 | with multiprocessing.Pool(processes=NUM_PROC) as pool: 90 | token_sets = [] 91 | shard_idx = 0 92 | datasets_processed = 0 93 | with tqdm(total=dataset_count, desc="Processing dataset", unit="entry") as pbar: 94 | 95 | for chunk_results in pool.imap(tokenize_to_uint16, dataset, chunksize=CHUNK_SIZE): 96 | token_sets.append(chunk_results) 97 | datasets_processed += 1 98 | pbar.update(1) 99 | 100 | if len(token_sets) >= dataset_per_shard or datasets_processed == dataset_count: 101 | shard_tokens = np.concatenate(token_sets[:dataset_per_shard]) 102 | token_sets = token_sets[dataset_per_shard:] 103 | file_path = os.path.join( 104 | shard_storage_dir, 105 | f"{SHARD_FILE_PREFIX}_i_{shard_idx:06d}_t_{len(shard_tokens)}.npy" 106 | ) 107 | np.save(file_path, shard_tokens) 108 | shard_idx += 1 109 | 110 | print(f'datasets_processed: {datasets_processed}') 111 | 112 | elapsed_time_secs = time.time() - start_time 113 | elapsed_time_mins = elapsed_time_secs / 60 114 | print(f"Time to download and process {SHARD_FILE_PREFIX} dataset: {elapsed_time_secs:.2f} seconds") 115 | print(f"({elapsed_time_mins:.2f} minutes)") 116 | 117 | ''' On mac, with 200 entries only and ending with 5 shards: 118 | Time to download edufineweb dataset: 20.03 seconds 119 | Or time to download: 0.33 minutes 120 | ''' 121 | ''' On gpu_8x_a100_80gb_sxm4, full dataset 122 | Time to download and process edufineweb dataset: 2221.01 seconds 123 | (37.02 minutes). 124 | Each shard has around 99,700,000 tokens 125 | ''' 126 | -------------------------------------------------------------------------------- /src/data_processing/training_data_loader.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import logging 4 | import torch 5 | import numpy as np 6 | from dataclasses import dataclass 7 | from collections import OrderedDict 8 | 9 | from src.utils.rand_idx_seq_gen import RandIdxSeqGen 10 | 11 | 12 | log = logging.getLogger(__name__) 13 | 14 | SHARD_RE_PATTERN = re.compile(r"_i_(\d+)_t_(\d+)\.npy") 15 | SHARD_RND_SEED_BASE = 42 16 | SAMPLE_RND_SEED_BASE = 42 17 | 18 | 19 | @dataclass 20 | class Shard: 21 | abs_path: str 22 | token_count: int 23 | 24 | 25 | class TrainingDataLoader: 26 | ''' 27 | This class will be in charge of loading data from disk into memory while 28 | training. It'll have the ability to work with various shards of training data, 29 | account for multi-GPU training and perform batched sequence-level random selection. 30 | 31 | Note this uses a seed for reproducibility. 32 | ''' 33 | 34 | 35 | def __init__(self, ddp, dataset_dir: str, batch_count: int, tokens_per_batch: int): 36 | self.ddp = ddp 37 | self.rank = ddp.local_rank 38 | self.world_size = ddp.world_size 39 | self.curr_batch_count = batch_count 40 | self.curr_tokens_per_batch = tokens_per_batch 41 | self.rnd_sample_idx_gen = None 42 | 43 | # Store one validation shard 44 | self.curr_val_idx = 0 45 | self.val_shard = None 46 | # Store training shards, keys will be 0 to dict length - 1. 47 | # All ranks will have the same key to shard mapping. 48 | self.train_shards = OrderedDict() 49 | 50 | # Load dataset 51 | 52 | self.dataset_dir = dataset_dir 53 | 54 | assert ( 55 | os.path.isdir(self.dataset_dir) 56 | and len(os.listdir(self.dataset_dir)) >= 2 # At least 1 val and 1 train shard 57 | ), f'Error loading dataset. dataset_dir: {self.dataset_dir}, proc_rank: {self.rank}, world_size: {self.world_size}' 58 | 59 | if self.rank == 0: print(f'Loading dataset from {self.dataset_dir}') 60 | 61 | # Setup train and val splits 62 | 63 | self._setup_splits() 64 | 65 | # Create random key generator for `train_shards` dict 66 | self.train_shrds_rnd_key_gen = RandIdxSeqGen( 67 | ddp = self.ddp, 68 | seqLen=len(self.train_shards), 69 | rank=self.rank, 70 | world_size=self.world_size, 71 | rnd_seed=SHARD_RND_SEED_BASE, 72 | ) 73 | 74 | # print(f'DEBUG: B rank: {self.rank}. rnd idx order: {self.train_shrds_rnd_key_gen.rnd_ordered_idx}') 75 | 76 | # Setup training shard to use first 77 | self._setup_training_shard() 78 | 79 | def get_train_samples(self, batch_count, tokens_per_batch): 80 | 81 | did_update_sampling_len = False 82 | 83 | if self.rnd_sample_idx_gen is None: 84 | # Setup rnd_sample_idx_gen for the first time 85 | self._setup_sampling_rnd_idx_gen(batch_count, tokens_per_batch) 86 | did_update_sampling_len = True 87 | 88 | start_idx = self.rnd_sample_idx_gen.next() 89 | 90 | if start_idx is None: 91 | # We've exhausted all training samples from this shard, go to next shard 92 | self._setup_training_shard() 93 | self._setup_sampling_rnd_idx_gen(batch_count, tokens_per_batch) 94 | did_update_sampling_len = True 95 | start_idx = self.rnd_sample_idx_gen.next() 96 | 97 | if ( 98 | not did_update_sampling_len 99 | and ( 100 | self.curr_batch_count != batch_count 101 | or self.curr_tokens_per_batch != tokens_per_batch 102 | ) 103 | and self.rank == 0 104 | ): 105 | print( 106 | f'''WARN: (rank-{self.rank}) Attempting to change batch_count ({batch_count}) and tokens_per_batch ''' 107 | f'''({tokens_per_batch}) in the middle of iterating through a batch. \n''' 108 | f'''Change will be allowed once new shard is loaded. \n''' 109 | f'''self.curr_batch_count: {self.curr_batch_count}, self.curr_tokens_per_batch: {self.curr_tokens_per_batch}''' 110 | ) 111 | 112 | return self._get_batched_tokens(start_idx, self.curr_train_tokens) 113 | 114 | def _get_batched_tokens(self, start_idx, tokens): 115 | tokens_per_rank = self.curr_batch_count * self.curr_tokens_per_batch 116 | start_idx_offset = start_idx * (self.world_size * tokens_per_rank) 117 | rank_idx_offset = self.rank * tokens_per_rank 118 | start_idx = start_idx_offset + rank_idx_offset 119 | end_idx = start_idx + tokens_per_rank + 1 120 | 121 | batch = tokens[start_idx: end_idx] 122 | inputs = (batch[:-1]).view(self.curr_batch_count, self.curr_tokens_per_batch) 123 | targets = (batch[1:]).view(self.curr_batch_count, self.curr_tokens_per_batch) 124 | 125 | inputs = inputs.to(self.ddp.assigned_device) 126 | targets = targets.to(self.ddp.assigned_device) 127 | return inputs, targets 128 | 129 | def reset_validation(self): 130 | self.curr_val_idx = 0 131 | 132 | def get_val_samples(self): 133 | sample_window = self.world_size * self.curr_batch_count * self.curr_tokens_per_batch + 1 134 | if ((self.curr_val_idx + 1) * sample_window) >= len(self.val_shard): 135 | # Amount of tokens needed does not fit in tokens left 136 | self.reset_validation() 137 | inputs, targets = self._get_batched_tokens(self.curr_val_idx, self.val_shard) 138 | self.curr_val_idx += 1 139 | return inputs, targets 140 | 141 | def _setup_sampling_rnd_idx_gen(self, batch_count, tokens_per_batch): 142 | self.curr_batch_count = batch_count 143 | self.curr_tokens_per_batch = tokens_per_batch 144 | sample_window_size = self.world_size * self.curr_batch_count * self.curr_tokens_per_batch 145 | 146 | seq_len = int(len(self.curr_train_tokens) / sample_window_size) 147 | 148 | # print(f'DEBUG: seq_len: {seq_len} | len-curr_train_tokens: {len(self.curr_train_tokens)} | sample_window_size: {sample_window_size}') 149 | 150 | if len(self.curr_train_tokens) % sample_window_size == 0: 151 | # There won't be enough tokens for the target tensors, since targe tensor 152 | # is always offset ahead by 1 token. 153 | seq_len -= 1 154 | 155 | if self.rnd_sample_idx_gen is None: 156 | self.rnd_sample_idx_gen = RandIdxSeqGen( 157 | ddp = self.ddp, 158 | seqLen=seq_len, 159 | rank=self.rank, 160 | world_size=self.world_size, 161 | rnd_seed=SAMPLE_RND_SEED_BASE, 162 | ) 163 | else: 164 | self.rnd_sample_idx_gen.reset(seq_len) 165 | 166 | # print(f'DEBUG: rnd_sample_idx_gen order: {self.rnd_sample_idx_gen.rnd_ordered_idx}') 167 | 168 | def _setup_splits(self): 169 | ''' 170 | Setup `self.val_shard`, `self.train_shards`, and self.rand_train_shards_order. 171 | For now, `self.val_shard` will hold only the first shard in the dataset, 172 | all the other shards will be held in `self.train_shards`. 173 | Note that the value of `self.val_shard` will never change. 174 | ''' 175 | 176 | # Setup self.val_shard and self.train_shards 177 | for file_name in os.listdir(self.dataset_dir): 178 | match = SHARD_RE_PATTERN.search(file_name) 179 | assert match, f'Filename {file_name} does not match the expected pattern' 180 | 181 | idx = int(match.group(1)) 182 | token_count = int(match.group(2)) 183 | file_path = os.path.join(self.dataset_dir, file_name) 184 | shard = Shard(file_path, token_count) 185 | 186 | if idx == 0: 187 | # Set validation Shard 188 | self.val_shard = self._load_np_arr(file_path) 189 | else: 190 | # Set all training Shards 191 | self.train_shards[idx-1] = shard 192 | 193 | def _setup_training_shard(self): 194 | ''' 195 | Figure out which training shard to use. 196 | If all have been used, reshuffle their order for the next epoch. 197 | ''' 198 | 199 | next_shrd_key = self.train_shrds_rnd_key_gen.next() 200 | 201 | if next_shrd_key is None: 202 | # One epoch of data has been completed 203 | if self.ddp.is_main: 204 | log.info('Entire training dataset has been seen, will shuffle and iterate through it again.') 205 | self.train_shrds_rnd_key_gen.reset(len(self.train_shards)) 206 | next_shrd_key = self.train_shrds_rnd_key_gen.next() 207 | # print(f'DEBUG: train_shrds_rnd_key_gen order: {self.train_shrds_rnd_key_gen.rnd_ordered_idx}') 208 | 209 | shard_file_path = self.train_shards[next_shrd_key].abs_path 210 | self.curr_train_tokens = self._load_np_arr(shard_file_path) 211 | 212 | if self.ddp.is_main: 213 | log.info(f'Next shard key to use: {next_shrd_key}. shard_file_path: {shard_file_path}') 214 | 215 | def _load_np_arr(self, npy_path): 216 | tokens = np.load(npy_path) 217 | tokens = tokens.astype(np.int32) 218 | return torch.tensor(tokens, dtype=torch.long) 219 | -------------------------------------------------------------------------------- /src/ffn.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | from src.params import HParams 5 | from src.model_utils.weight_init import init_linear, init_linear_res_proj 6 | 7 | 8 | HIDDEN_EMBD_SCALE = 4 9 | TWO_FOR_ONE = 2 # Use one linear layer to calculate the output needed from two linear layers 10 | 11 | 12 | class SwiGLU(nn.Module): 13 | def __init__(self): 14 | super().__init__() 15 | self.silu = nn.SiLU() 16 | 17 | def forward(self, x): 18 | x1, x2 = x.chunk(TWO_FOR_ONE, dim=-1) 19 | return x1 * self.silu(x2) 20 | 21 | 22 | class FFN(nn.Module): 23 | ''' 24 | Feed-forward neural network. Part of the transformer block, this will perform a 25 | non-linear transformation to capture complex patterns from the attention mechanism. 26 | - Keeping bias term in linear layers to help the small model's capacity to learn and generalize. 27 | - Using dropout to avoid overfitting in this large parameter space of this small model. Let's 28 | force the network to learn redundant representations, which should improve its 29 | generalization capabilities 30 | ''' 31 | 32 | def __init__(self, hParams: HParams): 33 | super().__init__() 34 | 35 | self.net = nn.Sequential( 36 | nn.Linear(hParams.n_embd, TWO_FOR_ONE * HIDDEN_EMBD_SCALE * hParams.n_embd), 37 | SwiGLU(), 38 | nn.Dropout(hParams.ffn_act_pdrop), 39 | nn.Linear(HIDDEN_EMBD_SCALE * hParams.n_embd, hParams.n_embd), 40 | ) 41 | self.reset_parameters(hParams) 42 | 43 | def reset_parameters(self, hParams: HParams): 44 | init_linear(self.net[0], hParams) 45 | init_linear_res_proj(self.net[-1], hParams) 46 | 47 | def forward(self, x): 48 | ''' 49 | x and output: (batch_size, n_ctx, n_embd) 50 | ''' 51 | return self.net(x) 52 | 53 | 54 | if __name__ == '__main__': 55 | torch.manual_seed(123) 56 | if torch.cuda.is_available(): 57 | torch.cuda.manual_seed(123) 58 | 59 | hParams = HParams( 60 | n_vocab = 0., 61 | n_ctx = 4, 62 | n_embd = 8, 63 | n_head = 2, 64 | n_layer = 6, 65 | ffn_act_pdrop = 0.1, 66 | ) 67 | 68 | batch_size, n_ctx, embed_dim = 2, hParams.n_ctx, hParams.n_embd 69 | 70 | x = torch.tensor([ 71 | [[0.0975, 0.2956, 0.9027, 0.3112, 0.9167, 0.4139, 0.4362, 0.6996], 72 | [0.4265, 0.4958, 0.8463, 0.6671, 0.4801, 0.6904, 0.9355, 0.6260], 73 | [0.3534, 0.6638, 0.4563, 0.1091, 0.3069, 0.7274, 0.5164, 0.6845], 74 | [0.2073, 0.9727, 0.2913, 0.6066, 0.2557, 0.2588, 0.7239, 0.3604]], 75 | [[0.1829, 0.2956, 0.8646, 0.8010, 0.8044, 0.0733, 0.7355, 0.6248], 76 | [0.1638, 0.5158, 0.6000, 0.2299, 0.2890, 0.9078, 0.4596, 0.4947], 77 | [0.1836, 0.2010, 0.9603, 0.6861, 0.4209, 0.8046, 0.2621, 0.0638], 78 | [0.0036, 0.7032, 0.3051, 0.8070, 0.9271, 0.6647, 0.9296, 0.3848]] 79 | ]) 80 | 81 | expected_output = torch.tensor([ 82 | [[ 0.0031, 0.0024, 0.0400, 0.0311, 0.0209, 0.0057, -0.0173, -0.0096], 83 | [-0.0224, -0.0248, 0.0107, 0.0238, -0.0034, 0.0012, -0.0131, -0.0165], 84 | [-0.0076, -0.0107, 0.0237, 0.0059, 0.0057, 0.0005, -0.0060, -0.0131], 85 | [-0.0216, -0.0077, -0.0132, 0.0093, 0.0035, 0.0114, 0.0076, -0.0013]], 86 | [[-0.0140, 0.0252, 0.0317, 0.0114, 0.0021, 0.0078, 0.0011, -0.0034], 87 | [ 0.0008, -0.0164, 0.0071, 0.0168, 0.0116, -0.0020, -0.0088, -0.0031], 88 | [-0.0047, -0.0136, -0.0043, 0.0080, -0.0085, -0.0126, -0.0115, 0.0066], 89 | [-0.0292, -0.0165, 0.0083, 0.0125, 0.0137, 0.0162, 0.0123, -0.0131]]]) 90 | 91 | ffn = FFN(hParams) 92 | # from utils.debugging import get_stats 93 | # get_stats(ffn.net[0].weight.data) 94 | # get_stats(ffn.net[3].weight.data) 95 | output = ffn(x) 96 | output = torch.round(output * 10000) / 10000 97 | 98 | # print(f'output: {output}') 99 | 100 | if torch.equal(output, expected_output): 101 | print('alls good') 102 | else: 103 | not_equal = output != expected_output 104 | different_indices = not_equal.nonzero(as_tuple=True) 105 | for idx in zip(*different_indices): 106 | print(f"Diff at index {idx}: output = {output[idx]}, expected_output = {expected_output[idx]}") 107 | -------------------------------------------------------------------------------- /src/global_cache.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | import torch 3 | 4 | 5 | class GlobalCache(Dict[str, torch.Tensor]): 6 | ''' 7 | Share repeated, pre-computed data across modules. 8 | ''' 9 | pass 10 | 11 | 12 | global_cache = GlobalCache() 13 | -------------------------------------------------------------------------------- /src/model.py: -------------------------------------------------------------------------------- 1 | from typing import Optional, Tuple 2 | import torch 3 | import torch.nn as nn 4 | from torch.nn import functional as F 5 | 6 | from src.params import HParams 7 | from src.transformer_block import TransformerBlock 8 | from src.model_utils.weight_init import init_embedding 9 | 10 | 11 | class LLM(nn.Module): 12 | 13 | def __init__(self, hParams: HParams): 14 | ''' 15 | Standard LLM structure, borrowing from GPT-2/3 and newer Llama models 16 | (also seen in models like MolmoE 1B). 17 | ''' 18 | super().__init__() 19 | self.hParams = hParams 20 | self.embd = nn.Embedding(hParams.n_vocab, hParams.n_embd) 21 | # Avoiding dropout here for now since it may lead to information loss (e.g. it 22 | # would mess with RoPE), and affect training stability since it's so early in the network. 23 | # self.embd_dropout = nn.Dropout(hParams.embd_pdrop) 24 | self.transformer_blocks = nn.Sequential( 25 | *[TransformerBlock(hParams) for _ in range(hParams.n_layer)] 26 | ) 27 | self.norm = nn.RMSNorm(hParams.n_embd, eps=1e-5) 28 | self.out_proj = nn.Linear(hParams.n_embd, hParams.n_vocab, bias=False) 29 | self.embd.weight = self.out_proj.weight 30 | self.reset_parameters(hParams) 31 | 32 | def reset_parameters(self, hParams: HParams): 33 | init_embedding(self.embd, hParams) 34 | 35 | def forward( 36 | self, x: torch.Tensor, y: torch.Tensor = None 37 | ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: 38 | 39 | batch_size, n_ctx = x.size() 40 | 41 | assert n_ctx <= self.hParams.n_ctx, f"Input context length {n_ctx} exceeds maximum {self.hParams.n_ctx}" 42 | 43 | ''' 44 | Create high-dimensional embedding of input, pass through the transformer blocks, 45 | apply efficient post-normalization, and lastly project into logits using weight 46 | sharing of the last layer. 47 | ''' 48 | x = self.embd(x) 49 | # x = self.embd_dropout(x) 50 | x = self.transformer_blocks(x) 51 | x = self.norm(x) 52 | logits = self.out_proj(x) 53 | 54 | loss = None 55 | if y is not None: 56 | # Get loss if expected target value y is provided 57 | # Reordering logits and y to work with cross_entropy 58 | tot_tokens = batch_size * n_ctx 59 | loss = F.cross_entropy( 60 | logits.view(tot_tokens, -1), 61 | y.view(tot_tokens) 62 | ) 63 | 64 | return logits, loss 65 | 66 | 67 | if __name__ == '__main__': 68 | torch.manual_seed(123) 69 | if torch.cuda.is_available(): 70 | torch.cuda.manual_seed(123) 71 | 72 | x = torch.tensor([ 73 | [2, 3, 3, 1, 3], # mock input sequence 74 | [2, 1, 3, 2, 0], 75 | ]) 76 | y = torch.tensor([ 77 | [3, 3, 1, 3, 0], # mock next tokens 78 | [1, 3, 2, 0, 1], 79 | ]) 80 | batch_size, n_ctx = x.shape 81 | 82 | hParams = HParams( 83 | n_vocab = torch.max(x) + 1, 84 | n_ctx = n_ctx, 85 | n_embd = 4, 86 | n_head = 2, 87 | n_layer = 2, 88 | ffn_act_pdrop = 0.1, 89 | ) 90 | 91 | expected_output = torch.tensor([ 92 | [[ 0.0643, 0.1504, 1.5457, -0.3968], 93 | [ 0.2599, 0.5008, 0.1130, 1.2352], 94 | [ 0.1778, 0.3794, 0.0348, 1.2232], 95 | [-0.1258, 1.1608, -0.3776, 0.7196], 96 | [ 0.0292, 0.2619, -0.3227, 1.1662]], 97 | [[ 0.0333, 0.1185, 1.5608, -0.3510], 98 | [-0.0135, 1.3279, -0.2422, 0.6294], 99 | [ 0.1876, 0.3131, -0.0958, 1.2011], 100 | [-0.0848, 0.2016, 1.4463, -0.3105], 101 | [ 0.1845, 0.6925, -0.4936, -0.5954]] 102 | ]) 103 | 104 | model = LLM(hParams) 105 | output, _ = model(x) 106 | output = torch.round(output * 10000) / 10000 107 | # print(f'output: {output}') 108 | 109 | if torch.equal(output, expected_output): 110 | print('Got expected output!') 111 | else: 112 | not_equal = output != expected_output 113 | different_indices = not_equal.nonzero(as_tuple=True) 114 | for idx in zip(*different_indices): 115 | print(f"Diff at index {idx}: output = {output[idx]}, expected_output = {expected_output[idx]}") 116 | 117 | output, loss = model(x, y) 118 | expected_loss = 1.576537 119 | output = torch.round(output * 10000) / 10000 120 | loss = loss.item() 121 | # print(f'loss: {(loss)}') 122 | 123 | if round(loss, 6) == expected_loss: 124 | print('Got expected loss!') 125 | else: 126 | print(f'Error, {round(loss, 5)} != {expected_loss}') 127 | -------------------------------------------------------------------------------- /src/model_assessment/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/src/model_assessment/__init__.py -------------------------------------------------------------------------------- /src/model_assessment/hellaswag.py: -------------------------------------------------------------------------------- 1 | # import os 2 | import logging 3 | 4 | import tiktoken 5 | from datasets import load_dataset 6 | import torch 7 | import torch.nn.functional as F 8 | import torch.distributed as dist 9 | from torch.nn.utils.rnn import pad_sequence 10 | 11 | 12 | from src.utils.root import create_temp_data_dir 13 | 14 | 15 | log = logging.getLogger(__name__) 16 | 17 | EVAL_DIR = "eval" 18 | HELLASWAG_KEY = "hellaswag" 19 | # NUM_PROC_FOR_DOWNLOAD = int(0.75 * os.cpu_count()) 20 | 21 | 22 | class HellaSwag: 23 | ''' 24 | Class to encapsulate loading HellaSwag validation dataset and 25 | running evaluation on MyLLM. 26 | 27 | Got the idea from Karpathy's evaluation of build-nanogpt, but prefer the implementation 28 | from Tenstorrent's Benchmarking, though my implementation is a bit more straightforward since 29 | I'm only doing HellaSwag eval. 30 | 31 | https://github.com/tenstorrent/benchmarking/blob/main/benchmark/models/falcon/falcon.py#L170 32 | https://github.com/karpathy/build-nanogpt/blob/master/hellaswag.py 33 | ''' 34 | 35 | def __init__(self, model, tParams, ddp): 36 | self.ddp = ddp 37 | self.model = model 38 | self.tokenizer = tiktoken.get_encoding("r50k_base") 39 | 40 | val_set_key = tParams.eval_hs_subset_key 41 | eval_dir = create_temp_data_dir(EVAL_DIR) 42 | 43 | # Only one worker should download data, all other workers should wait 44 | if self.ddp.is_main: 45 | # TODO: Store tokenized data on disk 46 | load_dataset( 47 | HELLASWAG_KEY, 48 | split=val_set_key, 49 | cache_dir=eval_dir, 50 | trust_remote_code=True, 51 | # num_proc=NUM_PROC_FOR_DOWNLOAD, # "validation" only contains 1 shard, not needed 52 | ) 53 | self.ddp.barrier() 54 | 55 | # Load from disk and shard 56 | self.eval_dataset = load_dataset( 57 | HELLASWAG_KEY, 58 | split=val_set_key, 59 | cache_dir=eval_dir, 60 | trust_remote_code=True, 61 | ).shard( 62 | num_shards=self.ddp.world_size, 63 | index=self.ddp.local_rank, 64 | ) 65 | 66 | log.info(f'Rank: {self.ddp.local_rank}. HellaSwag dataset size: {len(self.eval_dataset)}.') 67 | 68 | def run_eval(self, step): 69 | self.model.eval() 70 | self._run_eval(step) 71 | self.model.train() 72 | 73 | def _run_eval(self, step): 74 | total_correct = 0 75 | total_examples = 0 76 | 77 | for example in self.eval_dataset: 78 | context = example["ctx"] 79 | endings = example["endings"] 80 | label = int(example["label"]) 81 | context_ids = self.tokenizer.encode(context) 82 | context_len = len(context_ids) 83 | input_ids = [] 84 | ending_masks = [] 85 | 86 | for ending in endings: 87 | ending_ids = self.tokenizer.encode(f" {ending}") 88 | sample_ids = context_ids + ending_ids 89 | input_ids.append(torch.tensor(sample_ids)) 90 | ending_masks.append( 91 | torch.ones(len(ending_ids), dtype = torch.int) 92 | ) 93 | 94 | # Pad input_ids and ending_masks 95 | input_ids = pad_sequence(input_ids, batch_first=True, padding_value=0) 96 | input_ids = input_ids.to(self.ddp.assigned_device) 97 | ending_masks = pad_sequence(ending_masks, batch_first=True, padding_value=0) 98 | ending_masks = ending_masks.to(self.ddp.assigned_device) 99 | 100 | with torch.no_grad(): 101 | with torch.autocast(device_type=self.ddp.device_type, dtype=torch.bfloat16): 102 | #TODO: Batch more samples at once 103 | logits, _ = self.model(input_ids) 104 | 105 | # Get logits that belong to the generated 'end' only, and align with corresponding class labels 106 | logits = logits[:, (context_len-1):-1, :] 107 | labels = input_ids[:, context_len:] 108 | 109 | # Grab the log-probabilities of the target tokens (labels) 110 | log_probs = F.log_softmax(logits, dim=-1) 111 | labels = labels.unsqueeze(-1) 112 | targets_log_prob = torch.gather(log_probs, dim=-1, index=labels).squeeze(-1) 113 | targets_log_prob = targets_log_prob * ending_masks.float() 114 | 115 | # Select gen ending with the highest average log-likelihood 116 | avg_targets_log_prob = targets_log_prob.sum(dim=-1) / ending_masks.sum(dim=-1) 117 | predicted_label = torch.argmax(avg_targets_log_prob).item() 118 | 119 | if predicted_label == label: 120 | total_correct += 1 121 | total_examples += 1 122 | 123 | if self.ddp.is_avail: 124 | total_correct = torch.tensor(total_correct, device=self.ddp.assigned_device) 125 | total_examples = torch.tensor(total_examples, device=self.ddp.assigned_device) 126 | dist.all_reduce(total_correct, op=dist.ReduceOp.SUM) 127 | dist.all_reduce(total_examples, op=dist.ReduceOp.SUM) 128 | total_correct = total_correct.item() 129 | total_examples = total_examples.item() 130 | accuracy = total_correct / total_examples 131 | 132 | if self.ddp.is_main: 133 | log.info(f"Step ({step}). HellaSwag Evaluation Accuracy: {total_correct}/{total_examples} = {accuracy * 100:.2f}%") 134 | -------------------------------------------------------------------------------- /src/model_assessment/hf_sampling.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import fields 3 | 4 | from huggingface_hub import hf_hub_download 5 | 6 | from src.model import LLM 7 | from src.params import TParams 8 | from src.utils.handle_ddp import DDPHandler 9 | from src.utils.root import create_temp_data_dir 10 | from src.model_assessment.sampling import sample 11 | from src.model_configs.my_llm_config import get_llm_config 12 | from src.model_utils.checkpoint_utils import load_checkpoint 13 | 14 | 15 | log = logging.getLogger(__name__) 16 | HF_MODEL_DIR = "hf_model" 17 | REPO_ID = "LF-Luis/LF_LLM-269M" 18 | MODEL_NAME = "pytorch_model.pth" 19 | 20 | 21 | def download_model(): 22 | ''' 23 | Download model from Hugging Face. 24 | ''' 25 | model_dir = create_temp_data_dir(HF_MODEL_DIR) 26 | model_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_NAME, cache_dir=model_dir) 27 | log.info(f"Model downloaded to: {model_path}") 28 | return model_path 29 | 30 | def get_hf_model(ddp): 31 | model_path = download_model() 32 | 33 | hParams, _ = get_llm_config() 34 | model = LLM(hParams) 35 | load_checkpoint( 36 | model, 37 | optimizer=None, 38 | scheduler=None, 39 | filepath=model_path, 40 | load_random_state=False 41 | ) 42 | model.to(ddp.assigned_device) 43 | return model 44 | 45 | def hf_sample(model, ddp, tParams, prompt): 46 | sample(model, ddp, prompt, tParams) 47 | 48 | 49 | if __name__ == "__main__": 50 | logging.basicConfig(level=logging.INFO) 51 | 52 | tParams = TParams(**{f.name: None for f in fields(TParams)}) 53 | tParams.sampling_tokens = 5 54 | tParams.sampling_batch = 2 55 | tParams.sampling_top_k = 50 56 | 57 | ddp = DDPHandler() 58 | model = get_hf_model(ddp) 59 | hf_sample(model, ddp, tParams, "Let's talk about Rome, Rome is") 60 | -------------------------------------------------------------------------------- /src/model_assessment/sampling.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import torch 4 | import tiktoken 5 | 6 | 7 | log = logging.getLogger(__name__) 8 | TOKENIZER = tiktoken.get_encoding("r50k_base") 9 | 10 | 11 | def sample(model, ddp, prompt, tParams): 12 | ''' 13 | Sample single 'prompt' multiple times. 14 | ''' 15 | model.eval() 16 | _sample(model, ddp, prompt, tParams) 17 | model.train() 18 | 19 | 20 | def multi_sample(model, ddp, prompts, tParams): 21 | ''' 22 | Sample multiple 'prompts' multiple times. 23 | ''' 24 | model.eval() 25 | prompt_shard = [val for val in prompts[ddp.local_rank::ddp.world_size]] 26 | for prompt in prompt_shard: 27 | _sample(model, ddp, prompt, tParams) 28 | model.train() 29 | 30 | 31 | def _sample(model, ddp, prompt, tParams): 32 | ''' 33 | Sample 'model' to text-complete 'prompt'. This will be done 'batch_size' number 34 | of times. Not going to search for EOT token, just stop at 'sampling_tokens' number of tokens. 35 | 36 | Using top-k sampling. 37 | 38 | #TODO: Add temperature. 39 | #TODO: Add top-p sampling following top-k. 40 | ''' 41 | 42 | sampling_tokens = tParams.sampling_tokens 43 | batch_size = tParams.sampling_batch 44 | top_k = tParams.sampling_top_k 45 | 46 | input_ids = TOKENIZER.encode(prompt) 47 | sequence = torch.tensor([input_ids] * batch_size, device=ddp.assigned_device) 48 | 49 | with torch.no_grad(): 50 | for _ in range(sampling_tokens): 51 | with torch.autocast(device_type=ddp.device_type, dtype=torch.bfloat16): 52 | last_tokens_logits = model(sequence)[0][:, -1, :] 53 | 54 | # Sample only from top-k probabilities 55 | top_k_logits, top_k_indices = torch.topk(last_tokens_logits, top_k, dim=-1) 56 | probs = torch.nn.functional.softmax(top_k_logits, dim=-1) 57 | sampled_indices = torch.multinomial(probs, num_samples=1) 58 | 59 | next_tokens = top_k_indices.gather(-1, sampled_indices) 60 | sequence = torch.cat([sequence, next_tokens], dim=-1) 61 | 62 | # Decode and log generated text 63 | for output in sequence: 64 | decoded_text = TOKENIZER.decode(output.tolist()) 65 | log.info(decoded_text) 66 | -------------------------------------------------------------------------------- /src/model_assessment/validation.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import torch 4 | import torch.distributed as dist 5 | 6 | 7 | log = logging.getLogger(__name__) 8 | 9 | class Validation: 10 | ''' 11 | Module to test validation data set as the model is learning. 12 | Will test over the same dataset every time. 13 | ''' 14 | 15 | def __init__(self, model, data_loader, tParams, ddp): 16 | self.model = model 17 | self.data_loader = data_loader 18 | self.ddp = ddp 19 | self.validation_steps = tParams.validation_steps 20 | 21 | def run_validation(self, step): 22 | ''' 23 | Returns validation loss 24 | ''' 25 | self.model.eval() 26 | self.data_loader.reset_validation() 27 | 28 | val_loss = 0.0 29 | 30 | with torch.no_grad(): 31 | for _ in range(self.validation_steps): 32 | input, output = self.data_loader.get_val_samples() 33 | with torch.autocast(device_type=self.ddp.device_type, dtype=torch.bfloat16): 34 | _, loss = self.model(input, output) 35 | val_loss += loss.detach() 36 | 37 | if self.ddp.is_avail: 38 | # Reduce loss across all processes 39 | dist.all_reduce(val_loss, op=dist.ReduceOp.AVG) 40 | 41 | self.model.train() 42 | 43 | # Average over validation steps 44 | val_loss = val_loss / self.validation_steps 45 | 46 | if self.ddp.is_main: 47 | log.info(f'Step ({step}). Val Loss: {val_loss.item():.4f}') 48 | -------------------------------------------------------------------------------- /src/model_configs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/src/model_configs/__init__.py -------------------------------------------------------------------------------- /src/model_configs/my_llm_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from src.params import HParams, TParams 4 | 5 | 6 | def get_pre_train_sampling_prompts(): 7 | if os.getenv('DEBUG_MODE'): 8 | return [ 9 | "Test", 10 | "Test two", 11 | "Test number three,", 12 | ] 13 | else: 14 | return [ 15 | "HTML stands for", 16 | "If animals could talk, my pet would probably say", 17 | "The clever fox built the strange machine with just a feather, a pebble, and a tiny twig", 18 | ] 19 | 20 | 21 | def get_llm_config(): 22 | if os.getenv('DEBUG_MODE'): 23 | return _get_debug_config() 24 | else: 25 | return _get_production_config() 26 | 27 | 28 | def _get_production_config(): 29 | ''' 30 | Actual model and training values!! 31 | ''' 32 | 33 | # Looking at common trends from assets/some_open_source_models.png to help select n_ctx, n_head and n_layer 34 | hParams = HParams( 35 | n_vocab = 50_257, 36 | n_ctx = 2_048, 37 | n_embd = 1_024, 38 | n_head = 16, 39 | n_layer = 16, 40 | ffn_act_pdrop = 0.15, # Slightly larger dropout due to larger hidden space 41 | attn_res_pdrop = 0.1, 42 | ) 43 | 44 | # See `notebooks/parameters_tuning.ipynb` to see how I came up with my guessed 1.19e-02 ratio and max_lr = 0.0021 45 | tot_train_tokens = 10e9 # Training on 10BT 46 | batch_token_count = 524_288 47 | linear_warm_up_tokens = int(1.19e-02 * tot_train_tokens) 48 | linear_warm_up_steps = int(linear_warm_up_tokens / batch_token_count) 49 | total_training_steps = int(tot_train_tokens / batch_token_count) 50 | 51 | tParams = TParams( 52 | tot_steps = total_training_steps, 53 | grad_acc_steps = 2, 54 | warm_up_steps = linear_warm_up_steps, 55 | batch_token_count = batch_token_count, 56 | max_lr = 0.0021, 57 | min_lr_ratio = 0.1, 58 | adam_beta_1 = 0.9, 59 | adam_beta_2 = 0.95, 60 | adam_eps = 1e-8, 61 | clip_grad_max_norm = 1.0, 62 | weight_decay_rate = 0.1, 63 | logging_interval = 50, 64 | checkpointing_steps = set( 65 | list( 66 | range(0, total_training_steps, int(total_training_steps * 0.2)) 67 | )[:-1] # Excluding last since it's very near the actual last step 68 | ), 69 | validation_interval = 100, 70 | validation_steps = 30, 71 | sampling_interval = 500, 72 | sampling_batch = 4, 73 | sampling_tokens = 20, 74 | sampling_top_k = 50, # Moderate, fairly default value to start with 75 | eval_interval = 500, 76 | eval_hs_subset_key = "validation", 77 | ) 78 | 79 | return hParams, tParams 80 | 81 | 82 | def _get_debug_config(): 83 | ''' 84 | Debug model and training values!! 85 | ''' 86 | 87 | hParams = HParams( 88 | n_vocab = 50257, 89 | n_ctx = 32, 90 | n_embd = 4, 91 | n_head = 2, 92 | n_layer = 1, 93 | ffn_act_pdrop = 0.15, 94 | attn_res_pdrop = 0.1, 95 | ) 96 | tot_train_tokens = 600 97 | batch_token_count = 64 98 | linear_warm_up_tokens = 2 * 64 # int(1.19e-02 * tot_train_tokens) # 2 warm-up steps 99 | linear_warm_up_steps = int(linear_warm_up_tokens / batch_token_count) 100 | total_training_steps = int(tot_train_tokens / batch_token_count) # 9 total steps 101 | tParams = TParams( 102 | tot_steps = total_training_steps, 103 | grad_acc_steps = 2, 104 | warm_up_steps = linear_warm_up_steps, 105 | batch_token_count = batch_token_count, 106 | max_lr = 0.0021, 107 | min_lr_ratio = 0.1, 108 | adam_beta_1 = 0.9, 109 | adam_beta_2 = 0.95, 110 | adam_eps = 1e-8, 111 | clip_grad_max_norm = 1.0, 112 | weight_decay_rate = 0.1, 113 | logging_interval = 1, 114 | checkpointing_steps = {int(total_training_steps / 2)}, 115 | validation_interval = 5, 116 | validation_steps = 5, 117 | sampling_interval = 5, 118 | sampling_batch = 2, 119 | sampling_tokens = 3, 120 | sampling_top_k = 50, 121 | eval_interval = 6, 122 | eval_hs_subset_key = "validation[:2]", 123 | ) 124 | return hParams, tParams 125 | -------------------------------------------------------------------------------- /src/model_utils/adamw_opt.py: -------------------------------------------------------------------------------- 1 | import math 2 | import logging 3 | 4 | import torch.nn as nn 5 | import torch.optim as optim 6 | 7 | from src.params import TParams 8 | from src.utils.handle_ddp import DDPHandler 9 | 10 | 11 | log = logging.getLogger(__name__) 12 | 13 | 14 | class AdamWOptimizer: 15 | ''' 16 | Opinionated class that will handle all AdamW optimizer actions. 17 | ''' 18 | 19 | def __init__(self, tParams: TParams, ddp: DDPHandler, model: nn.Module): 20 | self.ddp = ddp 21 | self.tot_steps = tParams.tot_steps 22 | self.warm_up_steps = tParams.warm_up_steps 23 | self.max_lr = tParams.max_lr 24 | self.min_lr = self.max_lr * tParams.min_lr_ratio 25 | 26 | param_groups = self._get_param_groups(model, tParams.weight_decay_rate) 27 | 28 | self.optimizer = optim.AdamW( 29 | params = param_groups, 30 | lr=tParams.max_lr, 31 | betas=(tParams.adam_beta_1, tParams.adam_beta_2), 32 | eps=tParams.adam_eps, 33 | fused=ddp.is_avail, 34 | ) 35 | 36 | def zero_grad(self): 37 | self.optimizer.zero_grad() 38 | 39 | def step(self, step): 40 | # Updating with step count instead of token count to make things easier for now. 41 | # Might implement curriculum learning later on which would change this. 42 | 43 | # Update learning rate 44 | lr = self._get_scheduled_lr(step) 45 | for param_group in self.optimizer.param_groups: 46 | param_group['lr'] = lr 47 | 48 | # Update weights 49 | self.optimizer.step() 50 | 51 | return lr # Only used for debugging 52 | 53 | def _get_scheduled_lr(self, step): 54 | ''' 55 | Calculate learning-rate given training step. First perform linear warm-up and 56 | then cosine decay. 57 | ''' 58 | if step < self.warm_up_steps: 59 | # Linear warm-up 60 | lr = (self.max_lr / self.warm_up_steps) * (step + 1) 61 | else: 62 | # Cosine decay 63 | progress = (step - self.warm_up_steps) / (self.tot_steps - self.warm_up_steps) 64 | lr = self.min_lr + (self.max_lr - self.min_lr) * 0.5 * (1 + math.cos(math.pi * progress)) 65 | return lr 66 | 67 | def _get_param_groups(self, model, weight_decay): 68 | ''' 69 | Set up weight decay for learnable parameters. Avoiding bias and norm layers since 70 | they don't contribute (much) to overfitting and may actually be harmed by regularization. 71 | ''' 72 | decay = [] 73 | no_decay = [] 74 | decay_name = [] 75 | no_decay_name = [] 76 | 77 | for name, param in model.named_parameters(): 78 | if param.requires_grad: 79 | if "bias" in name.lower() or "norm" in name.lower(): 80 | no_decay.append(param) 81 | no_decay_name.append(name) 82 | else: 83 | decay.append(param) 84 | decay_name.append(name) 85 | 86 | if self.ddp.is_main: 87 | log.info(f'{weight_decay} decay params: {decay_name}') 88 | log.info(f'0.0 no-decay params: {no_decay_name}') 89 | 90 | return [ 91 | {'params': decay, 'weight_decay': weight_decay}, 92 | {'params': no_decay, 'weight_decay': 0.0} 93 | ] 94 | 95 | 96 | if __name__ == "__main__": 97 | import torch 98 | from src.model import LLM 99 | from src.params import HParams 100 | from src.utils.handle_ddp import DDPHandler 101 | 102 | ddp = DDPHandler() 103 | logging.basicConfig(level=logging.DEBUG) 104 | 105 | hParams = HParams( 106 | n_vocab = 32, 107 | n_ctx = 16, 108 | n_embd = 8, 109 | n_head = 4, 110 | n_layer = 4, 111 | ffn_act_pdrop = 0.15, 112 | attn_res_pdrop = 0.1, 113 | ) 114 | 115 | tParams = TParams( 116 | tot_steps = 100, 117 | warm_up_steps = 20, 118 | batch_token_count = 32, 119 | max_lr = 0.0021, 120 | min_lr_ratio = 0.1, 121 | adam_beta_1 = 0.9, 122 | adam_beta_2 = 0.95, 123 | adam_eps = 1e-8, 124 | clip_grad_max_norm = 1.0, 125 | weight_decay_rate = 0.1, 126 | ) 127 | 128 | model = LLM(hParams) 129 | opt = AdamWOptimizer(tParams, ddp, model) 130 | 131 | x = torch.tensor([ 132 | [2, 3, 3, 1, 3], 133 | [2, 1, 3, 2, 0], 134 | ]) 135 | y = torch.tensor([ 136 | [3, 3, 1, 3, 0], 137 | [1, 3, 2, 0, 1], 138 | ]) 139 | 140 | opt.zero_grad() # Zero the parameter gradients 141 | output, loss = model(x, y) # Forward pass 142 | loss.backward() # Backward pass 143 | opt.step(step=0) # Update weights 144 | 145 | ddp.end() 146 | -------------------------------------------------------------------------------- /src/model_utils/checkpoint_utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from datetime import datetime 3 | import logging 4 | 5 | from src.utils.root import create_temp_data_file 6 | 7 | ''' 8 | Utility functions to save and load model checkpoint. 9 | All info needed to continue training the model is saved in the checkpoint. 10 | ''' 11 | 12 | log = logging.getLogger(__name__) 13 | 14 | 15 | def save_checkpoint(model, optimizer, step, scheduler=None, save_random_state=True): 16 | #TODO: Needs to save the state of the training_data_loader.py as well. 17 | checkpoint = { 18 | 'model_state_dict': model.state_dict(), 19 | 'optimizer_state_dict': optimizer.state_dict(), 20 | 'scheduler_state_dict': scheduler.state_dict() if scheduler else None, # Might use this later 21 | 'step': step, 22 | 'hParams': model.hParams, 23 | } 24 | 25 | # Optionally save the random state 26 | if save_random_state: 27 | checkpoint['random_state'] = torch.get_rng_state() 28 | if torch.cuda.is_available(): 29 | checkpoint['cuda_random_state'] = torch.cuda.get_rng_state_all() 30 | else: 31 | checkpoint['random_state'] = None 32 | checkpoint['cuda_random_state'] = None 33 | 34 | date = datetime.now().astimezone() 35 | date = date.strftime('%Y_%m_%d-%H_%M_%Z') 36 | filepath = create_temp_data_file('checkpoints', f'checkpoint_step_{step}_date_{date}.pth') 37 | torch.save(checkpoint, filepath) 38 | log.info(f"Checkpoint saved at step {step}.") 39 | 40 | 41 | def load_checkpoint(model, optimizer=None, scheduler=None, filepath='checkpoint.pth', load_random_state=True): 42 | checkpoint = torch.load(filepath, map_location="cuda" if torch.cuda.is_available() else "cpu") 43 | # log.info(f'Loading checkpoint with data: {checkpoint}') 44 | 45 | # Load model and optimizer states 46 | state_dict = checkpoint['model_state_dict'] 47 | new_state_dict = {key.replace("_orig_mod.", ""): value for key, value in state_dict.items()} 48 | model.load_state_dict(new_state_dict) 49 | if optimizer: 50 | optimizer.load_state_dict(checkpoint['optimizer_state_dict']) 51 | 52 | # Load scheduler state if available 53 | if scheduler and checkpoint.get('scheduler_state_dict'): 54 | scheduler.load_state_dict(checkpoint['scheduler_state_dict']) 55 | 56 | # Optionally load the random state 57 | if load_random_state and checkpoint.get('random_state') is not None: 58 | torch.set_rng_state(checkpoint['random_state']) 59 | if torch.cuda.is_available() and checkpoint.get('cuda_random_state') is not None: 60 | torch.cuda.set_rng_state_all(checkpoint['cuda_random_state']) 61 | 62 | step = checkpoint['step'] 63 | # log.info(f"Checkpoint loaded, resuming training from step {step}.") 64 | 65 | return step, checkpoint['hParams'] 66 | -------------------------------------------------------------------------------- /src/model_utils/debugging.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import torch 4 | import torch.distributed as dist 5 | 6 | 7 | def get_stats(weights): 8 | # min_val = weights.min().item() 9 | max_val = weights.max().item() 10 | mean_val = weights.mean().item() 11 | std_val = weights.std().item() 12 | var_val = weights.var().item() 13 | print("Weight Statistics:") 14 | # print(f"Min: {min_val}") 15 | print(f"Max: {max_val}") 16 | print(f"Mean: {mean_val}") 17 | print(f"Standard Deviation: {std_val}") 18 | print(f"Variance: {var_val}") 19 | 20 | 21 | def get_model_size(model): 22 | trainable_param_count = sum(p.numel() for p in model.parameters() if p.requires_grad) 23 | double_counted = sum(p.numel() for p in model.out_proj.parameters()) # Due to weight-tying 24 | return trainable_param_count - double_counted 25 | 26 | 27 | def log_training_metrics( 28 | log, ddp, tParams, train_start, train_end, step, loss, grad_norm, lr 29 | ): 30 | ''' 31 | Offload all metric logging to one function. 32 | If running in a DDP env, this is expected to be called by rank 0 only. 33 | ''' 34 | 35 | if ddp.is_avail: 36 | dist.all_reduce(loss, op=dist.ReduceOp.AVG) 37 | 38 | perplexity = torch.exp(loss) 39 | perplexity = f'{perplexity.item():.4f}' 40 | loss = f'{loss.item():.4f}' 41 | grad_norm = f'{grad_norm:.4f}' 42 | 43 | time_elapsed = train_end - train_start # secs 44 | throughput = f'{(tParams.batch_token_count / time_elapsed):,.2f}' 45 | time_elapsed = f'{time_elapsed * 1_000:.2f}' # m.secs 46 | 47 | if ddp.is_main: 48 | log.info(f"Step {step}: Time: {time_elapsed} ms. LR: {lr:.4e}. Avg. loss: {loss}. Perplexity: {perplexity}. Grad Norm: {grad_norm}. Throughput: {throughput} tokens/sec") 49 | -------------------------------------------------------------------------------- /src/model_utils/weight_init.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import torch.nn as nn 4 | 5 | from src.params import HParams 6 | 7 | 8 | ''' 9 | Utils to help with weight initialization. 10 | 11 | Inspiration from the following, and the idea of making the variance of the layers feeding into the 12 | residual path smaller than those that are not. 13 | https://github.com/jzhang38/TinyLlama 14 | https://github.com/Lightning-AI/litgpt 15 | https://arxiv.org/pdf/2204.06745.pdf - GPT-NeoX 16 | ''' 17 | 18 | 19 | def init_embedding(module: nn.Module, hParams: HParams): 20 | ''' 21 | Initialization for embedding layer. 22 | ''' 23 | std = math.sqrt(2.0 / 5 / hParams.n_embd) 24 | nn.init.normal_(module.weight, mean=0.0, std=std) 25 | 26 | 27 | def init_linear(module, hParams: HParams): 28 | ''' 29 | Initialization for linear layer (all of which have a bias, except for 30 | weight sharing one, but that one is not initialize). 31 | ''' 32 | init_embedding(module, hParams) 33 | nn.init.zeros_(module.bias) 34 | 35 | 36 | def init_linear_res_proj(module, hParams: HParams): 37 | ''' 38 | Initialization for linear layer that are output projections before a residual connection. 39 | These benefit from lower variance. 40 | ''' 41 | std = 1 / math.sqrt(hParams.n_embd) / hParams.n_layer 42 | nn.init.normal_(module.weight, mean=0.0, std=std) 43 | nn.init.zeros_(module.bias) 44 | -------------------------------------------------------------------------------- /src/params.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | @dataclass 5 | class HParams: 6 | ''' 7 | Hyperparameters 8 | ''' 9 | # Lang. processing 10 | n_vocab: int # Vocab size 11 | n_ctx: int # token context (sequence) len 12 | # Model arch. 13 | n_embd: int # embedding dimension 14 | n_head: int # number of attention heads 15 | n_layer: int # number of attention blocks 16 | # Dropout rates 17 | # embd_pdrop: float = 0 # Embedding dropout 18 | # attn_pdrop: float = 0 # Attention dropout 19 | ffn_act_pdrop: float = 0 # Dropout after FFN activation 20 | attn_res_pdrop: float = 0 # After attention, in residual connection 21 | # ffn_res_pdrop: float = 0 # After FFN, in residual connection 22 | 23 | 24 | @dataclass 25 | class TParams: 26 | ''' 27 | Training parameters 28 | ''' 29 | tot_steps: int # Total number of training steps 30 | grad_acc_steps: int # Gradient accumulation steps (tune to system being used) 31 | warm_up_steps: int # Steps in which to perform initial linear LR warm up 32 | batch_token_count: int # Number of tokens that make up one global batch 33 | max_lr: float # Max learning rate to reach 34 | min_lr_ratio: float # % of max_lr reached at the end of cosine decay 35 | adam_beta_1: float # Used in AdamW optimizer 36 | adam_beta_2: float # Used in AdamW optimizer 37 | adam_eps: float # Used in AdamW optimizer 38 | clip_grad_max_norm: float # Max value to clip the gradient norm all parameters 39 | weight_decay_rate: float # L2 regularization factor to prevent overfitting 40 | 41 | logging_interval: int # At what intervals to log 42 | checkpointing_steps: set # At intervals to create a checkpoint 43 | validation_interval: int # Intervals at which to run validation 44 | validation_steps: int # Number of validation batches to evaluate for averaging 45 | sampling_interval: int # Intervals during training at which to sample from model 46 | sampling_batch: int # Number of times to run a single prompt for sampling 47 | sampling_tokens: int # Number of tokens to generate when sampling 48 | sampling_top_k: int # top-k value for sampling 49 | eval_interval: int # Training intervals at which to run HellaSwag evaluation 50 | eval_hs_subset_key: str # Validation subset to use from HellaSwag 51 | -------------------------------------------------------------------------------- /src/rope.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import torch 4 | from einops import rearrange, repeat 5 | 6 | from src.params import HParams 7 | from src.global_cache import global_cache 8 | 9 | 10 | BASE_THETA: float = 10_000.0 11 | COS_CACHE_KEY = 'cos_cache' 12 | SIN_CACHE_KEY = 'sin_cache' 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | class Rope(): 17 | ''' 18 | Implement Rotary Positional Embeddings (RoPE). 19 | Splitting the embedding space in half instead of interleaving entries. 20 | ''' 21 | 22 | def __init__(self, hParams: HParams): 23 | super().__init__() 24 | self.n_ctx = hParams.n_ctx 25 | self.head_dim = hParams.n_embd // hParams.n_head 26 | self._prepare_rotary_embeddings() 27 | 28 | def _prepare_rotary_embeddings(self): 29 | ''' 30 | Precompute the cosine and sine values for rotary embeddings. 31 | ''' 32 | assert self.head_dim % 2 == 0, 'Head dimension must be even for RoPE.' 33 | 34 | if COS_CACHE_KEY in global_cache and SIN_CACHE_KEY in global_cache: 35 | logger.info(f"{COS_CACHE_KEY} and {SIN_CACHE_KEY} have been previously created, skipping creation.") 36 | return 37 | else: 38 | # Compute inverse frequencies 39 | # Implicitly working with floats for this one-time operation 40 | half_dim = self.head_dim // 2 41 | freq_seq = torch.arange(half_dim, dtype=torch.float32) 42 | inverse_freq = 1.0 / (BASE_THETA ** (freq_seq / half_dim)) 43 | 44 | # Compute position indices 45 | position_seq = torch.arange(self.n_ctx, dtype=torch.float32) 46 | angle_rates = torch.outer(position_seq, inverse_freq) 47 | 48 | # Stack angles to match total head_dim, shape (n_ctx, head_dim) 49 | angles = repeat(angle_rates, 'n_ctx half_dim -> n_ctx (2 half_dim)') 50 | 51 | # Store cosine and sine values in cache to share with other modules 52 | global_cache[COS_CACHE_KEY] = torch.cos(angles) 53 | global_cache[SIN_CACHE_KEY] = torch.sin(angles) 54 | 55 | def _apply_rotary(self, x): 56 | ''' 57 | Apply rotary positional embedding to the input tensor. 58 | ''' 59 | _, _, n_ctx, _ = x.shape 60 | cos_cached = global_cache[COS_CACHE_KEY][:n_ctx, :].to(x.device) 61 | sin_cached = global_cache[SIN_CACHE_KEY][:n_ctx, :].to(x.device) 62 | 63 | # Reshape (1, 1, n_ctx, head_dim) 64 | cos_cached = rearrange(cos_cached, 'n_ctx head_dim -> 1 1 n_ctx head_dim') 65 | sin_cached = rearrange(sin_cached, 'n_ctx head_dim -> 1 1 n_ctx head_dim') 66 | 67 | # Split the last dimension into two halves (batch_size, n_head, n_ctx, head_dim // 2) 68 | x_r = rearrange(x, '... (two d) -> ... two d', two=2) 69 | x1, x2 = x_r.unbind(dim=-2) 70 | 71 | # Apply the rotary embeddings 72 | x_rotated = torch.cat([-x2, x1], dim=-1) # shape (batch_size, n_head, n_ctx, head_dim) 73 | return (x * cos_cached) + (x_rotated * sin_cached) 74 | 75 | def apply_rotary(self, x): 76 | ''' 77 | x and output shape: (batch_size, n_head, n_ctx, head_dim). 78 | ''' 79 | assert x.size(-1) == self.head_dim, 'Input head_dim does not match model head_dim.' 80 | return self._apply_rotary(x) 81 | 82 | 83 | if __name__ == '__main__': 84 | 85 | logging.basicConfig(level=logging.DEBUG) 86 | 87 | # (Batch Size, Number of Heads, Sequence Length, Head Dimension) 88 | B, H, S, HD = 2, 3, 2, 8 89 | # q = torch.empty(B, H, S, HD) 90 | # q[:,:,:,:] = torch.tensor([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]) 91 | 92 | q = torch.tensor([ 93 | [ 94 | [[0.0756, 0.1966, 0.3164, 0.4017, 0.1186, 0.8274, 0.3821, 0.6605], 95 | [0.8536, 0.5932, 0.6367, 0.9826, 0.2745, 0.6584, 0.2775, 0.8573]], 96 | [[0.8993, 0.0390, 0.9268, 0.7388, 0.7179, 0.7058, 0.9156, 0.4340], 97 | [0.0772, 0.3565, 0.1479, 0.5331, 0.4066, 0.2318, 0.4545, 0.9737]], 98 | [[0.4606, 0.5159, 0.4220, 0.5786, 0.9455, 0.8057, 0.6775, 0.6087], 99 | [0.6179, 0.6932, 0.4354, 0.0353, 0.1908, 0.9268, 0.5299, 0.0950]] 100 | ], 101 | [ 102 | [[0.5789, 0.9131, 0.0275, 0.1634, 0.3009, 0.5201, 0.3834, 0.4451], 103 | [0.0126, 0.7341, 0.9389, 0.8056, 0.1459, 0.0969, 0.7076, 0.5112]], 104 | [[0.7050, 0.0114, 0.4702, 0.8526, 0.7320, 0.5183, 0.5983, 0.4527], 105 | [0.2251, 0.3111, 0.1955, 0.9153, 0.7751, 0.6749, 0.1166, 0.8858]], 106 | [[0.6568, 0.8459, 0.3033, 0.6060, 0.9882, 0.8363, 0.9010, 0.3950], 107 | [0.8809, 0.1084, 0.5432, 0.2185, 0.3834, 0.3720, 0.5374, 0.9551]] 108 | ] 109 | ]) 110 | 111 | hParams = HParams( 112 | n_vocab = 16, 113 | n_ctx = S, 114 | n_embd = H * HD, 115 | n_head = H, 116 | n_layer = 2, 117 | ) 118 | 119 | r = Rope(hParams) 120 | 121 | # print(f'q shape: {q.shape}') 122 | # print(f'q: {q}') 123 | 124 | q_rotated = r.apply_rotary(q) 125 | 126 | # print(f'q_rotated shape: {q_rotated.shape}') 127 | # print(f'q_rotated: {q_rotated}') 128 | 129 | expected_rotated = torch.tensor([ 130 | [ 131 | [[ 0.0756, 0.1966, 0.3164, 0.4017, 0.1186, 0.8274, 0.3821, 0.6605], 132 | [ 0.2302, 0.5245, 0.6339, 0.9817, 0.8666, 0.7143, 0.2839, 0.8583]], 133 | [[ 0.8993, 0.0390, 0.9268, 0.7388, 0.7179, 0.7058, 0.9156, 0.4340], 134 | [-0.3004, 0.3316, 0.1433, 0.5321, 0.2846, 0.2662, 0.4560, 0.9742]], 135 | [[ 0.4606, 0.5159, 0.4220, 0.5786, 0.9455, 0.8057, 0.6775, 0.6087], 136 | [ 0.1733, 0.5972, 0.4301, 0.0352, 0.6230, 0.9914, 0.5342, 0.0950]] 137 | ], 138 | [ 139 | [[ 0.5789, 0.9131, 0.0275, 0.1634, 0.3009, 0.5201, 0.3834, 0.4451], 140 | [-0.1160, 0.7208, 0.9318, 0.8051, 0.0894, 0.1697, 0.7170, 0.5120]], 141 | [[ 0.7050, 0.0114, 0.4702, 0.8526, 0.7320, 0.5183, 0.5983, 0.4527], 142 | [-0.5306, 0.2422, 0.1943, 0.9144, 0.6082, 0.7026, 0.1185, 0.8867]], 143 | [[ 0.6568, 0.8459, 0.3033, 0.6060, 0.9882, 0.8363, 0.9010, 0.3950], 144 | [ 0.1533, 0.0707, 0.5378, 0.2175, 0.9484, 0.3810, 0.5428, 0.9553]] 145 | ] 146 | ]) 147 | 148 | if torch.equal(torch.round(q_rotated * 10000) / 10000, expected_rotated): 149 | print('alls good') 150 | else: 151 | print('ERROR: mismatch between q_rotated and expected_rotated!') 152 | 153 | # Check that cos/sin is cached 154 | r2 = Rope(hParams) 155 | -------------------------------------------------------------------------------- /src/transformer_block.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | from src.params import HParams 5 | from src.attention import Attention 6 | from src.ffn import FFN 7 | 8 | 9 | class TransformerBlock(nn.Module): 10 | 11 | def __init__(self, hParams: HParams): 12 | ''' 13 | - Using pre-layer normalization to improve training stability in deep network, 14 | allowing for faster convergence. 15 | - Using RMSNorm for its efficient (lower compute/memory w.r.t LayerNorm), stable normalization 16 | with the limited pre-training dataset and small LLM. 17 | ''' 18 | super().__init__() 19 | self.attn = Attention(hParams) # Casual, multi-head attention module. 20 | self.ffn = FFN(hParams) 21 | self.norm1 = nn.RMSNorm(hParams.n_embd, eps=1e-5) # Test later: scale=True) 22 | self.norm2 = nn.RMSNorm(hParams.n_embd, eps=1e-5) 23 | self.attn_dropout = nn.Dropout(hParams.attn_res_pdrop) 24 | ''' 25 | Will rely on dropout post SwiGLU() activation, where the hidden space is larger. This 26 | should encourage the model to develop more robust features, becoming less 27 | overly reliant on specific neurons 28 | ''' 29 | # self.ffn_dropout = nn.Dropout(hParams.ffn_res_pdrop) 30 | 31 | def forward(self, x): 32 | xn = self.norm1(x) 33 | x = x + self.attn_dropout(self.attn(xn)) 34 | xn = self.norm2(x) 35 | # return x + self.ffn_dropout(self.ffn(xn)) 36 | return x + self.ffn(xn) 37 | 38 | 39 | if __name__ == '__main__': 40 | torch.manual_seed(123) 41 | if torch.cuda.is_available(): 42 | torch.cuda.manual_seed(123) 43 | 44 | hParams = HParams( 45 | n_vocab = 0., 46 | n_ctx = 4, 47 | n_embd = 8, 48 | n_head = 2, 49 | n_layer = 6, 50 | ffn_act_pdrop = 0.1, 51 | ) 52 | 53 | batch_size, n_ctx, embed_dim = 2, hParams.n_ctx, hParams.n_embd 54 | 55 | x = torch.tensor([ 56 | [[0.0975, 0.2956, 0.9027, 0.3112, 0.9167, 0.4139, 0.4362, 0.6996], 57 | [0.4265, 0.4958, 0.8463, 0.6671, 0.4801, 0.6904, 0.9355, 0.6260], 58 | [0.3534, 0.6638, 0.4563, 0.1091, 0.3069, 0.7274, 0.5164, 0.6845], 59 | [0.2073, 0.9727, 0.2913, 0.6066, 0.2557, 0.2588, 0.7239, 0.3604]], 60 | [[0.1829, 0.2956, 0.8646, 0.8010, 0.8044, 0.0733, 0.7355, 0.6248], 61 | [0.1638, 0.5158, 0.6000, 0.2299, 0.2890, 0.9078, 0.4596, 0.4947], 62 | [0.1836, 0.2010, 0.9603, 0.6861, 0.4209, 0.8046, 0.2621, 0.0638], 63 | [0.0036, 0.7032, 0.3051, 0.8070, 0.9271, 0.6647, 0.9296, 0.3848]] 64 | ]) 65 | 66 | expected_output = torch.tensor([ 67 | [[ 0.1222, 0.3944, 0.9081, 0.4116, 0.9019, 0.4357, 0.5854, 0.5876], 68 | [ 0.4480, 0.6237, 0.8530, 0.8256, 0.4027, 0.7042, 1.0869, 0.5828], 69 | [ 0.4034, 0.7573, 0.4909, 0.2609, 0.2750, 0.7530, 0.7240, 0.6498], 70 | [ 0.2345, 0.9932, 0.4020, 0.7886, 0.1864, 0.2969, 0.9419, 0.3768]], 71 | [[ 0.2539, 0.3301, 0.8965, 0.9369, 0.6914, 0.0726, 0.8460, 0.4512], 72 | [ 0.2245, 0.6699, 0.6241, 0.3642, 0.2603, 0.9434, 0.6830, 0.4444], 73 | [ 0.2377, 0.3256, 0.9132, 0.7391, 0.3647, 0.8737, 0.4459, -0.0557], 74 | [ 0.0723, 0.8872, 0.3468, 0.9490, 0.8377, 0.6990, 1.0981, 0.3463]] 75 | ]) 76 | 77 | block = TransformerBlock(hParams) 78 | output = block(x) 79 | output = torch.round(output * 10000) / 10000 80 | 81 | # print(f'output: {output}') 82 | 83 | if torch.equal(output, expected_output): 84 | print('alls good') 85 | else: 86 | not_equal = output != expected_output 87 | different_indices = not_equal.nonzero(as_tuple=True) 88 | for idx in zip(*different_indices): 89 | print(f"Diff at index {idx}: output = {output[idx]}, expected_output = {expected_output[idx]}") 90 | -------------------------------------------------------------------------------- /src/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LF-Luis/MyLLM/4c833932aabb15ddc25d1fbcd52b383b3beb7894/src/utils/__init__.py -------------------------------------------------------------------------------- /src/utils/handle_ddp.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | 4 | import torch 5 | import torch.distributed as dist 6 | from torch.nn.parallel import DistributedDataParallel as DDP 7 | 8 | 9 | log = logging.getLogger(__name__) 10 | 11 | WORLD_SIZE = 'WORLD_SIZE' 12 | LOCAL_RANK = 'LOCAL_RANK' 13 | NCCL = 'nccl' 14 | CUDA = "cuda" 15 | MPS = "mps" 16 | CPU = "cpu" 17 | 18 | 19 | class DDPHandler: 20 | ''' 21 | Helper class to handle PyTorch's Distributed Data Parallel (DDP) states. 22 | Note, training with at most one node (with N-number of GPUs, usually 4 virtual or 8). 23 | ''' 24 | 25 | def __init__(self): 26 | self.is_avail = self._check_ddp_availability() 27 | 28 | if self.is_avail: 29 | dist.init_process_group(backend=NCCL) 30 | self.local_rank = int(os.environ[LOCAL_RANK]) 31 | self.world_size = int(os.environ[WORLD_SIZE]) 32 | self.is_main = self.local_rank == 0 33 | self.assigned_device = f'{CUDA}:{self.local_rank}' 34 | self.device_type = CUDA 35 | torch.cuda.set_device(self.assigned_device) 36 | else: 37 | self.local_rank = 0 38 | self.world_size = 1 39 | self.is_main = True 40 | if torch.cuda.is_available(): 41 | device = CUDA 42 | elif hasattr(torch.backends, MPS) and torch.backends.mps.is_available(): 43 | device = MPS 44 | else: 45 | device = CPU 46 | self.assigned_device = device 47 | self.device_type = CUDA if device.startswith(CUDA) else CPU 48 | 49 | log.info(( 50 | f'Launching worker with config: \n' 51 | f'local_rank: {self.local_rank} | world_size: {self.world_size} | is_main: {self.is_main} \n' 52 | f'assigned_device: {self.assigned_device} | device_type: {self.device_type}.' 53 | )) 54 | 55 | def _check_ddp_availability(self): 56 | return ( 57 | int(os.environ.get(WORLD_SIZE, 1)) > 1 and # WORLD_SIZE > 1 indicates DDP is intended 58 | (dist.is_nccl_available() or dist.is_gloo_available()) and # Required backend 59 | torch.cuda.is_available() and # Must be available 60 | torch.cuda.device_count() > 1 # At least two GPUs 61 | ) 62 | 63 | def wrap_model(self, model): 64 | ''' 65 | Only wrap if GPU + CUDA is available. 66 | Single node, single GPU, no need to use `output_device` for now 67 | ''' 68 | if self.is_avail: 69 | model = DDP(model, device_ids=[self.local_rank]) 70 | return model 71 | 72 | def get_actual_model(self, model): 73 | # Returns the actual model, whether it's wrapped in DDP or not. 74 | if isinstance(model, DDP): 75 | return model.module 76 | return model 77 | 78 | def barrier(self): 79 | # Synchronize all processes, only used when running with DDP. 80 | if self.is_avail: 81 | dist.barrier() 82 | 83 | def end(self): 84 | ''' 85 | Required to run at the end of training. 86 | ''' 87 | if self.is_avail: 88 | if self.is_main: 89 | log.info(f'Closing global process group.') 90 | dist.destroy_process_group() 91 | else: 92 | pass 93 | 94 | 95 | if __name__ == "__main__": 96 | # torchrun --standalone --nproc_per_node=8 src/utils/handle_ddp.py 97 | 98 | logging.basicConfig(level=logging.DEBUG) 99 | 100 | ddp = DDPHandler() 101 | ddp.end() 102 | -------------------------------------------------------------------------------- /src/utils/logger.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | from datetime import datetime 4 | from src.utils.root import create_temp_data_file 5 | 6 | 7 | def setup_logging(log_file='project_logs.log'): 8 | # Retrieve the logging level from the environment variable 9 | log_level = os.getenv('LOG_LEVEL', 'DEBUG').upper() # Default to 'DEBUG' if not set 10 | 11 | # Verify if log level is valid, else fallback to DEBUG and log an error 12 | level = getattr(logging, log_level, logging.DEBUG) 13 | if level == logging.DEBUG and log_level != 'DEBUG': 14 | logging.basicConfig(level=logging.DEBUG) 15 | logging.error(f'Invalid LOG_LEVEL "{log_level}" in environment; defaulting to DEBUG.') 16 | 17 | # Create the log directory we will write checkpoints to and log to 18 | current_time = datetime.now().astimezone() 19 | current_time = current_time.strftime('%Y_%m_%d-%H_%M_%Z') 20 | log_file = create_temp_data_file(path='logs/log_' + current_time, file_name='log.txt') 21 | 22 | # Configure the root logger 23 | logging.basicConfig( 24 | level=level, 25 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 26 | handlers=[ 27 | logging.FileHandler(log_file), # Write to log file 28 | logging.StreamHandler() # Also output to console 29 | ] 30 | ) 31 | -------------------------------------------------------------------------------- /src/utils/rand_idx_seq_gen.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.distributed as dist 3 | 4 | 5 | class RandIdxSeqGen: 6 | ''' 7 | Random Index Sequence Generator. 8 | Class to create a sequence of indices that have been randomly shuffled. 9 | Class allows for the indices to be updated. 10 | 11 | For example, for a given sequence length `seqLen` of 6, which would represent a 12 | list of 6 items, we would have the following indices: 13 | [0, 1, 2, 3, 4, 5] 14 | 15 | This class would shuffle the indices and give you access to the current and next index: 16 | shuffled: [5, 3, 2, 4, 0, 1] 17 | ↑ ↑ 18 | current next 19 | 20 | Set `rank` and `world_size` so that the random order created by rank=0 is shared to 21 | all ranks. 22 | ''' 23 | 24 | def __init__(self, ddp, seqLen, rank=None, world_size=None, rnd_seed=None): 25 | self.ddp = ddp 26 | self.seqLen = seqLen 27 | self.rank = rank 28 | self.world_size = world_size 29 | self.rnd_seed = rnd_seed 30 | self.generator = torch.Generator() 31 | self.rnd_ordered_idx = None 32 | self.current_pointer = None 33 | self.reset(self.seqLen) 34 | 35 | def reset(self, seqLen): 36 | assert self.seqLen > 0 37 | 38 | self.seqLen = seqLen 39 | self.current_pointer = None 40 | 41 | if self.rnd_seed: 42 | self.generator.manual_seed(self.rnd_seed) 43 | self.rnd_seed += 1 44 | 45 | self.rnd_ordered_idx = torch.randperm(n=self.seqLen, generator=self.generator) 46 | 47 | if ( 48 | self.rank is not None 49 | and self.world_size is not None 50 | and self.world_size > 1 51 | ): 52 | if self.ddp.is_avail: 53 | self.rnd_ordered_idx = self.rnd_ordered_idx.to(self.ddp.assigned_device) 54 | dist.broadcast(self.rnd_ordered_idx, src=0) 55 | 56 | def next(self): 57 | ''' 58 | Returns next random index value. 59 | If all values have been exhausted, this will return None until the `reset()` is run. 60 | ''' 61 | assert ( 62 | self.rnd_ordered_idx is not None and self.rnd_ordered_idx.numel() > 0 63 | ), f'ERROR: Calling next() before setting self.rnd_ordered_idx: {self.rnd_ordered_idx}' 64 | 65 | if self.current_pointer is None: 66 | self.current_pointer = 0 67 | else: 68 | self.current_pointer += 1 69 | 70 | if self.current_pointer >= self.rnd_ordered_idx.size(0,): 71 | self.current_pointer -= 1 72 | return None 73 | 74 | return self.current() 75 | 76 | def current(self): 77 | if self.current_pointer is None: 78 | return None 79 | return int(self.rnd_ordered_idx[self.current_pointer]) 80 | -------------------------------------------------------------------------------- /src/utils/root.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | 4 | 5 | log = logging.getLogger(__name__) 6 | 7 | 8 | def get_root_abs_path() -> str: 9 | ''' 10 | Get absolute path of root directory of the project. 11 | Note this file must be in /project_root/src/utils/root.py 12 | ''' 13 | current_dir = os.path.dirname(__file__) 14 | return os.path.abspath(os.path.join(current_dir, '../..')) 15 | 16 | def get_temp_data_abs_path() -> str: 17 | return os.path.join(get_root_abs_path(), 'temp_data') 18 | 19 | def create_temp_data_dir(path: str) -> str: 20 | ''' 21 | Recursive function to creates dir inside of `temp_data` dir. 22 | Returns path to directory. 23 | ''' 24 | dir = os.path.join(get_root_abs_path(), 'temp_data', path) 25 | log.info(f'Creating dir: {dir}') 26 | os.makedirs(dir, exist_ok=True) 27 | return dir 28 | 29 | def create_temp_data_file(path: str, file_name: str) -> str: 30 | ''' 31 | Recursive function to create file path and file inside of `temp_data` dir. 32 | Returns path to file. 33 | ''' 34 | dir = create_temp_data_dir(path) 35 | file_path = os.path.join(dir, file_name) 36 | log.info(f'Creating file: {file_path}') 37 | with open(file_path, 'w') as f: 38 | pass 39 | return file_path 40 | 41 | 42 | if __name__ == '__main__': 43 | pass 44 | # log.info(get_temp_data_abs_path()) --------------------------------------------------------------------------------