[
  {
    "path": ".gitignore",
    "content": "__pycache__\n.idea\n.DS_Store\n*.egg-info\nbuild\n.venv\n.vscode\n\n# data\ndata\ncheckpoints\nout\nwandb\n\ntests/original_falcon_40b.py\nsft/output\nsft/wandb"
  },
  {
    "path": "EVAL.md",
    "content": "## Evaluate TinyLlama\n\n### GPT4All Benchmarks\n\nWe evaluate TinyLlama's commonsense reasoning ability following the [GPT4All](https://gpt4all.io/index.html) evaluation suite. We include Pythia as our baseline. We report the acc_norm by default. \n\nBase models:\n\n| Model                                     | Pretrain Tokens | HellaSwag | Obqa | WinoGrande | ARC_c | ARC_e | boolq | piqa | avg |\n|-------------------------------------------|-----------------|-----------|------|------------|-------|-------|-------|------|-----|\n| Pythia-1.0B                               |        300B     | 47.16     | 31.40| 53.43      | 27.05 | 48.99 | 60.83 | 69.21 | 48.30 |\n| TinyLlama-1.1B-intermediate-step-50K-104b |        103B     | 43.50     | 29.80| 53.28      | 24.32 | 44.91 | 59.66 | 67.30 | 46.11|\n| TinyLlama-1.1B-intermediate-step-240k-503b|        503B     | 49.56     |31.40 |55.80       |26.54  |48.32  |56.91  |69.42  | 48.28 |\n| TinyLlama-1.1B-intermediate-step-480k-1007B |     1007B     | 52.54     | 33.40 | 55.96      | 27.82 | 52.36 | 59.54 | 69.91 | 50.22 |\n| TinyLlama-1.1B-intermediate-step-715k-1.5T |     1.5T     | 53.68     | 35.20 | 58.33      | 29.18 | 51.89 | 59.08 | 71.65 | 51.29 |\n| TinyLlama-1.1B-intermediate-step-955k-2T |     2T     | 54.63     | 33.40 | 56.83      | 28.07 | 54.67 | 63.21 | 70.67 | 51.64 |\n| TinyLlama-1.1B-intermediate-step-1195k-2.5T  |     2.5T     | 58.96     | 34.40 | 58.72      | 31.91 | 56.78 | 63.21 | 73.07 | 53.86|\n| TinyLlama-1.1B-intermediate-step-1431k-3T  |     3T     | 59.20     | 36.00 | 59.12      | 30.12 | 55.25 | 57.83 | 73.29 | 52.99|\n\n\nChat models:\n| Model                                     | Pretrain Tokens | HellaSwag | Obqa | WinoGrande | ARC_c | ARC_e | boolq | piqa | avg |\n|-------------------------------------------|-----------------|-----------|------|------------|-------|-------|-------|------|-----|\n| [TinyLlama-1.1B-Chat-v0.1](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.1)                 |   503B     | 53.81     |32.20 | 55.01  | 28.67 |49.62  | 58.04 | 69.64 | 49.57 |\n| [TinyLlama-1.1B-Chat-v0.2](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.2)                 |   503B     | 53.63     |32.80 | 54.85  | 28.75 |49.16  | 55.72 | 69.48 | 49.20 |\n| [TinyLlama-1.1B-Chat-v0.3](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.3)                 |   1T       | 56.81     |34.20 | 55.80  | 30.03 |53.20  | 59.57 | 69.91 | 51.36 |\n| [TinyLlama-1.1B-Chat-v0.4](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v0.4)             |   1.5T     | 58.59     |35.40 | 58.80  | 30.80 |54.04  | 57.31 | 71.16 | 52.30 |\n\n\nWe observed huge improvements once we finetuned the model. We attribute this phenomenon to: 1. the base model has not undergone lr cool-down and FT helps to cool down the lr. 2. the SFT stage better elicits the model's internal knowledge.\n\nYou can obtain the above scores by running [lm-eval-harness](https://github.com/EleutherAI/lm-evaluation-harness):\n```bash\npython main.py \\\n    --model hf-causal \\\n    --model_args pretrained=PY007/TinyLlama-1.1B-Chat-v0.1,dtype=\"float\" \\\n    --tasks hellaswag,openbookqa,winogrande,arc_easy,arc_challenge,boolq,piqa\\\n    --device cuda:0 --batch_size 32\n```\n\n\n\n### Instruct-Eval Benchmarks\nWe evaluate TinyLlama's ability in problem-solving on the [Instruct-Eval](https://github.com/declare-lab/instruct-eval) evaluation suite. \n\n\n| Model                                             | MMLU  | BBH   | HumanEval | DROP  |\n| ------------------------------------------------- | ----- | ----- | --------- | ----- |\n| Pythia-1.0B                                       | 25.70 | 28.19 | 1.83      | 4.25  |\n| TinyLlama-1.1B-intermediate-step-50K-104b         | 26.45 | 28.82 | 5.49      | 11.42 |\n| TinyLlama-1.1B-intermediate-step-240k-503b        | 26.16 | 28.83 | 4.88      | 12.43 |\n| TinyLlama-1.1B-intermediate-step-480K-1T          | 24.65 | 29.21 | 6.1       | 13.03 |\n| TinyLlama-1.1B-intermediate-step-715k-1.5T        | 24.85 | 28.2  | 7.93      | 14.43 |\n| TinyLlama-1.1B-intermediate-step-955k-2T          | 25.97 | 29.07 | 6.71      | 13.14 |\n| TinyLlama-1.1B-intermediate-step-1195k-token-2.5T | 25.92 | 29.32 | 9.15      | 15.45 |\n\nYou can obtain above scores by running [instruct-eval](https://github.com/declare-lab/instruct-eval):\n```bash\nCUDA_VISIBLE_DEVICES=0 python main.py mmlu --model_name llama --model_path PY007/TinyLlama-1.1B-intermediate-step-480K-1T\nCUDA_VISIBLE_DEVICES=1 python main.py bbh --model_name llama --model_path PY007/TinyLlama-1.1B-intermediate-step-480K-1T\nCUDA_VISIBLE_DEVICES=2 python main.py drop --model_name llama --model_path PY007/TinyLlama-1.1B-intermediate-step-480K-1T\nCUDA_VISIBLE_DEVICES=3 python main.py humaneval  --model_name llama  --n_sample 1 --model_path PY007/TinyLlama-1.1B-intermediate-step-480K-1T\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [2023] Lightning AI\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "PRETRAIN.md",
    "content": "## Pretrain TinyLlama\n\n### Installation\nWe expect you have CUDA 11.8 installed.\n#### Install Pytorch Nightly.\n```bash\npip install --index-url https://download.pytorch.org/whl/nightly/cu118 --pre 'torch>=2.1.0dev'\n```\n#### Build XFormers from Source\nNote: as of 2023/09/02, xformers does not provide pre-built binaries for torch 2.1. You have to build it from source.\n```bash\npip uninstall ninja -y && pip install ninja -U\npip install -v -U git+https://github.com/facebookresearch/xformers.git@main#egg=xformers\n```\n\n\n#### Install Flash-Attention 2 and other fused operators:\n```bash\ngit clone https://github.com/Dao-AILab/flash-attention\ncd flash-attention\npython setup.py install\ncd csrc/rotary && pip install .\ncd ../layer_norm && pip install .\ncd ../xentropy && pip install .\ncd ../.. && rm -rf flash-attention\n```\n#### Install Remaining Dependencies\n```\npip install -r requirements.txt tokenizers sentencepiece\n```\nto install other dependencies.\nIt may take >= 5 minutes to build xformers/flash-attention. Do not worry if the process seemly stagnant or the terminal print out many warnings.\n\nThen you are ready to go 🎉!\n\n### Data Preparation\n\n#### Download Datasets\nDownload the Slimpajama and Starcoderdata datasets to your chosen directory.\n```bash\ncd /path/to/dataset\ngit lfs install\ngit clone https://huggingface.co/datasets/cerebras/SlimPajama-627B\ngit clone https://huggingface.co/datasets/bigcode/starcoderdata\n```\nThe SlimPajama dataset eats 893GB diskspace and the starcoderdata takes 290GB.\n\n#### Tokenize data\nUse the provided scripts to tokenize the datasets and divide them into chunks.\n```bash\npython scripts/prepare_starcoder.py --source_path /path/to/starcoderdata/ --tokenizer_path data/llama --destination_path data/slim_star_combined --split train --percentage 1.0\npython scripts/prepare_slimpajama.py --source_path /path/to/SlimPajama --tokenizer_path data/llama  --destination_path data/slim_star_combined --split validation --percentage 1.0\npython scripts/prepare_slimpajama.py --source_path /path/to/SlimPajama --tokenizer_path data/llama  --destination_path data/slim_star_combined --split train --percentage 1.0\n```\nThe processed data will take 1.8T storage.\n\n### Pretraining\nIf your setup comprises two nodes, each with 8 GPUs, you can initiate pretraining with the following commands:\n\nOn node 1:\n```\nlightning run model \\\n    --node-rank=0  \\\n    --main-address=172.16.101.5 \\\n    --accelerator=cuda \\\n    --devices=8 \\\n    --num-nodes=2 \\\n    pretrain/tinyllama.py --devices 8 --train_data_dir data/slim_star  --val_data_dir data/slim_star\n```\nOn node 2:\n```\nlightning run model \\\n    --node-rank=1  \\\n    --main-address=172.16.101.5 \\\n    --accelerator=cuda \\\n    --devices=8 \\\n    --num-nodes=2 \\\n    pretrain/tinyllama.py --devices 8 --train_data_dir data/slim_star   --val_data_dir data/slim_star\n```\nYou can follow [these instructions](https://lightning.ai/docs/fabric/stable/guide/multi_node/slurm.html) if you have a slurm cluster.\n\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n\n# TinyLlama-1.1B\nEnglish | [中文](README_zh-CN.md)\n\n[Chat Demo](https://huggingface.co/spaces/TinyLlama/tinyllama-chat) | [Discord](https://discord.gg/74Wcx4j5Nb)\n</div>\n\nThe TinyLlama project aims to **pretrain** a **1.1B Llama model on 3 trillion tokens**. With some proper optimization, we can achieve this within a span of \"just\" 90 days using 16 A100-40G GPUs 🚀🚀. The training has started on 2023-09-01. \n\n<div align=\"center\">\n  <img src=\".github/TinyLlama_logo.png\" width=\"300\"/>\n</div>\n\nWe adopted exactly the same architecture and tokenizer as Llama 2. This means TinyLlama can be plugged and played in many open-source projects built upon Llama. Besides, TinyLlama is compact with only 1.1B parameters. This compactness allows it to cater to a multitude of applications demanding a restricted computation and memory footprint.\n\n#### News\n- 2023-12-18： Add two notes [1](https://whimsical-aphid-86d.notion.site/Release-of-TinyLlama-1-5T-Checkpoints-Postponed-01b266998c1c47f78f5ae1520196d194?pvs=4), [2](https://whimsical-aphid-86d.notion.site/Latest-Updates-from-TinyLlama-Team-7d30c01fff794da28ccc952f327c8d4f?pvs=4) explaining the changes of training curves, project schedules, and bug fixes.\n- 2023-10-03: Add examples in speculative decoding with llama.cpp. Do check out the [speculative_decoding/README.md](speculative_decoding/README.md).\n- 2023-10-02: 1. 1T-token checkpoint just dropped. 2. We document **all** intermediate checkpoints [here](https://huggingface.co/TinyLlama/tinyLlama-intermediate-checkpoints/tree/step-480k-token-1007B).\n- 2023-09-28: Add a discord server.\n- 2023-09-18: 1. We added a [chat demo](https://huggingface.co/spaces/PY007/TinyLlama-Chat) so that you can play with TinyLlama-Chat-V0.1 right away. \n- 2023-09-16: 1. We released the intermediate checkpoint trained on 503B tokens. 2. We released a chat model finetuned on OpenAssisant and simple [finetuning](sft) scripts is added. 3. More eval benchmarks are added and documented in [EVAL.md](EVAL.md). \n\n#### Evaluation\nYou can find the evaluation results of TinyLlama in [EVAL.md](EVAL.md).\n\n#### Releases Schedule\nWe will be rolling out intermediate checkpoints following the below schedule. \n\nBase models:\n\n| Date       | HF Checkpoint                                   | Tokens | Step | Commonsense Avg |\n|------------|-------------------------------------------------|--------|------| --------------- |\n| 2023-09-01 | Pythia-1.0B                                     | 300B   | 143k   | 48.30 |\n| 2023-09-04 | [TinyLlama-1.1B-intermediate-step-50k-105b](https://huggingface.co/PY007/TinyLlama-1.1B-step-50K-105b) | 105B   | 50k   | 46.11|\n| 2023-09-16 | [TinyLlama-1.1B-intermediate-step-240k-503b](https://huggingface.co/PY007/TinyLlama-1.1B-intermediate-step-240k-503b)                                            | 503B   | 240K    | 48.28 |\n| 2023-10-01 | [TinyLlama-1.1B-intermediate-step-480k-1T](https://huggingface.co/PY007/TinyLlama-1.1B-intermediate-step-480k-1T) | 1T     | 480k | 50.22 |\n| 2023-11-04 | [TinyLlama-1.1B-intermediate-step-715k-1.5T](https://huggingface.co/PY007/TinyLlama-1.1B-intermediate-step-715k-1.5T)                                            | 1.5T     |715k    |51.28 |\n| 2023-11-20 | [TinyLlama-1.1B-intermediate-step-955k-2T](https://huggingface.co/TinyLlama/TinyLlama-1.1B-intermediate-step-955k-token-2T)                                            | 2T     |955k    |51.64 |\n| 2023-12-11 | [TinyLlama-1.1B-intermediate-step-1195k-2.5T](https://huggingface.co/TinyLlama/TinyLlama-1.1B-intermediate-step-1195k-token-2.5T)              | 2.5T     | 1195k    |53.86 |\n| 2023-12-28 | [TinyLlama-1.1B-intermediate-step-1431k-3T](https://huggingface.co/TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T)              | 3T   | 1431k  | 52.99 |\n\nWe are crafting a note offering possible explaination on why there is a significant improvement from 2T to 2.5T checkpoint (It is related to [bos_id issue](https://github.com/jzhang38/TinyLlama/issues/83))\n\nChat models:\n\n| Date       | HF Checkpoint                                   | Tokens | Step | Commonsense Avg |\n|------------|-------------------------------------------------|--------|------| --------------- |\n| 2023-09-16 | [TinyLlama-1.1B-Chat-V0.1](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.1)                                            | 503B   | 240K    |  49.57 |\n| 2023-10-1 | [TinyLlama-1.1B-Chat-V0.3](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.3)                                            | 1T   | 480K    |  51.36 |\n| 2023-11-04 | [TinyLlama-1.1B-Chat-V0.4](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v0.4)                                            | 1.5T   | 715K    |  52.30 |\n\nNote that the learning rate of the base model has not cooled down yet so we recommend you to also use the finetuned chat model.\n\nMeanwhile, you can track the live cross entropy loss [here](https://wandb.ai/lance777/lightning_logs/reports/metric-train_loss-23-09-04-23-38-15---Vmlldzo1MzA4MzIw?accessToken=5eu2sndit2mo6eqls8h38sklcgfwt660ek1f2czlgtqjv2c6tida47qm1oty8ik9).\n\n## Potential Usecase\nTiny but strong language models are useful for many applications. Here are some potential usecases:\n- Assisting speculative decoding of larger models. (See this [tutorial](https://twitter.com/karpathy/status/1697318534555336961) by Andrej Karpathy)\n- Deployment on edge devices with restricted memory and computational capacities, for functionalities like real-time machine translation without an internet connection (the 4bit-quantized TinyLlama-1.1B's weight only takes up 637 MB).\n- Enabling real-time dialogue generation in video games.\n\nMoreover, our code can be a **reference for enthusiasts keen on pretraining language models under 5 billion parameters** without diving too early into [Megatron-LM](https://github.com/NVIDIA/Megatron-LM).\n\n## Training Details\nBelow are some details of our training setup:\n\n| Setting                         | Description                                                    |\n|---------------------------------|----------------------------------------------------------------|\n| Parameters                      | 1.1B                                                           |\n| Attention Variant               | Grouped Query Attention                                        |\n| Model Size                      | Layers: 22, Heads: 32, Query Groups: 4, Embedding Size: 2048, Intermediate Size (Swiglu): 5632|\n| Sequence Length                 | 2048                                                           |\n| Batch Size                      | 2 million tokens (2048 * 1024)                                             |\n| Learning Rate                   | 4e-4                                                           |\n| Learning Rate Schedule          | Cosine with 2000 warmup steps. See [Issue 27](https://github.com/jzhang38/TinyLlama/issues/27) for a minor bug     |\n| Training Data                   | [Slimpajama](https://huggingface.co/datasets/cerebras/slimpajama-627b) & [Starcoderdata](https://huggingface.co/datasets/bigcode/starcoderdata) |\n| Data Preprocessing              | Excluded GitHub subset of Slimpajama; Sampled all code from Starcoderdata |\n| Combined Dataset Size           | Around 950B tokens                                              |\n| Total Tokens During Training    | 3 trillion (slightly more than 3 epochs/1430k steps)                                          |\n| Natural Language to Code Ratio  | 7:3                                                            |\n| Hardware                        | 16 A100-40G GPUs                                               |\n\n\n\n\n\n\n## Blazingly Fast\nOur codebase supports the following features:\n- multi-gpu and multi-node distributed training with FSDP.\n- flash attention 2.\n- fused layernorm.\n- fused swiglu.\n- fused cross entropy loss .\n- fused rotary positional embedding.\n\nCredit: flash attention 2, fused layernorm, fused cross entropy loss, and fused\nrotary positional embedding are from the [FlashAttention repo](https://github.com/Dao-AILab/flash-attention/). Fused swiglu is from [xformers](https://github.com/facebookresearch/xformers).\n\nThanks to those optimizations, we achieve a throughput of **24k** tokens per second per A100-40G GPU, which translates to **56% model flops utilization** without activation checkpointing (We expect the MFU to be even higher on A100-80G). It means you can train a chinchilla-optimal TinyLlama (1.1B param, 22B tokens) in **32 hours with 8 A100**. Those optimizations also greatly reduce the memory footprint, allowing us to stuff our 1.1B model into 40GB GPU RAM and train with a per-gpu batch size of 16k tokens. **You can also pretrain TinyLlama on 3090/4090 GPUs with a smaller per-gpu batch size**.\nBelow is a comparison of the training speed of our codebase with that of Pythia and MPT.\n\n\n| Model                             | A100 GPU hours taken on 300B tokens| \n|-----------------------------------|------------------------------------|\n|TinyLlama-1.1B                     | 3456                               |    \n|[Pythia-1.0B](https://huggingface.co/EleutherAI/pythia-1b)                        | 4830                               |\n|[MPT-1.3B](https://huggingface.co/mosaicml/mpt-1b-redpajama-200b)                           | 7920                               |  \n\n<small> The Pythia number comes from their [paper](https://arxiv.org/abs/2304.01373). The MPT number comes from [here](https://huggingface.co/mosaicml/mpt-1b-redpajama-200b), in which they say MPT-1.3B \" was trained on 440 A100-40GBs for about half a day\" on 200B tokens. </small>\n\nThe fact that TinyLlama is a relatively small model with grouped query attention means it is also fast during inference. Below are some throughputs that we measure:\n\n| Framework | Device | Settings | Throughput (tokens/sec) |\n|-----------|--------------|-----|-----------|\n|[Llama.cpp](https://github.com/ggerganov/llama.cpp) | Mac M2 16GB RAM         |  batch_size=1; 4-bit inference|    71.8     | \n|[vLLM](https://github.com/vllm-project/vllm)       | A40 GPU  | batch_size=100, n=10 |   7094.5         |\n\n\n## Pretrain\nPlease refer to [PRETRAIN.md](PRETRAIN.md) for instructions on how to pretrain TinyLlama.\n\n## Finetune\nWe include a simple full-parameter finetuning & inference script in [sft](sft). Our V0.1 chat model is finetuned using this script. The FT dataset we use is [openassistant-guanaco](https://huggingface.co/datasets/timdettmers/openassistant-guanaco). \nFor finetuning with less than 4GB RAM, we refer you to the [Qlora](https://github.com/artidoro/qlora) and [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) repos.\nWe did not undergo extensive hyperparameter tuning nor choose more performant FT datasets. We hope the community can explore on finetuning TinyLlama and come up with better chat models. I will include community-finetuned models in this repo.\n\n## TODO\nThis project is still under active development. We are a really small team. Community feedback and contributions are highly appreciated. Here are some things we plan to work on:\n - [ ] Add scripts for pretraining on other datasets.\n - [ ] Sequence length extrapolation.\n - [ ] Test out speculative decoding for Llama-2-7B.\n - [ ] Test the throughput on RTX 3090/4090. \n - [ ] Add fine-tuning scripts.\n - [ ] Properly evaluate the model on downstream tasks.\n - [ ] A demo running on mobile phones. \n - [ ] Explore retrieval-augmentation.\n\n\n\n## Acknowledgements\nThis repository is built upon [lit-gpt](https://github.com/Lightning-AI/lit-gpt) and [flash-attention](https://github.com/Dao-AILab/flash-attention). Be sure to explore this fantastic open-source project if it's new to you!\n```\n@online{lit-gpt,\n  author    = {Lightning AI},\n  title     = {Lit-GPT},\n  url       = {https://github.com/Lightning-AI/lit-gpt},\n  year      = {2023},\n}\n@article{dao2023flashattention2,\n  title     ={Flash{A}ttention-2: Faster Attention with Better Parallelism and Work Partitioning},\n  author    ={Dao, Tri},\n  year      ={2023}\n}\n```\n\n## Citation\nThis project is currently contributed by [Peiyuan Zhang](https://veiled-texture-20c.notion.site/Peiyuan-Zhang-ab24b48621c9491db767a76df860873a?pvs=4) *, [Guangtao Zeng](https://github.com/ChaosCodes) *, [Tianduo Wang](https://github.com/TianduoWang) and [Wei Lu](https://istd.sutd.edu.sg/people/faculty/lu-wei/) from the StatNLP Research Group of Singapore University of Technology and Design. \n\nIf you find our work valuable, please cite:\n\n```\n@misc{zhang2024tinyllama,\n      title={TinyLlama: An Open-Source Small Language Model}, \n      author={Peiyuan Zhang and Guangtao Zeng and Tianduo Wang and Wei Lu},\n      year={2024},\n      eprint={2401.02385},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n```\n\n## Frequently Asked Questions\n\n#### 1. Why would pretraining a 1.1B model for so long make sense? Doesn't it contradict the Chinchilla Scaling Law?\n\n<img src=\".github/llama2-training.png\" alt=\"The training loss curve of Llama 2\" width=\"500\"/>\n\nAbove is the training loss curve taken from the Llama 2 paper. Here I quote from that paper: \"We observe that after pretraining on 2T Tokens, the models still did not show any sign of saturation\". That is why we believe pretraining a 1.1B model for 3T tokens is a reasonable thing to do. Even if the loss curve does not go down eventually, we can still study the phenomenon of saturation and learn something from it.\n\n#### 2. What does \"saturation\" mean?\n<img src=\".github/Pythia_saturation.png\" alt=\"Figure 10 of the Pythia paper\" width=\"500\"/>\n\nThe figure from the Pythia paper displays the LAMBADA accuracy plotted against the total training tokens (300B). The term \"saturation\" pertains specifically to the 70M and 160M models. Notably, even the 410M model does not saturate with 300B tokens, as it continues to show an increasing trend, similar to the trend of larger models. \n\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=jzhang38/TinyLlama&type=Date)](https://star-history.com/#jzhang38/TinyLlama&Date)\n\n"
  },
  {
    "path": "README_zh-CN.md",
    "content": "<div align=\"center\">\n\n# TinyLlama-1.1B\n[English](README.md) | 中文\n\n[Chat Demo](https://huggingface.co/spaces/TinyLlama/tinyllama-chat)\n</div>\n\nTinyLlama项目旨在在3万亿tokens上进行预训练，构建一个拥有11亿参数的Llama模型。经过精心优化，我们\"仅\"需16块A100-40G的GPU，便可在90天内完成这个任务🚀🚀。训练已于2023-09-01开始。\n\n\n<div align=\"center\">\n  <img src=\".github/TinyLlama_logo.png\" width=\"300\"/>\n</div>\n我们采用了与Llama 2完全相同的架构和分词器。这意味着TinyLlama可以在许多基于Llama的开源项目中即插即用。此外，TinyLlama只有1.1B的参数，体积小巧，适用于需要限制计算和内存占用的多种应用。\n\n#### 新闻\n\n* 2023-12-18：\n  * 添加两个文档 [1](https://whimsical-aphid-86d.notion.site/Release-of-TinyLlama-1-5T-Checkpoints-Postponed-01b266998c1c47f78f5ae1520196d194?pvs=4), [2](https://whimsical-aphid-86d.notion.site/Latest-Updates-from-TinyLlama-Team-7d30c01fff794da28ccc952f327c8d4f?pvs=4) 说明训练曲线、项目时间表和错误修复的变化。\n* 2023-10-03: \n  * 在speculative decoding中添加llama.cpp的代码示例。具体请查看 [speculative_decoding/README.md](speculative_decoding/README.md)。\n  * 2023-10-02: 1. 1T-token检查点刚发布。2. 我们在[huggingface](https://huggingface.co/TinyLlama/tinyLlama-intermediate-checkpoints/tree/step-480k-token-1007B)上记录了**所有**中间检查点。\n  * 2023-09-28: 启用[Discord](https://discord.gg/74Wcx4j5Nb)服务器。\n* 2023-09-18: \n  * 发布了一个 [chat demo](https://huggingface.co/spaces/TinyLlama/tinyllama-chat)，欢迎点击链接来尝试我们的模型。\n* 2023-09-16: \n  * 发布了目前已经训练了 5.03 亿个 token 的 [checkpoints 模型](https://huggingface.co/PY007/TinyLlama-1.1B-intermediate-step-240k-503b)。 \n  * 基于 5.03 亿 token 的 [checkpoints 模型](https://huggingface.co/PY007/TinyLlama-1.1B-intermediate-step-240k-503b) 在 OpenAssistant 数据集上微调并开源了聊天模型 [TinyLlama-Chat-V0.1](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.1) ，并添加了我们的 [微调脚本](sft) 。\n  * 添加了更多的评测数据集，您可以通过 [EVAL.md](EVAL.md) 文件来查看我们各模型的结果。\n\n\n\n\n#### 发布时间表\n\n我们会根据以下计划逐步发布中间checkpoint。我们也列了一些基线模型进行比较。\n\n基座模型:\n\n| Date       | 模型权重                                              | Tokens | Step | Commonsense Avg |\n| ---------- | ------------------------------------------------------------ | ------ | ---- | --------------- |\n| 2023-09-01 | Pythia-1.0B                                                  | 300B   | 143k | 48.30           |\n| 2023-09-04 | [TinyLlama-1.1B-intermediate-step-50k-105b](https://huggingface.co/PY007/TinyLlama-1.1B-step-50K-105b) ([ModelScope](https://www.modelscope.cn/models/chaoscodes/TinyLlama-1.1B-step-50K-105b/files)) | 105B   | 50k  | 46.11           |\n| 2023-09-16 | [TinyLlama-1.1B-intermediate-step-240k-503b](https://huggingface.co/PY007/TinyLlama-1.1B-intermediate-step-240k-503b) ([ModelScope](https://www.modelscope.cn/models/chaoscodes/TinyLlama-1.1B-intermediate-step-240k-503b/files)) | 503B   | 240K | 48.28           |\n| 2023-10-01 | [TinyLlama-1.1B-intermediate-step-480k-1T](https://huggingface.co/PY007/TinyLlama-1.1B-intermediate-step-480k-1T) | 1T     | 480k | 50.22 |\n| 2023-11-04 | [TinyLlama-1.1B-intermediate-step-715k-1.5T](https://huggingface.co/PY007/TinyLlama-1.1B-intermediate-step-715k-1.5T)                                            | 1.5T     |715k    |51.28 |\n| 2023-11-20 | [TinyLlama-1.1B-intermediate-step-955k-2T](https://huggingface.co/TinyLlama/TinyLlama-1.1B-intermediate-step-955k-token-2T)                                            | 2T     |955k    |51.64 |\n| 2023-12-11 | [TinyLlama-1.1B-intermediate-step-1195k-2.5T](https://huggingface.co/TinyLlama/TinyLlama-1.1B-intermediate-step-1195k-token-2.5T)              | 2.5T     | 1195k    |53.86 |\n| 2023-12-28 | [TinyLlama-1.1B-intermediate-step-1431k-3T](https://huggingface.co/TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T)              | 3T   | 1431k  | 52.99 |\n\n对话模型:\n\n| Date       | 模型权重                                  | Tokens | Step | Commonsense Avg |\n|------------|-------------------------------------------------|--------|------| --------------- |\n| 2023-09-16 | [TinyLlama-1.1B-Chat-V0.1](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.1) ([ModelScope](https://www.modelscope.cn/models/chaoscodes/TinyLlama-1.1B-Chat-v0.1/files))                                         | 503B   | 240K    |  49.57 |\n| 2023-10-1 | [TinyLlama-1.1B-Chat-V0.3](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.3)                                            | 1T   | 480K    |  51.36 |\n| 2023-11-04 | [TinyLlama-1.1B-Chat-V0.4](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v0.4)                                            | 1.5T   | 715K    |  52.30 |\n\n需要注意的是，由于我们的现在模型还处于训练初期，学习率并没有完全稳定下来，为了更好的体验我们的模型，您可以下载我们 [聊天模型](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0) 或者通过 [chat demo](https://huggingface.co/spaces/TinyLlama/tinyllama-chat) 来尝试我们的模型。\n\n\n你们也可以在[这里](https://api.wandb.ai/links/lance777/pgvhrsny)实时跟踪TinyLlama的训练损失。\n\n## 潜在场景\n小型但强大的语言模型对许多应用都很有用。以下是一些潜在的场景：\n- 帮助对大型模型进行speculative decoding。\n- 在边缘装置上运行，比如离线的实时机器翻译 (TinyLlama的4比特量化版本的模型权重只需要550MB的内存)。\n- 在游戏中实现实时对话生成(因为还得给游戏本身留显存所以模型要小)。\n\n此外，我们的代码可以给初学者做一个**入门预训练的简洁参考**。如果你要训练50亿以下参数的语言模型, 你其实不需要Megatron-LM。\n\n## 训练细节\n以下是我们训练设置的一些细节：\n\n| Setting                         | Description                                                    |\n|---------------------------------|----------------------------------------------------------------|\n| Parameters                      | 1.1B                                                           |\n| Attention Variant               | Grouped Query Attention                                        |\n| Model Size                      | Layers: 22, Heads: 32, Query Groups: 4, Embedding Size: 2048, Intermediate Size (Swiglu): 5632|\n| Sequence Length                 | 2048                                                           |\n| Batch Size                      | 2 million tokens (2048 * 1024)                                             |\n| Learning Rate                   | 4e-4                                                           |\n| Learning Rate Schedule          | Cosine with 2000 warmup steps                                  |\n| Training Data                   | [Slimpajama](https://huggingface.co/datasets/cerebras/slimpajama-627b) & [Starcoderdata](https://huggingface.co/datasets/bigcode/starcoderdata) |\n| Data Preprocessing              | Excluded GitHub subset of Slimpajama; Sampled all code from Starcoderdata |\n| Combined Dataset Size           | Around 950B tokens                                              |\n| Total Tokens During Training    | 3 trillion (slightly more than 3 epochs/143k steps)                                          |\n| Natural Language to Code Ratio  | 7:3                                                            |\n| Hardware                        | 16 A100-40G GPUs                                               |\n\n\n\n\n\n\n## 速度极快\n我们的代码库支持以下特性：\n- 使用FSDP进行多GPU和多节点分布式训练\n- flash attention 2\n- 融合层归一化 (fused layernorm)\n- 融合swiglu (fused swiglu)\n- 融合交叉熵损失 (fused cross entropy loss)\n- 融合旋转位置嵌入 (fused rotary positional embedding)\n\n致谢：flash attention 2、融合层归一化、融合交叉熵损失和融合旋转位置嵌入来自于[FlashAttention](https://github.com/Dao-AILab/flash-attention/)仓库；融合swiglu来自于[xformers](https://github.com/facebookresearch/xformers)。\n\n有了这些优化, 我们可以达到**24k tokens/秒/A100**的训练速度，也就是56%的MFU（在A100-80G上的MFU会更高）。这个速度可以让你可以在**8个A100上用32小时训练一个chinchilla-optimial的模型**(11亿参数，220亿token)。这些优化也大大减少了显存占用, 我们可以把11亿参数的模型塞入40GB的GPU里面还能同时维持16k tokens的per-gpu batch size。只需要把batch size改小一点， 你就可以在**RTX 3090/4090**上面训练TinyLlama。\n下面是我们的代码库与Pythia和MPT的训练速度的比较。\n\n\n| Model                             | A100 GPU hours taken on 300B tokens| \n|-----------------------------------|------------------------------------|\n|TinyLlama-1.1B                     | 3456                               |    \n|[Pythia-1.0B](https://huggingface.co/EleutherAI/pythia-1b)                        | 4830                               |\n|[MPT-1.3B](https://huggingface.co/mosaicml/mpt-1b-redpajama-200b)                           | 7920                               |  \n\n<small> Pythia的数字来自他们的论文。MPT的数字来自[这里](https://huggingface.co/mosaicml/mpt-1b-redpajama-200b)，作者说MPT-1.3B\"was trained on 440 A100-40GBs for about half a day\" on 200B tokens。</small>\n\nTinyLlama是一个相对较小的模型, 同时我们用了GQA, 这意味着它在推理期间也很快。以下是我们测量的一些推理速度：\n\n| Framework | Device | Settings | Throughput (tokens/sec) |\n|-----------|--------------|-----|-----------|\n|[Llama.cpp](https://github.com/ggerganov/llama.cpp) | Mac M2 16GB RAM         |  batch_size=1; 4-bit inference|    71.8     | \n|[vLLM](https://github.com/vllm-project/vllm)       | A40 GPU  | batch_size=100, n=10 |   7094.5         |\n\n\n## 开始预训练\n请参考[PRETRAIN.md](PRETRAIN.md)。\n\n\n\n## 微调\n\n* 我们在 [sft](sft) 中添加了我们进行微调和推理的代码。并且基于这个代码我们在[openassistant-guanaco](https://huggingface.co/datasets/timdettmers/openassistant-guanaco) 数据集上进行了微调，得到了我们的第一版[聊天模型](https://huggingface.co/PY007/TinyLlama-1.1B-Chat-v0.1)。\n* 如果您希望在 RAM 小于 4GB 的 GPU 上对用我们的模型进行微调，可以参考并使用 [Qlora](https://github.com/artidoro/qlora) 和 [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) 项目。\n* 目前微调的时候我们并没有广泛对超参进行搜索，也没有选择潜在更优的 instruction 数据集。我们希望促进 NLP 社区对于我们的TinyLlama模型的开放研究，并开源更好的微调聊天模型。我们也会把这些模型放在这个项目中。\n\n\n\n## TODO\n该项目仍在积极开发中。我们团队很小，非常欢迎社区的反馈和贡献。以下是我们计划进行的一些工作：\n - [ ] Add scripts for pretraining on other datasets.\n - [ ] Sequence length extrapolation.\n - [ ] Test out speculative decoding for Llama-2-7B.\n - [ ] Test the throughput on RTX 3090/4090. \n - [ ] Add fine-tuning scripts.\n - [ ] Properly evaluate the model on downstream tasks.\n - [ ] A demo running on mobile phones. \n - [ ] Explore retrieval-augmentation.\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=jzhang38/TinyLlama&type=Date)](https://star-history.com/#jzhang38/TinyLlama&Date)\n\n\n## Acknowledgements\n这个仓库基于出色的开源项目[lit-gpt](https://github.com/Lightning-AI/lit-gpt)和[flash-attention](https://github.com/Dao-AILab/flash-attention)构建. \n```\n@online{lit-gpt,\n  author    = {Lightning AI},\n  title     = {Lit-GPT},\n  url       = {https://github.com/Lightning-AI/lit-gpt},\n  year      = {2023},\n}\n@article{dao2023flashattention2,\n  title     ={Flash{A}ttention-2: Faster Attention with Better Parallelism and Work Partitioning},\n  author    ={Dao, Tri},\n  year      ={2023}\n}\n```\n\n## Citation\n此项目目前由[Peiyuan Zhang](https://github.com/jzhang38)，[Guangtao Zeng](https://github.com/ChaosCodes)，[Tianduo Wang](https://github.com/TianduoWang)和[Wei Lu](https://istd.sutd.edu.sg/people/faculty/lu-wei/)贡献。 \n\n如果您觉得我们的工作有价值， 可以引用:\n\n```\n@misc{zhang2024tinyllama,\n      title={TinyLlama: An Open-Source Small Language Model}, \n      author={Peiyuan Zhang and Guangtao Zeng and Tianduo Wang and Wei Lu},\n      year={2024},\n      eprint={2401.02385},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n```\n\n"
  },
  {
    "path": "chat_gradio/README.md",
    "content": "## Tinyllama Chatbot Implementation with Gradio\n\nWe offer an easy way to interact with Tinyllama. This guide explains how to set up a local Gradio demo for a chatbot using TinyLlama.\n(A demo is also available on the Hugging Face Space [TinyLlama/tinyllama_chatbot](https://huggingface.co/spaces/TinyLlama/tinyllama-chat)) or Colab [colab](https://colab.research.google.com/drive/1qAuL5wTIa-USaNBu8DH35KQtICTnuLsy?usp=sharing).\n\n### Requirements\n* Python>=3.8\n* PyTorch>=2.0\n* Transformers>=4.34.0\n* Gradio>=4.13.0\n\n### Installation\n`pip install -r requirements.txt`\n\n### Usage\n\n`python TinyLlama/chat_gradio/app.py`\n\n* After running it, open the local URL displayed in your terminal in your web browser. (For server setup, use SSH local port forwarding with the command: `ssh -L [local port]:localhost:[remote port] [username]@[server address]`.)\n* Interact with the chatbot by typing questions or commands.\n\n\n**Note:** The chatbot's performance may vary based on your system's hardware. Ensure your system meets the above requirements for optimal experience.\n"
  },
  {
    "path": "chat_gradio/app.py",
    "content": "import gradio as gr\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom transformers import StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer\nfrom threading import Thread\n\n# Loading the tokenizer and model from Hugging Face's model hub.\ntokenizer = AutoTokenizer.from_pretrained(\"TinyLlama/TinyLlama-1.1B-Chat-v1.0\")\nmodel = AutoModelForCausalLM.from_pretrained(\"TinyLlama/TinyLlama-1.1B-Chat-v1.0\")\n\n# using CUDA for an optimal experience\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = model.to(device)\n\n\n# Defining a custom stopping criteria class for the model's text generation.\nclass StopOnTokens(StoppingCriteria):\n    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n        stop_ids = [2]  # IDs of tokens where the generation should stop.\n        for stop_id in stop_ids:\n            if input_ids[0][-1] == stop_id:  # Checking if the last generated token is a stop token.\n                return True\n        return False\n\n\n# Function to generate model predictions.\ndef predict(message, history):\n    history_transformer_format = history + [[message, \"\"]]\n    stop = StopOnTokens()\n\n    # Formatting the input for the model.\n    messages = \"</s>\".join([\"</s>\".join([\"\\n<|user|>:\" + item[0], \"\\n<|assistant|>:\" + item[1]])\n                        for item in history_transformer_format])\n    model_inputs = tokenizer([messages], return_tensors=\"pt\").to(device)\n    streamer = TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)\n    generate_kwargs = dict(\n        model_inputs,\n        streamer=streamer,\n        max_new_tokens=1024,\n        do_sample=True,\n        top_p=0.95,\n        top_k=50,\n        temperature=0.7,\n        num_beams=1,\n        stopping_criteria=StoppingCriteriaList([stop])\n    )\n    t = Thread(target=model.generate, kwargs=generate_kwargs)\n    t.start()  # Starting the generation in a separate thread.\n    partial_message = \"\"\n    for new_token in streamer:\n        partial_message += new_token\n        if '</s>' in partial_message:  # Breaking the loop if the stop token is generated.\n            break\n        yield partial_message\n\n\n# Setting up the Gradio chat interface.\ngr.ChatInterface(predict,\n                 title=\"Tinyllama_chatBot\",\n                 description=\"Ask Tiny llama any questions\",\n                 examples=['How to cook a fish?', 'Who is the president of US now?']\n                 ).launch()  # Launching the web interface.\n"
  },
  {
    "path": "chat_gradio/requirements.txt",
    "content": "torch>=2.0\ntransformers>=4.35.0\ngradio>=4.13.0\n"
  },
  {
    "path": "lit_gpt/__init__.py",
    "content": "from lit_gpt.model import GPT\nfrom lit_gpt.config import Config\nfrom lit_gpt.tokenizer import Tokenizer\nfrom lit_gpt.fused_cross_entropy import FusedCrossEntropyLoss\nfrom lightning_utilities.core.imports import RequirementCache\n\nif not bool(RequirementCache(\"torch>=2.1.0dev\")):\n    raise ImportError(\n        \"Lit-GPT requires torch nightly (future torch 2.1). Please follow the installation instructions in the\"\n        \" repository README.md\"\n    )\n_LIGHTNING_AVAILABLE = RequirementCache(\"lightning>=2.1.0.dev0\")\nif not bool(_LIGHTNING_AVAILABLE):\n    raise ImportError(\n        \"Lit-GPT requires Lightning nightly (future lightning 2.1). Please run:\\n\"\n        f\" pip uninstall -y lightning; pip install -r requirements.txt\\n{str(_LIGHTNING_AVAILABLE)}\"\n    )\n\n\n__all__ = [\"GPT\", \"Config\", \"Tokenizer\"]\n"
  },
  {
    "path": "lit_gpt/adapter.py",
    "content": "\"\"\"Implementation of the paper:\n\nLLaMA-Adapter: Efficient Fine-tuning of Language Models with Zero-init Attention\nhttps://arxiv.org/abs/2303.16199\n\nPort for Lit-GPT\n\"\"\"\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nfrom typing_extensions import Self\n\nfrom lit_gpt.config import Config as BaseConfig\nfrom lit_gpt.model import GPT as BaseModel\nfrom lit_gpt.model import CausalSelfAttention as BaseCausalSelfAttention\nfrom lit_gpt.model import KVCache, RoPECache, apply_rope\n\n\n@dataclass\nclass Config(BaseConfig):\n    adapter_prompt_length: int = 10\n    adapter_start_layer: int = 2\n\n\nclass GPT(BaseModel):\n    \"\"\"The implementation is identical to `lit_gpt.model.GPT` with the exception that\n    the `Block` saves the layer index and passes it down to the attention layer.\"\"\"\n\n    def __init__(self, config: Config) -> None:\n        nn.Module.__init__(self)\n        assert config.padded_vocab_size is not None\n        self.config = config\n\n        self.lm_head = nn.Linear(config.n_embd, config.padded_vocab_size, bias=False)\n        self.transformer = nn.ModuleDict(\n            dict(\n                wte=nn.Embedding(config.padded_vocab_size, config.n_embd),\n                h=nn.ModuleList(Block(config, i) for i in range(config.n_layer)),\n                ln_f=config.norm_class(config.n_embd, eps=config.norm_eps),\n            )\n        )\n\n        self.rope_cache: Optional[RoPECache] = None\n        self.mask_cache: Optional[torch.Tensor] = None\n        self.kv_caches: List[KVCache] = []\n        self.adapter_kv_caches: List[KVCache] = []\n\n    def reset_cache(self) -> None:\n        super().reset_cache()\n        self.adapter_kv_caches.clear()\n\n    def forward(\n        self,\n        idx: torch.Tensor,\n        max_seq_length: Optional[int] = None,\n        input_pos: Optional[torch.Tensor] = None,\n        lm_head_chunk_size: int = 0,\n    ) -> Union[torch.Tensor, List[torch.Tensor]]:\n        B, T = idx.size()\n        use_kv_cache = input_pos is not None\n\n        block_size = self.config.block_size\n        if max_seq_length is None:\n            max_seq_length = block_size\n        if use_kv_cache:  # not relevant otherwise\n            assert (\n                max_seq_length >= T\n            ), f\"Cannot forward sequence of length {T}, max seq length is only {max_seq_length}\"\n        assert max_seq_length <= block_size, f\"Cannot attend to {max_seq_length}, block size is only {block_size}\"\n        assert block_size >= T, f\"Cannot forward sequence of length {T}, block size is only {block_size}\"\n\n        if self.rope_cache is None:\n            self.rope_cache = self.build_rope_cache(idx)\n        # passing `attn_mask` to SDPA downgrades it to use the inefficient implementation. since we only need the mask\n        # for the kv-cache support (only during inference), we only create it in that situation\n        # this will be resolved by https://github.com/pytorch/pytorch/issues/96099\n        if use_kv_cache and self.mask_cache is None:\n            self.mask_cache = self.build_mask_cache(idx)\n\n        cos, sin = self.rope_cache\n        if use_kv_cache:\n            cos = cos.index_select(0, input_pos)\n            sin = sin.index_select(0, input_pos)\n            mask = self.mask_cache.index_select(2, input_pos)\n            mask = mask[:, :, :, :max_seq_length]\n        else:\n            cos = cos[:T]\n            sin = sin[:T]\n            mask = None\n\n        # forward the model itself\n        x = self.transformer.wte(idx)  # token embeddings of shape (b, t, n_embd)\n\n        if not use_kv_cache:\n            for block in self.transformer.h:\n                x, *_ = block(x, (cos, sin), max_seq_length)\n        else:\n            self.kv_caches = self.kv_caches or self.build_kv_caches(x, max_seq_length, cos.size(-1))\n            self.adapter_kv_caches = self.adapter_kv_caches or [None for _ in range(self.config.n_layer)]\n            for i, block in enumerate(self.transformer.h):\n                x, self.kv_caches[i], self.adapter_kv_caches[i] = block(\n                    x, (cos, sin), max_seq_length, mask, input_pos, self.kv_caches[i], self.adapter_kv_caches[i]\n                )\n\n        x = self.transformer.ln_f(x)\n\n        if lm_head_chunk_size > 0:\n            # chunk the lm head logits to reduce the peak memory used by autograd\n            return [self.lm_head(x_i) for x_i in x.split(lm_head_chunk_size, dim=1)]\n        return self.lm_head(x)  # (b, t, vocab_size)\n\n    @classmethod\n    def from_name(cls, name: str, **kwargs: Any) -> Self:\n        return cls(Config.from_name(name, **kwargs))\n\n    def _init_weights(self, module: nn.Module) -> None:\n        \"\"\"Meant to be used with `gpt.apply(gpt._init_weights)`. Unused method left for completeness.\"\"\"\n        super()._init_weights(module)\n        if isinstance(module, CausalSelfAttention):\n            module.reset_parameters()\n\n\nclass Block(nn.Module):\n    \"\"\"The implementation is identical to `lit_gpt.model.Block` with the exception that\n    we replace the attention layer where adaption is implemented.\"\"\"\n\n    def __init__(self, config: Config, block_idx: int) -> None:\n        super().__init__()\n        self.norm_1 = config.norm_class(config.n_embd, eps=config.norm_eps)\n        self.attn = CausalSelfAttention(config, block_idx)\n        if not config.shared_attention_norm:\n            self.norm_2 = config.norm_class(config.n_embd, eps=config.norm_eps)\n        self.mlp = config.mlp_class(config)\n\n        self.config = config\n\n    def forward(\n        self,\n        x: torch.Tensor,\n        rope: RoPECache,\n        max_seq_length: int,\n        mask: Optional[torch.Tensor] = None,\n        input_pos: Optional[torch.Tensor] = None,\n        kv_cache: Optional[KVCache] = None,\n        adapter_kv_cache: Optional[KVCache] = None,\n    ) -> Tuple[torch.Tensor, Optional[KVCache], Optional[KVCache]]:\n        n_1 = self.norm_1(x)\n        h, new_kv_cache, new_adapter_kv_cache = self.attn(\n            n_1, rope, max_seq_length, mask, input_pos, kv_cache, adapter_kv_cache\n        )\n        if self.config.parallel_residual:\n            n_2 = n_1 if self.config.shared_attention_norm else self.norm_2(x)\n            x = x + h + self.mlp(n_2)\n        else:\n            if self.config.shared_attention_norm:\n                raise NotImplementedError(\n                    \"No checkpoint amongst the ones we support uses this configuration\"\n                    \" (non-parallel residual and shared attention norm).\"\n                )\n            x = x + h\n            x = x + self.mlp(self.norm_2(x))\n        return x, new_kv_cache, new_adapter_kv_cache\n\n\nclass CausalSelfAttention(BaseCausalSelfAttention):\n    \"\"\"A modification of `lit_gpt.model.CausalSelfAttention` that adds the attention\n    over the adaption prompt.\"\"\"\n\n    def __init__(self, config: Config, block_idx: int) -> None:\n        super().__init__(config)\n        if block_idx >= config.adapter_start_layer:\n            # adapter embedding layer\n            self.adapter_wte = nn.Embedding(config.adapter_prompt_length, config.n_embd)\n            # gate for adaption\n            self.gating_factor = torch.nn.Parameter(torch.zeros(1, 1, config.n_head, 1))\n            self.reset_parameters()\n        self.block_idx = block_idx\n\n    def forward(\n        self,\n        x: torch.Tensor,\n        rope: RoPECache,\n        max_seq_length: int,\n        mask: Optional[torch.Tensor] = None,\n        input_pos: Optional[torch.Tensor] = None,\n        kv_cache: Optional[KVCache] = None,\n        adapter_kv_cache: Optional[KVCache] = None,\n    ) -> Tuple[torch.Tensor, Optional[KVCache], Optional[KVCache]]:\n        B, T, C = x.size()  # batch size, sequence length, embedding dimensionality (n_embd)\n\n        qkv = self.attn(x)\n\n        # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n        q_per_kv = self.config.n_head // self.config.n_query_groups\n        total_qkv = q_per_kv + 2  # each group has 1+ queries, 1 key, and 1 value\n        qkv = qkv.view(B, T, self.config.n_query_groups, total_qkv, self.config.head_size)\n        qkv = qkv.permute(0, 2, 3, 1, 4)  # (B, n_query_groups, total_qkv, T, hs)\n\n        # split batched computation into three\n        q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n\n        # repeat k and v if necessary\n        if self.config.n_query_groups != 1:  # doing this would require a full kv cache with MQA (inefficient!)\n            # for MHA this is a no-op\n            k = k.expand(B, self.config.n_query_groups, q_per_kv, T, self.config.head_size)\n            v = v.expand(B, self.config.n_query_groups, q_per_kv, T, self.config.head_size)\n\n        q = q.reshape(B, -1, T, self.config.head_size)  # (B, nh_q, T, hs)\n        k = k.reshape(B, -1, T, self.config.head_size)  # (B, nh_k, T, hs)\n        v = v.reshape(B, -1, T, self.config.head_size)  # (B, nh_v, T, hs)\n\n        n_elem = int(self.config.rotary_percentage * self.config.head_size)\n\n        cos, sin = rope\n        q_roped = apply_rope(q[..., :n_elem], cos, sin)\n        k_roped = apply_rope(k[..., :n_elem], cos, sin)\n        q = torch.cat((q_roped, q[..., n_elem:]), dim=-1)\n        k = torch.cat((k_roped, k[..., n_elem:]), dim=-1)\n\n        if kv_cache is not None:\n            cache_k, cache_v = kv_cache\n            cache_k, cache_v = cache_k.to(dtype=k.dtype), cache_v.to(dtype=v.dtype)\n            # check if reached token limit\n            if input_pos[-1] >= max_seq_length:\n                input_pos = torch.tensor(max_seq_length - 1, device=input_pos.device)\n                # shift 1 position to the left\n                cache_k = torch.roll(cache_k, -1, dims=2)\n                cache_v = torch.roll(cache_v, -1, dims=2)\n            k = cache_k.index_copy_(2, input_pos, k)\n            v = cache_v.index_copy_(2, input_pos, v)\n            kv_cache = k, v\n\n        y = self.scaled_dot_product_attention(q, k, v, mask=mask)\n\n        if self.block_idx >= self.config.adapter_start_layer:\n            aT = self.config.adapter_prompt_length\n            if adapter_kv_cache is not None:\n                ak, av = adapter_kv_cache\n            else:\n                prefix = self.adapter_wte.weight.reshape(1, aT, C)\n                aqkv = self.attn(prefix)\n                aqkv = aqkv.view(1, aT, self.config.n_query_groups, q_per_kv + 2, self.config.head_size)\n                aqkv = aqkv.permute(0, 2, 3, 1, 4)\n                _, ak, av = aqkv.split((q_per_kv, 1, 1), dim=2)\n                if self.config.n_query_groups != 1:\n                    # for MHA this is a no-op\n                    ak = ak.repeat_interleave(q_per_kv, dim=2)\n                    av = av.repeat_interleave(q_per_kv, dim=2)\n                ak = ak.view(1, -1, aT, self.config.head_size)  # (1, nh_ak, aT, hs)\n                av = av.view(1, -1, aT, self.config.head_size)  # (1, nh_av, aT, hs)\n                adapter_kv_cache = (ak, av)\n\n            amask = torch.ones(T, aT, dtype=torch.bool, device=x.device)\n            ay = self.scaled_dot_product_attention(q, ak, av, amask)\n            y = y + self.gating_factor * ay\n\n        y = y.reshape(B, T, C)  # re-assemble all head outputs side by side\n\n        # output projection\n        y = self.proj(y)\n\n        return y, kv_cache, adapter_kv_cache\n\n    def reset_parameters(self) -> None:\n        torch.nn.init.zeros_(self.gating_factor)\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with older checkpoints.\"\"\"\n        if (key := prefix + \"gating_factor\") in state_dict and state_dict[key].size(1) == self.config.n_head:\n            state_dict[key] = state_dict[key].permute(0, 2, 1, 3)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\ndef mark_only_adapter_as_trainable(model: GPT) -> None:\n    \"\"\"Sets `requires_grad=False` for all non-adapter weights.\"\"\"\n    for name, param in model.named_parameters():\n        param.requires_grad = adapter_filter(name, param)\n\n\ndef adapter_filter(key: str, value: Any) -> bool:\n    return \"adapter_wte\" in key or \"gating_factor\" in key\n"
  },
  {
    "path": "lit_gpt/adapter_v2.py",
    "content": "\"\"\"Implementation of the paper:\n\nLLaMA-Adapter V2: Parameter-Efficient Visual Instruction Model\nhttps://arxiv.org/abs/2304.15010\n\nPort for Lit-GPT\n\"\"\"\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Tuple, Type\n\nimport torch\nimport torch.nn as nn\nfrom typing_extensions import Self\n\nimport lit_gpt\nfrom lit_gpt.adapter import GPT as BaseModel\nfrom lit_gpt.adapter import Block as BaseBlock\nfrom lit_gpt.adapter import Config as BaseConfig\nfrom lit_gpt.adapter import KVCache, RoPECache\nfrom lit_gpt.model import CausalSelfAttention as BaseCausalSelfAttention\nfrom lit_gpt.model import apply_rope\nfrom lit_gpt.utils import map_old_state_dict_weights\n\n\n@dataclass\nclass Config(BaseConfig):\n    @property\n    def mlp_class(self) -> Type:\n        return getattr(lit_gpt.adapter_v2, self._mlp_class)\n\n\ndef adapter_filter(key: str, value: Any) -> bool:\n    adapter_substrings = (\n        # regular adapter v1 parameters\n        \"adapter_wte\",\n        \"gating_factor\",\n        # adapter v2: new bias and scale used in Linear\n        \"adapter_scale\",\n        \"adapter_bias\",\n        # adapter v2: Norm parameters are now trainable\n        \"norm_1\",\n        \"norm_2\",\n        \"ln_f\",\n    )\n    return any(s in key for s in adapter_substrings)\n\n\nclass AdapterV2Linear(torch.nn.Module):\n    def __init__(self, in_features: int, out_features: int, **kwargs) -> None:\n        super().__init__()\n        self.linear = torch.nn.Linear(in_features, out_features, **kwargs)\n        self.adapter_bias = torch.nn.Parameter(torch.zeros(out_features), requires_grad=False)\n        self.adapter_scale = torch.nn.Parameter(torch.ones(out_features), requires_grad=False)\n        self.reset_parameters()\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        return self.adapter_scale * (self.linear(x) + self.adapter_bias)\n\n    def reset_parameters(self) -> None:\n        nn.init.zeros_(self.adapter_bias)\n        nn.init.ones_(self.adapter_scale)\n\n\nclass GPT(BaseModel):\n    def __init__(self, config: Config) -> None:\n        # Skip the parent class __init__ altogether and replace it to avoid useless allocations\n        nn.Module.__init__(self)\n        assert config.padded_vocab_size is not None\n        self.config = config\n\n        self.lm_head = AdapterV2Linear(config.n_embd, config.padded_vocab_size, bias=False)\n        self.transformer = nn.ModuleDict(\n            dict(\n                wte=nn.Embedding(config.padded_vocab_size, config.n_embd),\n                h=nn.ModuleList(Block(config, i) for i in range(config.n_layer)),\n                ln_f=config.norm_class(config.n_embd, eps=config.norm_eps),\n            )\n        )\n\n        self.rope_cache: Optional[RoPECache] = None\n        self.mask_cache: Optional[torch.Tensor] = None\n        self.kv_caches: List[KVCache] = []\n        self.adapter_kv_caches: List[KVCache] = []\n\n    @classmethod\n    def from_name(cls, name: str, **kwargs: Any) -> Self:\n        return cls(Config.from_name(name, **kwargs))\n\n    def _init_weights(self, module: nn.Module) -> None:\n        \"\"\"Meant to be used with `gpt.apply(gpt._init_weights)`. Unused method left for completeness.\"\"\"\n        super()._init_weights(module)\n        if isinstance(module, CausalSelfAttention):\n            module.reset_parameters()\n        if isinstance(module, AdapterV2Linear):\n            module.reset_parameters()\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with base checkpoints.\"\"\"\n        mapping = {\"lm_head.weight\": \"lm_head.linear.weight\"}\n        state_dict = map_old_state_dict_weights(state_dict, mapping, prefix)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\nclass Block(BaseBlock):\n    \"\"\"The implementation is identical to `lit_gpt.model.Block` with the exception that\n    we replace the attention layer where adaption is implemented.\"\"\"\n\n    def __init__(self, config: Config, block_idx: int) -> None:\n        # Skip the parent class __init__ altogether and replace it to avoid useless allocations\n        nn.Module.__init__(self)\n        self.norm_1 = config.norm_class(config.n_embd, eps=config.norm_eps)\n        self.attn = CausalSelfAttention(config, block_idx)\n        if not config.shared_attention_norm:\n            self.norm_2 = config.norm_class(config.n_embd, eps=config.norm_eps)\n        self.mlp = config.mlp_class(config)\n\n        self.config = config\n\n\nclass CausalSelfAttention(BaseCausalSelfAttention):\n    def __init__(self, config: Config, block_idx: int) -> None:\n        \"\"\"Causal self-attention with calculating qkv matrices with a single matrix* and Low Ranking Adaptation for\n        parameter-efficient fine-tuning.\n\n        *Instead of creating multiple heads and concatenating the result (in addition to creating separate matrices for\n        query, key and value for each head) we can do this in a single pass with a single weight matrix.\n        \"\"\"\n        # Skip the parent class __init__ altogether and replace it to avoid useless allocations\n        nn.Module.__init__(self)\n        shape = (config.n_head + 2 * config.n_query_groups) * config.head_size\n        # key, query, value projections for all heads, but in a batch\n        self.attn = AdapterV2Linear(in_features=config.n_embd, out_features=shape, bias=config.bias)\n        # output projection\n        self.proj = AdapterV2Linear(config.n_embd, config.n_embd, bias=config.bias)\n        if block_idx >= config.adapter_start_layer:\n            # adapter embedding layer\n            self.adapter_wte = nn.Embedding(config.adapter_prompt_length, config.n_embd)\n            # gate for adaption\n            self.gating_factor = torch.nn.Parameter(torch.zeros(1, 1, config.n_head, 1))\n            self.reset_parameters()\n        self.block_idx = block_idx\n\n        self.config = config\n\n    def forward(\n        self,\n        x: torch.Tensor,\n        rope: RoPECache,\n        max_seq_length: int,\n        mask: Optional[torch.Tensor] = None,\n        input_pos: Optional[torch.Tensor] = None,\n        kv_cache: Optional[KVCache] = None,\n        adapter_kv_cache: Optional[KVCache] = None,\n    ) -> Tuple[torch.Tensor, Optional[KVCache], Optional[KVCache]]:\n        B, T, C = x.size()  # batch size, sequence length, embedding dimensionality (n_embd)\n\n        qkv = self.attn(x)\n\n        # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n        q_per_kv = self.config.n_head // self.config.n_query_groups\n        total_qkv = q_per_kv + 2  # each group has 1+ queries, 1 key, and 1 value\n        qkv = qkv.view(B, T, self.config.n_query_groups, total_qkv, self.config.head_size)\n        qkv = qkv.permute(0, 2, 3, 1, 4)  # (B, n_query_groups, total_qkv, T, hs)\n\n        # split batched computation into three\n        q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n\n        # repeat k and v if necessary\n        if self.config.n_query_groups != 1:  # doing this would require a full kv cache with MQA (inefficient!)\n            # for MHA this is a no-op\n            k = k.expand(B, self.config.n_query_groups, q_per_kv, T, self.config.head_size)\n            v = v.expand(B, self.config.n_query_groups, q_per_kv, T, self.config.head_size)\n\n        q = q.reshape(B, -1, T, self.config.head_size)  # (B, nh_q, T, hs)\n        k = k.reshape(B, -1, T, self.config.head_size)  # (B, nh_k, T, hs)\n        v = v.reshape(B, -1, T, self.config.head_size)  # (B, nh_v, T, hs)\n\n        n_elem = int(self.config.rotary_percentage * self.config.head_size)\n\n        cos, sin = rope\n        q_roped = apply_rope(q[..., :n_elem], cos, sin)\n        k_roped = apply_rope(k[..., :n_elem], cos, sin)\n        q = torch.cat((q_roped, q[..., n_elem:]), dim=-1)\n        k = torch.cat((k_roped, k[..., n_elem:]), dim=-1)\n\n        if kv_cache is not None:\n            cache_k, cache_v = kv_cache\n            cache_k, cache_v = cache_k.to(dtype=k.dtype), cache_v.to(dtype=v.dtype)\n            # check if reached token limit\n            if input_pos[-1] >= max_seq_length:\n                input_pos = torch.tensor(max_seq_length - 1, device=input_pos.device)\n                # shift 1 position to the left\n                cache_k = torch.roll(cache_k, -1, dims=2)\n                cache_v = torch.roll(cache_v, -1, dims=2)\n            k = cache_k.index_copy_(2, input_pos, k)\n            v = cache_v.index_copy_(2, input_pos, v)\n            kv_cache = k, v\n\n        y = self.scaled_dot_product_attention(q, k, v, mask=mask)\n\n        if self.block_idx >= self.config.adapter_start_layer:\n            aT = self.config.adapter_prompt_length\n            if adapter_kv_cache is not None:\n                ak, av = adapter_kv_cache\n            else:\n                prefix = self.adapter_wte.weight.reshape(1, aT, C)\n                aqkv = self.attn(prefix)\n                aqkv = aqkv.view(1, aT, self.config.n_query_groups, q_per_kv + 2, self.config.head_size)\n                aqkv = aqkv.permute(0, 2, 3, 1, 4)\n                _, ak, av = aqkv.split((q_per_kv, 1, 1), dim=2)\n                if self.config.n_query_groups != 1:\n                    # for MHA this is a no-op\n                    ak = ak.repeat_interleave(q_per_kv, dim=2)\n                    av = av.repeat_interleave(q_per_kv, dim=2)\n                ak = ak.view(1, -1, aT, self.config.head_size)  # (1, nh_ak, aT, hs)\n                av = av.view(1, -1, aT, self.config.head_size)  # (1, nh_av, aT, hs)\n                adapter_kv_cache = (ak, av)\n\n            amask = torch.ones(T, aT, dtype=torch.bool, device=x.device)\n            ay = self.scaled_dot_product_attention(q, ak, av, amask)\n            y = y + self.gating_factor * ay\n\n        y = y.reshape(B, T, C)  # re-assemble all head outputs side by side\n\n        # output projection\n        y = self.proj(y)\n\n        return y, kv_cache, adapter_kv_cache\n\n    def reset_parameters(self) -> None:\n        torch.nn.init.zeros_(self.gating_factor)\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with base checkpoints.\"\"\"\n        mapping = {\n            \"attn.weight\": \"attn.linear.weight\",\n            \"attn.bias\": \"attn.linear.bias\",\n            \"proj.weight\": \"proj.linear.weight\",\n            \"proj.bias\": \"proj.linear.bias\",\n        }\n        state_dict = map_old_state_dict_weights(state_dict, mapping, prefix)\n        # For compatibility with older checkpoints\n        if (key := prefix + \"gating_factor\") in state_dict and state_dict[key].size(1) == self.config.n_head:\n            state_dict[key] = state_dict[key].permute(0, 2, 1, 3)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\nclass GptNeoxMLP(lit_gpt.model.GptNeoxMLP):\n    def __init__(self, config: Config) -> None:\n        nn.Module.__init__(self)\n        self.fc = AdapterV2Linear(config.n_embd, config.intermediate_size, bias=config.bias)\n        self.proj = AdapterV2Linear(config.intermediate_size, config.n_embd, bias=config.bias)\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with base checkpoints.\"\"\"\n        mapping = {\n            \"fc.weight\": \"fc.linear.weight\",\n            \"fc.bias\": \"fc.linear.bias\",\n            \"proj.weight\": \"proj.linear.weight\",\n            \"proj.bias\": \"proj.linear.bias\",\n        }\n        state_dict = map_old_state_dict_weights(state_dict, mapping, prefix)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\nclass LLaMAMLP(lit_gpt.model.LLaMAMLP):\n    def __init__(self, config: Config) -> None:\n        nn.Module.__init__(self)\n        self.fc_1 = AdapterV2Linear(config.n_embd, config.intermediate_size, bias=config.bias)\n        self.fc_2 = AdapterV2Linear(config.n_embd, config.intermediate_size, bias=config.bias)\n        self.proj = AdapterV2Linear(config.intermediate_size, config.n_embd, bias=config.bias)\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with base checkpoints.\"\"\"\n        mapping = {\n            \"fc_1.weight\": \"fc_1.linear.weight\",\n            \"fc_1.bias\": \"fc_1.linear.bias\",\n            \"fc_2.weight\": \"fc_2.linear.weight\",\n            \"fc_2.bias\": \"fc_2.linear.bias\",\n            \"proj.weight\": \"proj.linear.weight\",\n            \"proj.bias\": \"proj.linear.bias\",\n        }\n        state_dict = map_old_state_dict_weights(state_dict, mapping, prefix)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\ndef mark_only_adapter_v2_as_trainable(model: GPT) -> None:\n    \"\"\"Sets requires_grad=False for all non-adapter weights\"\"\"\n    for name, param in model.named_parameters():\n        param.requires_grad = adapter_filter(name, param)\n"
  },
  {
    "path": "lit_gpt/config.py",
    "content": "from dataclasses import dataclass\nfrom typing import Any, Literal, Optional, Type\n\nimport torch\nfrom typing_extensions import Self\n\nimport lit_gpt.model\nfrom lit_gpt.utils import find_multiple\n\n\n@dataclass\nclass Config:\n    org: str = \"Lightning-AI\"\n    name: str = \"lit-GPT\"\n    block_size: int = 4096\n    vocab_size: int = 50254\n    padding_multiple: int = 512\n    padded_vocab_size: Optional[int] = None\n    n_layer: int = 16\n    n_head: int = 32\n    n_embd: int = 4096\n    rotary_percentage: float = 0.25\n    parallel_residual: bool = True\n    bias: bool = True\n    # to use multi-head attention (MHA), set this to `n_head` (default)\n    # to use multi-query attention (MQA), set this to 1\n    # to use grouped-query attention (GQA), set this to a value in between\n    # Example with `n_head=4`\n    # ┌───┐┌───┐┌───┐┌───┐     ┌───┐    ┌───┐             ┌───┐\n    # │ v ││ v ││ v ││ v │     │ v │    │ v │             │ v │\n    # └───┘└───┘└───┘└───┘     └───┘    └───┘             └───┘\n    #   │    │    │    │         │        │                 │\n    # ┌───┐┌───┐┌───┐┌───┐     ┌───┐    ┌───┐             ┌───┐\n    # │ k ││ k ││ k ││ k │     │ k │    │ k │             │ k │\n    # └───┘└───┘└───┘└───┘     └───┘    └───┘             └───┘\n    #   │    │    │    │      ┌──┴──┐  ┌──┴──┐      ┌────┬──┴─┬────┐\n    # ┌───┐┌───┐┌───┐┌───┐  ┌───┐┌───┐┌───┐┌───┐  ┌───┐┌───┐┌───┐┌───┐\n    # │ q ││ q ││ q ││ q │  │ q ││ q ││ q ││ q │  │ q ││ q ││ q ││ q │\n    # └───┘└───┘└───┘└───┘  └───┘└───┘└───┘└───┘  └───┘└───┘└───┘└───┘\n    # ◀──────────────────▶  ◀──────────────────▶  ◀──────────────────▶\n    #         MHA                    GQA                   MQA\n    #   n_query_groups=4       n_query_groups=2      n_query_groups=1\n    #\n    # credit https://arxiv.org/pdf/2305.13245.pdf\n    n_query_groups: Optional[int] = None\n    shared_attention_norm: bool = False\n    _norm_class: Literal[\"LayerNorm\", \"RMSNorm\"] = \"LayerNorm\"\n    norm_eps: float = 1e-5\n    _mlp_class: Literal[\"GptNeoxMLP\", \"LLaMAMLP\"] = \"GptNeoxMLP\"\n    intermediate_size: Optional[int] = None\n    condense_ratio: int = 1\n\n    def __post_init__(self):\n        # error checking\n        assert self.n_embd % self.n_head == 0\n        # vocab size should be a power of 2 to be optimal on hardware. compute the closest value\n        if self.padded_vocab_size is None:\n            self.padded_vocab_size = find_multiple(self.vocab_size, self.padding_multiple)\n        # compute the number of query groups\n        if self.n_query_groups is not None:\n            assert self.n_head % self.n_query_groups == 0\n        else:\n            self.n_query_groups = self.n_head\n        # compute the intermediate size for MLP if not set\n        if self.intermediate_size is None:\n            if self._mlp_class == \"LLaMAMLP\":\n                raise ValueError(\"The config needs to set the `intermediate_size`\")\n            self.intermediate_size = 4 * self.n_embd\n\n    @property\n    def head_size(self) -> int:\n        return self.n_embd // self.n_head\n\n    @classmethod\n    def from_name(cls, name: str, **kwargs: Any) -> Self:\n        conf_dict = name_to_config[name].copy()\n        conf_dict.update(kwargs)\n        return cls(**conf_dict)\n\n    @property\n    def mlp_class(self) -> Type:\n        # `self._mlp_class` cannot be the type to keep the config json serializable\n        return getattr(lit_gpt.model, self._mlp_class)\n\n    @property\n    def norm_class(self) -> Type:\n        # `self._norm_class` cannot be the type to keep the config json serializable\n        if self._norm_class == \"RMSNorm\":\n            from lit_gpt.rmsnorm import RMSNorm\n\n            return RMSNorm\n        elif self._norm_class == \"FusedRMSNorm\":\n            from lit_gpt.rmsnorm import FusedRMSNorm\n            return FusedRMSNorm\n        return getattr(torch.nn, self._norm_class)\n\n\n########################\n# Stability AI StableLM\n########################\nconfigs = [\n    # https://huggingface.co/stabilityai/stablelm-base-alpha-3b/blob/main/config.json\n    dict(org=\"stabilityai\", name=\"stablelm-base-alpha-3b\", padding_multiple=512),\n    # https://huggingface.co/stabilityai/stablelm-base-alpha-7b/blob/main/config.json\n    dict(org=\"stabilityai\", name=\"stablelm-base-alpha-7b\", n_head=48, n_embd=6144, padding_multiple=256),\n    # https://huggingface.co/stabilityai/stablelm-tuned-alpha-3b/blob/main/config.json\n    dict(org=\"stabilityai\", name=\"stablelm-tuned-alpha-3b\", n_head=32, padding_multiple=512),\n    # https://huggingface.co/stabilityai/stablelm-tuned-alpha-7b/blob/main/config.json\n    dict(org=\"stabilityai\", name=\"stablelm-tuned-alpha-7b\", n_head=48, n_embd=6144, padding_multiple=256),\n]\n\n####################\n# EleutherAI Pythia\n####################\npythia = [\n    # https://huggingface.co/EleutherAI/pythia-70m/blob/main/config.json\n    dict(org=\"EleutherAI\", name=\"pythia-70m\", block_size=2048, n_layer=6, n_embd=512, n_head=8, padding_multiple=128),\n    # https://huggingface.co/EleutherAI/pythia-160m/blob/main/config.json\n    dict(\n        org=\"EleutherAI\", name=\"pythia-160m\", block_size=2048, n_layer=12, n_embd=768, n_head=12, padding_multiple=128\n    ),\n    # https://huggingface.co/EleutherAI/pythia-410m/blob/main/config.json\n    dict(\n        org=\"EleutherAI\", name=\"pythia-410m\", block_size=2048, n_layer=24, n_embd=1024, n_head=16, padding_multiple=128\n    ),\n    # https://huggingface.co/EleutherAI/pythia-1b/blob/main/config.json\n    dict(org=\"EleutherAI\", name=\"pythia-1b\", block_size=2048, n_layer=16, n_embd=2048, n_head=8, padding_multiple=128),\n    # https://huggingface.co/EleutherAI/pythia-1.4b/blob/main/config.json\n    dict(\n        org=\"EleutherAI\", name=\"pythia-1.4b\", block_size=2048, n_layer=24, n_embd=2048, n_head=16, padding_multiple=128\n    ),\n    # https://huggingface.co/EleutherAI/pythia-2.8b/blob/main/config.json\n    dict(\n        org=\"EleutherAI\", name=\"pythia-2.8b\", block_size=2048, n_layer=32, n_embd=2560, n_head=32, padding_multiple=128\n    ),\n    # https://huggingface.co/EleutherAI/pythia-6.9b/blob/main/config.json\n    dict(\n        org=\"EleutherAI\", name=\"pythia-6.9b\", block_size=2048, n_layer=32, n_embd=4096, n_head=32, padding_multiple=256\n    ),\n    # https://huggingface.co/EleutherAI/pythia-12b/blob/main/config.json\n    dict(\n        org=\"EleutherAI\", name=\"pythia-12b\", block_size=2048, n_layer=36, n_embd=5120, n_head=40, padding_multiple=512\n    ),\n]\nconfigs.extend(pythia)\nfor c in pythia:\n    copy = c.copy()\n    copy[\"name\"] = f\"{c['name']}-deduped\"\n    configs.append(copy)\n\n\n####################################\n# togethercomputer RedPajama INCITE\n####################################\nredpajama_incite = [\n    # https://huggingface.co/togethercomputer/RedPajama-INCITE-Base-3B-v1/blob/main/config.json\n    dict(\n        org=\"togethercomputer\",\n        name=\"RedPajama-INCITE-{}-3B-v1\",\n        block_size=2048,\n        n_layer=32,\n        n_embd=2560,\n        n_head=32,\n        padding_multiple=256,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n    ),\n    # https://huggingface.co/togethercomputer/RedPajama-INCITE-7B-Base/blob/main/config.json\n    dict(\n        org=\"togethercomputer\",\n        name=\"RedPajama-INCITE-7B-{}\",\n        block_size=2048,\n        n_layer=32,\n        n_embd=4096,\n        n_head=32,\n        padding_multiple=256,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n    ),\n    # this redirects to the checkpoint above. kept for those who had the old weights already downloaded\n    dict(\n        org=\"togethercomputer\",\n        name=\"RedPajama-INCITE-{}-7B-v0.1\",\n        block_size=2048,\n        n_layer=32,\n        n_embd=4096,\n        n_head=32,\n        padding_multiple=256,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n    ),\n]\nfor c in redpajama_incite:\n    for kind in (\"Base\", \"Chat\", \"Instruct\"):\n        copy = c.copy()\n        copy[\"name\"] = c[\"name\"].format(kind)\n        configs.append(copy)\n\n\n#################\n# TII UAE Falcon\n#################\nfalcon = [\n    # https://huggingface.co/tiiuae/falcon-7b/blob/main/config.json\n    dict(\n        org=\"tiiuae\",\n        name=\"falcon-7b{}\",\n        block_size=2048,\n        padded_vocab_size=65024,\n        n_layer=32,\n        n_head=71,\n        n_embd=4544,\n        rotary_percentage=1.0,\n        parallel_residual=True,\n        n_query_groups=1,\n        bias=False,\n        # this is not in the config, but in the original model implementation, only for this config\n        shared_attention_norm=True,\n    ),\n    # https://huggingface.co/tiiuae/falcon-40b/blob/main/config.json\n    dict(\n        org=\"tiiuae\",\n        name=\"falcon-40b{}\",\n        block_size=2048,\n        padded_vocab_size=65024,\n        n_layer=60,\n        n_head=128,\n        n_embd=8192,\n        rotary_percentage=1.0,\n        parallel_residual=True,\n        n_query_groups=8,\n        bias=False,\n    ),\n]\nfor c in falcon:\n    for kind in (\"\", \"-instruct\"):\n        copy = c.copy()\n        copy[\"name\"] = c[\"name\"].format(kind)\n        configs.append(copy)\n\n\n#############################\n# StatNLP Research\n#############################\ntiny_LLaMA = [\n     \n    # https://twitter.com/cwolferesearch/status/1691929174175264858\n    dict(\n        org=\"StatNLP-research\",\n        name=\"tiny_LLaMA_1b\",\n        block_size=2048,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=22,\n        n_head=32,\n        n_embd=2048,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"FusedRMSNorm\",\n        norm_eps=1e-5, #Llama 2 use 1e-5. Llama 1 use 1e-6\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=5632,\n        n_query_groups=4,\n    ),\n    dict(\n        org=\"StatNLP-research\",\n        name=\"tiny_LLaMA_120M\",\n        block_size=2048,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=12,\n        n_head=12,\n        n_embd=768,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"FusedRMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=2048,\n        n_query_groups=1,\n    ),\n    dict(\n        org=\"StatNLP-research\",\n        name=\"code_tiny_LLaMA_1b\",\n        block_size=8192,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=22,\n        n_head=32,\n        n_embd=2048,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"FusedRMSNorm\",\n        norm_eps=1e-5, #Llama 2 use 1e-5. Llama 1 use 1e-6\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=5632,\n        n_query_groups=4,\n        condense_ratio= 4\n    ),\n]\nconfigs.extend(tiny_LLaMA)\n\n\n#############################\n# OpenLM Research Open LLaMA\n#############################\nopen_LLaMA = [\n    # https://huggingface.co/openlm-research/open_llama_3b/blob/main/config.json\n    dict(\n        org=\"openlm-research\",\n        name=\"open_llama_3b\",\n        block_size=2048,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=26,\n        n_head=32,\n        n_embd=3200,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=8640,\n    ),\n    # https://huggingface.co/openlm-research/open_llama_7b/blob/main/config.json\n    dict(\n        org=\"openlm-research\",\n        name=\"open_llama_7b\",\n        block_size=2048,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=32,\n        n_head=32,\n        n_embd=4096,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=11008,\n    ),\n    # https://huggingface.co/openlm-research/open_llama_13b/blob/main/config.json\n    dict(\n        org=\"openlm-research\",\n        name=\"open_llama_13b\",\n        block_size=2048,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=40,\n        n_head=40,\n        n_embd=5120,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=13824,\n    ),\n]\nconfigs.extend(open_LLaMA)\n\n\n###############\n# LMSYS Vicuna\n###############\nvicuna = [\n    # https://huggingface.co/lmsys/vicuna-7b-v1.3/blob/main/config.json\n    dict(\n        org=\"lmsys\",\n        name=\"vicuna-7b-v1.3\",\n        block_size=2048,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=32,\n        n_head=32,\n        n_embd=4096,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=11008,\n    ),\n    # https://huggingface.co/lmsys/vicuna-13b-v1.3/blob/main/config.json\n    dict(\n        org=\"lmsys\",\n        name=\"vicuna-13b-v1.3\",\n        block_size=2048,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=40,\n        n_head=40,\n        n_embd=5120,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=13824,\n    ),\n    # https://huggingface.co/lmsys/vicuna-33b-v1.3/blob/main/config.json\n    dict(\n        org=\"lmsys\",\n        name=\"vicuna-33b-v1.3\",\n        block_size=2048,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=60,\n        n_head=52,\n        n_embd=6656,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=17920,\n    ),\n    dict(\n        org=\"lmsys\",\n        name=\"vicuna-7b-v1.5\",\n        block_size=4096,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=32,\n        n_head=32,\n        n_embd=4096,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=11008,\n    ),\n    dict(\n        org=\"lmsys\",\n        name=\"vicuna-7b-v1.5-16k\",\n        block_size=16384,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=32,\n        n_head=32,\n        n_embd=4096,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=11008,\n        condense_ratio=4,\n    ),\n    dict(\n        org=\"lmsys\",\n        name=\"vicuna-13b-v1.5\",\n        block_size=4096,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=40,\n        n_head=40,\n        n_embd=5120,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=13824,\n    ),\n    dict(\n        org=\"lmsys\",\n        name=\"vicuna-13b-v1.5-16k\",\n        block_size=16384,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=40,\n        n_head=40,\n        n_embd=5120,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=13824,\n        condense_ratio=4,\n    ),\n]\nconfigs.extend(vicuna)\n\n\n#################\n# LMSYS LongChat\n#################\nlong_chat = [\n    # https://huggingface.co/lmsys/longchat-7b-16k/blob/main/config.json\n    dict(\n        org=\"lmsys\",\n        name=\"longchat-7b-16k\",\n        block_size=16384,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=32,\n        n_head=32,\n        n_embd=4096,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=11008,\n        condense_ratio=8,\n    ),\n    # https://huggingface.co/lmsys/longchat-13b-16k/blob/main/config.json\n    dict(\n        org=\"lmsys\",\n        name=\"longchat-13b-16k\",\n        block_size=16384,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=40,\n        n_head=40,\n        n_embd=5120,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=13824,\n        condense_ratio=8,\n    ),\n]\nconfigs.extend(long_chat)\n\n\n######################\n# NousResearch Hermes\n######################\nnous_research = [\n    # https://huggingface.co/NousResearch/Nous-Hermes-13B/blob/main/config.json\n    dict(\n        org=\"NousResearch\",\n        name=\"Nous-Hermes-13b\",\n        block_size=2048,\n        padded_vocab_size=32001,\n        n_layer=40,\n        n_head=40,\n        n_embd=5120,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-6,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=13824,\n    )\n]\nconfigs.extend(nous_research)\n\n\n###############\n# Meta LLaMA 2\n###############\nllama_2 = [\n    # https://huggingface.co/meta-llama/Llama-2-7b-hf/blob/main/config.json\n    dict(\n        org=\"meta-llama\",\n        name=\"Llama-2-7b{}-hf\",\n        block_size=4096,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=32,\n        n_head=32,\n        n_embd=4096,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=11008,\n    ),\n    dict(\n        org=\"meta-llama\",\n        name=\"CodeLlama-2-7b-hf\",\n        block_size=4096,\n        vocab_size=32016,\n        padded_vocab_size=32016,\n        padding_multiple=64,\n        n_layer=32,\n        n_head=32,\n        n_embd=4096,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=11008,\n    ),\n    # https://huggingface.co/meta-llama/Llama-2-13b-hf/blob/main/config.json\n    dict(\n        org=\"meta-llama\",\n        name=\"Llama-2-13b{}-hf\",\n        block_size=4096,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=40,\n        n_head=40,\n        n_embd=5120,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=13824,\n    ),\n    # https://huggingface.co/meta-llama/Llama-2-70b-hf/blob/main/config.json\n    dict(\n        org=\"meta-llama\",\n        name=\"Llama-2-70b{}-hf\",\n        block_size=4096,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=80,\n        n_head=64,\n        n_embd=8192,\n        n_query_groups=8,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=28672,\n    ),\n]\nfor c in llama_2:\n    for kind in (\"\", \"-chat\"):\n        copy = c.copy()\n        copy[\"name\"] = c[\"name\"].format(kind)\n        configs.append(copy)\n\n\n##########################\n# Stability AI FreeWilly2\n##########################\nfreewilly_2 = [\n    # https://huggingface.co/stabilityai/FreeWilly2/blob/main/config.json\n    dict(\n        org=\"stabilityai\",\n        name=\"FreeWilly2\",\n        block_size=4096,\n        vocab_size=32000,\n        padding_multiple=64,\n        n_layer=80,\n        n_head=64,\n        n_embd=8192,\n        n_query_groups=8,\n        rotary_percentage=1.0,\n        parallel_residual=False,\n        bias=False,\n        _norm_class=\"RMSNorm\",\n        norm_eps=1e-5,\n        _mlp_class=\"LLaMAMLP\",\n        intermediate_size=28672,\n    )\n]\nconfigs.extend(freewilly_2)\n\n\nname_to_config = {config[\"name\"]: config for config in configs}\n"
  },
  {
    "path": "lit_gpt/fused_cross_entropy.py",
    "content": "# Copyright (c) 2023, Tri Dao.\n\nimport torch\nimport torch.nn as nn\nimport xentropy_cuda_lib\n\n# `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for\n# `_all_gather_base` and `_reduce_scatter_base`. They require the most recent\n# version of PyTorch. The following 2 lines are for backward compatibility with\n# older PyTorch.\nif \"all_gather_into_tensor\" not in dir(torch.distributed):\n    torch.distributed.all_gather_into_tensor = torch.distributed._all_gather_base\n\n\nclass SoftmaxCrossEntropyLossFn(torch.autograd.Function):\n    @staticmethod\n    def forward(\n        ctx,\n        logits,\n        labels,\n        smoothing=0.0,\n        ignored_index=-100,\n        inplace_backward=False,\n        process_group=None,\n    ):\n        \"\"\"\n        logits: (batch, vocab_size)\n        labels: (batch,)\n        If process_group is not None, we're doing Tensor Parallel: each process is responsible for\n        one part of the vocab. The loss needs to be aggregated across processes.\n        \"\"\"\n        batch, vocab_size = logits.shape\n        assert labels.shape == (batch,)\n        world_size = 1 if process_group is None else torch.distributed.get_world_size(process_group)\n        ctx.total_classes = world_size * vocab_size\n\n        if world_size == 1:\n            losses, lse = xentropy_cuda_lib.forward(logits, labels, smoothing)\n            losses.masked_fill_(labels == ignored_index, 0)\n            labels_local = labels\n        else:\n            rank = torch.distributed.get_rank(process_group)\n            vocab_start_index, vocab_end_index = rank * vocab_size, (rank + 1) * vocab_size\n\n            # Create a mask of valid vocab ids (1 means it needs to be masked).\n            labels_mask = (labels < vocab_start_index) | (labels >= vocab_end_index)\n            ignored_mask = labels == ignored_index\n            labels_local = torch.where(ignored_mask, labels, labels - vocab_start_index)\n\n            # For tensor parallel cross entropy with smoothing, we want to pass in the total number\n            # of classes so that smoothing can be applied correctly. If total_classes=-1, use the\n            # last dimension of the input tensor.\n            losses, lse_local = xentropy_cuda_lib.forward(\n                logits, labels_local, smoothing, world_size * vocab_size\n            )\n            assert lse_local.shape == (batch,)\n            assert losses.shape == (batch,)\n            losses.masked_fill_(ignored_mask, 0)\n            # For labels == ignored_index, the loss is always 0.\n            # If there's no smoothing, if labels are in the vocab of this partition, losses contains\n            # lse_local - predicted logit, and 0 otherwise.\n            # If there's smoothing=0.1, for labels in the vocab of this partition, losses contains\n            # 0.9 * (lse_local - predicted logit) + 0.1 * (lse_local - sum logit / total_classes)\n            # For labels not in the vocab of this partition, losses contains\n            # 0.1 * (lse_local - sum logit / total_classes).\n\n            lse_allgather = torch.empty(\n                world_size, batch, dtype=lse_local.dtype, device=lse_local.device\n            )\n            torch.distributed.all_gather_into_tensor(\n                lse_allgather, lse_local.contiguous(), group=process_group\n            )\n            handle_losses = torch.distributed.all_reduce(\n                losses, op=torch.distributed.ReduceOp.SUM, group=process_group, async_op=True\n            )\n            lse = torch.logsumexp(lse_allgather, dim=0)\n            # If there's no smoothing, the total losses are lse_local - predicted_logit,\n            # we just have to subtract the lse_local and add the lse (global).\n            # If there's smoothing=0.1, the total losses are\n            # 0.9 * (lse_local - predicted_logit) + 0.1 * (sum of all lse_local - sum logit / total_classes)\n            # We want 0.9 * (lse - predicted_logit) + 0.1 * (lse - sum logit / total_classes).\n            rank_per_sample = torch.div(labels, vocab_size, rounding_mode=\"floor\")\n            lse_local = lse_allgather[\n                rank_per_sample, torch.arange(batch, device=lse_allgather.device)\n            ]\n\n            handle_losses.wait()\n            if smoothing == 0.0:\n                losses += lse - lse_local\n            else:\n                losses += (1 - smoothing) * (lse - lse_local) + smoothing * (\n                    lse - lse_allgather.sum(dim=0)\n                )\n            losses.masked_fill_(ignored_mask, 0)\n\n        ctx.save_for_backward(logits, lse, labels_local)\n        ctx.smoothing = smoothing\n        ctx.ignored_index = ignored_index\n        ctx.inplace_backward = inplace_backward\n        return losses\n\n    @staticmethod\n    def backward(ctx, grad_loss):\n        logits, lse, labels = ctx.saved_tensors\n        grad_loss = grad_loss.contiguous()\n        grad_loss.masked_fill_(labels == ctx.ignored_index, 0)\n        grad_logits = xentropy_cuda_lib.backward(\n            grad_loss, logits, lse, labels, ctx.smoothing, ctx.inplace_backward, ctx.total_classes\n        )\n        return grad_logits, None, None, None, None, None, None\n\n\nclass FusedCrossEntropyLoss(nn.Module):\n    def __init__(\n        self,\n        ignore_index=-100,\n        reduction=\"mean\",\n        label_smoothing=0.0,\n        inplace_backward=True,\n        process_group=None,\n    ):\n        super().__init__()\n        if reduction not in [\"mean\", \"none\"]:\n            raise NotImplementedError(\"Only support reduction = 'mean' or 'none'\")\n        self.ignore_index = ignore_index\n        self.reduction = reduction\n        self.label_smoothing = label_smoothing\n        self.inplace_backward = inplace_backward\n        self.process_group = process_group\n\n    def forward(self, input, target):\n        assert input.is_cuda and target.is_cuda\n        # SoftmaxCrossEntropyLoss implicitly casts to float\n        if len(input.shape) == 3:\n            input = input.view(-1, input.size(-1))\n            target = target.view(-1)\n        loss = SoftmaxCrossEntropyLossFn.apply(\n            input,\n            target,\n            self.label_smoothing,\n            self.ignore_index,\n            self.inplace_backward,\n            self.process_group,\n        )\n        if self.reduction == \"mean\":\n            return loss.sum() / (target != self.ignore_index).sum()\n        else:\n            return loss"
  },
  {
    "path": "lit_gpt/fused_rotary_embedding.py",
    "content": "# Copyright (c) 2023, Tri Dao.\n\nimport math\nfrom typing import Optional, Tuple\n\nimport rotary_emb\nimport torch\nfrom einops import rearrange, repeat\n\nclass ApplyRotaryEmb(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, x, cos, sin, interleaved=False, inplace=False):\n        \"\"\"\n            x: (batch_size, seqlen, nheads, headdim)\n            cos, sin: (seqlen, rotary_dim / 2)\n            interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead\n                of 1st half and 2nd half (GPT-NeoX style).\n        rotary_dim must be <= headdim\n        Apply rotary embedding to the first rotary_dim of x.\n        \"\"\"\n        batch, seqlen, nheads, headdim = x.shape\n        rotary_seqlen, rotary_dim = cos.shape\n        rotary_dim *= 2\n        assert rotary_dim <= headdim\n        assert seqlen <= rotary_seqlen\n        assert sin.shape == (rotary_seqlen, rotary_dim // 2)\n        x_ro = x[..., :rotary_dim]\n        x1, x2 = x_ro.chunk(2, dim=-1) if not interleaved else (x_ro[..., ::2], x_ro[..., 1::2])\n        out = torch.empty_like(x) if not inplace else x\n        out_ro = out[..., :rotary_dim]\n        if inplace:\n            o1, o2 = x1, x2\n        else:\n            o1, o2 = (\n                out_ro.chunk(2, dim=-1)\n                if not interleaved\n                else (out_ro[..., ::2], out_ro[..., 1::2])\n            )\n        rotary_emb.apply_rotary(\n            x1,\n            x2,\n            rearrange(cos[:seqlen], \"s d -> s 1 d\"),\n            rearrange(sin[:seqlen], \"s d -> s 1 d\"),\n            o1,\n            o2,\n            False,\n        )\n        if not inplace and rotary_dim < headdim:\n            out[..., rotary_dim:].copy_(x[..., rotary_dim:])\n        ctx.save_for_backward(cos, sin)\n        ctx.interleaved = interleaved\n        ctx.inplace = inplace\n        return out if not inplace else x\n\n    @staticmethod\n    def backward(ctx, do):\n        cos, sin = ctx.saved_tensors\n        _, seqlen, _, headdim = do.shape\n        rotary_dim = cos.shape[-1]\n        rotary_dim *= 2\n        inplace = ctx.inplace\n        do_ro = do[..., :rotary_dim]\n        do1, do2 = (\n            do_ro.chunk(2, dim=-1) if not ctx.interleaved else (do_ro[..., ::2], do_ro[..., 1::2])\n        )\n        dx = torch.empty_like(do) if not inplace else do\n        if inplace:\n            dx1, dx2 = do1, do2\n        else:\n            dx_ro = dx[..., :rotary_dim]\n            dx1, dx2 = (\n                dx_ro.chunk(2, dim=-1)\n                if not ctx.interleaved\n                else (dx_ro[..., ::2], dx_ro[..., 1::2])\n            )\n        rotary_emb.apply_rotary(\n            do1,\n            do2,\n            rearrange(cos[:seqlen], \"s d -> s 1 d\"),\n            rearrange(sin[:seqlen], \"s d -> s 1 d\"),\n            dx1,\n            dx2,\n            True,\n        )\n        if not inplace and rotary_dim < headdim:\n            dx[..., rotary_dim:].copy_(do[..., rotary_dim:])\n        return dx, None, None, None, None\n\n\napply_rotary_emb_func = ApplyRotaryEmb.apply\n\n"
  },
  {
    "path": "lit_gpt/lora.py",
    "content": "# Derived from https://github.com/microsoft/LoRA\n#  ------------------------------------------------------------------------------------------\n#  Copyright (c) Microsoft Corporation. All rights reserved.\n#  Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.\n#  ------------------------------------------------------------------------------------------\n\nr\"\"\"\n    Low Ranking Adaptation for LLMs scheme.\n\n             ┌───────────────────┐\n             ┆         h         ┆\n             └───────────────────┘\n                       ▲\n                       |\n                       +\n                    /     \\\n    ┌─────────────────┐    ╭───────────────╮     Matrix initialization:\n    ┆                 ┆     \\      B      /      B = 0\n    ┆   pretrained    ┆      \\    r*d    /       A = N(0, sigma^2)\n    ┆    weights      ┆       ╰─────────╯\n    ┆                 ┆       |    r    |        r - rank\n    ┆   W e R^(d*d)   ┆       | ◀─────▶ |\n    ┆                 ┆       ╭─────────╮\n    └─────────────────┘      /     A     \\\n              ▲             /     d*r     \\\n               \\           ╰───────────────╯\n                \\                ▲\n                 \\              /\n                  \\            /\n             ┌───────────────────┐\n             ┆         x         ┆\n             └───────────────────┘\n\nWith LoRA (Low Ranking Adaptation: https://arxiv.org/abs/2106.09685) instead of learning weights of size d*d,\nwe can freeze the pretrained weights and instead learn two matrices of size d*r and r*d (they will store weight updates\nfor the pretrained weights): the number of parameters in this case will be reduced drastically (depending on the rank of\ncourse) yet after multiplication of matrices d*r and r*d we will get a matrix d*d which we can sum with frozen\npretrained weights and thus fine-tune the model.\n\nThe goal of this approach is to move weight updates into a separate matrix which is decomposed with\ntwo matrices of a lower rank.\n\"\"\"\n\nimport math\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Tuple, Type, Union\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom typing_extensions import Self\n\nimport lit_gpt\nfrom lit_gpt.config import Config as BaseConfig\nfrom lit_gpt.model import GPT as BaseModel\nfrom lit_gpt.model import Block as BaseBlock\nfrom lit_gpt.model import CausalSelfAttention as BaseCausalSelfAttention\nfrom lit_gpt.model import KVCache, RoPECache\nfrom lit_gpt.utils import map_old_state_dict_weights\n\n\nclass LoRALayer(nn.Module):\n    def __init__(self, r: int, lora_alpha: int, lora_dropout: float):\n        \"\"\"Store LoRA specific attributes in a class.\n\n        Args:\n            r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of\n                the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2)\n            lora_alpha: alpha is needed for scaling updates as alpha/r\n                \"This scaling helps to reduce the need to retune hyperparameters when we vary r\"\n                https://arxiv.org/pdf/2106.09685.pdf (section 4.1)\n            lora_dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A)\n        \"\"\"\n        super().__init__()\n        assert r >= 0\n        self.r = r\n        self.lora_alpha = lora_alpha\n        # Optional dropout\n        if lora_dropout > 0.0:\n            self.lora_dropout = nn.Dropout(p=lora_dropout)\n        else:\n            self.lora_dropout = lambda x: x\n        # Mark the weight as unmerged\n        self.merged = False\n\n\nclass LoRALinear(LoRALayer):\n    # LoRA implemented in a dense layer\n    def __init__(\n        self,\n        # ↓ this part is for pretrained weights\n        in_features: int,\n        out_features: int,\n        # ↓ the remaining part is for LoRA\n        r: int = 0,\n        lora_alpha: int = 1,\n        lora_dropout: float = 0.0,\n        **kwargs,\n    ):\n        \"\"\"LoRA wrapper around linear class.\n\n        This class has three weight matrices:\n            1. Pretrained weights are stored as `self.linear.weight`\n            2. LoRA A matrix as `self.lora_A`\n            3. LoRA B matrix as `self.lora_B`\n        Only LoRA's A and B matrices are updated, pretrained weights stay frozen.\n\n        Args:\n            in_features: number of input features of the pretrained weights\n            out_features: number of output features of the pretrained weights\n            r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of\n                the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2)\n            lora_alpha: alpha is needed for scaling updates as alpha/r\n                \"This scaling helps to reduce the need to retune hyperparameters when we vary r\"\n                https://arxiv.org/pdf/2106.09685.pdf (section 4.1)\n            lora_dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A)\n        \"\"\"\n        super().__init__(r=r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)\n        self.linear = torch.nn.Linear(in_features, out_features, **kwargs)\n\n        # Actual trainable parameters\n        if r > 0:\n            self.lora_A = nn.Parameter(self.linear.weight.new_zeros((r, in_features)))\n            self.lora_B = nn.Parameter(self.linear.weight.new_zeros((out_features, r)))\n            self.scaling = self.lora_alpha / self.r\n            self.reset_parameters()\n\n    def reset_parameters(self):\n        \"\"\"Reset all the weights, even including pretrained ones.\"\"\"\n        if hasattr(self, \"lora_A\"):\n            # initialize A the same way as the default for nn.Linear and B to zero\n            # Wondering why 'a' is equal to math.sqrt(5)?: https://github.com/pytorch/pytorch/issues/15314\n            nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))\n            nn.init.zeros_(self.lora_B)\n\n    def merge(self):\n        \"\"\"Merges the LoRA weights into the full-rank weights (W = W + delta_W).\"\"\"\n        if self.r > 0 and not self.merged:\n            # Merge the weights and mark it\n            self.linear.weight.data += (self.lora_B @ self.lora_A) * self.scaling\n            self.merged = True\n\n    def forward(self, x: torch.Tensor):\n        # if weights are merged or rank is less or equal to zero (LoRA is disabled) - it's only a regular nn.Linear forward pass;\n        # otherwise in addition do the forward pass with LoRA weights and add it's output to the output from pretrained weights\n        pretrained = self.linear(x)\n        if self.r == 0 or self.merged:\n            return pretrained\n        lora = (self.lora_dropout(x) @ self.lora_A.transpose(0, 1) @ self.lora_B.transpose(0, 1)) * self.scaling\n        return pretrained + lora\n\n\nclass LoRAQKVLinear(LoRALinear):\n    # LoRA implemented in a dense layer\n    def __init__(\n        self,\n        # ↓ this part is for pretrained weights\n        in_features: int,\n        out_features: int,\n        # ↓ the remaining part is for LoRA\n        n_head: int,\n        n_query_groups: int,\n        r: int = 0,\n        lora_alpha: int = 1,\n        lora_dropout: float = 0.0,\n        enable_lora: Union[bool, Tuple[bool, bool, bool]] = False,\n        **kwargs,\n    ):\n        \"\"\"LoRA wrapper around linear class that is used for calculation of q, k and v matrices.\n\n        This class has three weight matrices:\n            1. Pretrained weights are stored as `self.linear.weight`\n            2. LoRA A matrix as `self.lora_A`\n            3. LoRA B matrix as `self.lora_B`\n        Only LoRA's A and B matrices are updated, pretrained weights stay frozen.\n\n        Args:\n            in_features: number of input features of the pretrained weights\n            out_features: number of output features of the pretrained weights\n            n_head: number of attention heads\n            n_query_groups: number of query groups (see diagram in `lit_gpt/config.py`)\n            r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of\n                the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2)\n            lora_alpha: alpha is needed for scaling updates as alpha/r\n                \"This scaling helps to reduce the need to retune hyperparameters when we vary r\"\n                https://arxiv.org/pdf/2106.09685.pdf (section 4.1)\n            lora_dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A)\n            enable_lora: MergeLinear class is for attention mechanism where qkv are calculated with a single weight matrix. If we\n                don't want to apply LoRA we can set it as False. For example if we want to apply LoRA only to `query`\n                and `value` but keep `key` without weight updates we should pass `[True, False, True]`\n        \"\"\"\n        super(LoRALinear, self).__init__(r=r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)\n        self.linear = torch.nn.Linear(in_features, out_features, **kwargs)\n        self.n_head = n_head\n        self.n_query_groups = n_query_groups\n        if isinstance(enable_lora, bool):\n            enable_lora = [enable_lora] * 3\n        assert len(enable_lora) == 3\n        self.enable_lora = enable_lora\n\n        # Actual trainable parameters\n        # To better understand initialization let's imagine that we have such parameters:\n        # ⚬ in_features: 128 (embeddings_size)\n        # ⚬ out_features: 384 (3 * embedding_size)\n        # ⚬ r: 2\n        # ⚬ enable_lora: [True, False, True]\n        if r > 0 and any(enable_lora):\n            self.lora_A = nn.Parameter(self.linear.weight.new_zeros((r * sum(enable_lora), in_features)))  # (4, 128)\n            enable_q, enable_k, enable_v = enable_lora\n            self.kv_embd_size = self.linear.in_features // (n_head // n_query_groups)\n            # qkv_shapes will be used to split a tensor with weights correctly\n            qkv_shapes = (\n                self.linear.in_features * enable_q,\n                self.kv_embd_size * enable_k,\n                self.kv_embd_size * enable_v,\n            )\n            self.qkv_shapes = [s for s in qkv_shapes if s]\n            self.lora_B = nn.Parameter(self.linear.weight.new_zeros(sum(self.qkv_shapes), r))  # (256, 2))\n            # Notes about shapes above\n            # - self.lora_A has shape (4, 128): 4 because rank is 2 and LoRA is applied only to two matrices;\n            # 128 is the input size of the x (embedding size). (4, 128) and not (128, 4) because later on in\n            # F.linear function weights are automatically transposed. In addition conv1d requires channels to\n            # be before seq length\n            # - self.lora_B has shape (256, 2): 256 because LoRA is applied only to two matrices, so the output is\n            # 128*2; 2 tells to have two channels per group for group convolution\n\n            # Scaling:\n            # This balances the pretrained model`s knowledge and the new task-specific adaptation\n            # https://lightning.ai/pages/community/tutorial/lora-llm/\n            # So, set alpha to 1.0 to fully add LoRA. If the LoRA seems to have too much effect (i.e., overfitted), set\n            # alpha to lower value. If the LoRA seems to have too little effect, set alpha to higher than 1.0. You can\n            # tune these values to your needs. This value can be even slightly greater than 1.0!\n            # https://github.com/cloneofsimo/lora\n            self.scaling = self.lora_alpha / self.r\n\n            # Compute the indices\n            # Indices are needed to properly pad weight updates with zeros. If we want to fine-tune queries and values,\n            # but not keys, then the weights update should be:\n            #\n            # [[ΔW,ΔW,ΔW, ..., 0,0,0, ..., ΔW,ΔW,ΔW,],\n            #  [....................................],\n            #  [ΔW,ΔW,ΔW, ..., 0,0,0, ..., ΔW,ΔW,ΔW,]]\n            #      ↑              ↑            ↑\n            # ________________________________________\n            # | query         | key       | value    |\n            # ----------------------------------------\n            self.lora_ind = []\n            if enable_q:\n                self.lora_ind.extend(range(0, self.linear.in_features))\n            if enable_k:\n                self.lora_ind.extend(range(self.linear.in_features, self.linear.in_features + self.kv_embd_size))\n            if enable_v:\n                self.lora_ind.extend(range(self.linear.in_features + self.kv_embd_size, self.linear.out_features))\n            self.reset_parameters()\n\n    def zero_pad(self, x: torch.Tensor) -> torch.Tensor:\n        \"\"\"Properly pad weight updates with zeros.\n\n        If, based on `self.enable_lora`, we want to fine-tune queries and values, but not keys,\n        then the weights update should be:\n\n        [[ΔW,ΔW,ΔW, ..., 0,0,0, ..., ΔW,ΔW,ΔW,],\n         [....................................],\n         [ΔW,ΔW,ΔW, ..., 0,0,0, ..., ΔW,ΔW,ΔW,]]\n            ↑              ↑            ↑\n        ________________________________________\n        | query         | key       | value    |\n        ----------------------------------------\n\n        Args:\n            x: tensor with weights update that will be padded with zeros if necessary\n\n        Returns:\n            A tensor with weight updates and zeros for deselected q, k or v\n        \"\"\"\n        # we need to do zero padding only if LoRA is disabled for one of QKV matrices\n        if all(self.enable_lora):\n            return x\n\n        # Let's image that:\n        # ⚬ input x has shape (64, 64, 256): (batch_size, sequence_length, embeddings_size)\n        # ⚬ embeddings_size: 128\n        # ⚬ self.linear.out_features: 384 (3 * embeddings_size)\n        # ⚬ enable_lora: [True, False, True]\n        # Then x has embeddings_size of 256 (2 * 128 as enable_lora only for query and value, not keys) and expected\n        # embeddings_size is 384 (self.linear.out_features), so that means that we need to pad from 256 to 384 with zeros, but\n        # only for key updates (this is where self.lora_ind comes in handy)\n        # Note: double transpose (in the beginning and in the end) is basically a guard for two-dimensional tensors\n        # for example when we want to merge/unmerge LoRA weights and pretrained weights\n        x = x.transpose(0, 1)\n        result = x.new_zeros((*x.shape[:-1], self.linear.out_features))  # (64, 64, 384)\n        result = result.view(-1, self.linear.out_features)  # (4096, 384)\n        result = result.index_copy(\n            1, torch.tensor(self.lora_ind, device=result.device), x.reshape(-1, sum(self.qkv_shapes))\n        )  # (4096, 256)\n        return result.view((*x.shape[:-1], self.linear.out_features)).transpose(0, 1)  # (64, 64, 384)\n\n    def conv1d(self, input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:\n        \"\"\"An extension of the `torch.nn.functional.conv1d` function with a logic specific to grouped queries.\n\n        If the number of heads is equal to the number of query groups - grouped queries are disabled\n        (see scheme in `lit_gpt/config.py:Config`). In this case the combined QKV matrix consists of equally sized\n        query, key and value parts, which means we can utilize `groups` argument from `conv1d`: with this argument the\n        input and weight matrices will be splitted in equally sized parts and applied separately (like having multiple\n        conv layers side by side).\n\n        Otherwise QKV matrix consists of unequally sized parts and thus we have to split input and weight matrices manually,\n        apply each part of the weight matrix to the corresponding input's part and concatenate the result.\n\n        Args:\n            input: input matrix of shape (B, C, T)\n            weight: weight matrix of shape (C_output, rank, 1).\n                \"C_output\" is defined as a sum of embedding sizes for each enabled LoRA layer (see init method of the class).\n\n        Returns:\n            A tensor with a shape (B, C_output, T)\n\n        \"\"\"\n        if self.n_head == self.n_query_groups:\n            return F.conv1d(input, weight, groups=sum(self.enable_lora))  # (B, C_output, T)\n\n        # Notation:\n        # ⚬ N: number of enabled LoRA layers (self.enable_lora)\n        # ⚬ C_output': embeddings size for each LoRA layer (not equal in size)\n        # ⚬ r: rank of all LoRA layers (equal in size)\n\n        input_splitted = input.chunk(sum(self.enable_lora), dim=1)  # N * (B, C // N, T)\n        weight_splitted = weight.split(self.qkv_shapes)  # N * (C_output', r, 1)\n        return torch.cat(\n            [F.conv1d(a, b) for a, b in zip(input_splitted, weight_splitted)], dim=1  # (B, C_output', T)\n        )  # (B, C_output, T)\n\n    def merge(self):\n        \"\"\"Merges the LoRA weights into the full-rank weights (W = W + delta_W).\"\"\"\n\n        # Let's assume that:\n        # ⚬ self.linear.weight.data: (384, 128) or (3 * embedding_size, embedding_size)\n        # ⚬ self.lora_A.data: (4, 128)\n        # ⚬ self.lora_B.data: (256, 2)\n        if self.r > 0 and any(self.enable_lora) and not self.merged:\n            delta_w = self.conv1d(\n                self.lora_A.data.unsqueeze(0),  # (4, 128) -> (1, 4, 128)\n                self.lora_B.data.unsqueeze(-1),  # (256, 2) -> (256, 2, 1)\n            ).squeeze(\n                0\n            )  # (1, 4, 128) @ (256, 2, 1) -> (1, 256, 128) -> (256, 128)\n            # W = W + delta_W (merge)\n            self.linear.weight.data += self.zero_pad(delta_w * self.scaling)  # (256, 128) after zero_pad (384, 128)\n            self.merged = True\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        \"\"\"Do the forward pass.\n\n        If LoRA's weights are merged with pretrained ones then it's a simple matrix multiplication.\n        If not, then multiply pretrained weights with input, apply LoRA on input and do summation.\n\n        Args:\n            x: input tensor of shape (batch_size, context_length, embedding_size)\n\n        Returns:\n            Output tensor of shape (batch_size, context_length, 3 * embedding_size)\n        \"\"\"\n\n        # Let's assume that:\n        # ⚬ x: (64, 64, 128) or (batch_size, context_length, embedding_size)\n        # ⚬ self.linear.weight: (384, 128) or (3 * embedding_size, embedding_size)\n        # ⚬ self.lora_A.data: (4, 128)\n        # ⚬ self.lora_B.data: (256, 2)\n\n        # if weights are merged or LoRA is disabled (r <= 0 or all `enable_lora` are False) - it's only a regular nn.Linear forward pass;\n        # otherwise in addition do the forward pass with LoRA weights and add it's output to the output from pretrained weights\n        pretrained = self.linear(x)\n        if self.r == 0 or not any(self.enable_lora) or self.merged:\n            return pretrained\n        after_A = F.linear(self.lora_dropout(x), self.lora_A)  # (64, 64, 128) @ (4, 128) -> (64, 64, 4)\n        # For F.conv1d:\n        # ⚬ input: input tensor of shape (mini-batch, in_channels, iW)\n        # ⚬ weight: filters of shape (out_channels, in_channels/groups, kW)\n        after_B = self.conv1d(\n            after_A.transpose(-2, -1),  # (64, 64, 4) -> (64, 4, 64)\n            self.lora_B.unsqueeze(-1),  # (256, 2) -> (256, 2, 1)\n        ).transpose(\n            -2, -1\n        )  # (64, 4, 64) @ (256, 2, 1) -> (64, 256, 64) -> (64, 64, 256)\n        lora = self.zero_pad(after_B) * self.scaling  # (64, 64, 256) after zero_pad (64, 64, 384)\n        return pretrained + lora\n\n\ndef mark_only_lora_as_trainable(model: nn.Module, bias: str = \"none\") -> None:\n    \"\"\"Freeze all modules except LoRA's and depending on 'bias' value unfreezes bias weights.\n\n    Args:\n        model: model with LoRA layers\n        bias:\n            ``\"none\"``: all bias weights will be frozen,\n            ``\"lora_only\"``: only bias weight for LoRA layers will be unfrozen,\n            ``\"all\"``: all bias weights will be unfrozen.\n\n    Raises:\n        NotImplementedError: if `bias` not in [\"none\", \"lora_only\", \"all\"]\n    \"\"\"\n    # freeze all layers except LoRA's\n    for n, p in model.named_parameters():\n        if \"lora_\" not in n:\n            p.requires_grad = False\n\n    # depending on the `bias` value unfreeze bias weights\n    if bias == \"none\":\n        return\n    if bias == \"all\":\n        for n, p in model.named_parameters():\n            if \"bias\" in n:\n                p.requires_grad = True\n    elif bias == \"lora_only\":\n        for m in model.modules():\n            if isinstance(m, LoRALayer) and hasattr(m, \"bias\") and m.bias is not None:\n                m.bias.requires_grad = True\n    else:\n        raise NotImplementedError\n\n\ndef lora_filter(key: str, value: Any) -> bool:\n    return \"lora_\" in key\n\n\n@dataclass\nclass Config(BaseConfig):\n    \"\"\"\n    Args:\n        r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of\n            the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2)\n        alpha: alpha is needed for scaling updates as alpha/r\n            \"This scaling helps to reduce the need to retune hyperparameters when we vary r\"\n            https://arxiv.org/pdf/2106.09685.pdf (section 4.1)\n        dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A)\n        to_*: either apply LoRA to the specified weights or not\n    \"\"\"\n\n    r: int = 0\n    alpha: int = 1\n    dropout: float = 0.0\n    to_query: bool = False\n    to_key: bool = False\n    to_value: bool = False\n    to_projection: bool = False\n    to_mlp: bool = False\n    to_head: bool = False\n\n    @property\n    def mlp_class(self) -> Type:\n        return getattr(lit_gpt.lora, self._mlp_class)\n\n\nclass GPT(BaseModel):\n    def __init__(self, config: Config) -> None:\n        nn.Module.__init__(self)\n        assert config.padded_vocab_size is not None\n        self.config = config\n\n        self.lm_head = LoRALinear(\n            config.n_embd,\n            config.padded_vocab_size,\n            bias=False,\n            r=(config.r if config.to_head else 0),\n            lora_alpha=config.alpha,\n            lora_dropout=config.dropout,\n        )\n\n        self.transformer = nn.ModuleDict(\n            dict(\n                wte=nn.Embedding(config.padded_vocab_size, config.n_embd),\n                h=nn.ModuleList(Block(config) for _ in range(config.n_layer)),\n                ln_f=config.norm_class(config.n_embd, eps=config.norm_eps),\n            )\n        )\n\n        self.rope_cache: Optional[RoPECache] = None\n        self.mask_cache: Optional[torch.Tensor] = None\n        self.kv_caches: List[KVCache] = []\n\n    def forward(\n        self,\n        idx: torch.Tensor,\n        max_seq_length: Optional[int] = None,\n        input_pos: Optional[torch.Tensor] = None,\n        lm_head_chunk_size: int = 0,\n    ) -> Union[torch.Tensor, List[torch.Tensor]]:\n        B, T = idx.size()\n        use_kv_cache = input_pos is not None\n\n        block_size = self.config.block_size\n        if max_seq_length is None:\n            max_seq_length = block_size\n        if use_kv_cache:  # not relevant otherwise\n            assert (\n                max_seq_length >= T\n            ), f\"Cannot forward sequence of length {T}, max seq length is only {max_seq_length}\"\n        assert max_seq_length <= block_size, f\"Cannot attend to {max_seq_length}, block size is only {block_size}\"\n        assert block_size >= T, f\"Cannot forward sequence of length {T}, block size is only {block_size}\"\n\n        if self.rope_cache is None:\n            self.rope_cache = self.build_rope_cache(idx)  # 2 * (block_size, head_size * rotary_percentage)\n        # passing `attn_mask` to SDPA downgrades it to use the inefficient implementation. since we only need the mask\n        # for the kv-cache support (only during inference), we only create it in that situation\n        # this will be resolved by https://github.com/pytorch/pytorch/issues/96099\n        if use_kv_cache and self.mask_cache is None:\n            self.mask_cache = self.build_mask_cache(idx)  # (1, 1, block_size, block_size)\n\n        cos, sin = self.rope_cache\n        if use_kv_cache:\n            cos = cos.index_select(0, input_pos)\n            sin = sin.index_select(0, input_pos)\n            mask = self.mask_cache.index_select(2, input_pos)\n            mask = mask[:, :, :, :max_seq_length]\n        else:\n            cos = cos[:T]\n            sin = sin[:T]\n            mask = None\n\n        # forward the model itself\n        x = self.transformer.wte(idx)  # token embeddings of shape (B, T, n_embd)\n\n        if not use_kv_cache:\n            for block in self.transformer.h:\n                x, *_ = block(x, (cos, sin), max_seq_length)\n        else:\n            self.kv_caches = self.kv_caches or self.build_kv_caches(x, max_seq_length, cos.size(-1))\n            for i, block in enumerate(self.transformer.h):\n                x, self.kv_caches[i] = block(x, (cos, sin), max_seq_length, mask, input_pos, self.kv_caches[i])\n\n        x = self.transformer.ln_f(x)\n\n        if lm_head_chunk_size > 0:\n            # chunk the lm head logits to reduce the peak memory used by autograd\n            return [self.lm_head(x_i) for x_i in x.split(lm_head_chunk_size, dim=1)]\n        return self.lm_head(x)  # (B, T, vocab_size)\n\n    @classmethod\n    def from_name(cls, name: str, **kwargs: Any) -> Self:\n        return cls(Config.from_name(name, **kwargs))\n\n    def _init_weights(self, module: nn.Module) -> None:\n        \"\"\"Meant to be used with `gpt.apply(gpt._init_weights)`. Unused method left for completeness.\"\"\"\n        super()._init_weights(module)\n        if isinstance(module, LoRALinear):\n            module.reset_parameters()\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with base checkpoints.\"\"\"\n        mapping = {\"lm_head.weight\": \"lm_head.linear.weight\"}\n        state_dict = map_old_state_dict_weights(state_dict, mapping, prefix)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\nclass Block(BaseBlock):\n    def __init__(self, config: Config) -> None:\n        nn.Module.__init__(self)\n        self.norm_1 = config.norm_class(config.n_embd, eps=config.norm_eps)\n        self.attn = CausalSelfAttention(config)\n        if not config.shared_attention_norm:\n            self.norm_2 = config.norm_class(config.n_embd, eps=config.norm_eps)\n        self.mlp = config.mlp_class(config)\n\n        self.config = config\n\n\nclass CausalSelfAttention(BaseCausalSelfAttention):\n    def __init__(self, config: Config) -> None:\n        \"\"\"Causal self-attention with calculating qkv matrices with a single matrix* and Low Ranking Adaptation for\n        parameter-efficient fine-tuning.\n\n        *Instead of creating multiple heads and concatenating the result (in addition to creating separate matrices for\n        query, key and value for each head) we can do this in a single pass with a single weight matrix.\n        \"\"\"\n        # Skip the parent class __init__ altogether and replace it to avoid\n        # useless allocations\n        nn.Module.__init__(self)\n        shape = (config.n_head + 2 * config.n_query_groups) * config.head_size\n        # key, query, value projections for all heads, but in a batch\n        self.attn = LoRAQKVLinear(\n            in_features=config.n_embd,\n            out_features=shape,\n            r=config.r,\n            lora_alpha=config.alpha,\n            lora_dropout=config.dropout,\n            enable_lora=(config.to_query, config.to_key, config.to_value),\n            bias=config.bias,\n            # for MQA/GQA support\n            n_head=config.n_head,\n            n_query_groups=config.n_query_groups,\n        )\n        # output projection\n        self.proj = LoRALinear(\n            config.n_embd,\n            config.n_embd,\n            bias=config.bias,\n            r=(config.r if config.to_projection else 0),\n            lora_alpha=config.alpha,\n            lora_dropout=config.dropout,\n        )\n\n        self.config = config\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with base checkpoints.\"\"\"\n        mapping = {\n            \"attn.weight\": \"attn.linear.weight\",\n            \"attn.bias\": \"attn.linear.bias\",\n            \"proj.weight\": \"proj.linear.weight\",\n            \"proj.bias\": \"proj.linear.bias\",\n        }\n        state_dict = map_old_state_dict_weights(state_dict, mapping, prefix)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\nclass GptNeoxMLP(lit_gpt.model.GptNeoxMLP):\n    def __init__(self, config: Config) -> None:\n        nn.Module.__init__(self)\n        self.fc = LoRALinear(\n            config.n_embd,\n            config.intermediate_size,\n            bias=config.bias,\n            r=(config.r if config.to_mlp else 0),\n            lora_alpha=config.alpha,\n            lora_dropout=config.dropout,\n        )\n        self.proj = LoRALinear(\n            config.intermediate_size,\n            config.n_embd,\n            bias=config.bias,\n            r=(config.r if config.to_mlp else 0),\n            lora_alpha=config.alpha,\n            lora_dropout=config.dropout,\n        )\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with base checkpoints.\"\"\"\n        mapping = {\n            \"fc.weight\": \"fc.linear.weight\",\n            \"fc.bias\": \"fc.linear.bias\",\n            \"proj.weight\": \"proj.linear.weight\",\n            \"proj.bias\": \"proj.linear.bias\",\n        }\n        state_dict = map_old_state_dict_weights(state_dict, mapping, prefix)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\nclass LLaMAMLP(lit_gpt.model.LLaMAMLP):\n    def __init__(self, config: Config) -> None:\n        nn.Module.__init__(self)\n        self.fc_1 = LoRALinear(\n            config.n_embd,\n            config.intermediate_size,\n            bias=config.bias,\n            r=(config.r if config.to_mlp else 0),\n            lora_alpha=config.alpha,\n            lora_dropout=config.dropout,\n        )\n        self.fc_2 = LoRALinear(\n            config.n_embd,\n            config.intermediate_size,\n            bias=config.bias,\n            r=(config.r if config.to_mlp else 0),\n            lora_alpha=config.alpha,\n            lora_dropout=config.dropout,\n        )\n        self.proj = LoRALinear(\n            config.intermediate_size,\n            config.n_embd,\n            bias=config.bias,\n            r=(config.r if config.to_mlp else 0),\n            lora_alpha=config.alpha,\n            lora_dropout=config.dropout,\n        )\n\n    def _load_from_state_dict(self, state_dict: Dict, prefix: str, *args: Any, **kwargs: Any) -> None:\n        \"\"\"For compatibility with base checkpoints.\"\"\"\n        mapping = {\n            \"fc_1.weight\": \"fc_1.linear.weight\",\n            \"fc_1.bias\": \"fc_1.linear.bias\",\n            \"fc_2.weight\": \"fc_2.linear.weight\",\n            \"fc_2.bias\": \"fc_2.linear.bias\",\n            \"proj.weight\": \"proj.linear.weight\",\n            \"proj.bias\": \"proj.linear.bias\",\n        }\n        state_dict = map_old_state_dict_weights(state_dict, mapping, prefix)\n        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)\n\n\ndef merge_lora_weights(model: GPT) -> None:\n    \"\"\"Merge LoRA weights into the full-rank weights to speed up inference.\"\"\"\n    for module in model.modules():\n        if isinstance(module, LoRALinear):\n            module.merge()\n"
  },
  {
    "path": "lit_gpt/model.py",
    "content": "\"\"\"Full definition of a GPT NeoX Language Model, all of it in this single file.\n\nBased on the nanoGPT implementation: https://github.com/karpathy/nanoGPT and\nhttps://github.com/EleutherAI/gpt-neox/tree/main/megatron/model.\n\"\"\"\nimport math\nfrom typing import Any, List, Optional, Tuple\n\nimport torch\nimport torch.nn as nn\nfrom lightning_utilities.core.imports import RequirementCache\nfrom typing_extensions import Self\nfrom flash_attn import flash_attn_func\nfrom lit_gpt.config import Config\nfrom xformers.ops import SwiGLU\nfrom .fused_rotary_embedding import apply_rotary_emb_func\nRoPECache = Tuple[torch.Tensor, torch.Tensor]\nKVCache = Tuple[torch.Tensor, torch.Tensor]\nFlashAttention2Available = RequirementCache(\"flash-attn>=2.0.0.post1\")\n\n\nclass GPT(nn.Module):\n    def __init__(self, config: Config) -> None:\n        super().__init__()\n        assert config.padded_vocab_size is not None\n        self.config = config\n\n        self.lm_head = nn.Linear(config.n_embd, config.padded_vocab_size, bias=False)\n        self.transformer = nn.ModuleDict(\n            dict(\n                wte=nn.Embedding(config.padded_vocab_size, config.n_embd),\n                h=nn.ModuleList(Block(config) for _ in range(config.n_layer)),\n                ln_f=config.norm_class(config.n_embd, eps=config.norm_eps),\n            )\n        )\n        self.rope_cache: Optional[RoPECache] = None\n        self.mask_cache: Optional[torch.Tensor] = None\n        self.kv_caches: List[KVCache] = []\n\n    def _init_weights(self, module: nn.Module, n_layer) -> None:\n        \"\"\"Meant to be used with `gpt.apply(gpt._init_weights)`.\"\"\"\n        # GPT-NeoX  https://arxiv.org/pdf/2204.06745.pdf\n        if isinstance(module, nn.Embedding):\n            torch.nn.init.normal_(module.weight, mean=0.0, std=math.sqrt(2.0 / 5 / self.config.n_embd))\n            # RWKV: set it to 1e-4\n            # torch.nn.init.uniform_(module.weight,  -1e-4, 1e-4)\n        elif isinstance(module, nn.Linear):\n            torch.nn.init.normal_(module.weight, mean=0.0, std=math.sqrt(2.0 / 5 / self.config.n_embd))\n            if module.bias is not None:\n                torch.nn.init.zeros_(module.bias)\n        # GPT-NeoX       \n        for name, p in module.named_parameters():\n            if (name == \"proj.weight\" and isinstance(module, LLaMAMLP)) or (name == \"w3.weight\" and isinstance(module, SwiGLU) or (name==\"proj.weight\" and isinstance(module, CausalSelfAttention))):  #if use xformer swiglu, fc2 layer will be renamed to w3\n                nn.init.normal_(p, mean=0.0, std=1 / math.sqrt(self.config.n_embd)  /  n_layer)\n        \n\n    def reset_cache(self) -> None:\n        self.kv_caches.clear()\n        if self.mask_cache is not None and self.mask_cache.device.type == \"xla\":\n            # https://github.com/Lightning-AI/lit-gpt/pull/83#issuecomment-1558150179\n            self.rope_cache = None\n            self.mask_cache = None\n\n    def forward(\n        self, idx: torch.Tensor, max_seq_length: Optional[int] = None, input_pos: Optional[torch.Tensor] = None\n    ) -> torch.Tensor:\n        B, T = idx.size()\n        use_kv_cache = input_pos is not None\n\n        block_size = self.config.block_size\n        if max_seq_length is None:\n            max_seq_length = block_size\n        if use_kv_cache:  # not relevant otherwise\n            assert (\n                max_seq_length >= T\n            ), f\"Cannot forward sequence of length {T}, max seq length is only {max_seq_length}\"\n        assert max_seq_length <= block_size, f\"Cannot attend to {max_seq_length}, block size is only {block_size}\"\n        assert block_size >= T, f\"Cannot forward sequence of length {T}, block size is only {block_size}\"\n\n        if self.rope_cache is None:\n            self.rope_cache = self.build_rope_cache(idx)\n        # passing `attn_mask` to SDPA downgrades it to use the inefficient implementation. since we only need the mask\n        # for the kv-cache support (only during inference), we only create it in that situation\n        # this will be resolved by https://github.com/pytorch/pytorch/issues/96099\n        if use_kv_cache and self.mask_cache is None:\n            self.mask_cache = self.build_mask_cache(idx)\n\n        cos, sin = self.rope_cache\n        if use_kv_cache:\n\n            cos = cos.index_select(0, input_pos)\n            sin = sin.index_select(0, input_pos)\n            mask = self.mask_cache.index_select(2, input_pos)\n            mask = mask[:, :, :, :max_seq_length]\n        else:\n            cos = cos[:T]\n            sin = sin[:T]\n            mask = None\n\n        # forward the model itself\n        x = self.transformer.wte(idx)  # token embeddings of shape (b, t, n_embd)\n            \n        if not use_kv_cache:\n            for block in self.transformer.h:\n                x, *_ = block(x, (cos, sin), max_seq_length)\n        else:\n            self.kv_caches = self.kv_caches or self.build_kv_caches(x, max_seq_length, cos.size(-1) * 2)\n            for i, block in enumerate(self.transformer.h):\n                x, self.kv_caches[i] = block(x, (cos, sin), max_seq_length, mask, input_pos, self.kv_caches[i])\n\n        x = self.transformer.ln_f(x)\n\n        return self.lm_head(x)  # (b, t, vocab_size)\n\n    @classmethod\n    def from_name(cls, name: str, **kwargs: Any) -> Self:\n        return cls(Config.from_name(name, **kwargs))\n\n    def build_rope_cache(self, idx: torch.Tensor) -> RoPECache:\n        return build_rope_cache(\n            seq_len=self.config.block_size,\n            n_elem=int(self.config.rotary_percentage * self.config.head_size),\n            dtype=torch.bfloat16,\n            device=idx.device,\n            condense_ratio=self.config.condense_ratio,\n        )\n\n    def build_mask_cache(self, idx: torch.Tensor) -> torch.Tensor:\n        ones = torch.ones((self.config.block_size, self.config.block_size), device=idx.device, dtype=torch.bool)\n        return torch.tril(ones).unsqueeze(0).unsqueeze(0)\n\n    def build_kv_caches(self, idx: torch.Tensor, max_seq_length: int, rope_cache_length: int) -> List[KVCache]:\n        B = idx.size(0)\n        heads = 1 if self.config.n_query_groups == 1 else self.config.n_query_groups\n\n        k_cache_shape = (\n            B,\n            max_seq_length,\n            heads,\n            rope_cache_length + self.config.head_size - int(self.config.rotary_percentage * self.config.head_size),\n        )\n        v_cache_shape = (B, max_seq_length, heads, self.config.head_size)\n        device = idx.device\n        return [\n            (torch.zeros(k_cache_shape, device=device), torch.zeros(v_cache_shape, device=device))\n            for _ in range(self.config.n_layer)\n        ]\n\n\nclass Block(nn.Module):\n    def __init__(self, config: Config) -> None:\n        super().__init__()\n        self.norm_1 = config.norm_class(config.n_embd, eps=config.norm_eps)\n        self.attn = CausalSelfAttention(config)\n        if not config.shared_attention_norm:\n            self.norm_2 = config.norm_class(config.n_embd, eps=config.norm_eps)\n        self.mlp = config.mlp_class(config)\n        self.config = config\n    def forward(\n        self,\n        x: torch.Tensor,\n        rope: RoPECache,\n        max_seq_length: int,\n        mask: Optional[torch.Tensor] = None,\n        input_pos: Optional[torch.Tensor] = None,\n        kv_cache: Optional[KVCache] = None,\n    ) -> Tuple[torch.Tensor, Optional[KVCache]]:\n\n        n_1 = self.norm_1(x)\n        h, new_kv_cache = self.attn(n_1, rope, max_seq_length, mask, input_pos, kv_cache)\n        if self.config.parallel_residual:\n            n_2 = n_1 if self.config.shared_attention_norm else self.norm_2(x)\n            x = x + h + self.mlp(n_2)\n        else:\n            if self.config.shared_attention_norm:\n                raise NotImplementedError(\n                    \"No checkpoint amongst the ones we support uses this configuration\"\n                    \" (non-parallel residual and shared attention norm).\"\n                )\n            \n            x = x + h\n            x = x + self.mlp(self.norm_2(x))\n        return x, new_kv_cache\n\n\nclass CausalSelfAttention(nn.Module):\n    def __init__(self, config: Config) -> None:\n        super().__init__()\n        shape = (config.n_head + 2 * config.n_query_groups) * config.head_size\n        # key, query, value projections for all heads, but in a batch\n        self.attn = nn.Linear(config.n_embd, shape, bias=config.bias)\n        # output projection\n        self.proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)\n\n        self.config = config\n\n    def forward(\n        self,\n        x: torch.Tensor,\n        rope: RoPECache,\n        max_seq_length: int,\n        mask: Optional[torch.Tensor] = None,\n        input_pos: Optional[torch.Tensor] = None,\n        kv_cache: Optional[KVCache] = None,\n    ) -> Tuple[torch.Tensor, Optional[KVCache]]:\n        B, T, C = x.size()  # batch size, sequence length, embedding dimensionality (n_embd)\n\n        qkv = self.attn(x)\n\n        # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n        q_per_kv = self.config.n_head // self.config.n_query_groups\n        total_qkv = q_per_kv + 2  # each group has 1+ queries, 1 key, and 1 value\n        qkv = qkv.view(B, T, self.config.n_query_groups, total_qkv, self.config.head_size) # (B, T, n_query_groups, total_qkv, hs)\n        # qkv = qkv.permute(0, 2, 3, 1, 4)  # (B, n_query_groups, total_qkv, T, hs)\n\n        # split batched computation into three\n        q, k, v = qkv.split((q_per_kv, 1, 1), dim=-2)\n\n        # repeat k and v if necessary\n        # Peiyuan: we do not need to do this as flash attention 2 already support GQA\n        # if self.config.n_query_groups != 1:  # doing this would require a full kv cache with MQA (inefficient!)\n        #     # for MHA this is a no-op\n        #     k = k.expand(B, self.config.n_query_groups, q_per_kv, T, self.config.head_size)\n        #     v = v.expand(B, self.config.n_query_groups, q_per_kv, T, self.config.head_size)\n\n        q = q.reshape(B,  T, -1, self.config.head_size)  # (B, T, nh_q, hs)\n        k = k.reshape(B,  T, -1, self.config.head_size)  \n        v = v.reshape(B,  T, -1, self.config.head_size)  \n\n        cos, sin = rope\n\n        # apply rope in fp32 significanly stabalize training\n        # fused rope expect (batch_size, seqlen, nheads, headdim)\n        q = apply_rotary_emb_func(q, cos, sin, False, True)\n        k = apply_rotary_emb_func(k, cos, sin, False, True)\n        \n        # n_elem = int(self.config.rotary_percentage * self.config.head_size)\n    \n        # q_roped = apply_rope(q[..., :n_elem], cos.repeat(1,2), sin.repeat(1,2))\n        # k_roped = apply_rope(k[..., :n_elem], cos.repeat(1,2), sin.repeat(1,2))\n        # print( (q_roped - q).sum())\n        # q = torch.cat((q_roped, q[..., n_elem:]), dim=-1)\n        # k = torch.cat((k_roped, k[..., n_elem:]), dim=-1)\n\n        if kv_cache is not None:\n            cache_k, cache_v = kv_cache\n            cache_k, cache_v = cache_k.to(dtype=k.dtype), cache_v.to(dtype=v.dtype)\n            # check if reached token limit\n            if input_pos[-1] >= max_seq_length:\n                input_pos = torch.tensor(max_seq_length - 1, device=input_pos.device)\n                # shift 1 position to the left\n                cache_k = torch.roll(cache_k, -1, dims=1)\n                cache_v = torch.roll(cache_v, -1, dims=1)\n\n            k = cache_k.index_copy_(1, input_pos, k)\n            v = cache_v.index_copy_(1, input_pos, v)\n            kv_cache = k, v\n\n        y = self.scaled_dot_product_attention(q, k, v, mask=mask)\n\n        y = y.reshape(B, T, C)  # re-assemble all head outputs side by side\n\n        # output projection\n        y = self.proj(y)\n\n        return y, kv_cache\n\n    def scaled_dot_product_attention(\n        self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: Optional[torch.Tensor] = None\n    ):\n        scale = 1.0 / math.sqrt(self.config.head_size)\n        \n        if (\n            FlashAttention2Available\n            and mask is None\n            and q.device.type == \"cuda\"\n            and q.dtype in (torch.float16, torch.bfloat16)\n        ):\n            from flash_attn import flash_attn_func\n\n            return flash_attn_func(q, k, v, dropout_p=0.0, softmax_scale=scale, causal=True)\n        q = q.transpose(1, 2)\n        k = k.transpose(1, 2)\n        v = v.transpose(1, 2)\n        if q.size() != k.size():\n             k = k.repeat_interleave(q.shape[1]//k.shape[1], dim=1)\n             v = v.repeat_interleave(q.shape[1]//v.shape[1], dim=1)\n        y = torch.nn.functional.scaled_dot_product_attention(\n            q, k, v, attn_mask=mask, dropout_p=0.0, scale=scale, is_causal=mask is None\n        )\n        return y.transpose(1, 2)\n\n\nclass GptNeoxMLP(nn.Module):\n    def __init__(self, config: Config) -> None:\n        super().__init__()\n        self.fc = nn.Linear(config.n_embd, config.intermediate_size, bias=config.bias)\n        self.proj = nn.Linear(config.intermediate_size, config.n_embd, bias=config.bias)\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.fc(x)\n        x = torch.nn.functional.gelu(x)\n        return self.proj(x)\n\n\nclass LLaMAMLP(nn.Module):\n    def __init__(self, config: Config) -> None:\n        super().__init__()\n        # self.fc_1 = nn.Linear(config.n_embd, config.intermediate_size, bias=config.bias)\n        # self.fc_2 = nn.Linear(config.n_embd, config.intermediate_size, bias=config.bias)\n        # self.proj = nn.Linear(config.intermediate_size, config.n_embd, bias=config.bias)\n        self.swiglu = SwiGLU(config.n_embd,config.intermediate_size, bias=False, _pack_weights=False)\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        # x_fc_1 = self.fc_1(x)\n        # x_fc_2 = self.fc_2(x)\n        # x = torch.nn.functional.silu(x_fc_1) * x_fc_2\n        # return self.proj(x)\n        return self.swiglu(x)\n\n\ndef build_rope_cache(\n    seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000, condense_ratio: int = 1\n) -> RoPECache:\n    \"\"\"Enhanced Transformer with Rotary Position Embedding.\n\n    Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/\n    transformers/rope/__init__.py. MIT License:\n    https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.\n    \"\"\"\n    # $\\Theta = {\\theta_i = 10000^{\\frac{2(i-1)}{d}}, i \\in [1, 2, ..., \\frac{d}{2}]}$\n    theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, device=device) / n_elem))\n\n    # Create position indexes `[0, 1, ..., seq_len - 1]`\n    seq_idx = torch.arange(seq_len, device=device) / condense_ratio\n\n    # Calculate the product of position index and $\\theta_i$\n    idx_theta = torch.outer(seq_idx, theta)\n\n    cos, sin = torch.cos(idx_theta), torch.sin(idx_theta)\n\n    # added by peiyuan to ensure same data type with q, k, to use fused rotary embedding\n    if dtype == torch.bfloat16:\n        return cos.bfloat16(), sin.bfloat16()\n    # this is to mimic the behaviour of complex32, else we will get different results\n    if dtype in (torch.float16, torch.bfloat16, torch.int8):\n        return cos.half(), sin.half()\n    return cos, sin\n\n\ndef apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:\n    head_size = x.size(-1)\n    x1 = x[..., : head_size // 2]  # (B, nh, T, hs/2)\n    x2 = x[..., head_size // 2 :]  # (B, nh, T, hs/2)\n    rotated = torch.cat((-x2, x1), dim=-1)  # (B, nh, T, hs)\n    roped = (x * cos) + (rotated * sin)\n    return roped.type_as(x)\n"
  },
  {
    "path": "lit_gpt/packed_dataset.py",
    "content": "# Very loosely inspired by indexed_dataset in Fairseq, Megatron\n# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/data/indexed_dataset.py\n\n\nimport os\nimport random\nimport struct\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import IterableDataset, get_worker_info\n\ndtypes = {1: np.uint8, 2: np.int8, 3: np.int16, 4: np.int32, 5: np.int64, 6: np.float32, 7: np.float64, 8: np.uint16}\n\n\ndef code(dtype):\n    for k in dtypes:\n        if dtypes[k] == dtype:\n            return k\n    raise ValueError(dtype)\n\n\nHDR_MAGIC = b\"LITPKDS\"\nHDR_SIZE = 24  # bytes\n\n\nclass PackedDataset(IterableDataset):\n    def __init__(\n        self, filenames, n_chunks, block_size, seed=12345, shuffle=True, wrap=False, num_processes=1, process_rank=0\n    ):\n        self._filenames = filenames\n        self._n_chunks = n_chunks\n        self._block_size = block_size\n        self._seed = seed\n        self._shuffle = shuffle\n        self._wrap = wrap\n        self._num_processes = num_processes\n        self._process_rank = process_rank\n\n    def __iter__(self):\n        worker_info = get_worker_info()\n        num_workers = worker_info.num_workers if worker_info is not None else 1\n        worker_id = worker_info.id if worker_info is not None else 0\n        num_shards = num_workers * self._num_processes\n        shard_id = self._process_rank * num_workers + worker_id\n\n        max_num_files = len(self._filenames) // num_shards * num_shards\n        filenames = self._filenames[shard_id:max_num_files:num_shards]\n\n        return PackedDatasetIterator(\n            filenames=filenames,\n            n_chunks=self._n_chunks,\n            block_size=self._block_size,\n            seed=self._seed,\n            shuffle=self._shuffle,\n            wrap=self._wrap,\n        )\n\n\nclass PackedDatasetBuilder(object):\n    def __init__(self, outdir, prefix, chunk_size, sep_token, dtype=\"auto\", vocab_size=None):\n        if dtype == \"auto\":\n            if vocab_size is None:\n                raise ValueError(\"vocab_size cannot be None when dtype='auto'\")\n            if vocab_size is not None and vocab_size < 65500:\n                self._dtype = np.uint16\n            else:\n                self._dtype = np.int32\n        else:\n            self._dtype = dtype\n        self._counter = 0\n        self._chunk_size = chunk_size\n        self._outdir = outdir\n        self._prefix = prefix\n        self._sep_token = sep_token\n        self._arr = np.zeros(self._chunk_size, dtype=self._dtype)\n        self._arr.fill(self._sep_token)\n        self._idx = 0\n        self._version = 1\n        self._filenames = []\n\n    def _write_chunk(self):\n        filename = f\"{self._prefix}_{self._counter:010d}.bin\"\n        filename = os.path.join(self._outdir, filename)\n\n        with open(filename, \"wb\") as f:\n            f.write(HDR_MAGIC)\n            f.write(struct.pack(\"<Q\", self._version))\n            f.write(struct.pack(\"<B\", code(self._dtype)))\n            f.write(struct.pack(\"<Q\", self._chunk_size))\n            f.write(self._arr.tobytes(order=\"C\"))\n\n        self._filenames.append(filename)\n        self._counter += 1\n        self._arr.fill(self._sep_token)\n        self._idx = 0\n\n    @property\n    def dtype(self):\n        return self._dtype\n\n    @property\n    def filenames(self):\n        return self._filenames.copy()\n\n    def add_array(self, arr):\n        while self._idx + arr.shape[0] > self._chunk_size:\n            part_len = self._chunk_size - self._idx\n            self._arr[self._idx : self._idx + part_len] = arr[:part_len]\n            self._write_chunk()\n            arr = arr[part_len:]\n\n        arr_len = arr.shape[0]\n        self._arr[self._idx : self._idx + arr_len] = arr\n        self._idx += arr_len\n\n    def write_reminder(self):\n        self._write_chunk()\n\n\nclass PackedDatasetIterator:\n    def __init__(self, filenames, n_chunks, block_size, seed, shuffle, wrap):\n        self._seed = seed\n        self._shuffle = shuffle\n        self._rng = np.random.default_rng(seed) if shuffle else None\n        self._block_idxs = None\n\n        self._wrap = wrap\n\n        # TODO: instead of filenames, we could have a single text stream\n        #       (or text file) with the sequence of all files to be\n        #       fetched/loaded.\n        self._filenames = filenames\n        self._file_idx = 0\n\n        self._n_chunks = n_chunks\n\n        self._dtype = None\n        self._block_size = block_size\n        self._n_blocks = None\n\n        self._mmaps = []\n        self._buffers = []\n\n        self._block_idxs = []\n        self._curr_idx = 0\n\n        self._load_n_chunks()\n\n    def _read_header(self, path):\n        with open(path, \"rb\") as f:\n            magic = f.read(len(HDR_MAGIC))\n            assert magic == HDR_MAGIC, \"File doesn't match expected format.\"\n            version = struct.unpack(\"<Q\", f.read(8))\n            assert version == (1,)\n            (dtype_code,) = struct.unpack(\"<B\", f.read(1))\n            dtype = dtypes[dtype_code]\n            (chunk_size,) = struct.unpack(\"<Q\", f.read(8))\n        return dtype, chunk_size\n\n    def _close_mmaps(self):\n        for mmap in self._mmaps:\n            mmap._mmap.close()\n\n    def _load_n_chunks(self):\n        self._close_mmaps()\n        self._mmaps = []\n        self._buffers = []\n\n        if self._n_chunks > len(self._filenames[self._file_idx :]):\n            # if not self._wrap:\n            #     raise StopIteration\n            self._file_idx = 0\n\n        for i in range(self._n_chunks):\n            filename = self._filenames[self._file_idx + i]\n            if self._dtype is None:\n                self._dtype, self._chunk_size = self._read_header(filename)\n                self._n_blocks = self._chunk_size // self._block_size\n            # TODO: check header matches with previous files\n            mmap = np.memmap(filename, mode=\"r\", order=\"C\", offset=HDR_SIZE)\n            self._mmaps.append(mmap)\n            self._buffers.append(memoryview(mmap))\n\n        self._file_idx += self._n_chunks\n        n_all_blocks = self._n_chunks * self._n_blocks\n\n        self._block_idxs = self._rng.permutation(n_all_blocks) if self._shuffle else range(n_all_blocks)\n\n        self._curr_idx = 0\n\n    def __del__(self):\n        self._close_mmaps()\n        del self._mmaps\n        del self._buffers\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self._curr_idx >= len(self._block_idxs):\n            self._load_n_chunks()\n            # TODO: trigger fetching next next n_chunks if remote\n        block_idx = self._block_idxs[self._curr_idx]\n        chunk_id = block_idx // self._n_blocks\n        buffer = self._buffers[chunk_id]\n        elem_id = (block_idx % self._n_blocks) * self._block_size\n        offset = np.dtype(self._dtype).itemsize * elem_id\n        arr = np.frombuffer(buffer, dtype=self._dtype, count=self._block_size, offset=offset)\n        self._curr_idx += 1\n        return torch.from_numpy(arr.astype(np.int64))\n\n\nclass CombinedDataset(IterableDataset):\n    def __init__(self, datasets, seed, weights=None):\n        self._seed = seed\n        self._datasets = datasets\n        self._weights = weights\n        n_datasets = len(datasets)\n        if weights is None:\n            self._weights = [1 / n_datasets] * n_datasets\n\n    def __iter__(self):\n        return CombinedDatasetIterator(self._datasets, self._seed, self._weights)\n\n\nclass CombinedDatasetIterator:\n    def __init__(self, datasets, seed, weights):\n        self._datasets = [iter(el) for el in datasets]\n        self._weights = weights\n        self._rng = random.Random(seed)\n\n    def __next__(self):\n        (dataset,) = self._rng.choices(self._datasets, weights=self._weights, k=1)\n        return next(dataset)\n"
  },
  {
    "path": "lit_gpt/rmsnorm.py",
    "content": "import torch\n# Copyright (c) 2022, Tri Dao.\n# Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py AND https://github.com/Dao-AILab/flash-attention/blob/7a983df74215e035e566e37125b0a71e3618f39d/flash_attn/ops/layer_norm.py#L16\n\nimport dropout_layer_norm\nimport torch\nfrom torch.nn import init\n\n\ndef maybe_align(x, alignment_in_bytes=16):\n    \"\"\"Assume that x already has last dim divisible by alignment_in_bytes\"\"\"\n    # TD [2023-07-04] I'm not 100% sure that clone will align the memory\n    # https://discuss.pytorch.org/t/how-to-ensure-that-tensor-data-ptr-is-aligned-to-16-bytes/183440\n    return x if x.data_ptr() % alignment_in_bytes == 0 else x.clone()\n\n\ndef _dropout_add_layer_norm_forward(\n    x0,\n    residual,\n    gamma,\n    beta,\n    rowscale,\n    colscale,\n    dropout_p,\n    epsilon,\n    residual_in_fp32=False,\n    is_rms_norm=False,\n):\n    \"\"\"Assume that arguments are contiguous and aligned to 16 bytes\"\"\"\n    hidden_size = gamma.numel()\n    x0mat = x0.view((-1, hidden_size))\n    residualmat = residual.view((-1, hidden_size)) if residual is not None else None\n    rowscale = rowscale.view(-1) if rowscale is not None else None\n    zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd(\n        x0mat,\n        residualmat,\n        gamma,\n        beta,\n        rowscale,\n        colscale,\n        None,\n        None,\n        dropout_p,\n        epsilon,\n        1.0,\n        0,\n        None,\n        residual_in_fp32,\n        is_rms_norm,\n    )\n    # dmask is None if dropout_p == 0.0\n    # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype\n    return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma\n\n\ndef _dropout_add_layer_norm_backward(\n    dz,\n    dx,\n    x,\n    x0,\n    dmask,\n    mu,\n    rsigma,\n    gamma,\n    rowscale,\n    colscale,\n    dropout_p,\n    has_residual,\n    is_rms_norm=False,\n):\n    \"\"\"Assume that arguments are contiguous and aligned to 16 bytes\n    dx == None means that it was a post-norm architecture\n    (x = drop(x0) + residual was not returned in the fwd).\n    x0 must not be None if we have colscale.\n    \"\"\"\n    hidden_size = gamma.numel()\n    xmat = x.view((-1, hidden_size))\n    dzmat = dz.view(xmat.shape)\n    dxmat = dx.view(xmat.shape) if dx is not None else None\n    x0mat = x0.view((-1, hidden_size)) if x0 is not None else None\n    rowscale = rowscale.view(-1) if rowscale is not None else None\n    if colscale is not None:\n        assert x0 is not None, \"x0 is required to compute the gradient of colscale\"\n    dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd(\n        dzmat,\n        dxmat,\n        xmat,\n        x0mat,\n        dmask,\n        mu,\n        rsigma,\n        gamma,\n        rowscale,\n        colscale,\n        None,\n        None,\n        dropout_p,\n        1.0,\n        0,\n        has_residual,\n        is_rms_norm,\n    )\n    # dresidualmat is None if not has_residual\n    if colscale is None:\n        return dx0mat, dresidualmat, dgamma, dbeta\n    else:\n        dcolscale = rest[0]\n        return dx0mat, dresidualmat, dgamma, dbeta, dcolscale\n\n\ndef _dropout_add_layer_norm_subset_forward(\n    x0,\n    residual,\n    gamma,\n    beta,\n    colscale,\n    x0_subset,\n    out_subset,\n    dropout_p,\n    epsilon,\n    rowscale_const,\n    out_numrows,\n    residual_in_fp32=False,\n    is_rms_norm=False,\n):\n    \"\"\"Assume that arguments are contiguous and aligned to 16 bytes\"\"\"\n    hidden_size = gamma.numel()\n    x0mat = x0.view((-1, hidden_size))\n    residualmat = residual.view((-1, hidden_size)) if residual is not None else None\n    x0_subset = x0_subset.view(-1) if x0_subset is not None else None\n    out_subset = out_subset.view(-1) if out_subset is not None else None\n    zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd(\n        x0mat,\n        residualmat,\n        gamma,\n        beta,\n        None,\n        colscale,\n        x0_subset,\n        out_subset,\n        dropout_p,\n        epsilon,\n        rowscale_const,\n        out_numrows,\n        None,\n        residual_in_fp32,\n        is_rms_norm,\n    )\n    # dmask is None if dropout_p == 0.0\n    # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype\n    return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma\n\n\ndef _dropout_add_layer_norm_subset_backward(\n    dz,\n    dx,\n    x,\n    x0,\n    dmask,\n    mu,\n    rsigma,\n    gamma,\n    colscale,\n    x0_subset,\n    out_subset,\n    dropout_p,\n    rowscale_const,\n    x0_numrows,\n    has_residual,\n    is_rms_norm=False,\n):\n    \"\"\"Assume that arguments are contiguous and aligned to 16 bytes\n    dx == None means that it was a post-norm architecture\n    (x = drop(x0) + residual was not returned in the fwd).\n    x0 must not be None if we have colscale.\n    \"\"\"\n    hidden_size = gamma.numel()\n    xmat = x.view((-1, hidden_size))\n    dzmat = dz.view(-1, hidden_size)\n    dxmat = dx.view(xmat.shape) if dx is not None else None\n    x0mat = x0.view((-1, hidden_size)) if x0 is not None else None\n    x0_subset = x0_subset.view(-1) if x0_subset is not None else None\n    out_subset = out_subset.view(-1) if out_subset is not None else None\n    if colscale is not None:\n        assert x0 is not None, \"x0 is required to compute the gradient of colscale\"\n    dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd(\n        dzmat,\n        dxmat,\n        xmat,\n        x0mat,\n        dmask,\n        mu,\n        rsigma,\n        gamma,\n        None,\n        colscale,\n        x0_subset,\n        out_subset,\n        dropout_p,\n        rowscale_const,\n        x0_numrows,\n        has_residual,\n        is_rms_norm,\n    )\n    # dresidualmat is None if not has_residual\n    if colscale is None:\n        return dx0mat, dresidualmat, dgamma, dbeta\n    else:\n        dcolscale = rest[0]\n        return dx0mat, dresidualmat, dgamma, dbeta, dcolscale\n\n\ndef _dropout_add_layer_norm_parallel_residual_forward(\n    x0,\n    x1,\n    residual,\n    gamma0,\n    beta0,\n    gamma1,\n    beta1,\n    dropout_p,\n    epsilon,\n    residual_in_fp32=False,\n    is_rms_norm=False,\n):\n    \"\"\"Assume that arguments are contiguous and aligned to 16 bytes\"\"\"\n    hidden_size = gamma0.numel()\n    x0mat = x0.view((-1, hidden_size))\n    x1mat = x1.view((-1, hidden_size)) if x1 is not None else None\n    residualmat = residual.view((-1, hidden_size)) if residual is not None else None\n    (\n        z0mat,\n        z1mat,\n        xmat,\n        dmask0,\n        dmask1,\n        mu,\n        rsigma,\n    ) = dropout_layer_norm.dropout_add_ln_parallel_residual_fwd(\n        x0mat,\n        x1mat,\n        residualmat,\n        gamma0,\n        beta0,\n        gamma1,\n        beta1,\n        dropout_p,\n        epsilon,\n        None,\n        residual_in_fp32,\n        is_rms_norm,\n    )\n    # dmask0 and dmask1 are None if dropout_p == 0.0\n    # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype\n    return z0mat, z1mat, xmat if xmat is not None else x0mat, dmask0, dmask1, mu, rsigma\n\n\ndef _dropout_add_layer_norm_parallel_residual_backward(\n    dz0,\n    dz1,\n    dx,\n    x,\n    dmask0,\n    dmask1,\n    mu,\n    rsigma,\n    gamma0,\n    gamma1,\n    dropout_p,\n    has_x1,\n    has_residual,\n    is_rms_norm=False,\n):\n    \"\"\"Assume that arguments are contiguous and aligned to 16 bytes\n    dx == None means that it was a post-norm architecture\n    (x = drop(x0) + residual was not returned in the fwd).\n    \"\"\"\n    hidden_size = gamma0.numel()\n    xmat = x.view((-1, hidden_size))\n    dz0mat = dz0.view(xmat.shape)\n    dz1mat = dz1.view(xmat.shape) if dz1 is not None else None\n    dxmat = dx.view(xmat.shape) if dx is not None else None\n    (\n        dx0mat,\n        dx1mat,\n        dresidualmat,\n        dgamma0,\n        dbeta0,\n        dgamma1,\n        dbeta1,\n        *rest,\n    ) = dropout_layer_norm.dropout_add_ln_parallel_residual_bwd(\n        dz0mat,\n        dz1mat,\n        dxmat,\n        xmat,\n        dmask0,\n        dmask1,\n        mu,\n        rsigma,\n        gamma0,\n        gamma1,\n        dropout_p,\n        has_x1,\n        has_residual,\n        is_rms_norm,\n    )\n    # dresidualmat is None if not has_residual\n    return dx0mat, dx1mat, dresidualmat, dgamma0, dbeta0, dgamma1, dbeta1\n\n\nclass DropoutAddLayerNormFn(torch.autograd.Function):\n    @staticmethod\n    def forward(\n        ctx,\n        x0,\n        residual,\n        gamma,\n        beta,\n        rowscale,\n        colscale,\n        dropout_p,\n        epsilon,\n        residual_in_fp32=False,\n        prenorm=False,\n        is_rms_norm=False,\n        return_dmask=False,\n    ):\n        x0 = maybe_align(x0.contiguous(), 16)\n        residual = maybe_align(residual.contiguous(), 16) if residual is not None else None\n        gamma = maybe_align(gamma.contiguous(), 16)\n        beta = maybe_align(beta.contiguous(), 16) if beta is not None else None\n        rowscale = maybe_align(rowscale.contiguous(), 16) if rowscale is not None else None\n        colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None\n        zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_forward(\n            x0,\n            residual,\n            gamma,\n            beta,\n            rowscale,\n            colscale,\n            dropout_p,\n            epsilon,\n            residual_in_fp32,\n            is_rms_norm,\n        )\n        # Only need to save x0 if we need to compute gradient wrt colscale\n        x0_saved = x0 if colscale is not None else None\n        ctx.save_for_backward(\n            xmat.view(x0.shape), x0_saved, dmask, gamma, mu, rsigma, rowscale, colscale\n        )\n        ctx.prenorm = prenorm\n        ctx.dropout_p = dropout_p\n        ctx.has_residual = residual is not None\n        ctx.is_rms_norm = is_rms_norm\n        ctx.has_beta = beta is not None\n        if not return_dmask:\n            return (\n                zmat.view(x0.shape) if not prenorm else (zmat.view(x0.shape), xmat.view(x0.shape))\n            )\n        else:\n            dmask = (\n                dmask.view(x0.shape)\n                if dropout_p > 0.0\n                else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)\n            )\n            ctx.mark_non_differentiable(dmask)\n            return (\n                (zmat.view(x0.shape), dmask)\n                if not prenorm\n                else (zmat.view(x0.shape), xmat.view(x0.shape), dmask)\n            )\n\n    @staticmethod\n    def backward(ctx, dz, *args):\n        # assert dz.is_contiguous()\n        dz = maybe_align(dz.contiguous(), 16)  # this happens!\n        dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None\n        x, x0, dmask, gamma, mu, rsigma, rowscale, colscale = ctx.saved_tensors\n        # x0 is None if colscale is None\n        dropout_p = ctx.dropout_p\n        has_residual = ctx.has_residual\n        dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_backward(\n            dz,\n            dx,\n            x,\n            x0,\n            dmask,\n            mu,\n            rsigma,\n            gamma,\n            rowscale,\n            colscale,\n            dropout_p,\n            has_residual,\n            ctx.is_rms_norm,\n        )\n        dx0 = dx0mat.view(x.shape)\n        dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None\n        dcolscale = rest[0] if colscale is not None else None\n        return (\n            dx0,\n            dresidual,\n            dgamma,\n            dbeta if ctx.has_beta else None,\n            None,\n            dcolscale,\n            None,\n            None,\n            None,\n            None,\n            None,\n            None,\n        )\n\n\nclass DropoutAddLayerNormSubsetFn(torch.autograd.Function):\n    @staticmethod\n    def forward(\n        ctx,\n        x0,\n        residual,\n        gamma,\n        beta,\n        colscale,\n        x0_subset,\n        out_subset,\n        dropout_p,\n        epsilon,\n        rowscale_const,\n        out_numrows,\n        residual_in_fp32=False,\n        prenorm=False,\n        is_rms_norm=False,\n        return_dmask=False,\n    ):\n        x0 = maybe_align(x0.contiguous(), 16)\n        residual = maybe_align(residual.contiguous(), 16) if residual is not None else None\n        gamma = maybe_align(gamma.contiguous(), 16)\n        beta = maybe_align(beta.contiguous(), 16) if beta is not None else None\n        colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None\n        zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_subset_forward(\n            x0,\n            residual,\n            gamma,\n            beta,\n            colscale,\n            x0_subset,\n            out_subset,\n            dropout_p,\n            epsilon,\n            rowscale_const,\n            out_numrows,\n            residual_in_fp32,\n            is_rms_norm,\n        )\n        # Only need to save x0 if we need to compute gradient wrt colscale\n        x0_saved = x0 if colscale is not None else None\n        x_shape = (-1, *x0.shape[1:])\n        ctx.save_for_backward(\n            xmat.view(x_shape), x0_saved, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset\n        )\n        ctx.prenorm = prenorm\n        ctx.dropout_p = dropout_p\n        ctx.rowscale_const = rowscale_const\n        ctx.x0_numrows = x0.shape[:-1].numel()\n        ctx.has_residual = residual is not None\n        ctx.is_rms_norm = is_rms_norm\n        ctx.has_beta = beta is not None\n        z_shape = (-1, *x0.shape[1:])\n        if not return_dmask:\n            return zmat.view(z_shape) if not prenorm else (zmat.view(z_shape), xmat.view(x0.shape))\n        else:\n            z = zmat.view(z_shape)\n            dmask = (\n                dmask.view(x0.shape)\n                if dropout_p > 0.0\n                else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)\n            )\n            ctx.mark_non_differentiable(dmask)\n            return (z, dmask) if not prenorm else (z, xmat.view(x_shape), dmask)\n\n    @staticmethod\n    def backward(ctx, dz, *args):\n        # assert dz.is_contiguous()\n        dz = maybe_align(dz.contiguous(), 16)  # this happens!\n        dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None\n        x, x0, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset = ctx.saved_tensors\n        # x0 is None if colscale is None\n        dropout_p = ctx.dropout_p\n        has_residual = ctx.has_residual\n        dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_subset_backward(\n            dz,\n            dx,\n            x,\n            x0,\n            dmask,\n            mu,\n            rsigma,\n            gamma,\n            colscale,\n            x0_subset,\n            out_subset,\n            dropout_p,\n            ctx.rowscale_const,\n            ctx.x0_numrows,\n            has_residual,\n            ctx.is_rms_norm,\n        )\n        dx0 = dx0mat.view(-1, *x.shape[1:])\n        dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None\n        dcolscale = rest[0] if colscale is not None else None\n        return (\n            dx0,\n            dresidual,\n            dgamma,\n            dbeta if ctx.has_beta else None,\n            dcolscale,\n            None,\n            None,\n            None,\n            None,\n            None,\n            None,\n            None,\n            None,\n            None,\n            None,\n        )\n\n\nclass DropoutAddLayerNormParallelResidualFn(torch.autograd.Function):\n    @staticmethod\n    def forward(\n        ctx,\n        x0,\n        x1,\n        residual,\n        gamma0,\n        beta0,\n        gamma1,\n        beta1,\n        dropout_p,\n        epsilon,\n        residual_in_fp32=False,\n        prenorm=False,\n        is_rms_norm=False,\n        return_dmask=False,\n    ):\n        x0 = maybe_align(x0.contiguous(), 16)\n        x1 = maybe_align(x1.contiguous(), 16) if x1 is not None else None\n        residual = maybe_align(residual.contiguous(), 16) if residual is not None else None\n        gamma0 = maybe_align(gamma0.contiguous(), 16)\n        beta0 = maybe_align(beta0.contiguous(), 16) if beta0 is not None else None\n        gamma1 = maybe_align(gamma1.contiguous(), 16) if gamma1 is not None else None\n        beta1 = maybe_align(beta1.contiguous(), 16) if beta1 is not None else None\n        (\n            z0mat,\n            z1mat,\n            xmat,\n            dmask0,\n            dmask1,\n            mu,\n            rsigma,\n        ) = _dropout_add_layer_norm_parallel_residual_forward(\n            x0,\n            x1,\n            residual,\n            gamma0,\n            beta0,\n            gamma1,\n            beta1,\n            dropout_p,\n            epsilon,\n            residual_in_fp32,\n            is_rms_norm,\n        )\n        ctx.save_for_backward(xmat.view(x0.shape), dmask0, dmask1, gamma0, gamma1, mu, rsigma)\n        ctx.prenorm = prenorm\n        ctx.dropout_p = dropout_p\n        ctx.has_x1 = x1 is not None\n        ctx.has_residual = residual is not None\n        ctx.is_rms_norm = is_rms_norm\n        ctx.has_beta = beta0 is not None\n        z = (z0mat.view(x0.shape), z1mat.view(x0.shape) if z1mat is not None else None)\n        if not return_dmask:\n            return z if not prenorm else (*z, xmat.view(x0.shape))\n        else:\n            dmask0 = (\n                dmask0.view(x0.shape)\n                if dropout_p > 0.0\n                else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)\n            )\n            dmask1 = (\n                dmask1.view(x0.shape)\n                if dropout_p > 0.0 and x1 is not None\n                else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)\n            )\n            ctx.mark_non_differentiable(dmask0)\n            ctx.mark_non_differentiable(dmask1)\n            return (\n                (*z, dmask0, dmask1) if not prenorm else (*z, xmat.view(x0.shape), dmask0, dmask1)\n            )\n\n    @staticmethod\n    def backward(ctx, dz0, dz1, *args):\n        dz0 = maybe_align(dz0.contiguous(), 16)  # this happens!\n        dz1 = maybe_align(dz1.contiguous(), 16) if dz1 is not None else None\n        dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None\n        x, dmask0, dmask1, gamma0, gamma1, mu, rsigma = ctx.saved_tensors\n        dropout_p = ctx.dropout_p\n        has_x1 = ctx.has_x1\n        has_residual = ctx.has_residual\n        (\n            dx0mat,\n            dx1mat,\n            dresidualmat,\n            dgamma0,\n            dbeta0,\n            dgamma1,\n            dbeta1,\n        ) = _dropout_add_layer_norm_parallel_residual_backward(\n            dz0,\n            dz1,\n            dx,\n            x,\n            dmask0,\n            dmask1,\n            mu,\n            rsigma,\n            gamma0,\n            gamma1,\n            dropout_p,\n            has_x1,\n            has_residual,\n            ctx.is_rms_norm,\n        )\n        dx0 = dx0mat.view(x.shape)\n        dx1 = dx1mat.view(x.shape) if dx1mat is not None else None\n        dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None\n        return (\n            dx0,\n            dx1,\n            dresidual,\n            dgamma0,\n            dbeta0 if ctx.has_beta else None,\n            dgamma1,\n            dbeta1 if ctx.has_beta else None,\n            None,\n            None,\n            None,\n            None,\n            None,\n            None,\n        )\n\n\ndef layer_norm(x, weight, bias, epsilon):\n    return DropoutAddLayerNormFn.apply(x, None, weight, bias, None, None, 0.0, epsilon, False)\n\n\ndef dropout_add_layer_norm(\n    x0,\n    residual,\n    weight,\n    bias,\n    dropout_p,\n    epsilon,\n    rowscale=None,\n    layerscale=None,\n    prenorm=False,\n    residual_in_fp32=False,\n    return_dropout_mask=False,\n):\n    \"\"\"residual_in_fp32 only has an effect if residual is None.\n    Otherwise residual dtype is residual.dtype.\n    \"\"\"\n    return DropoutAddLayerNormFn.apply(\n        x0,\n        residual,\n        weight,\n        bias,\n        rowscale,\n        layerscale,\n        dropout_p,\n        epsilon,\n        residual_in_fp32,\n        prenorm,\n        False,\n        return_dropout_mask,\n    )\n\n\ndef dropout_add_layer_norm_subset(\n    x0,\n    residual,\n    weight,\n    bias,\n    dropout_p,\n    epsilon,\n    layerscale=None,\n    x0_subset=None,\n    out_subset=None,\n    rowscale_const=1.0,\n    out_numrows=0,\n    prenorm=False,\n    residual_in_fp32=False,\n    return_dropout_mask=False,\n):\n    \"\"\"residual_in_fp32 only has an effect if residual is None.\n    Otherwise residual dtype is residual.dtype.\n    \"\"\"\n    return DropoutAddLayerNormSubsetFn.apply(\n        x0,\n        residual,\n        weight,\n        bias,\n        layerscale,\n        x0_subset,\n        out_subset,\n        dropout_p,\n        epsilon,\n        rowscale_const,\n        out_numrows,\n        residual_in_fp32,\n        prenorm,\n        False,\n        return_dropout_mask,\n    )\n\n\ndef dropout_add_layer_norm_parallel_residual(\n    x0,\n    x1,\n    residual,\n    weight0,\n    bias0,\n    weight1,\n    bias1,\n    dropout_p,\n    epsilon,\n    prenorm=False,\n    residual_in_fp32=False,\n    return_dropout_mask=False,\n):\n    \"\"\"residual_in_fp32 only has an effect if residual is None.\n    Otherwise residual dtype is residual.dtype.\n    \"\"\"\n    return DropoutAddLayerNormParallelResidualFn.apply(\n        x0,\n        x1,\n        residual,\n        weight0,\n        bias0,\n        weight1,\n        bias1,\n        dropout_p,\n        epsilon,\n        residual_in_fp32,\n        prenorm,\n        False,\n        return_dropout_mask,\n    )\n\n\nclass DropoutAddLayerNorm(torch.nn.Module):\n    def __init__(\n        self,\n        hidden_size,\n        prenorm=False,\n        p=0.0,\n        eps=1e-5,\n        residual_in_fp32=False,\n        device=None,\n        dtype=None,\n    ):\n        factory_kwargs = {\"device\": device, \"dtype\": dtype}\n        super().__init__()\n        self.prenorm = prenorm\n        self.p = p\n        self.eps = eps\n        self.residual_in_fp32 = residual_in_fp32\n        self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))\n        self.bias = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        init.ones_(self.weight)\n        init.zeros_(self.bias)\n\n    def forward(self, x0, residual=None):\n        return dropout_add_layer_norm(\n            x0,\n            residual,\n            self.weight,\n            self.bias,\n            self.p if self.training else 0.0,\n            self.eps,\n            prenorm=self.prenorm,\n            residual_in_fp32=self.residual_in_fp32,\n        )\n        \ndef rms_norm(x, weight, epsilon):\n    return DropoutAddLayerNormFn.apply(\n        x, None, weight, None, None, None, 0.0, epsilon, False, False, True\n    )\nclass FusedRMSNorm(torch.nn.Module):\n    def __init__(self, size: int, dim: int = -1, eps: float = 1e-5):\n        super().__init__()\n        self.eps = eps\n        self.weight = torch.nn.Parameter(torch.ones(size))\n        self.dim = dim\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        init.ones_(self.weight)\n\n    def forward(self, x):\n        return rms_norm(x, self.weight, self.eps)\n    \n    \nclass RMSNorm(torch.nn.Module):\n    \"\"\"Root Mean Square Layer Normalization.\n\n    Derived from https://github.com/bzhangGo/rmsnorm/blob/master/rmsnorm_torch.py. BSD 3-Clause License:\n    https://github.com/bzhangGo/rmsnorm/blob/master/LICENSE.\n    \"\"\"\n\n    def __init__(self, size: int, dim: int = -1, eps: float = 1e-5) -> None:\n        super().__init__()\n        self.weight = torch.nn.Parameter(torch.ones(size))\n        self.eps = eps\n        self.dim = dim\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        # NOTE: the original RMSNorm paper implementation is not equivalent\n        norm_x = torch.mean(x * x, dim=self.dim, keepdim=True)\n        x_normed = x * torch.rsqrt(norm_x + self.eps)\n        return self.weight * x_normed\n\n    def reset_parameters(self):\n        torch.nn.init.ones_(self.weight)\n"
  },
  {
    "path": "lit_gpt/speed_monitor.py",
    "content": "import time\nfrom collections import deque\nfrom contextlib import nullcontext\nfrom typing import Any, Callable, Deque, Dict, Optional\n\nimport torch\nfrom lightning import Callback, Fabric, LightningModule, Trainer\nfrom lightning.fabric.utilities.rank_zero import rank_zero_only as fabric_rank_zero_only\nfrom lightning.pytorch.utilities.rank_zero import rank_zero_only as trainer_rank_zero_only\nfrom torch.utils.flop_counter import FlopCounterMode\nimport math\nfrom lit_gpt import GPT, Config\nfrom lit_gpt.utils import num_parameters\n\nGPU_AVAILABLE_FLOPS = {\n    # source: https://resources.nvidia.com/en-us-tensor-core/nvidia-tensor-core-gpu-datasheet\n    # nvidia publishes spec sheet with a 2x sparsity factor\n    \"h100-sxm\": {\n        \"64-true\": 67e12,\n        \"32-true\": 67e12,\n        \"16-true\": 1.979e15 / 2,\n        \"16-mixed\": 1.979e15 / 2,\n        \"bf16-true\": 1.979e15 / 2,\n        \"bf16-mixed\": 1.979e15 / 2,\n        \"8-true\": 3.958e15 / 2,\n        \"8-mixed\": 3.958e15 / 2,\n    },\n    \"h100-pcie\": {\n        \"64-true\": 51e12,\n        \"32-true\": 51e12,\n        \"16-true\": 1.513e15 / 2,\n        \"16-mixed\": 1.513e15 / 2,\n        \"bf16-true\": 1.513e15 / 2,\n        \"bf16-mixed\": 1.513e15 / 2,\n        \"8-true\": 3.026e15 / 2,\n        \"8-mixed\": 3.026e15 / 2,\n    },\n    # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf\n    # sxm and pcie have same flop counts\n    \"a100\": {\n        \"64-true\": 19.5e12,\n        \"32-true\": 19.5e12,\n        \"16-true\": 312e12,\n        \"16-mixed\": 312e12,\n        \"bf16-true\": 312e12,\n        \"bf16-mixed\": 312e12,\n    },\n    # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a10/pdf/a10-datasheet.pdf\n    \"a10g\": {\"32-true\": 31.2e12, \"16-true\": 125e12, \"16-mixed\": 125e12, \"bf16-true\": 125e12, \"bf16-mixed\": 125e12},\n    # source: https://images.nvidia.com/content/technologies/volta/pdf/volta-v100-datasheet-update-us-1165301-r5.pdf\n    \"v100-sxm\": {\"64-true\": 7.8e12, \"32-true\": 15.7e12, \"16-true\": 125e12, \"16-mixed\": 125e12},\n    \"v100-pcie\": {\"64-true\": 7e12, \"32-true\": 14e12, \"16-true\": 112e12, \"16-mixed\": 112e12},\n    \"v100s-pcie\": {\"64-true\": 8.2e12, \"32-true\": 16.4e12, \"16-true\": 130e12, \"16-mixed\": 130e12},\n    # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/tesla-t4/t4-tensor-core-datasheet-951643.pdf\n    # sxm and pcie have same flop counts\n    \"t4\": {\"32-true\": 8.1e12, \"16-true\": 65e12, \"16-mixed\": 65e12, \"8-true\": 130e12, \"int4\": 260e12},\n    # https://www.nvidia.com/content/dam/en-zz/Solutions/design-visualization/quadro-product-literature/quadro-rtx-5000-data-sheet-us-nvidia-704120-r4-web.pdf\n    \"quadro rtx 5000\": {\"32-true\": 11.2e12, \"16-true\": 89.2e12, \"16-mixed\": 89.2e12},\n}\n\nTPU_AVAILABLE_FLOPS = {\n    # flop count for each TPU generation is the same for all precisions\n    # since bfloat16 precision is always used for performing matrix operations\n    # for more info: https://cloud.google.com/tpu/docs/bfloat16#choosing_bfloat16\n    # source: https://arxiv.org/pdf/1907.10701.pdf\n    \"v2\": 45e12,\n    # source: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_v3\n    \"v3\": 123e12,\n    # source: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_v4\n    \"v4\": 275e12,\n}\n\n\ndef get_flops_available(device: torch.device, precision: str) -> Optional[float]:\n    if device.type == \"cuda\":\n        device_name = torch.cuda.get_device_name(device).lower()\n        if \"h100\" in device_name and \"hbm3\" in device_name:\n            device_name = \"h100-sxm\"\n        elif \"h100\" in device_name and (\"pcie\" in device_name or \"hbm2e\" in device_name):\n            device_name = \"h100-pcie\"\n        elif \"a100\" in device_name:\n            device_name = \"a100\"\n        elif \"a10g\" in device_name:\n            device_name = \"a10g\"\n        elif \"v100-sxm\" in device_name:\n            device_name = \"v100-sxm\"\n        elif \"v100-pcie\" in device_name:\n            device_name = \"v100-pcie\"\n        elif \"t4\" in device_name:\n            device_name = \"t4\"\n        elif \"quadro rtx 5000\" in device_name:\n            device_name = \"quadro rtx 5000\"\n        else:\n            device_name = None\n\n        if device_name is not None:\n            try:\n                return int(GPU_AVAILABLE_FLOPS[device_name][precision])\n            except KeyError:\n                raise KeyError(\n                    f\"flop count not found for {device_name} with precision: {precision}; \"\n                    \"MFU cannot be calculated and reported.\"\n                )\n    elif device.type == \"xla\":\n        from torch_xla.experimental import tpu\n\n        device_name = tpu.get_tpu_env()[\"TYPE\"].lower()\n        try:\n            return int(TPU_AVAILABLE_FLOPS[device_name])\n        except KeyError:\n            raise KeyError(\n                f\"flop count not found for {device_name} with precision: {precision}; \"\n                \"MFU cannot be calculated and reported.\"\n            )\n\n    return None\n\n\n# Adapted from https://github.com/mosaicml/composer/blob/f2a2dc820cb75023b9eb7c46fdfd25273712abd0/composer/callbacks/speed_monitor.py\n\n\nclass SpeedMonitorBase:\n    \"\"\"Logs the training throughput and utilization.\n\n    +-------------------------------------+-----------------------------------------------------------+\n    | Key                                 | Logged data                                               |\n    +=====================================+===========================================================+\n    |                                     | Rolling average (over `window_size` most recent           |\n    | `throughput/batches_per_sec`        | batches) of the number of batches processed per second    |\n    |                                     |                                                           |\n    +-------------------------------------+-----------------------------------------------------------+\n    |                                     | Rolling average (over `window_size` most recent           |\n    | `throughput/samples_per_sec`        | batches) of the number of samples processed per second    |\n    |                                     |                                                           |\n    +-------------------------------------+-----------------------------------------------------------+\n    |                                     | Rolling average (over `window_size` most recent           |\n    | `throughput/tokens_per_sec`         | batches) of the number of tokens processed per second.    |\n    |                                     | This may include padding depending on dataset             |\n    +-------------------------------------+-----------------------------------------------------------+\n    |                                     | Estimates flops by `flops_per_batch * batches_per_sec`    |\n    | `throughput/flops_per_sec`          |                                                           |\n    |                                     |                                                           |\n    +-------------------------------------+-----------------------------------------------------------+\n    | `throughput/device/batches_per_sec` | `throughput/batches_per_sec` divided by world size        |\n    +-------------------------------------+-----------------------------------------------------------+\n    | `throughput/device/samples_per_sec` | `throughput/samples_per_sec` divided by world size        |\n    +-------------------------------------+-----------------------------------------------------------+\n    |                                     | `throughput/tokens_per_sec` divided by world size. This   |\n    | `throughput/device/tokens_per_sec`  | may include pad tokens depending on dataset               |\n    |                                     |                                                           |\n    +-------------------------------------+-----------------------------------------------------------+\n    |                                     | `throughput/flops_per_sec` divided by world size. Only    |\n    | `throughput/device/flops_per_sec`   | logged when model has attribute `flops_per_batch`         |\n    |                                     |                                                           |\n    +-------------------------------------+-----------------------------------------------------------+\n    |                                     | `throughput/device/flops_per_sec` divided by world size.  |\n    | `throughput/device/mfu`             |                                                           |\n    |                                     |                                                           |\n    +-------------------------------------+-----------------------------------------------------------+\n    | `time/train`                        | Total elapsed training time                               |\n    +-------------------------------------+-----------------------------------------------------------+\n    | `time/val`                          | Total elapsed validation time                             |\n    +-------------------------------------+-----------------------------------------------------------+\n    | `time/total`                        | Total elapsed time (time/train + time/val)                |\n    +-------------------------------------+-----------------------------------------------------------+\n\n    Notes:\n        - The implementation assumes that devices are homogeneous as it normalizes by the world size.\n        - Tokens/sec, flops/sec and MFU do not account for padding tokens if present. We suggest using samples/sec or\n          batches/sec to measure throughput under this circumstance.\n        - Be careful when comparing MFU numbers across projects, as this will highly depend on the ``flops_per_batch``.\n          There is no widespread, realistic, and reliable implementation to compute them.\n          We suggest using our ``measure_flops`` function, but many other works will use ``estimated_flops`` which\n          will almost always be an overestimate when compared to the true value.\n\n    Args:\n        window_size (int, optional): Number of batches to use for a rolling average of throughput.\n            Defaults to 100.\n        time_unit (str, optional): Time unit to use for `time` logging. Can be one of\n            'seconds', 'minutes', 'hours', or 'days'. Defaults to 'hours'.\n    \"\"\"\n\n    def __init__(\n        self,\n        flops_available: float,\n        log_dict: Callable[[Dict, int], None],\n        window_size: int = 100,\n        time_unit: str = \"hours\",\n        log_iter_interval: int = 1,\n    ):\n        self.flops_available = flops_available\n        self.log_dict = log_dict\n        self.log_iter_interval = log_iter_interval\n        # Track the batch num samples and wct to compute throughput over a window of batches\n        self.history_samples: Deque[int] = deque(maxlen=window_size + 1)\n        self.history_training_loss: Deque[int] = deque(maxlen=log_iter_interval)\n        self.history_wct: Deque[float] = deque(maxlen=window_size + 1)\n        self.history_lengths: Deque[int] = deque(maxlen=window_size + 1)\n        self.history_flops: Deque[int] = deque(maxlen=window_size + 1)\n\n        self.divider = 1\n        if time_unit == \"seconds\":\n            self.divider = 1\n        elif time_unit == \"minutes\":\n            self.divider = 60\n        elif time_unit == \"hours\":\n            self.divider = 60 * 60\n        elif time_unit == \"days\":\n            self.divider = 60 * 60 * 24\n        else:\n            raise ValueError(\n                f'Invalid time_unit: {time_unit}. Must be one of \"seconds\", \"minutes\", \"hours\", or \"days\".'\n            )\n\n        # Keep track of time spent evaluating\n        self.total_eval_wct = 0.0\n        self.iter = -1\n\n    def on_train_batch_end(\n        self,\n        samples: int,  # total samples seen (per device)\n        train_elapsed: float,  # total training time (seconds)\n        world_size: int,\n        step_count: int,\n        flops_per_batch: Optional[int] = None,  # (per device)\n        lengths: Optional[int] = None,  # total length of the samples seen (per device)\n        train_loss: Optional[float] = None,\n    ):\n        self.iter += 1\n        metrics = {}\n\n        self.history_samples.append(samples)\n        self.history_training_loss.append(train_loss)\n        if lengths is not None:\n            self.history_lengths.append(lengths)\n            # if lengths are passed, there should be as many values as samples\n            assert len(self.history_samples) == len(self.history_lengths)\n        self.history_wct.append(train_elapsed)\n        if len(self.history_wct) == self.history_wct.maxlen:\n            elapsed_batches = len(self.history_samples) - 1\n            elapsed_samples = self.history_samples[-1] - self.history_samples[0]\n            elapsed_wct = self.history_wct[-1] - self.history_wct[0]\n            samples_per_sec = elapsed_samples * world_size / elapsed_wct\n            dev_samples_per_sec = elapsed_samples / elapsed_wct\n            metrics.update(\n                {\n                    \"throughput/batches_per_sec\": elapsed_batches * world_size / elapsed_wct,\n                    \"throughput/samples_per_sec\": samples_per_sec,\n                    \"throughput/device/batches_per_sec\": elapsed_batches / elapsed_wct,\n                    \"throughput/device/samples_per_sec\": dev_samples_per_sec,\n                }\n            )\n            if lengths is not None:\n                elapsed_lengths = int(self.history_lengths[-1]) - int(self.history_lengths[0])\n                avg_length = elapsed_lengths / elapsed_batches  \n                metrics.update(\n                    {\n                        \"throughput/tokens_per_sec\": samples_per_sec * avg_length,\n                        \"throughput/device/tokens_per_sec\": dev_samples_per_sec * avg_length,\n                        \"total_tokens\": avg_length * world_size * samples,\n                    }\n                )\n                if train_loss is not None:\n                    avg_loss = sum(self.history_training_loss) / len(self.history_training_loss)\n                    metrics.update(\n                        {\n                            \"metric/train_loss\": avg_loss,\n                            \"metric/train_ppl\": math.exp(avg_loss)\n                        }\n                    )\n\n        if flops_per_batch is not None:\n            # sum of flops per batch across ranks\n            self.history_flops.append(flops_per_batch * world_size)\n        if len(self.history_flops) == self.history_flops.maxlen:\n            elapsed_flops = sum(self.history_flops) - self.history_flops[0]\n            elapsed_wct = self.history_wct[-1] - self.history_wct[0]\n            flops_per_sec = elapsed_flops / elapsed_wct\n            device_flops_per_sec = flops_per_sec / world_size\n            metrics.update(\n                {\"throughput/flops_per_sec\": flops_per_sec, \"throughput/device/flops_per_sec\": device_flops_per_sec}\n            )\n            if self.flops_available:\n                metrics[\"throughput/device/mfu\"] = device_flops_per_sec / self.flops_available\n\n        metrics.update(\n            {\n                \"time/train\": train_elapsed / self.divider,\n                \"time/val\": self.total_eval_wct / self.divider,\n                \"time/total\": (train_elapsed + self.total_eval_wct) / self.divider,\n                \"samples\": samples,\n            }\n        )\n        if self.iter % self.log_iter_interval == 0:\n            self.log_dict(metrics, step_count)\n\n    def eval_end(self, eval_elapsed: float):\n        self.total_eval_wct += eval_elapsed  # seconds\n\n\nclass SpeedMonitorFabric(SpeedMonitorBase):\n    def __init__(self, fabric: Fabric, *args: Any, **kwargs: Any) -> None:\n        # TODO: this will not work properly if a precision plugin is passed to Fabric\n        flops_available = get_flops_available(fabric.device, fabric._connector._precision_input)\n        super().__init__(flops_available, fabric.log_dict, *args, **kwargs)\n\n    @fabric_rank_zero_only\n    def on_train_batch_end(self, *args: Any, **kwargs: Any):\n        super().on_train_batch_end(*args, **kwargs)\n\n\nclass SpeedMonitorCallback(Callback):\n    def __init__(self, length_fn: Callable[[Any], int], batch_size: int, **kwargs: Any) -> None:\n        super().__init__()\n        self.speed_monitor: Optional[SpeedMonitorBase] = None\n        self.speed_monitor_kwargs = kwargs\n        self.length_fn = length_fn\n        self.batch_size = batch_size\n        self.eval_t0: int = 0\n        self.train_t0: int = 0\n        self.total_lengths: int = 0\n\n    def setup(self, trainer: Trainer, pl_module: LightningModule, stage: str) -> None:\n        if self.speed_monitor is not None:\n            return  # already setup\n        # TODO: this will not work properly if a precision plugin is passed to Trainer\n        flops_available = get_flops_available(\n            trainer.strategy.root_device, trainer._accelerator_connector._precision_flag\n        )\n        self.speed_monitor = SpeedMonitorBase(flops_available, trainer.logger.log_metrics, **self.speed_monitor_kwargs)\n\n    @trainer_rank_zero_only\n    def on_train_start(self, trainer: Trainer, pl_module: LightningModule) -> None:\n        if trainer.fit_loop._should_accumulate():\n            return\n\n        self.train_t0 = time.perf_counter()\n\n    @trainer_rank_zero_only\n    def on_train_batch_end(\n        self, trainer: Trainer, pl_module: LightningModule, outputs: Any, batch: Any, batch_idx: int\n    ) -> None:\n        self.total_lengths += self.length_fn(batch)\n        if trainer.fit_loop._should_accumulate():\n            return\n        train_elapsed = time.perf_counter() - self.train_t0\n        assert self.speed_monitor is not None\n        iter_num = trainer.fit_loop.total_batch_idx\n        assert (measured_flops := pl_module.measured_flops) is not None\n        self.speed_monitor.on_train_batch_end(\n            (iter_num + 1) * self.batch_size,\n            train_elapsed,\n            # this assumes that device FLOPs are the same and that all devices have the same batch size\n            trainer.world_size,\n            flops_per_batch=measured_flops,\n            lengths=self.total_lengths,\n        )\n\n    @trainer_rank_zero_only\n    def on_validation_start(self, trainer: Trainer, pl_module: LightningModule) -> None:\n        self.eval_t0 = time.perf_counter()\n\n    @trainer_rank_zero_only\n    def on_validation_end(self, trainer: Trainer, pl_module: LightningModule) -> None:\n        eval_elapsed = time.perf_counter() - self.eval_t0\n        assert self.speed_monitor is not None\n        self.speed_monitor.eval_end(eval_elapsed)\n\n\ndef flops_per_param(config: Config, n_params: int) -> int:\n    flops_per_token = 2 * n_params  # each parameter is used for a MAC (2 FLOPS) per network operation\n    # this assumes that all samples have a fixed length equal to the block size\n    # which is most likely false during finetuning\n    flops_per_seq = flops_per_token * config.block_size\n    attn_flops_per_seq = config.n_layer * 2 * 2 * (config.n_embd * (config.block_size**2))\n    return flops_per_seq + attn_flops_per_seq\n\n\ndef estimate_flops(model: GPT) -> int:\n    \"\"\"Measures estimated FLOPs for MFU.\n\n    Refs:\n        * https://ar5iv.labs.arxiv.org/html/2205.05198#A1\n        * https://ar5iv.labs.arxiv.org/html/2204.02311#A2\n    \"\"\"\n    # using all parameters for this is a naive over estimation because not all model parameters actually contribute to\n    # this FLOP computation (e.g. embedding, norm). For this reason, the result will be higher by a fixed percentage\n    # (~10%) compared to the measured FLOPs, making those lower but more realistic.\n    # For a proper estimate, this needs a more fine-grained calculation as in Appendix A of the paper.\n    n_trainable_params = num_parameters(model, requires_grad=True)\n    trainable_flops = flops_per_param(model.config, n_trainable_params)\n    # forward + backward + gradients (assumes no gradient accumulation)\n    ops_per_step = 3 if model.training else 1\n    n_frozen_params = num_parameters(model, requires_grad=False)\n    frozen_flops = flops_per_param(model.config, n_frozen_params)\n    # forward + backward\n    frozen_ops_per_step = 2 if model.training else 1\n    return ops_per_step * trainable_flops + frozen_ops_per_step * frozen_flops\n\n\ndef measure_flops(model: GPT, x: torch.Tensor) -> int:\n    \"\"\"Measures real FLOPs for HFU\"\"\"\n    flop_counter = FlopCounterMode(model, display=False)\n    ctx = nullcontext() if model.training else torch.no_grad()\n    with ctx, flop_counter:\n        y = model(x)\n        if model.training:\n            y.sum().backward()\n    return flop_counter.get_total_flops()\n"
  },
  {
    "path": "lit_gpt/tokenizer.py",
    "content": "import json\nfrom pathlib import Path\nfrom typing import Optional\n\nimport torch\n\n\nclass Tokenizer:\n    def __init__(self, checkpoint_dir: Path) -> None:\n        # some checkpoints have both files, `.model` takes precedence\n        if (vocabulary_path := checkpoint_dir / \"tokenizer.model\").is_file():\n            from sentencepiece import SentencePieceProcessor\n\n            self.processor = SentencePieceProcessor(model_file=str(vocabulary_path))\n            self.backend = \"sentencepiece\"\n            self.bos_id = self.processor.bos_id()\n            self.eos_id = self.processor.eos_id()\n        elif (vocabulary_path := checkpoint_dir / \"tokenizer.json\").is_file():\n            from tokenizers import Tokenizer as HFTokenizer\n\n            self.processor = HFTokenizer.from_file(str(vocabulary_path))\n            self.backend = \"huggingface\"\n            with open(checkpoint_dir / \"tokenizer_config.json\") as fp:\n                config = json.load(fp)\n            bos_token = config.get(\"bos_token\")\n            self.bos_id = self.token_to_id(bos_token) if bos_token is not None else None\n            self.eos_id = self.token_to_id(config[\"eos_token\"])\n        else:\n            raise NotImplementedError\n\n    @property\n    def vocab_size(self) -> int:\n        if self.backend == \"huggingface\":\n            return self.processor.get_vocab_size(with_added_tokens=False)\n        if self.backend == \"sentencepiece\":\n            return self.processor.vocab_size()\n        raise RuntimeError\n\n    def token_to_id(self, token: str) -> int:\n        if self.backend == \"huggingface\":\n            id_ = self.processor.token_to_id(token)\n        elif self.backend == \"sentencepiece\":\n            id_ = self.processor.piece_to_id(token)\n        else:\n            raise RuntimeError\n        if id_ is None:\n            raise ValueError(f\"token {token!r} not found in the collection.\")\n        return id_\n\n    def encode(\n        self,\n        string: str,\n        device: Optional[torch.device] = None,\n        bos: bool = False,\n        eos: bool = True,\n        max_length: int = -1,\n    ) -> torch.Tensor:\n        if self.backend == \"huggingface\":\n            tokens = self.processor.encode(string).ids\n        elif self.backend == \"sentencepiece\":\n            tokens = self.processor.encode(string)\n        else:\n            raise RuntimeError\n        if bos:\n            bos_id = self.bos_id\n            if bos_id is None:\n                raise NotImplementedError(\"This tokenizer does not defined a bos token\")\n            tokens = [bos_id] + tokens\n        if eos:\n            tokens = tokens + [self.eos_id]\n        if max_length > 0:\n            tokens = tokens[:max_length]\n        return torch.tensor(tokens, dtype=torch.int, device=device)\n\n    def decode(self, tensor: torch.Tensor) -> str:\n        tokens = [tensor.item()] if tensor.ndim == 0 else tensor.tolist()\n        return self.processor.decode(tokens)\n"
  },
  {
    "path": "lit_gpt/utils.py",
    "content": "\"\"\"Utility functions for training and inference.\"\"\"\n\nimport pickle\nimport sys\nimport warnings\nfrom contextlib import contextmanager\nfrom functools import partial\nfrom io import BytesIO\nfrom pathlib import Path\nfrom types import MethodType\nfrom typing import Any, Dict, List, Mapping, Optional, Type, TypeVar, Union\n\nimport torch\nimport torch.nn as nn\nimport torch.utils._device\nfrom lightning.fabric.loggers import CSVLogger\nfrom torch.serialization import normalize_storage_type\n\n\ndef find_multiple(n: int, k: int) -> int:\n    assert k > 0\n    if n % k == 0:\n        return n\n    return n + k - (n % k)\n\n\ndef num_parameters(module: nn.Module, requires_grad: Optional[bool] = None) -> int:\n    return sum(p.numel() for p in module.parameters() if requires_grad is None or p.requires_grad == requires_grad)\n\n\n@contextmanager\ndef quantization(mode: Optional[str] = None):\n    if mode is None:\n        yield\n        return\n\n    if mode == \"bnb.int8\":\n        from quantize.bnb import InferenceLinear8bitLt\n\n        quantized_linear_cls = InferenceLinear8bitLt\n    elif mode == \"bnb.fp4\":\n        from quantize.bnb import Linear4bit\n\n        # Use a class instead `functools.partial` to respect `isinstance` checks and attribute accesses\n        class QuantizedLinear(Linear4bit):\n            def __init__(self, *args, **kwargs):\n                super().__init__(*args, quant_type=\"fp4\", compress_statistics=False, **kwargs)\n\n        quantized_linear_cls = QuantizedLinear\n    elif mode == \"bnb.fp4-dq\":\n        from quantize.bnb import Linear4bit\n\n        class QuantizedLinear(Linear4bit):\n            def __init__(self, *args, **kwargs):\n                super().__init__(*args, quant_type=\"fp4\", compress_statistics=True, **kwargs)\n\n        quantized_linear_cls = QuantizedLinear\n    elif mode == \"bnb.nf4\":\n        from quantize.bnb import Linear4bit\n\n        class QuantizedLinear(Linear4bit):\n            def __init__(self, *args, **kwargs):\n                super().__init__(*args, quant_type=\"nf4\", compress_statistics=False, **kwargs)\n\n        quantized_linear_cls = QuantizedLinear\n    elif mode == \"bnb.nf4-dq\":\n        from quantize.bnb import Linear4bit\n\n        class QuantizedLinear(Linear4bit):\n            def __init__(self, *args, **kwargs):\n                super().__init__(*args, quant_type=\"nf4\", compress_statistics=True, **kwargs)\n\n        quantized_linear_cls = QuantizedLinear\n    elif mode == \"gptq.int4\":\n        from quantize.gptq import ColBlockQuantizedLinear\n\n        class QuantizedLinear(ColBlockQuantizedLinear):\n            def __init__(self, *args, **kwargs):\n                super().__init__(*args, bits=4, tile_cols=-1, **kwargs)\n\n        quantized_linear_cls = QuantizedLinear\n    else:\n        raise ValueError(f\"Unknown quantization mode: {mode}\")\n\n    torch_linear_cls = torch.nn.Linear\n    torch.nn.Linear = quantized_linear_cls\n    yield\n    torch.nn.Linear = torch_linear_cls\n\n\n# this is taken from torchhacks https://github.com/lernapparat/torchhacks\n\n\nclass NotYetLoadedTensor:\n    def __init__(self, metatensor, archiveinfo, storageinfo, rebuild_args):\n        self.metatensor = metatensor\n        self.archiveinfo = archiveinfo\n        self.storageinfo = storageinfo\n        self.rebuild_args = rebuild_args\n\n    @classmethod\n    def rebuild_from_type_v2(cls, func, new_type, args, state, *, archiveinfo=None):\n        ret = func(*args)\n        if isinstance(ret, NotYetLoadedTensor):\n            old_lt = ret._load_tensor\n\n            def _load_tensor():\n                t = old_lt()\n                return torch._tensor._rebuild_from_type_v2(lambda: t, new_type, (), state)\n\n            ret._load_tensor = _load_tensor\n            return ret\n        return torch._tensor._rebuild_from_type_v2(func, new_type, args, state)\n\n    @classmethod\n    def rebuild_parameter(cls, data, requires_grad, backward_hooks, *, archiveinfo=None):\n        if isinstance(data, NotYetLoadedTensor):\n            old_lt = data._load_tensor\n\n            def _load_tensor():\n                t = old_lt()\n                return torch._utils._rebuild_parameter(t, requires_grad, backward_hooks)\n\n            data._load_tensor = _load_tensor\n            return data\n        return torch._utils._rebuild_parameter(data, requires_grad, backward_hooks)\n\n    @classmethod\n    def rebuild_tensor_v2(\n        cls, storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata=None, *, archiveinfo=None\n    ):\n        rebuild_args = (storage_offset, size, stride, requires_grad, backward_hooks, metadata)\n        metatensor = torch._utils._rebuild_tensor_v2(\n            storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata\n        )\n        storageinfo = storage.archiveinfo\n        return NotYetLoadedTensor(metatensor, archiveinfo, storageinfo, rebuild_args)\n\n    def _load_tensor(self):\n        name, storage_cls, fn, device, size = self.storageinfo\n        dtype = self.metatensor.dtype\n\n        uts = (\n            self.archiveinfo.zipfile_context.zf.get_storage_from_record(\n                f\"data/{fn}\", size * torch._utils._element_size(dtype), torch.UntypedStorage\n            )\n            ._typed_storage()\n            ._untyped_storage\n        )\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            storage = torch.storage.TypedStorage(wrap_storage=uts, dtype=self.metatensor.dtype, _internal=True)\n        return torch._utils._rebuild_tensor_v2(storage, *self.rebuild_args)\n\n    @classmethod\n    def __torch_function__(cls, func, types, args=(), kwargs=None):\n        if kwargs is None:\n            kwargs = {}\n        loaded_args = [(a._load_tensor() if isinstance(a, NotYetLoadedTensor) else a) for a in args]\n        return func(*loaded_args, **kwargs)\n        # gc.collect would be costly here, maybe do it optionally\n\n    def __getattr__(self, name):\n        # properties\n        ## TODO: device, is_...??\n        ## TODO: mH, mT, H, T, data, imag, real\n        ## name ???\n        if name in {\n            \"dtype\",\n            \"grad\",\n            \"grad_fn\",\n            \"layout\",\n            \"names\",\n            \"ndim\",\n            \"output_nr\",\n            \"requires_grad\",\n            \"retains_grad\",\n            \"shape\",\n            \"volatile\",\n        }:\n            return getattr(self.metatensor, name)\n        if name in {\"size\"}:\n            return getattr(self.metatensor, name)\n        # materializing with contiguous is needed for quantization\n        if name in {\"contiguous\"}:\n            return getattr(self._load_tensor(), name)\n\n        raise AttributeError(f\"{type(self)} does not have {name}\")\n\n    def __repr__(self):\n        return f\"NotYetLoadedTensor({repr(self.metatensor)})\"\n\n\nclass LazyLoadingUnpickler(pickle.Unpickler):\n    def __init__(self, file, zipfile_context):\n        super().__init__(file)\n        self.zipfile_context = zipfile_context\n\n    def find_class(self, module, name):\n        res = super().find_class(module, name)\n        if module == \"torch._utils\" and name == \"_rebuild_tensor_v2\":\n            return partial(NotYetLoadedTensor.rebuild_tensor_v2, archiveinfo=self)\n        if module == \"torch._tensor\" and name == \"_rebuild_from_type_v2\":\n            return partial(NotYetLoadedTensor.rebuild_from_type_v2, archiveinfo=self)\n        if module == \"torch._utils\" and name == \"_rebuild_parameter\":\n            return partial(NotYetLoadedTensor.rebuild_parameter, archiveinfo=self)\n        return res\n\n    def persistent_load(self, pid):\n        name, cls, fn, device, size = pid\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            s = torch.storage.TypedStorage(dtype=cls().dtype, device=\"meta\")\n        s.archiveinfo = pid\n        return s\n\n\nclass lazy_load:\n    def __init__(self, fn):\n        self.zf = torch._C.PyTorchFileReader(str(fn))\n        with BytesIO(self.zf.get_record(\"data.pkl\")) as pkl:\n            mup = LazyLoadingUnpickler(pkl, self)\n            self.sd = mup.load()\n\n    def __enter__(self):\n        return self.sd\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        del self.zf  # I don't think there is a way to force closing...\n        self.zf = None\n\n\ndef check_valid_checkpoint_dir(checkpoint_dir: Path) -> None:\n    files = {\n        \"lit_model.pth\": (checkpoint_dir / \"lit_model.pth\").is_file(),\n        \"lit_config.json\": (checkpoint_dir / \"lit_config.json\").is_file(),\n        \"tokenizer.json OR tokenizer.model\": (checkpoint_dir / \"tokenizer.json\").is_file() or (\n            checkpoint_dir / \"tokenizer.model\"\n        ).is_file(),\n        \"tokenizer_config.json\": (checkpoint_dir / \"tokenizer_config.json\").is_file(),\n    }\n    if checkpoint_dir.is_dir():\n        if all(files.values()):\n            # we're good\n            return\n        problem = f\" is missing the files: {[f for f, exists in files.items() if not exists]!r}\"\n    else:\n        problem = \" is not a checkpoint directory\"\n\n    # list locally available checkpoints\n    available = list(Path(\"checkpoints\").glob(\"*/*\"))\n    if available:\n        options = \"\\n --checkpoint_dir \".join([\"\"] + [repr(str(p.resolve())) for p in available])\n        extra = f\"\\nYou have downloaded locally:{options}\\n\"\n    else:\n        extra = \"\"\n\n    error_message = (\n        f\"--checkpoint_dir {str(checkpoint_dir.absolute())!r}{problem}.\"\n        \"\\nFind download instructions at https://github.com/Lightning-AI/lit-gpt/blob/main/tutorials\\n\"\n        f\"{extra}\\nSee all download options by running:\\n python scripts/download.py\"\n    )\n    print(error_message, file=sys.stderr)\n    raise SystemExit(1)\n\n\nclass SavingProxyForStorage:\n    def __init__(self, obj, saver, protocol_version=5):\n        self.protocol_version = protocol_version\n        self.saver = saver\n        if not (isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj)):\n            raise TypeError(f\"expected storage, not {type(obj)}\")\n\n        # this logic is taken from PyTorch 2.0+ torch/serialization.py\n        if isinstance(obj, torch.storage.TypedStorage):\n            # PT upstream wants to deprecate this eventually...\n            storage = obj._untyped_storage\n            storage_type_str = obj._pickle_storage_type()\n            storage_type = getattr(torch, storage_type_str)\n            storage_numel = obj._size()\n        else:\n            storage = obj\n            storage_type = normalize_storage_type(type(obj))\n            storage_numel = storage.nbytes()\n\n        storage_key = saver._write_storage_and_return_key(storage)\n        location = torch.serialization.location_tag(storage)\n\n        self.storage_info = (\"storage\", storage_type, storage_key, location, storage_numel)\n\n    def __reduce_ex__(self, protocol_version):\n        assert False, \"this should be handled with out of band\"\n\n\nclass SavingProxyForTensor:\n    def __init__(self, tensor, saver, protocol_version=5):\n        self.protocol_version = protocol_version\n        self.reduce_ret_fn, (storage, *other_reduce_args) = tensor.__reduce_ex__(protocol_version)\n        assert isinstance(storage, torch.storage.TypedStorage), \"Please check for updates\"\n        storage_proxy = SavingProxyForStorage(storage, saver, protocol_version=protocol_version)\n        self.reduce_args = (storage_proxy, *other_reduce_args)\n\n    def __reduce_ex__(self, protocol_version):\n        if protocol_version != self.protocol_version:\n            raise RuntimeError(f\"Unexpected protocol version: expected {self.protocol_version}, got {protocol_version}\")\n        return self.reduce_ret_fn, self.reduce_args\n\n\nclass IncrementalPyTorchPickler(pickle.Pickler):\n    def __init__(self, saver, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.storage_dtypes = {}\n        self.saver = saver\n        self.id_map = {}\n\n    # this logic is taken from PyTorch 2.0+ torch/serialization.py\n    def persistent_id(self, obj):\n        # FIXME: the docs say that persistent_id should only return a string\n        # but torch store returns tuples. This works only in the binary protocol\n        # see\n        # https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-external-objects\n        # https://github.com/python/cpython/blob/master/Lib/pickle.py#L527-L537\n        if isinstance(obj, SavingProxyForStorage):\n            return obj.storage_info\n\n        if isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj):\n            if isinstance(obj, torch.storage.TypedStorage):\n                # TODO: Once we decide to break serialization FC, this case\n                # can be deleted\n                storage = obj._untyped_storage\n                storage_dtype = obj.dtype\n                storage_type_str = obj._pickle_storage_type()\n                storage_type = getattr(torch, storage_type_str)\n                storage_numel = obj._size()\n\n            else:\n                storage = obj\n                storage_dtype = torch.uint8\n                storage_type = normalize_storage_type(type(obj))\n                storage_numel = storage.nbytes()\n\n            # If storage is allocated, ensure that any other saved storages\n            # pointing to the same data all have the same dtype. If storage is\n            # not allocated, don't perform this check\n            if storage.data_ptr() != 0:\n                if storage.data_ptr() in self.storage_dtypes:\n                    if storage_dtype != self.storage_dtypes[storage.data_ptr()]:\n                        raise RuntimeError(\n                            \"Cannot save multiple tensors or storages that view the same data as different types\"\n                        )\n                else:\n                    self.storage_dtypes[storage.data_ptr()] = storage_dtype\n\n            storage_key = self.id_map.get(storage._cdata)\n            if storage_key is None:\n                storage_key = self.saver._write_storage_and_return_key(storage)\n                self.id_map[storage._cdata] = storage_key\n            location = torch.serialization.location_tag(storage)\n\n            return (\"storage\", storage_type, storage_key, location, storage_numel)\n\n        return None\n\n\nclass incremental_save:\n    def __init__(self, name):\n        self.name = name\n        self.zipfile = torch._C.PyTorchFileWriter(str(name))\n        self.has_saved = False\n        self.next_key = 0\n\n    def __enter__(self):\n        return self\n\n    def store_early(self, tensor):\n        if isinstance(tensor, torch.Tensor):\n            return SavingProxyForTensor(tensor, self)\n        raise TypeError(f\"can only store tensors early, not {type(tensor)}\")\n\n    def save(self, obj):\n        if self.has_saved:\n            raise RuntimeError(\"have already saved\")\n        # Write the pickle data for `obj`\n        data_buf = BytesIO()\n        pickler = IncrementalPyTorchPickler(self, data_buf, protocol=5)\n        pickler.dump(obj)\n        data_value = data_buf.getvalue()\n        self.zipfile.write_record(\"data.pkl\", data_value, len(data_value))\n        self.has_saved = True\n\n    def _write_storage_and_return_key(self, storage):\n        if self.has_saved:\n            raise RuntimeError(\"have already saved\")\n        key = self.next_key\n        self.next_key += 1\n        name = f\"data/{key}\"\n        if storage.device.type != \"cpu\":\n            storage = storage.cpu()\n        num_bytes = storage.nbytes()\n        self.zipfile.write_record(name, storage.data_ptr(), num_bytes)\n        return key\n\n    def __exit__(self, type, value, traceback):\n        self.zipfile.write_end_of_file()\n\n\nT = TypeVar(\"T\")\n\n\ndef step_csv_logger(*args: Any, cls: Type[T] = CSVLogger, **kwargs: Any) -> T:\n    logger = cls(*args, **kwargs)\n\n    def merge_by(dicts, key):\n        from collections import defaultdict\n\n        out = defaultdict(dict)\n        for d in dicts:\n            if key in d:\n                out[d[key]].update(d)\n        return [v for _, v in sorted(out.items())]\n\n    def save(self) -> None:\n        \"\"\"Overridden to merge CSV by the step number.\"\"\"\n        import csv\n\n        if not self.metrics:\n            return\n        metrics = merge_by(self.metrics, \"step\")\n        keys = sorted({k for m in metrics for k in m})\n        with self._fs.open(self.metrics_file_path, \"w\", newline=\"\") as f:\n            writer = csv.DictWriter(f, fieldnames=keys)\n            writer.writeheader()\n            writer.writerows(metrics)\n\n    logger.experiment.save = MethodType(save, logger.experiment)\n\n    return logger\n\n\ndef chunked_cross_entropy(\n    logits: Union[torch.Tensor, List[torch.Tensor]], targets: torch.Tensor, chunk_size: int = 128\n) -> torch.Tensor:\n    # with large max_sequence_lengths, the beginning of `backward` allocates a large memory chunk which can dominate\n    # the memory usage in fine-tuning settings with low number of parameters.\n    # as a workaround hack, the cross entropy computation is chunked to force it to deallocate on the go, reducing\n    # the memory spike's magnitude\n\n    # lm_head was chunked (we are fine-tuning)\n    if isinstance(logits, list):\n        # don't want to chunk cross entropy\n        if chunk_size == 0:\n            logits = torch.cat(logits, dim=1)\n            logits = logits.reshape(-1, logits.size(-1))\n            targets = targets.reshape(-1)\n            return torch.nn.functional.cross_entropy(logits, targets, ignore_index=-1)\n\n        # chunk cross entropy\n        logit_chunks = [logit_chunk.reshape(-1, logit_chunk.size(-1)) for logit_chunk in logits]\n        target_chunks = [target_chunk.reshape(-1) for target_chunk in targets.split(logits[0].size(1), dim=1)]\n        loss_chunks = [\n            torch.nn.functional.cross_entropy(logit_chunk, target_chunk, ignore_index=-1, reduction=\"none\")\n            for logit_chunk, target_chunk in zip(logit_chunks, target_chunks)\n        ]\n        return torch.cat(loss_chunks).mean()\n\n    # no chunking at all\n    logits = logits.reshape(-1, logits.size(-1))\n    targets = targets.reshape(-1)\n    if chunk_size == 0:\n        return torch.nn.functional.cross_entropy(logits, targets, ignore_index=-1)\n\n    # lm_head wasn't chunked, chunk cross entropy\n    logit_chunks = logits.split(chunk_size)\n    target_chunks = targets.split(chunk_size)\n    loss_chunks = [\n        torch.nn.functional.cross_entropy(logit_chunk, target_chunk, ignore_index=-1, reduction=\"none\")\n        for logit_chunk, target_chunk in zip(logit_chunks, target_chunks)\n    ]\n    return torch.cat(loss_chunks).mean()\n\n\ndef map_old_state_dict_weights(state_dict: Dict, mapping: Mapping, prefix: str) -> Dict:\n    for checkpoint_name, attribute_name in mapping.items():\n        full_checkpoint_name = prefix + checkpoint_name\n        if full_checkpoint_name in state_dict:\n            full_attribute_name = prefix + attribute_name\n            state_dict[full_attribute_name] = state_dict.pop(full_checkpoint_name)\n    return state_dict\n\n\ndef get_default_supported_precision(training: bool, tpu: bool = False) -> str:\n    \"\"\"Return default precision that is supported by the hardware.\n\n    Args:\n        training: `-mixed` or `-true` version of the precision to use\n        tpu: whether TPU device is used\n\n    Returns:\n        default precision that is suitable for the task and is supported by the hardware\n    \"\"\"\n    if tpu:\n        return \"32-true\"\n    if not torch.cuda.is_available() or torch.cuda.is_bf16_supported():\n        return \"bf16-mixed\" if training else \"bf16-true\"\n    return \"16-mixed\" if training else \"16-true\"\n"
  },
  {
    "path": "pretrain/tinyllama.py",
    "content": "import glob\nimport math\nimport sys\nimport time\nfrom pathlib import Path\nfrom typing import Optional, Tuple, Union\nimport math\nimport lightning as L\nimport torch\nfrom lightning.fabric.strategies import FSDPStrategy, XLAStrategy\nfrom torch.utils.data import DataLoader\nfrom functools import partial\n# support running without installing as a package\nwd = Path(__file__).parent.parent.resolve()\nsys.path.append(str(wd))\n# from apex.optimizers import FusedAdam #torch optimizer has a cuda backend, which is faster actually\nfrom lit_gpt.model import GPT, Block, Config, CausalSelfAttention\nfrom lit_gpt.packed_dataset import CombinedDataset, PackedDataset\nfrom lit_gpt.speed_monitor import SpeedMonitorFabric as Monitor\nfrom lit_gpt.speed_monitor import estimate_flops, measure_flops\nfrom lit_gpt.utils import chunked_cross_entropy, get_default_supported_precision, num_parameters, step_csv_logger, lazy_load\nfrom pytorch_lightning.loggers import WandbLogger\nfrom lit_gpt import FusedCrossEntropyLoss\nimport random\n\nmodel_name = \"tiny_LLaMA_1b\"\nname = \"tinyllama_1b\"\nout_dir = Path(\"out\") / name\n\n# Hyperparameters\nnum_of_devices = 8\nglobal_batch_size = 512\nlearning_rate = 4e-4\nmicro_batch_size = 8\nmax_step = 715256 * 2\nwarmup_steps = 2000\nlog_step_interval = 10\neval_iters = 100\nsave_step_interval = 5000\neval_step_interval = 5000\n\n\nweight_decay = 1e-1\nbeta1 = 0.9\nbeta2 = 0.95\ngrad_clip = 1.0\ndecay_lr = True\nmin_lr = 4e-5\n\nbatch_size = global_batch_size // num_of_devices\ngradient_accumulation_steps = batch_size // micro_batch_size\nassert gradient_accumulation_steps > 0\nwarmup_iters = warmup_steps * gradient_accumulation_steps\n\n\n\n\nmax_iters = max_step * gradient_accumulation_steps\nlr_decay_iters = max_iters\nlog_iter_interval = log_step_interval * gradient_accumulation_steps\n\n\n# Treat all dataset equally by their size. If you want to use a different weight for a dataset, add it to the list with the weight.\ntrain_data_config = [\n    (\"train_slim\", 0.693584),\n    (\"train_star\", 0.306416),\n]\n\nval_data_config = [\n    (\"validation\", 1.0),\n]\n\nhparams = {k: v for k, v in locals().items() if isinstance(v, (int, float, str)) and not k.startswith(\"_\")}\nlogger = step_csv_logger(\"out\", name, flush_logs_every_n_steps=log_iter_interval)\nwandb_logger = WandbLogger()\n\n\ndef setup(\n    devices: int = 8,\n    train_data_dir: Path = Path(\"data/redpajama_sample\"),\n    val_data_dir: Optional[Path] = None,\n    precision: Optional[str] = None,\n    tpu: bool = False,\n    resume: Union[bool, Path] = False,\n) -> None:\n    precision = precision or get_default_supported_precision(training=True, tpu=tpu)\n\n    if devices > 1:\n        if tpu:\n            # For multi-host TPU training, the device count for Fabric is limited to the count on a single host.\n            devices = \"auto\"\n            strategy = XLAStrategy(sync_module_states=False)\n        else:\n            strategy = FSDPStrategy(\n                auto_wrap_policy={Block},\n                activation_checkpointing_policy=None,\n                state_dict_type=\"full\",\n                limit_all_gathers=True,\n                cpu_offload=False,\n            )\n    else:\n        strategy = \"auto\"\n\n    fabric = L.Fabric(devices=devices, strategy=strategy, precision=precision, loggers=[logger, wandb_logger])\n    fabric.print(hparams)\n    #fabric.launch(main, train_data_dir, val_data_dir, resume)\n    main(fabric, train_data_dir, val_data_dir, resume)\n\n\ndef main(fabric, train_data_dir, val_data_dir, resume):\n    monitor = Monitor(fabric, window_size=2, time_unit=\"seconds\", log_iter_interval=log_iter_interval)\n\n    if fabric.global_rank == 0:\n        out_dir.mkdir(parents=True, exist_ok=True)\n\n    config = Config.from_name(model_name)\n\n    train_dataloader, val_dataloader = create_dataloaders(\n        batch_size=micro_batch_size,\n        block_size=config.block_size,\n        fabric=fabric,\n        train_data_dir=train_data_dir,\n        val_data_dir=val_data_dir,\n        seed=3407,\n    )\n    if val_dataloader is None:\n        train_dataloader = fabric.setup_dataloaders(train_dataloader)\n    else:\n        train_dataloader, val_dataloader = fabric.setup_dataloaders(train_dataloader, val_dataloader)\n\n    fabric.seed_everything(3407)  # same seed for every process to init model (FSDP)\n\n    fabric.print(f\"Loading model with {config.__dict__}\")\n    t0 = time.perf_counter()\n    with fabric.init_module(empty_init=False):\n        model = GPT(config)\n        model.apply(partial(model._init_weights ,n_layer=config.n_layer))\n \n\n    fabric.print(f\"Time to instantiate model: {time.perf_counter() - t0:.02f} seconds.\")\n    fabric.print(f\"Total parameters {num_parameters(model):,}\")\n\n    model = fabric.setup(model)\n    optimizer = torch.optim.AdamW(\n        model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2), foreach=False\n    )\n    # optimizer = FusedAdam(model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2),adam_w_mode=True)\n    optimizer = fabric.setup_optimizers(optimizer)\n\n    state = {\"model\": model, \"optimizer\": optimizer, \"hparams\": hparams, \"iter_num\": 0, \"step_count\": 0}\n\n    if resume is True:\n        resume = sorted(out_dir.glob(\"*.pth\"))[-1]\n    if resume :\n        fabric.print(f\"Resuming training from {resume}\")\n        fabric.load(resume, state)\n\n    train_time = time.perf_counter()\n    train(fabric, state, train_dataloader, val_dataloader, monitor, resume)\n    fabric.print(f\"Training time: {(time.perf_counter()-train_time):.2f}s\")\n    if fabric.device.type == \"cuda\":\n        fabric.print(f\"Memory used: {torch.cuda.max_memory_allocated() / 1e9:.02f} GB\")\n\n\ndef train(fabric, state, train_dataloader, val_dataloader, monitor, resume):\n    model = state[\"model\"]\n    optimizer = state[\"optimizer\"]\n\n    if val_dataloader is not None:\n        validate(fabric, model, val_dataloader)  # sanity check\n\n    with torch.device(\"meta\"):\n        meta_model = GPT(model.config)\n        # \"estimated\" is not as precise as \"measured\". Estimated is optimistic but widely used in the wild.\n        # When comparing MFU or FLOP numbers with other projects that use estimated FLOPs,\n        # consider passing `SpeedMonitor(flops_per_batch=estimated_flops)` instead\n        estimated_flops = estimate_flops(meta_model) * micro_batch_size\n        fabric.print(f\"Estimated TFLOPs: {estimated_flops * fabric.world_size / 1e12:.2f}\")\n        x = torch.randint(0, 1, (micro_batch_size, model.config.block_size))\n        # measured_flos run in meta. Will trigger fusedRMSNorm error\n        #measured_flops = measure_flops(meta_model, x)\n        #fabric.print(f\"Measured TFLOPs: {measured_flops * fabric.world_size / 1e12:.2f}\")\n        del meta_model, x\n\n    total_lengths = 0\n    total_t0 = time.perf_counter()\n\n    if fabric.device.type == \"xla\":\n        import torch_xla.core.xla_model as xm\n\n        xm.mark_step()\n    \n    \n    initial_iter = state[\"iter_num\"]\n    curr_iter = 0\n            \n    loss_func = FusedCrossEntropyLoss()\n    for  train_data in train_dataloader:\n        # resume loader state. This is not elegant but it works. Should rewrite it in the future.\n        if resume:\n            if curr_iter < initial_iter:\n                curr_iter += 1\n                continue\n            else:\n                resume = False\n                curr_iter = -1\n                fabric.barrier()\n                fabric.print(\"resume finished, taken {} seconds\".format(time.perf_counter() - total_t0))\n        if state[\"iter_num\"] >= max_iters:\n            break\n        \n        # determine and set the learning rate for this iteration\n        lr = get_lr(state[\"iter_num\"]) if decay_lr else learning_rate\n        for param_group in optimizer.param_groups:\n            param_group[\"lr\"] = lr\n\n        iter_t0 = time.perf_counter()\n\n        input_ids = train_data[:, 0 : model.config.block_size].contiguous()\n        targets = train_data[:, 1 : model.config.block_size + 1].contiguous()\n        is_accumulating = (state[\"iter_num\"] + 1) % gradient_accumulation_steps != 0\n        with fabric.no_backward_sync(model, enabled=is_accumulating):\n            logits = model(input_ids)\n            loss = loss_func(logits, targets)\n            # loss = chunked_cross_entropy(logits, targets, chunk_size=0)\n            fabric.backward(loss / gradient_accumulation_steps)\n\n        if not is_accumulating:\n            fabric.clip_gradients(model, optimizer, max_norm=grad_clip)\n            optimizer.step()\n            optimizer.zero_grad()\n            state[\"step_count\"] += 1\n        elif fabric.device.type == \"xla\":\n            xm.mark_step()\n        state[\"iter_num\"] += 1\n        # input_id: B L \n        total_lengths += input_ids.size(1)\n        t1 = time.perf_counter()\n        fabric.print(\n                f\"iter {state['iter_num']} step {state['step_count']}: loss {loss.item():.4f}, iter time:\"\n                f\" {(t1 - iter_t0) * 1000:.2f}ms{' (optimizer.step)' if not is_accumulating else ''}\"\n                f\" remaining time: {(t1 - total_t0) / (state['iter_num'] - initial_iter) * (max_iters - state['iter_num']) / 3600:.2f} hours. \" \n                # print days as well\n                f\" or {(t1 - total_t0) / (state['iter_num'] - initial_iter) * (max_iters - state['iter_num']) / 3600 / 24:.2f} days. \"\n            )\n \n        monitor.on_train_batch_end(\n            state[\"iter_num\"] * micro_batch_size,\n            t1 - total_t0,\n            # this assumes that device FLOPs are the same and that all devices have the same batch size\n            fabric.world_size,\n            state[\"step_count\"],\n            flops_per_batch=estimated_flops,\n            lengths=total_lengths,\n            train_loss = loss.item()\n        )\n\n            \n            \n            \n        if val_dataloader is not None and not is_accumulating and state[\"step_count\"] % eval_step_interval == 0:\n            \n            t0 = time.perf_counter()\n            val_loss = validate(fabric, model, val_dataloader)\n            t1 = time.perf_counter() - t0\n            monitor.eval_end(t1)\n            fabric.print(f\"step {state['iter_num']}: val loss {val_loss:.4f}, val time: {t1 * 1000:.2f}ms\")\n            fabric.log_dict({\"metric/val_loss\": val_loss.item(), \"total_tokens\": model.config.block_size * (state[\"iter_num\"] + 1) * micro_batch_size * fabric.world_size}, state[\"step_count\"])\n            fabric.log_dict({\"metric/val_ppl\": math.exp(val_loss.item()), \"total_tokens\": model.config.block_size * (state[\"iter_num\"] + 1) * micro_batch_size * fabric.world_size}, state[\"step_count\"])\n            fabric.barrier()\n        if not is_accumulating and state[\"step_count\"] % save_step_interval == 0:\n            checkpoint_path = out_dir / f\"iter-{state['iter_num']:06d}-ckpt.pth\"\n            fabric.print(f\"Saving checkpoint to {str(checkpoint_path)!r}\")\n            fabric.save(checkpoint_path, state)\n\n        \n@torch.no_grad()\ndef validate(fabric: L.Fabric, model: torch.nn.Module, val_dataloader: DataLoader) -> torch.Tensor:\n    fabric.print(\"Validating ...\")\n    model.eval()\n\n    losses = torch.zeros(eval_iters, device=fabric.device)\n    for k, val_data in enumerate(val_dataloader):\n        if k >= eval_iters:\n            break\n        input_ids = val_data[:, 0 : model.config.block_size].contiguous()\n        targets = val_data[:, 1 : model.config.block_size + 1].contiguous()\n        logits = model(input_ids)\n        loss = chunked_cross_entropy(logits, targets, chunk_size=0)\n\n        # loss_func = FusedCrossEntropyLoss()\n        # loss = loss_func(logits, targets)\n        losses[k] = loss.item()\n        \n    out = losses.mean()\n\n    model.train()\n    return out\n\n\ndef create_dataloader(\n    batch_size: int, block_size: int, data_dir: Path, fabric, shuffle: bool = True, seed: int = 12345, split=\"train\"\n) -> DataLoader:\n    datasets = []\n    data_config = train_data_config if split == \"train\" else val_data_config\n    for prefix, _ in data_config:\n        filenames = sorted(glob.glob(str(data_dir / f\"{prefix}*\")))\n        random.seed(seed)\n        random.shuffle(filenames)\n\n        dataset = PackedDataset(\n            filenames,\n            # n_chunks control the buffer size. \n            # Note that the buffer size also impacts the random shuffle\n            # (PackedDataset is an IterableDataset. So the shuffle is done by prefetch a buffer and shuffle the buffer)\n            n_chunks=8,\n            block_size=block_size,\n            shuffle=shuffle,\n            seed=seed+fabric.global_rank,\n            num_processes=fabric.world_size,\n            process_rank=fabric.global_rank,\n        )\n        datasets.append(dataset)\n\n    if not datasets:\n        raise RuntimeError(\n            f\"No data found at {data_dir}. Make sure you ran prepare_redpajama.py to create the dataset.\"\n        )\n\n    weights = [weight for _, weight in data_config]\n    sum_weights = sum(weights)\n    weights = [el / sum_weights for el in weights]\n\n    combined_dataset = CombinedDataset(datasets=datasets, seed=seed, weights=weights)\n\n    return DataLoader(combined_dataset, batch_size=batch_size, shuffle=False, pin_memory=True)\n\n\ndef create_dataloaders(\n    batch_size: int,\n    block_size: int,\n    fabric,\n    train_data_dir: Path = Path(\"data/redpajama_sample\"),\n    val_data_dir: Optional[Path] = None,\n    seed: int = 12345,\n) -> Tuple[DataLoader, DataLoader]:\n    # Increase by one because we need the next word as well\n    effective_block_size = block_size + 1\n    train_dataloader = create_dataloader(\n        batch_size=batch_size,\n        block_size=effective_block_size,\n        fabric=fabric,\n        data_dir=train_data_dir,\n        shuffle=True,\n        seed=seed,\n        split=\"train\"\n    )\n    val_dataloader = (\n        create_dataloader(\n            batch_size=batch_size,\n            block_size=effective_block_size,\n            fabric=fabric,\n            data_dir=val_data_dir,\n            shuffle=False,\n            seed=seed,\n            split=\"validation\"\n        )\n        if val_data_dir\n        else None\n    )\n    return train_dataloader, val_dataloader\n\n\n# learning rate decay scheduler (cosine with warmup)\ndef get_lr(it):\n    # 1) linear warmup for warmup_iters steps\n    if it < warmup_iters:\n        return learning_rate * it / warmup_iters\n    # 2) if it > lr_decay_iters, return min learning rate\n    if it > lr_decay_iters:\n        return min_lr\n    # 3) in between, use cosine decay down to min learning rate\n    decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)\n    assert 0 <= decay_ratio <= 1\n    coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))  # coeff ranges 0..1\n    return min_lr + coeff * (learning_rate - min_lr)\n\n\nif __name__ == \"__main__\":\n    # Uncomment this line if you see an error: \"Expected is_sm80 to be true, but got false\"\n    # torch.backends.cuda.enable_flash_sdp(False)\n    torch.set_float32_matmul_precision(\"high\")\n\n    from jsonargparse import CLI\n\n    CLI(setup)\n"
  },
  {
    "path": "pretrain/tinyllama_code.py",
    "content": "import glob\nimport math\nimport sys\nimport time\nfrom pathlib import Path\nfrom typing import Optional, Tuple, Union\nimport math\nimport lightning as L\nimport torch\nfrom lightning.fabric.strategies import FSDPStrategy, XLAStrategy\nfrom torch.utils.data import DataLoader\nfrom functools import partial\n# support running without installing as a package\nwd = Path(__file__).parent.parent.resolve()\nsys.path.append(str(wd))\n# from apex.optimizers import FusedAdam #torch optimizer has a cuda backend, which is faster actually\nfrom lit_gpt.model import GPT, Block, Config, CausalSelfAttention\nfrom lit_gpt.packed_dataset import CombinedDataset, PackedDataset\nfrom lit_gpt.speed_monitor import SpeedMonitorFabric as Monitor\nfrom lit_gpt.speed_monitor import estimate_flops, measure_flops\nfrom lit_gpt.utils import chunked_cross_entropy, get_default_supported_precision, num_parameters, step_csv_logger, lazy_load\nfrom pytorch_lightning.loggers import WandbLogger\nfrom lit_gpt import FusedCrossEntropyLoss\nimport random\n\n\nmodel_name = \"tiny_LLaMA_1b\"\nname = \"tiny_LLaMA_1b\"\nout_dir = Path(\"out\") / name\ncheckpoint_path = \"out/TinyLlama-1.1B-intermediate-step-240k-503b/lit_model.pth\"\n# Hyperparameters\nnum_of_devices = 6\nglobal_batch_size = 360\nlearning_rate = 2e-4\nmin_lr = 2e-5\nmicro_batch_size = 6\nmax_step = 10000\nwarmup_steps = 0 \nlog_step_interval = 1\neval_iters = 1000000\nsave_step_interval = 2000\neval_step_interval = 2000\n\nweight_decay = 1e-1\nbeta1 = 0.9\nbeta2 = 0.95\ngrad_clip = 1.0\ndecay_lr = True\n\nbatch_size = global_batch_size // num_of_devices\ngradient_accumulation_steps = batch_size // micro_batch_size\nassert gradient_accumulation_steps > 0\nwarmup_iters = warmup_steps * gradient_accumulation_steps\n\n\n\n\nmax_iters = max_step * gradient_accumulation_steps\nlr_decay_iters = max_iters\nlog_iter_interval = log_step_interval * gradient_accumulation_steps\n\n\n# Treat all dataset equally by their size. If you want to use a different weight for a dataset, add it to the list with the weight.\ntrain_data_config = [\n    (\"train_starcoder\", 1),\n]\n\nval_data_config = [\n    (\"validation\", 1.0),\n]\n\nhparams = {k: v for k, v in locals().items() if isinstance(v, (int, float, str)) and not k.startswith(\"_\")}\nlogger = step_csv_logger(\"out\", name, flush_logs_every_n_steps=log_iter_interval)\nwandb_logger = WandbLogger()\n\n\ndef setup(\n    devices: int = 8,\n    train_data_dir: Path = Path(\"data/redpajama_sample\"),\n    val_data_dir: Optional[Path] = None,\n    precision: Optional[str] = None,\n    tpu: bool = False,\n    resume: Union[bool, Path] = False,\n) -> None:\n    precision = precision or get_default_supported_precision(training=True, tpu=tpu)\n\n    if devices > 1:\n        if tpu:\n            # For multi-host TPU training, the device count for Fabric is limited to the count on a single host.\n            devices = \"auto\"\n            strategy = XLAStrategy(sync_module_states=False)\n        else:\n            strategy = FSDPStrategy(\n                auto_wrap_policy={Block},\n                activation_checkpointing_policy=None,\n                state_dict_type=\"full\",\n                limit_all_gathers=True,\n                cpu_offload=False,\n            )\n    else:\n        strategy = \"auto\"\n\n    fabric = L.Fabric(devices=devices, strategy=strategy, precision=precision, loggers=[logger, wandb_logger])\n    fabric.print(hparams)\n    fabric.launch(main, train_data_dir, val_data_dir, resume)\n    # main(fabric, train_data_dir, val_data_dir, resume)\n\n\ndef main(fabric, train_data_dir, val_data_dir, resume):\n    monitor = Monitor(fabric, window_size=2, time_unit=\"seconds\", log_iter_interval=log_iter_interval)\n\n    if fabric.global_rank == 0:\n        out_dir.mkdir(parents=True, exist_ok=True)\n\n    config = Config.from_name(model_name)\n\n    train_dataloader, val_dataloader = create_dataloaders(\n        batch_size=micro_batch_size,\n        block_size=config.block_size,\n        fabric=fabric,\n        train_data_dir=train_data_dir,\n        val_data_dir=val_data_dir,\n        seed=3407,\n    )\n    if val_dataloader is None:\n        train_dataloader = fabric.setup_dataloaders(train_dataloader)\n    else:\n        train_dataloader, val_dataloader = fabric.setup_dataloaders(train_dataloader, val_dataloader)\n\n    fabric.seed_everything(3407)  # same seed for every process to init model (FSDP)\n\n    fabric.print(f\"Loading model {str(checkpoint_path)!r} with {config.__dict__}\")\n    t0 = time.perf_counter()\n    with fabric.init_module(empty_init=True):\n        model = GPT(config)\n    \n \n    model = fabric.setup(model)\n    fabric.load_raw(checkpoint_path, model, strict=True)\n    fabric.print(f\"Time to instantiate model: {time.perf_counter() - t0:.02f} seconds.\")\n    fabric.print(f\"Total parameters {num_parameters(model):,}\")\n\n    \n    optimizer = torch.optim.AdamW(\n        model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2), foreach=False\n    )\n    # import bitsandbytes as bnb\n    # optimizer = bnb.optim.AdamW8bit(\n    #     model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2)\n    # )\n    # optimizer = FusedAdam(model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2),adam_w_mode=True)\n    optimizer = fabric.setup_optimizers(optimizer)\n\n    state = {\"model\": model, \"optimizer\": optimizer, \"hparams\": hparams, \"iter_num\": 0, \"step_count\": 0}\n\n    if resume is True:\n        resume = sorted(out_dir.glob(\"*.pth\"))[-1]\n    if resume :\n        fabric.print(f\"Resuming training from {resume}\")\n        fabric.load(resume, state)\n\n    train_time = time.perf_counter()\n    train(fabric, state, train_dataloader, val_dataloader, monitor, resume)\n    fabric.print(f\"Training time: {(time.perf_counter()-train_time):.2f}s\")\n    if fabric.device.type == \"cuda\":\n        fabric.print(f\"Memory used: {torch.cuda.max_memory_allocated() / 1e9:.02f} GB\")\n\n\ndef train(fabric, state, train_dataloader, val_dataloader, monitor, resume):\n    model = state[\"model\"]\n    optimizer = state[\"optimizer\"]\n\n    if val_dataloader is not None:\n        validate(fabric, model, val_dataloader)  # sanity check\n\n    with torch.device(\"meta\"):\n        meta_model = GPT(model.config)\n        # \"estimated\" is not as precise as \"measured\". Estimated is optimistic but widely used in the wild.\n        # When comparing MFU or FLOP numbers with other projects that use estimated FLOPs,\n        # consider passing `SpeedMonitor(flops_per_batch=estimated_flops)` instead\n        estimated_flops = estimate_flops(meta_model) * micro_batch_size\n        fabric.print(f\"Estimated TFLOPs: {estimated_flops * fabric.world_size / 1e12:.2f}\")\n        x = torch.randint(0, 1, (micro_batch_size, model.config.block_size))\n        # measured_flos run in meta. Will trigger fusedRMSNorm error\n        #measured_flops = measure_flops(meta_model, x)\n        #fabric.print(f\"Measured TFLOPs: {measured_flops * fabric.world_size / 1e12:.2f}\")\n        del meta_model, x\n\n    total_lengths = 0\n    total_t0 = time.perf_counter()\n\n    if fabric.device.type == \"xla\":\n        import torch_xla.core.xla_model as xm\n\n        xm.mark_step()\n    \n    \n    initial_iter = state[\"iter_num\"]\n    curr_iter = 0\n            \n    loss_func = FusedCrossEntropyLoss()\n    for  train_data in train_dataloader:\n        # resume loader state. This is not elegant but it works. Should rewrite it in the future.\n        if resume:\n            if curr_iter < initial_iter:\n                curr_iter += 1\n                continue\n            else:\n                resume = False\n                curr_iter = -1\n                fabric.barrier()\n                fabric.print(\"resume finished, taken {} seconds\".format(time.perf_counter() - total_t0))\n        if state[\"iter_num\"] >= max_iters:\n            break\n        \n        # determine and set the learning rate for this iteration\n        lr = get_lr(state[\"iter_num\"]) if decay_lr else learning_rate\n        for param_group in optimizer.param_groups:\n            param_group[\"lr\"] = lr\n\n        iter_t0 = time.perf_counter()\n        input_ids = train_data[:, 0 : model.config.block_size].contiguous()\n        targets = train_data[:, 1 : model.config.block_size + 1].contiguous()\n\n        is_accumulating = (state[\"iter_num\"] + 1) % gradient_accumulation_steps != 0\n        with fabric.no_backward_sync(model, enabled=is_accumulating):\n            logits = model(input_ids)\n            loss = loss_func(logits, targets)\n            # loss = chunked_cross_entropy(logits, targets, chunk_size=0)\n            fabric.backward(loss / gradient_accumulation_steps)\n\n        if not is_accumulating:\n            fabric.clip_gradients(model, optimizer, max_norm=grad_clip)\n            optimizer.step()\n            optimizer.zero_grad()\n            state[\"step_count\"] += 1\n        elif fabric.device.type == \"xla\":\n            xm.mark_step()\n        state[\"iter_num\"] += 1\n        # input_id: B L \n        total_lengths += input_ids.size(1)\n        t1 = time.perf_counter()\n        fabric.print(\n                f\"iter {state['iter_num']} step {state['step_count']}: loss {loss.item():.4f}, iter time:\"\n                f\" {(t1 - iter_t0) * 1000:.2f}ms{' (optimizer.step)' if not is_accumulating else ''}\"\n                f\" remaining time: {(t1 - total_t0) / (state['iter_num'] - initial_iter) * (max_iters - state['iter_num']) / 3600:.2f} hours. \" \n                # print days as well\n                f\" or {(t1 - total_t0) / (state['iter_num'] - initial_iter) * (max_iters - state['iter_num']) / 3600 / 24:.2f} days. \"\n            )\n \n        monitor.on_train_batch_end(\n            state[\"iter_num\"] * micro_batch_size,\n            t1 - total_t0,\n            # this assumes that device FLOPs are the same and that all devices have the same batch size\n            fabric.world_size,\n            state[\"step_count\"],\n            flops_per_batch=estimated_flops,\n            lengths=total_lengths,\n            train_loss = loss.item()\n        )\n\n            \n            \n            \n        if val_dataloader is not None and not is_accumulating and state[\"step_count\"] % eval_step_interval == 0:\n            \n            t0 = time.perf_counter()\n            val_loss = validate(fabric, model, val_dataloader)\n            t1 = time.perf_counter() - t0\n            monitor.eval_end(t1)\n            fabric.print(f\"step {state['iter_num']}: val loss {val_loss:.4f}, val time: {t1 * 1000:.2f}ms\")\n            fabric.log_dict({\"metric/val_loss\": val_loss.item(), \"total_tokens\": model.config.block_size * (state[\"iter_num\"] + 1) * micro_batch_size * fabric.world_size}, state[\"step_count\"])\n            fabric.log_dict({\"metric/val_ppl\": math.exp(val_loss.item()), \"total_tokens\": model.config.block_size * (state[\"iter_num\"] + 1) * micro_batch_size * fabric.world_size}, state[\"step_count\"])\n            fabric.barrier()\n        if not is_accumulating and state[\"step_count\"] % save_step_interval == 0:\n            checkpoint_path = out_dir / f\"iter-{state['iter_num']:06d}-ckpt.pth\"\n            fabric.print(f\"Saving checkpoint to {str(checkpoint_path)!r}\")\n            fabric.save(checkpoint_path, state)\n\n        \n@torch.no_grad()\ndef validate(fabric: L.Fabric, model: torch.nn.Module, val_dataloader: DataLoader) -> torch.Tensor:\n    fabric.print(\"Validating ...\")\n    model.eval()\n\n    losses = torch.zeros(eval_iters, device=fabric.device)\n    for k, val_data in enumerate(val_dataloader):\n        if k >= eval_iters:\n            break\n        input_ids = val_data[:, 0 : model.config.block_size].contiguous()\n        targets = val_data[:, 1 : model.config.block_size + 1].contiguous()\n        logits = model(input_ids)\n        loss = chunked_cross_entropy(logits, targets, chunk_size=0)\n\n        # loss_func = FusedCrossEntropyLoss()\n        # loss = loss_func(logits, targets)\n        losses[k] = loss.item()\n        \n    out = losses.mean()\n\n    model.train()\n    return out\n\n\ndef create_dataloader(\n    batch_size: int, block_size: int, data_dir: Path, fabric, shuffle: bool = True, seed: int = 12345, split=\"train\"\n) -> DataLoader:\n    datasets = []\n    data_config = train_data_config if split == \"train\" else val_data_config\n    for prefix, _ in data_config:\n        filenames = sorted(glob.glob(str(data_dir / f\"{prefix}*\")))\n        random.seed(seed)\n        random.shuffle(filenames)\n\n        dataset = PackedDataset(\n            filenames,\n            # n_chunks control the buffer size. \n            # Note that the buffer size also impacts the random shuffle\n            # (PackedDataset is an IterableDataset. So the shuffle is done by prefetch a buffer and shuffle the buffer)\n            n_chunks=8,\n            block_size=block_size,\n            shuffle=shuffle,\n            seed=seed+fabric.global_rank,\n            num_processes=fabric.world_size,\n            process_rank=fabric.global_rank,\n        )\n        datasets.append(dataset)\n\n    if not datasets:\n        raise RuntimeError(\n            f\"No data found at {data_dir}. Make sure you ran prepare_redpajama.py to create the dataset.\"\n        )\n\n    weights = [weight for _, weight in data_config]\n    sum_weights = sum(weights)\n    weights = [el / sum_weights for el in weights]\n\n    combined_dataset = CombinedDataset(datasets=datasets, seed=seed, weights=weights)\n\n    return DataLoader(combined_dataset, batch_size=batch_size, shuffle=False, pin_memory=True)\n\n\ndef create_dataloaders(\n    batch_size: int,\n    block_size: int,\n    fabric,\n    train_data_dir: Path = Path(\"data/redpajama_sample\"),\n    val_data_dir: Optional[Path] = None,\n    seed: int = 12345,\n) -> Tuple[DataLoader, DataLoader]:\n    # Increase by one because we need the next word as well\n    effective_block_size = block_size + 1\n    train_dataloader = create_dataloader(\n        batch_size=batch_size,\n        block_size=effective_block_size,\n        fabric=fabric,\n        data_dir=train_data_dir,\n        shuffle=True,\n        seed=seed,\n        split=\"train\"\n    )\n    val_dataloader = (\n        create_dataloader(\n            batch_size=batch_size,\n            block_size=effective_block_size,\n            fabric=fabric,\n            data_dir=val_data_dir,\n            shuffle=False,\n            seed=seed,\n            split=\"validation\"\n        )\n        if val_data_dir\n        else None\n    )\n    return train_dataloader, val_dataloader\n\n\n# learning rate decay scheduler (cosine with warmup)\ndef get_lr(it):\n    # 1) linear warmup for warmup_iters steps\n    if it < warmup_iters:\n        return learning_rate * it / warmup_iters\n    # 2) if it > lr_decay_iters, return min learning rate\n    if it > lr_decay_iters:\n        return min_lr\n    # 3) in between, use cosine decay down to min learning rate\n    decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)\n    assert 0 <= decay_ratio <= 1\n    coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))  # coeff ranges 0..1\n    return min_lr + coeff * (learning_rate - min_lr)\n\n\nif __name__ == \"__main__\":\n    # Uncomment this line if you see an error: \"Expected is_sm80 to be true, but got false\"\n    # torch.backends.cuda.enable_flash_sdp(False)\n    torch.set_float32_matmul_precision(\"high\")\n\n    from jsonargparse import CLI\n\n    CLI(setup)\n"
  },
  {
    "path": "requirements.txt",
    "content": "torch>=2.1.0dev\nlightning==2.1.2\nlightning[app]\njsonargparse[signatures]  # CLI\npandas\npyarrow\ntokenizers\nsentencepiece\nwandb\nzstd\n\n# for finetuning\nbitsandbytes==0.40.0\ntransformers==4.31.0\npeft==0.4.0\naccelerate==0.21.0\neinops==0.6.1\nevaluate==0.4.0\nscikit-learn==1.2.2\nsentencepiece==0.1.99\nwandb==0.15.3\n# other optional dependencies are\n# sentencepiece  # pythia, falcon, redpajama\n# tokenizers  #  llama-based models\n# bitsandbytes>=0.41.1  # quantize/bnb.py\n# scipy  # TODO: remove when https://github.com/TimDettmers/bitsandbytes/pull/525 is released\n# datasets  # quantize/gptq.py\n# zstandard  # scripts/prepare_redpajama.py\n# git+https://github.com/EleutherAI/lm-evaluation-harness.git@master  # eval\n"
  },
  {
    "path": "script.sh",
    "content": "python scripts/convert_hf_checkpoint.py --checkpoint_dir  out/TinyLlama-1.1B-900B --model_name tiny_LLaMA_1b\n\npython test_weight.py --checkpoint_dir out/TinyLlama-1.1B-intermediate-900B\n\n\npython pretrain/tinyllama_code.py --devices 8 --train_data_dir data/code_specialist_python_java_javascript_c_go_8192\n\n\n\npython scripts/prepare_starcoder.py --source_path data/starcoderdata/ --tokenizer_path data/llama --destination_path data/code_specialist_python_java_javascript_c_go_8192 --split train --percentage 1.0 --filenames_subset [\"python\",\"cpp\",\"go\",\"java\",\"javascript\"] --chunk_size 4194816\n\n\n\n\n/data/TinyLlama/out/code_tiny_LLaMA_1b_python_java_go_cpp_javascript/iter-032000-ckpt.pth\n\npython scripts/convert_lit_checkpoint.py --out_dir /data/TinyLlama/out/tiny_LLaMA_1b/ --checkpoint_name iter-100000-ckpt.pth --model_name tiny_LLaMA_1b"
  },
  {
    "path": "scripts/convert_hf_checkpoint.py",
    "content": "import contextlib\nimport gc\nimport json\nimport sys\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import Dict, List, Literal, Optional, Tuple, Union\n\nimport torch\n\n# support running without installing as a package\nwd = Path(__file__).parent.parent.resolve()\nsys.path.append(str(wd))\n\nfrom lit_gpt import Config\nfrom lit_gpt.utils import NotYetLoadedTensor, incremental_save, lazy_load\n\n\ndef copy_weights_gpt_neox(\n    state_dict: Dict[str, torch.Tensor],\n    hf_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],\n    saver: Optional[incremental_save] = None,\n    dtype: Optional[torch.dtype] = None,\n) -> None:\n    weight_map = {\n        \"gpt_neox.embed_in.weight\": \"transformer.wte.weight\",\n        \"gpt_neox.layers.{}.input_layernorm.bias\": \"transformer.h.{}.norm_1.bias\",\n        \"gpt_neox.layers.{}.input_layernorm.weight\": \"transformer.h.{}.norm_1.weight\",\n        \"gpt_neox.layers.{}.attention.query_key_value.bias\": \"transformer.h.{}.attn.attn.bias\",\n        \"gpt_neox.layers.{}.attention.query_key_value.weight\": \"transformer.h.{}.attn.attn.weight\",\n        \"gpt_neox.layers.{}.attention.dense.bias\": \"transformer.h.{}.attn.proj.bias\",\n        \"gpt_neox.layers.{}.attention.dense.weight\": \"transformer.h.{}.attn.proj.weight\",\n        \"gpt_neox.layers.{}.attention.rotary_emb.inv_freq\": None,\n        \"gpt_neox.layers.{}.attention.bias\": None,\n        \"gpt_neox.layers.{}.attention.masked_bias\": None,\n        \"gpt_neox.layers.{}.post_attention_layernorm.bias\": \"transformer.h.{}.norm_2.bias\",\n        \"gpt_neox.layers.{}.post_attention_layernorm.weight\": \"transformer.h.{}.norm_2.weight\",\n        \"gpt_neox.layers.{}.mlp.dense_h_to_4h.bias\": \"transformer.h.{}.mlp.fc.bias\",\n        \"gpt_neox.layers.{}.mlp.dense_h_to_4h.weight\": \"transformer.h.{}.mlp.fc.weight\",\n        \"gpt_neox.layers.{}.mlp.dense_4h_to_h.bias\": \"transformer.h.{}.mlp.proj.bias\",\n        \"gpt_neox.layers.{}.mlp.dense_4h_to_h.weight\": \"transformer.h.{}.mlp.proj.weight\",\n        \"gpt_neox.final_layer_norm.bias\": \"transformer.ln_f.bias\",\n        \"gpt_neox.final_layer_norm.weight\": \"transformer.ln_f.weight\",\n        \"embed_out.weight\": \"lm_head.weight\",\n    }\n\n    for name, param in hf_weights.items():\n        if \"gpt_neox.layers\" in name:\n            from_name, number = layer_template(name, 2)\n            to_name = weight_map[from_name]\n            if to_name is None:\n                continue\n            to_name = to_name.format(number)\n        else:\n            to_name = weight_map[name]\n        param = load_param(param, name, dtype)\n        if saver is not None:\n            param = saver.store_early(param)\n        state_dict[to_name] = param\n\n\ndef copy_weights_falcon(\n    size: Literal[\"7b\", \"40b\"],\n    state_dict: Dict[str, torch.Tensor],\n    hf_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],\n    saver: Optional[incremental_save] = None,\n    dtype: Optional[torch.dtype] = None,\n) -> None:\n    weight_map = {\n        \"transformer.word_embeddings.weight\": \"transformer.wte.weight\",\n        \"transformer.h.{}.self_attention.query_key_value.weight\": \"transformer.h.{}.attn.attn.weight\",\n        \"transformer.h.{}.self_attention.dense.weight\": \"transformer.h.{}.attn.proj.weight\",\n        \"transformer.h.{}.mlp.dense_h_to_4h.weight\": \"transformer.h.{}.mlp.fc.weight\",\n        \"transformer.h.{}.mlp.dense_4h_to_h.weight\": \"transformer.h.{}.mlp.proj.weight\",\n        \"transformer.ln_f.bias\": \"transformer.ln_f.bias\",\n        \"transformer.ln_f.weight\": \"transformer.ln_f.weight\",\n        \"lm_head.weight\": \"lm_head.weight\",\n    }\n    # the original model definition is different for each size\n    if size == \"7b\":\n        weight_map.update(\n            {\n                \"transformer.h.{}.input_layernorm.bias\": \"transformer.h.{}.norm_1.bias\",\n                \"transformer.h.{}.input_layernorm.weight\": \"transformer.h.{}.norm_1.weight\",\n            }\n        )\n    elif size == \"40b\":\n        weight_map.update(\n            {\n                \"transformer.h.{}.ln_attn.bias\": \"transformer.h.{}.norm_1.bias\",\n                \"transformer.h.{}.ln_attn.weight\": \"transformer.h.{}.norm_1.weight\",\n                \"transformer.h.{}.ln_mlp.bias\": \"transformer.h.{}.norm_2.bias\",\n                \"transformer.h.{}.ln_mlp.weight\": \"transformer.h.{}.norm_2.weight\",\n            }\n        )\n    else:\n        raise NotImplementedError\n\n    for name, param in hf_weights.items():\n        if \"transformer.h\" in name:\n            from_name, number = layer_template(name, 2)\n            to_name = weight_map[from_name].format(number)\n        else:\n            to_name = weight_map[name]\n        param = load_param(param, name, dtype)\n        if saver is not None:\n            param = saver.store_early(param)\n        state_dict[to_name] = param\n\n\ndef copy_weights_hf_llama(\n    config: Config,\n    qkv_weights: Dict[int, List[Optional[NotYetLoadedTensor]]],\n    state_dict: Dict[str, torch.Tensor],\n    hf_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],\n    saver: Optional[incremental_save] = None,\n    dtype: Optional[torch.dtype] = None,\n) -> None:\n    weight_map = {\n        \"model.embed_tokens.weight\": \"transformer.wte.weight\",\n        \"model.layers.{}.input_layernorm.weight\": \"transformer.h.{}.norm_1.weight\",\n        \"model.layers.{}.self_attn.q_proj.weight\": None,\n        \"model.layers.{}.self_attn.k_proj.weight\": None,\n        \"model.layers.{}.self_attn.v_proj.weight\": None,\n        \"model.layers.{}.self_attn.o_proj.weight\": \"transformer.h.{}.attn.proj.weight\",\n        \"model.layers.{}.self_attn.rotary_emb.inv_freq\": None,\n        \"model.layers.{}.post_attention_layernorm.weight\": \"transformer.h.{}.norm_2.weight\",\n        \"model.layers.{}.mlp.gate_proj.weight\": \"transformer.h.{}.mlp.swiglu.w1.weight\",\n        \"model.layers.{}.mlp.up_proj.weight\": \"transformer.h.{}.mlp.swiglu.w2.weight\",\n        \"model.layers.{}.mlp.down_proj.weight\": \"transformer.h.{}.mlp.swiglu.w3.weight\",\n        \"model.norm.weight\": \"transformer.ln_f.weight\",\n        \"lm_head.weight\": \"lm_head.weight\",\n    }\n\n    for name, param in hf_weights.items():\n        if \"model.layers\" in name:\n            from_name, number = layer_template(name, 2)\n            qkv = qkv_weights.setdefault(number, [None, None, None])\n            if \"q_proj\" in name:\n                qkv[0] = param\n            elif \"k_proj\" in name:\n                qkv[1] = param\n            elif \"v_proj\" in name:\n                qkv[2] = param\n            to_name = weight_map[from_name]\n            if to_name is None:\n                continue\n            to_name = to_name.format(number)\n        else:\n            to_name = weight_map[name]\n        param = load_param(param, name, dtype)\n        if saver is not None:\n            param = saver.store_early(param)\n        state_dict[to_name] = param\n\n    for i, (q, k, v) in list(qkv_weights.items()):\n        if q is None or k is None or v is None:\n            # split across different .bin files\n            continue\n        q = load_param(q, f\"layer {i} q\", dtype)\n        k = load_param(k, f\"layer {i} k\", dtype)\n        v = load_param(v, f\"layer {i} v\", dtype)\n        q_per_kv = config.n_head // config.n_query_groups\n        qs = torch.split(q, config.head_size * q_per_kv)\n        ks = torch.split(k, config.head_size)\n        vs = torch.split(v, config.head_size)\n        cycled = [t for group in zip(qs, ks, vs) for t in group]\n        qkv = torch.cat(cycled)\n        state_dict[f\"transformer.h.{i}.attn.attn.weight\"] = qkv\n        del qkv_weights[i]\n\n\ndef layer_template(layer_name: str, idx: int) -> Tuple[str, int]:\n    split = layer_name.split(\".\")\n    number = int(split[idx])\n    split[idx] = \"{}\"\n    from_name = \".\".join(split)\n    return from_name, number\n\n\ndef load_param(param: Union[torch.Tensor, NotYetLoadedTensor], name: str, dtype: Optional[torch.dtype]) -> torch.Tensor:\n    if hasattr(param, \"_load_tensor\"):\n        # support tensors loaded via `lazy_load()`\n        print(f\"Loading {name!r} into RAM\")\n        param = param._load_tensor()\n    if dtype is not None and type(dtype) is not NotYetLoadedTensor and dtype != param.dtype:\n        print(f\"Converting {name!r} from {param.dtype} to {dtype}\")\n        param = param.to(dtype)\n    return param\n\n\n@torch.inference_mode()\ndef convert_hf_checkpoint(\n    *,\n    checkpoint_dir: Path = Path(\"checkpoints/stabilityai/stablelm-base-alpha-3b\"),\n    model_name: Optional[str] = None,\n    dtype: Optional[str] = None,\n) -> None:\n    if model_name is None:\n        model_name = checkpoint_dir.name\n    if dtype is not None:\n        dtype = getattr(torch, dtype)\n\n    config = Config.from_name(model_name)\n    print(f\"Model config {config.__dict__}\")\n    with open(checkpoint_dir / \"lit_config.json\", \"w\") as json_config:\n        json.dump(config.__dict__, json_config)\n\n    if \"falcon\" in model_name:\n        copy_fn = partial(copy_weights_falcon, \"40b\" if config.n_embd == 8192 else \"7b\")\n    elif config._mlp_class == \"LLaMAMLP\":\n        # holder to reconstitute the split q, k, v\n        qkv_weights = {}\n        copy_fn = partial(copy_weights_hf_llama, config, qkv_weights)\n    else:\n        copy_fn = copy_weights_gpt_neox\n\n    # initialize a new empty state dict to hold our new weights\n    sd = {}\n\n    # Load the json file containing weight mapping\n    pytorch_bin_map_json_path = checkpoint_dir / \"pytorch_model.bin.index.json\"\n    if pytorch_bin_map_json_path.is_file():  # not all checkpoints have this file\n        with open(pytorch_bin_map_json_path) as json_map:\n            bin_index = json.load(json_map)\n        bin_files = {checkpoint_dir / bin for bin in bin_index[\"weight_map\"].values()}\n    else:\n        bin_files = set(checkpoint_dir.glob(\"*.bin\"))\n    if not bin_files:\n        raise ValueError(f\"Expected {str(checkpoint_dir)!r} to contain .bin files\")\n\n    with incremental_save(checkpoint_dir / \"lit_model.pth\") as saver:\n        # for checkpoints that split the QKV across several files, we need to keep all the bin files\n        # open, so we use `ExitStack` to close them all together at the end\n        with contextlib.ExitStack() as stack:\n            for bin_file in sorted(bin_files):\n                print(\"Processing\", bin_file)\n                hf_weights = stack.enter_context(lazy_load(bin_file))\n                copy_fn(sd, hf_weights, saver=None, dtype=dtype)\n            gc.collect()\n        print(\"Saving converted checkpoint\")\n        saver.save(sd)\n\n\nif __name__ == \"__main__\":\n    from jsonargparse import CLI\n\n    CLI(convert_hf_checkpoint)\n"
  },
  {
    "path": "scripts/convert_lit_checkpoint.py",
    "content": "import contextlib\nimport gc\nimport sys\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import Dict, Literal, Optional, Tuple, Union\nfrom dataclasses import asdict\nimport json\nimport torch\n\n# support running without installing as a package\nwd = Path(__file__).parent.parent.resolve()\nsys.path.append(str(wd))\n\nfrom lit_gpt import Config\nfrom lit_gpt.utils import NotYetLoadedTensor, incremental_save, lazy_load\n# from scripts.convert_hf_checkpoint import layer_template, load_param\n\n\ndef layer_template(layer_name: str, idx: int) -> Tuple[str, int]:\n    split = layer_name.split(\".\")\n    number = int(split[idx])\n    split[idx] = \"{}\"\n    from_name = \".\".join(split)\n    return from_name, number\n\n\ndef load_param(param: Union[torch.Tensor, NotYetLoadedTensor], name: str, dtype: Optional[torch.dtype]) -> torch.Tensor:\n    if hasattr(param, \"_load_tensor\"):\n        # support tensors loaded via `lazy_load()`\n        print(f\"Loading {name!r} into RAM\")\n        param = param._load_tensor()\n    if dtype is not None and type(dtype) is not NotYetLoadedTensor and dtype != param.dtype:\n        print(f\"Converting {name!r} from {param.dtype} to {dtype}\")\n        param = param.to(dtype)\n    return param\ndef copy_weights_falcon(\n    size: Literal[\"7b\", \"40b\"],\n    state_dict: Dict[str, torch.Tensor],\n    lit_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],\n    saver: Optional[incremental_save] = None,\n):\n    weight_map = {\n        \"transformer.wte.weight\": \"transformer.word_embeddings.weight\",\n        \"transformer.h.{}.attn.attn.weight\": \"transformer.h.{}.self_attention.query_key_value.weight\",\n        \"transformer.h.{}.attn.proj.weight\": \"transformer.h.{}.self_attention.dense.weight\",\n        \"transformer.h.{}.mlp.fc.weight\": \"transformer.h.{}.mlp.dense_h_to_4h.weight\",\n        \"transformer.h.{}.mlp.proj.weight\": \"transformer.h.{}.mlp.dense_4h_to_h.weight\",\n        \"transformer.ln_f.bias\": \"transformer.ln_f.bias\",\n        \"transformer.ln_f.weight\": \"transformer.ln_f.weight\",\n        \"lm_head.weight\": \"lm_head.weight\",\n    }\n    # the original model definition is different for each size\n    if size == \"7b\":\n        weight_map.update(\n            {\n                \"transformer.h.{}.norm_1.bias\": \"transformer.h.{}.input_layernorm.bias\",\n                \"transformer.h.{}.norm_1.weight\": \"transformer.h.{}.input_layernorm.weight\",\n            }\n        )\n    elif size == \"40b\":\n        weight_map.update(\n            {\n                \"transformer.h.{}.norm_1.bias\": \"transformer.h.{}.ln_attn.bias\",\n                \"transformer.h.{}.norm_1.weight\": \"transformer.h.{}.ln_attn.weight\",\n                \"transformer.h.{}.norm_2.bias\": \"transformer.h.{}.ln_mlp.bias\",\n                \"transformer.h.{}.norm_2.weight\": \"transformer.h.{}.ln_mlp.weight\",\n            }\n        )\n    else:\n        raise NotImplementedError\n\n    for name, param in lit_weights.items():\n        if \"transformer.h\" in name:\n            from_name, number = layer_template(name, 2)\n            to_name = weight_map[from_name].format(number)\n        else:\n            to_name = weight_map[name]\n        param = load_param(param, name, None)\n        if saver is not None:\n            param = saver.store_early(param)\n        state_dict[to_name] = param\n\n\ndef copy_weights_gpt_neox(\n    state_dict: Dict[str, torch.Tensor],\n    lit_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],\n    saver: Optional[incremental_save] = None,\n) -> None:\n    weight_map = {\n        \"transformer.wte.weight\": \"gpt_neox.embed_in.weight\",\n        \"transformer.h.{}.norm_1.bias\": \"gpt_neox.layers.{}.input_layernorm.bias\",\n        \"transformer.h.{}.norm_1.weight\": \"gpt_neox.layers.{}.input_layernorm.weight\",\n        \"transformer.h.{}.attn.attn.bias\": \"gpt_neox.layers.{}.attention.query_key_value.bias\",\n        \"transformer.h.{}.attn.attn.weight\": \"gpt_neox.layers.{}.attention.query_key_value.weight\",\n        \"transformer.h.{}.attn.proj.bias\": \"gpt_neox.layers.{}.attention.dense.bias\",\n        \"transformer.h.{}.attn.proj.weight\": \"gpt_neox.layers.{}.attention.dense.weight\",\n        \"transformer.h.{}.norm_2.bias\": \"gpt_neox.layers.{}.post_attention_layernorm.bias\",\n        \"transformer.h.{}.norm_2.weight\": \"gpt_neox.layers.{}.post_attention_layernorm.weight\",\n        \"transformer.h.{}.mlp.fc.bias\": \"gpt_neox.layers.{}.mlp.dense_h_to_4h.bias\",\n        \"transformer.h.{}.mlp.fc.weight\": \"gpt_neox.layers.{}.mlp.dense_h_to_4h.weight\",\n        \"transformer.h.{}.mlp.proj.bias\": \"gpt_neox.layers.{}.mlp.dense_4h_to_h.bias\",\n        \"transformer.h.{}.mlp.proj.weight\": \"gpt_neox.layers.{}.mlp.dense_4h_to_h.weight\",\n        \"transformer.ln_f.bias\": \"gpt_neox.final_layer_norm.bias\",\n        \"transformer.ln_f.weight\": \"gpt_neox.final_layer_norm.weight\",\n        \"lm_head.weight\": \"embed_out.weight\",\n    }\n\n    for name, param in lit_weights.items():\n        if \"transformer.h\" in name:\n            from_name, number = layer_template(name, 2)\n            to_name = weight_map[from_name].format(number)\n        else:\n            to_name = weight_map[name]\n        param = load_param(param, name, None)\n        if saver is not None:\n            param = saver.store_early(param)\n        state_dict[to_name] = param\n\n\ndef copy_weights_llama(\n    config: Config,\n    state_dict: Dict[str, torch.Tensor],\n    lit_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],\n    saver: Optional[incremental_save] = None,\n):\n    weight_map = {\n        \"transformer.wte.weight\": \"model.embed_tokens.weight\",\n        \"transformer.h.{}.norm_1.weight\": \"model.layers.{}.input_layernorm.weight\",\n        \"transformer.h.{}.attn.proj.weight\": \"model.layers.{}.self_attn.o_proj.weight\",\n        \"transformer.h.{}.norm_2.weight\": \"model.layers.{}.post_attention_layernorm.weight\",\n        \"transformer.h.{}.mlp.swiglu.w1.weight\": \"model.layers.{}.mlp.gate_proj.weight\",\n        \"transformer.h.{}.mlp.swiglu.w2.weight\": \"model.layers.{}.mlp.up_proj.weight\",\n        \"transformer.h.{}.mlp.swiglu.w3.weight\": \"model.layers.{}.mlp.down_proj.weight\",\n        \"transformer.ln_f.weight\": \"model.norm.weight\",\n        \"lm_head.weight\": \"lm_head.weight\",\n    }\n    for name, param in lit_weights.items():\n        if name.endswith(\".attn.attn.weight\"):\n            from_name, number = layer_template(name, 2)\n            q = \"model.layers.{}.self_attn.q_proj.weight\".format(number)\n            k = \"model.layers.{}.self_attn.k_proj.weight\".format(number)\n            v = \"model.layers.{}.self_attn.v_proj.weight\".format(number)\n            qkv = load_param(param, name,None)\n            qp, kp, vp = tensor_split(qkv, config)\n            for to_name, param in zip((q, k, v), (qp, kp, vp)):\n                if saver is not None:\n                    param = saver.store_early(param)\n                state_dict[to_name] = param\n        elif \"transformer.h\" in name:\n            from_name, number = layer_template(name, 2)\n            to_name = weight_map[from_name]\n            \n            if to_name is None:\n                continue\n            to_name = to_name.format(number)\n            param = load_param(param, name,None)\n            if saver is not None:\n                param = saver.store_early(param)\n            state_dict[to_name] = param\n\n        else:\n            to_name = weight_map[name]\n            param = load_param(param, name, None)\n            if saver is not None:\n                param = saver.store_early(param)\n            state_dict[to_name] = param\n\n\ndef tensor_split(\n    param: Union[torch.Tensor, NotYetLoadedTensor], config: Config\n) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n    def kstart(start, blen, klen) -> int:\n        \"\"\"returns start index of keys in batch\"\"\"\n        return start + (blen - (klen * 2))\n\n    def vstart(start, blen, klen) -> int:\n        \"\"\"returns start index of values in batch\"\"\"\n        return start + blen - klen\n\n    def vend(start, blen) -> int:\n        \"\"\"returns last index of values in batch\"\"\"\n        return start + blen\n\n    # num observations\n    nobs = param.shape[0]\n    # batch length\n    blen = nobs // config.n_query_groups\n    # key length in batch\n    klen = config.head_size\n    # value length in batch\n    vlen = config.head_size\n    # the starting index of each new batch\n    starts = range(0, nobs, blen)\n    # the indices to splice on\n    splices = [(s, kstart(s, blen, klen), vstart(s, blen, vlen), vend(s, blen)) for s in starts]\n\n    qc = ()\n    kc = ()\n    vc = ()\n\n    for splice in splices:\n        qs, ks, vs, ve = splice\n        qc += (param[qs:ks, :],)\n        kc += (param[ks:vs, :],)\n        vc += (param[vs:ve, :],)\n\n    q = torch.cat(qc)\n    k = torch.cat(kc)\n    v = torch.cat(vc)\n\n    return q, k, v\n\n\ndef maybe_unwrap_state_dict(lit_weights: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n    return lit_weights.get(\"model\", lit_weights)\n\n\ndef check_conversion_supported(lit_weights: Dict[str, torch.Tensor]) -> None:\n    weight_names = {wk.split(\".\")[-1] for wk in lit_weights}\n    # LoRA or QLoRA\n    if any(\"lora\" in wn for wn in weight_names):\n        raise ValueError(\"Model weights must be merged using `lora.merge_lora_weights()` before conversion.\")\n    # adapter v2. adapter_bias will only be in adapter_v2\n    elif \"adapter_bias\" in weight_names:\n        raise NotImplementedError(\"Converting models finetuned with adapter_v2 not yet supported.\")\n    # adapter. gating_factor is in adapter and adapter_v2\n    elif \"gating_factor\" in weight_names:\n        raise NotImplementedError(\"Converting models finetuned with adapter not yet supported.\")\n\n\ndef get_tinyllama_init_hf_config() -> dict:\n    return {\n        \"architectures\": [\"LlamaForCausalLM\"],\n        \"bos_token_id\": 1,\n        \"eos_token_id\": 2,\n        \"hidden_act\": \"silu\",\n        \"hidden_size\": None,\n        \"initializer_range\": 0.02,\n        \"intermediate_size\": None,\n        \"max_position_embeddings\": None,\n        \"model_type\": \"llama\",\n        \"num_attention_heads\": None,\n        \"num_hidden_layers\": None,\n        \"num_key_value_heads\": None,\n        \"pretraining_tp\": 1,\n        \"rms_norm_eps\": None,\n        \"rope_scaling\": None,\n        \"tie_word_embeddings\": False,\n        \"torch_dtype\": \"float32\",\n        \"transformers_version\": \"4.31.0.dev0\",\n        \"use_cache\": True,\n        \"vocab_size\": None,\n    }\n\n\ndef convert_config_lit_to_hf(lit_config_dict: dict) -> dict:\n    lit_hf_mapping = {\n        \"block_size\": \"max_position_embeddings\",\n        \"vocab_size\": \"vocab_size\",\n        \"n_layer\": \"num_hidden_layers\",\n        \"n_embd\": \"hidden_size\",\n        \"n_head\": \"num_attention_heads\",\n        \"n_query_groups\": \"num_key_value_heads\",\n        \"intermediate_size\": \"intermediate_size\",\n        \"norm_eps\": \"rms_norm_eps\",\n\n    }\n    hf_config_dict = get_tinyllama_init_hf_config()\n    \n    for lit_key, hf_key in lit_hf_mapping.items():\n        hf_config_dict[hf_key] = lit_config_dict[lit_key]\n    return hf_config_dict\n\n\n@torch.inference_mode()\ndef convert_lit_checkpoint(*, \n    checkpoint_name: str, \n    out_dir: Path, \n    model_name: str,\n    model_only: bool = True) -> None:\n    config = Config.from_name(model_name)\n\n    if \"falcon\" in model_name:\n        copy_fn = partial(copy_weights_falcon, \"40b\" if config.n_embd == 8192 else \"7b\")\n    elif config._mlp_class == \"LLaMAMLP\":\n        copy_fn = partial(copy_weights_llama, config)\n    else:\n        copy_fn = copy_weights_gpt_neox\n\n    # initialize a new empty state dict to hold our new weights\n    sd = {}\n\n    # checkpoint_name cannot be hardcoded because there exists different outputs such as\n    # (\"lit_model_finetuned.pth\", \"lit_model_lora_finetuned.pth\", \"lit_model_adapter_finetuned.pth\"\")\n    pth_file = out_dir / checkpoint_name\n    bin_file = pth_file.with_suffix(\".bin\")\n\n    with incremental_save(bin_file) as saver:\n        with contextlib.ExitStack() as stack:\n            lit_weights = stack.enter_context(lazy_load(pth_file))\n            lit_weights = maybe_unwrap_state_dict(lit_weights)\n            check_conversion_supported(lit_weights)\n            # Incremental save will trigger error\n            copy_fn(sd, lit_weights, saver=None)\n            gc.collect()\n        saver.save(sd)\n\n    # convert lit config file to hf-style\n    if not model_only:\n        print('Converting config file...')\n        lit_config = asdict(config)\n        hf_config = convert_config_lit_to_hf(lit_config)\n        config_path = out_dir / \"config.json\"\n        with open(config_path, \"w\") as f:\n            json.dump(hf_config, f, indent=4)\n\n\n\n\nif __name__ == \"__main__\":\n    from jsonargparse import CLI\n\n    CLI(convert_lit_checkpoint, as_positional=False)\n"
  },
  {
    "path": "scripts/prepare_redpajama.py",
    "content": "import glob\nimport json\nimport os\nimport sys\nfrom pathlib import Path\n\nimport numpy as np\nfrom tqdm import tqdm\n\n# support running without installing as a package\nwd = Path(__file__).parent.parent.resolve()\nsys.path.append(str(wd))\n\nimport lit_gpt.packed_dataset as packed_dataset\nfrom lit_gpt import Config, Tokenizer\n\nfilenames_sample = [\n    \"arxiv_sample.jsonl\",\n    \"book_sample.jsonl\",\n    \"c4_sample.jsonl\",\n    \"cc_2019-30_sample.jsonl\",\n    \"cc_2020-05_sample.jsonl\",\n    \"cc_2021-04_sample.jsonl\",\n    \"cc_2022-05_sample.jsonl\",\n    \"cc_2023-06_sample.jsonl\",\n    \"github_sample.jsonl\",\n    \"stackexchange_sample.jsonl\",\n    \"wikipedia_sample.jsonl\",\n]\n\nfilename_sets = {\n    \"arxiv\": \"arxiv/arxiv*\",\n    \"book\": \"book/book*\",\n    \"c4\": \"c4/c4-train*\",\n    \"common_crawl\": \"common_crawl/*\",\n    \"github\": \"github/filtered*\",\n    \"stackexchange\": \"stackexchange/stackexchange*\",\n    \"wikipedia\": \"wikipedia/wiki*\",\n}\n\n\ndef prepare_sample(\n    source_path: Path, checkpoint_dir: Path, destination_path: Path, chunk_size: int, match: str = \"\"\n) -> None:\n    \"\"\"Prepare the \"Red Pajama\" dataset using the original tokenizer.\"\"\"\n    destination_path.mkdir(parents=True, exist_ok=True)\n\n    tokenizer = Tokenizer(checkpoint_dir)\n\n    for name in filenames_sample:\n        if match and match not in name:\n            continue\n\n        filepath = source_path / name\n\n        if not filepath.is_file():\n            raise RuntimeError(\n                f\"Input file not found at {filepath}. \\nMake sure you download the data, e.g. wget -i\"\n                \" https://data.together.xyz/redpajama-data-1T/v1.0.0/urls.txt or through\"\n                \" \\nhttps://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T\"\n                \" \\nhttps://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T-Sample \\n\"\n            )\n\n        prefix, _ = os.path.splitext(name)\n\n        builder = packed_dataset.PackedDatasetBuilder(\n            outdir=destination_path,\n            prefix=prefix,\n            chunk_size=chunk_size,\n            sep_token=tokenizer.eos_id,\n            dtype=\"auto\",\n            vocab_size=tokenizer.vocab_size,\n        )\n\n        print(f\"Processing {name}\")\n\n        with open(filepath, encoding=\"utf-8\") as f:\n            for row in tqdm(f):\n                text = json.loads(row)[\"text\"]\n                text_ids = tokenizer.encode(text)\n                builder.add_array(np.array(text_ids, dtype=builder.dtype))\n\n        builder.write_reminder()\n\n\ndef prepare_full(\n    source_path: Path, checkpoint_dir: Path, destination_path: Path, chunk_size: int, match: str = \"\"\n) -> None:\n    \"\"\"Prepare the \"Red Pajama\" dataset using the original tokenizer.\"\"\"\n    import zstandard as zstd\n\n    destination_path.mkdir(parents=True, exist_ok=True)\n\n    tokenizer = Tokenizer(checkpoint_dir)\n\n    for set_name, pattern in filename_sets.items():\n        if match and match not in set_name:\n            continue\n\n        is_cc = set_name == \"common_crawl\"\n\n        filenames = glob.glob(os.path.join(source_path, pattern), recursive=True)\n\n        if not filenames:\n            raise RuntimeError(\n                f\"No files matching {pattern} found at {source_path}. \\nMake sure you download the data, e.g. wget -i\"\n                \" https://data.together.xyz/redpajama-data-1T/v1.0.0/urls.txt or through\"\n                \" \\nhttps://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T\"\n                \" \\nhttps://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T-Sample \\n\"\n            )\n\n        builder = packed_dataset.PackedDatasetBuilder(\n            outdir=destination_path,\n            prefix=set_name,\n            chunk_size=chunk_size,\n            sep_token=tokenizer.eos_id,\n            dtype=\"auto\",\n            vocab_size=tokenizer.vocab_size,\n        )\n\n        for name in filenames:\n            filepath = source_path / name\n\n            print(f\"Processing {name}\")\n\n            if is_cc:\n                with zstd.open(open(filepath, \"rb\"), \"rt\", encoding=\"utf-8\") as f:\n                    for row in tqdm(f):\n                        text = json.loads(row)[\"text\"]\n                        text_ids = tokenizer.encode(text)\n                        builder.add_array(np.array(text_ids, dtype=builder.dtype))\n            else:\n                with open(filepath, encoding=\"utf-8\") as f:\n                    for row in tqdm(f):\n                        text = json.loads(row)[\"text\"]\n                        text_ids = tokenizer.encode(text)\n                        builder.add_array(np.array(text_ids, dtype=builder.dtype))\n\n        builder.write_reminder()\n\n\ndef prepare(\n    source_path: Path = Path(\"data/RedPajama-Data-1T-Sample\"),\n    checkpoint_dir: Path = Path(\"checkpoints/stabilityai/stablelm-base-alpha-3b\"),\n    destination_path: Path = Path(\"data/redpajama_sample\"),\n    sample: bool = True,\n    match: str = \"\",\n) -> None:\n    \"\"\"Prepare the \"Red Pajama\" dataset. We assume tokenizer has been trained.\"\"\"\n    with open(checkpoint_dir / \"lit_config.json\") as fp:\n        config = Config(**json.load(fp))\n\n    prepare_fn = prepare_sample if sample else prepare_full\n    prepare_fn(\n        source_path=source_path,\n        checkpoint_dir=checkpoint_dir,\n        destination_path=destination_path,\n        chunk_size=(config.block_size + 1) * 1024,  # block size + 1 for causal, 1024 blocks\n        match=match,\n    )\n\n\nif __name__ == \"__main__\":\n    from jsonargparse import CLI\n\n    CLI(prepare)"
  },
  {
    "path": "scripts/prepare_slimpajama.py",
    "content": "import json\nimport glob\nimport os\nfrom pathlib import Path\nimport sys\nfrom typing import List\nimport numpy as np\nfrom tqdm import tqdm\nfrom multiprocessing import Process, cpu_count\n\n# support running without installing as a package\nwd = Path(__file__).parent.parent.resolve()\nsys.path.append(str(wd))\n\nimport lit_gpt.packed_dataset as packed_dataset\nfrom lit_gpt import Tokenizer\n\n# Filename for SlimPajama\nslimpajama_sets = {\n    \"train\": \"train/chunk*/*\",\n    \"validation\": \"validation/chunk*/*\",\n    \"test\": \"test/chunk*/*\",\n}\n\n\ndef prepare_full(\n    source_path: Path,\n    tokenizer_path: Path,\n    destination_path: Path,\n    chunk_size: int,\n    split: str=\"train\",\n    filenames_subset: List[str] = None,\n    process_id: int = 0\n) -> None:\n    import zstandard as zstd\n\n    destination_path.mkdir(parents=True, exist_ok=True)\n\n    tokenizer = Tokenizer(tokenizer_path)\n\n    # Use the provided filenames_subset or default to all filenames\n    filenames = filenames_subset \n    \n    if not filenames:\n        raise RuntimeError(\n            f\"No files matching {slimpajama_sets[split]} found at {source_path}. \\n\"\n            \"Make sure you download the data...\"\n        )\n\n    builder = packed_dataset.PackedDatasetBuilder(\n        outdir=destination_path,\n        prefix=f\"{split}_slimpajama_{process_id}\",  # Use process_id to differentiate builders\n        chunk_size=chunk_size,\n        sep_token=tokenizer.bos_id,\n        dtype=\"auto\",\n        vocab_size=tokenizer.vocab_size,\n    )\n\n    for filepath in filenames:\n        print(f\"Processing {filepath}\")\n        with zstd.open(open(filepath, \"rb\"), \"rt\", encoding=\"utf-8\") as f:\n            for row in tqdm(f):\n                text = json.loads(row)[\"text\"]\n                if json.loads(row)[\"meta\"][\"redpajama_set_name\"] == \"RedPajamaGithub\":\n                    continue # we don't want to include the github data\n                text_ids = tokenizer.encode(text)\n                builder.add_array(np.array(text_ids, dtype=builder.dtype))\n\n    # we throw away the final corpus to avoid meaningless corpus filled with bos_ids, see https://github.com/jzhang38/TinyLlama/issues/83 for more details\n    # builder.write_reminder()\n\n\ndef prepare(\n    source_path: Path = Path(\"data/RedPajama-Data-1T-Sample\"),\n    tokenizer_path: Path = Path(\"checkpoints/lit-llama/tokenizer.model\"),\n    destination_path: Path = Path(\"data/red_pajama_sample\"),\n    chunk_size: int = 2049 * 1024,\n    split: str=\"train\",\n    percentage: float = 1.0,\n) -> None:\n    import time\n\n    filenames = glob.glob(os.path.join(source_path, slimpajama_sets[split]), recursive=True)\n    filenames = filenames[:int(len(filenames) * percentage)]\n    \n    num_processes = cpu_count() \n    chunked_filenames = np.array_split(filenames, num_processes)\n\n    processes = []\n    start_time = time.time()\n\n    for i, subset in enumerate(chunked_filenames):\n        p = Process(target=prepare_full, args=(source_path, tokenizer_path, destination_path, chunk_size, split, list(subset), i))\n        processes.append(p)\n        p.start()\n\n    for p in processes:\n        p.join()\n    end_time = time.time()\n    elapsed_time = end_time - start_time\n    print(f\"Time taken: {elapsed_time:.2f} seconds\")\n\n\nif __name__ == \"__main__\":\n    from jsonargparse import CLI\n    CLI(prepare)"
  },
  {
    "path": "scripts/prepare_starcoder.py",
    "content": "import json\nimport glob\nimport os\nfrom pathlib import Path\nimport sys\nfrom typing import List\nimport numpy as np\nfrom tqdm import tqdm\nfrom multiprocessing import Process, cpu_count\n\n# support running without installing as a package\nwd = Path(__file__).parent.parent.resolve()\nsys.path.append(str(wd))\n\nimport lit_gpt.packed_dataset as packed_dataset\nfrom lit_gpt import Tokenizer\n\nimport pandas as pd\n\n\ndef prepare_full(\n    source_path: Path,\n    tokenizer_path: Path,\n    destination_path: Path,\n    chunk_size: int,\n    split: str=\"train\",\n    filenames_subset: List[str] = None,\n    process_id: int = 0\n) -> None:\n    import zstandard as zstd\n\n    destination_path.mkdir(parents=True, exist_ok=True)\n\n    tokenizer = Tokenizer(tokenizer_path)\n\n    # Use the provided filenames_subset or default to all filenames\n    filenames = filenames_subset \n    \n    if not filenames:\n        raise RuntimeError(\n            f\"No files matching  found at {source_path}. \\n\"\n            \"Make sure you download the data...\"\n        )\n\n    builder = packed_dataset.PackedDatasetBuilder(\n        outdir=destination_path,\n        prefix=f\"{split}_starcoder_{process_id}\",  # Use process_id to differentiate builders\n        chunk_size=chunk_size,\n        sep_token=tokenizer.bos_id,\n        dtype=\"auto\",\n        vocab_size=tokenizer.vocab_size,\n    )\n\n    for filepath in filenames:\n        print(f\"Processing {filepath}\")\n        try:\n            contents = pd.read_parquet(filepath, engine='pyarrow')['content']\n        except:\n            print(f\"Error reading {filepath}!!\")\n            continue\n        for text in contents:\n            text_ids = tokenizer.encode(text)\n            builder.add_array(np.array(text_ids, dtype=builder.dtype))\n\n    # we throw away the final corpus to avoid meaningless corpus filled with bos_ids, see https://github.com/jzhang38/TinyLlama/issues/83 for more details\n    # builder.write_reminder()\n\n\ndef prepare(\n    source_path: Path = Path(\"data/RedPajama-Data-1T-Sample\"),\n    tokenizer_path: Path = Path(\"checkpoints/lit-llama/tokenizer.model\"),\n    destination_path: Path = Path(\"data/red_pajama_sample\"),\n    chunk_size: int = 2049 * 1024,\n    split: str=\"train\",\n    percentage: float = 1.0,\n    filenames_subset: List[str] = None,\n) -> None:\n    import time\n    assert split == \"train\" #  starcoder only has train data\n    filenames = glob.glob(os.path.join(source_path, \"*/*.parquet\"), recursive=True)\n    # only retrain subsets that follow the prefix in filenames_subset\n    if filenames_subset:\n        filenames = [f for f in filenames if any([prefix in f for prefix in filenames_subset])]\n    filenames = filenames[:int(len(filenames) * percentage)]\n    num_processes = 64\n    chunked_filenames = np.array_split(filenames, num_processes)\n\n    processes = []\n    start_time = time.time()\n\n    for i, subset in enumerate(chunked_filenames):\n        p = Process(target=prepare_full, args=(source_path, tokenizer_path, destination_path, chunk_size, split, list(subset), i))\n        processes.append(p)\n        p.start()\n\n    for p in processes:\n        p.join()\n    end_time = time.time()\n    elapsed_time = end_time - start_time\n    print(f\"Time taken: {elapsed_time:.2f} seconds\")\n\n\nif __name__ == \"__main__\":\n    from jsonargparse import CLI\n    CLI(prepare)\n"
  },
  {
    "path": "sft/finetune.py",
    "content": "# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom collections import defaultdict\nimport copy\nimport json\nimport os\nfrom os.path import exists, join, isdir\nfrom dataclasses import dataclass, field\nimport sys\nfrom typing import Optional, Dict, Sequence\nimport numpy as np\nfrom tqdm import tqdm\nimport logging\n\nimport pandas as pd\nimport importlib\nfrom packaging import version\nfrom packaging.version import parse\n\nimport torch\nimport transformers\nfrom torch.nn.utils.rnn import pad_sequence\nimport argparse\nfrom transformers import (\n    AutoTokenizer,\n    AutoModelForCausalLM,\n    set_seed,\n    Seq2SeqTrainer,\n    BitsAndBytesConfig,\n    LlamaTokenizer\n\n)\nfrom datasets import load_dataset, Dataset\nimport evaluate\n\n\nfrom transformers.trainer_utils import PREFIX_CHECKPOINT_DIR\n\n\n    \n\nif torch.cuda.is_available():   \n    torch.backends.cuda.matmul.allow_tf32 = True\n\nlogger = logging.getLogger(__name__)\n\nIGNORE_INDEX = -100\nDEFAULT_PAD_TOKEN = \"[PAD]\"\n\n@dataclass\nclass ModelArguments:\n    model_name_or_path: Optional[str] = field(\n        default=\"EleutherAI/pythia-12b\"\n    )\n    trust_remote_code: Optional[bool] = field(\n        default=False,\n        metadata={\"help\": \"Enable unpickling of arbitrary code in AutoModelForCausalLM#from_pretrained.\"}\n    )\n\n\n@dataclass\nclass DataArguments:\n    eval_dataset_size: int = field(\n        default=1024, metadata={\"help\": \"Size of validation dataset.\"}\n    )\n    max_train_samples: Optional[int] = field(\n        default=None,\n        metadata={\n            \"help\": \"For debugging purposes or quicker training, truncate the number of training examples to this \"\n            \"value if set.\"\n        },\n    )\n    max_eval_samples: Optional[int] = field(\n        default=None,\n        metadata={\n            \"help\": \"For debugging purposes or quicker training, truncate the number of evaluation examples to this \"\n            \"value if set.\"\n        },\n    )\n    source_max_len: int = field(\n        default=1024,\n        metadata={\"help\": \"Maximum source sequence length. Sequences will be right padded (and possibly truncated).\"},\n    )\n    target_max_len: int = field(\n        default=256,\n        metadata={\"help\": \"Maximum target sequence length. Sequences will be right padded (and possibly truncated).\"},\n    )\n    dataset: str = field(\n        default='alpaca',\n        metadata={\"help\": \"Which dataset to finetune on. See datamodule for options.\"}\n    )\n    dataset_format: Optional[str] = field(\n        default=None,\n        metadata={\"help\": \"Which dataset format is used. [alpaca|chip2|self-instruct|hh-rlhf]\"}\n    )\n\n@dataclass\nclass TrainingArguments(transformers.Seq2SeqTrainingArguments):\n\n    train_on_source: Optional[bool] = field(\n        default=False,\n        metadata={\"help\": \"Whether to train on the input in addition to the target text.\"}\n    )\n\n\n\n\n    report_to: str = field(\n        default='none',\n        metadata={\"help\": \"To use wandb or something else for reporting.\"}\n    )\n    output_dir: str = field(default='./output', metadata={\"help\": 'The output dir for logs and checkpoints'})\n    optim: str = field(default='adamw_torch', metadata={\"help\": 'The optimizer to be used'})\n    per_device_train_batch_size: int = field(default=16, metadata={\"help\": 'The training batch size per GPU. Increase for better speed.'})\n    gradient_accumulation_steps: int = field(default=1, metadata={\"help\": 'How many gradients to accumulate before to perform an optimizer step'})\n    max_steps: int = field(default=10000, metadata={\"help\": 'How many optimizer update steps to take'})\n    weight_decay: float = field(default=0.0, metadata={\"help\": 'The L2 weight decay rate of AdamW'})\n    learning_rate: float = field(default=0.0002, metadata={\"help\": 'The learnign rate'})\n    remove_unused_columns: bool = field(default=False, metadata={\"help\": 'Removed unused columns. Needed to make this codebase work.'})\n    max_grad_norm: float = field(default=0.3, metadata={\"help\": 'Gradient clipping max norm. This is tuned and works well for all models tested.'})\n    gradient_checkpointing: bool = field(default=True, metadata={\"help\": 'Use gradient checkpointing. You want to use this.'})\n    do_train: bool = field(default=True, metadata={\"help\": 'To train or not to train, that is the question?'})\n    lr_scheduler_type: str = field(default='constant', metadata={\"help\": 'Learning rate schedule. Constant a bit better than cosine, and has advantage for analysis'})\n    warmup_ratio: float = field(default=0.03, metadata={\"help\": 'Fraction of steps to do a warmup for'})\n    logging_steps: int = field(default=10, metadata={\"help\": 'The frequency of update steps after which to log the loss'})\n    group_by_length: bool = field(default=True, metadata={\"help\": 'Group sequences into batches with same length. Saves memory and speeds up training considerably.'})\n    save_strategy: str = field(default='steps', metadata={\"help\": 'When to save checkpoints'})\n    save_steps: int = field(default=250, metadata={\"help\": 'How often to save a model'})\n    save_total_limit: int = field(default=40, metadata={\"help\": 'How many checkpoints to save before the oldest is overwritten'})\n\n@dataclass\nclass GenerationArguments:\n    # For more hyperparameters check:\n    # https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig\n    # Length arguments\n    max_new_tokens: Optional[int] = field(\n        default=256,\n        metadata={\"help\": \"Maximum number of new tokens to be generated in evaluation or prediction loops\"\n                          \"if predict_with_generate is set.\"}\n    )\n    min_new_tokens : Optional[int] = field(\n        default=None,\n        metadata={\"help\": \"Minimum number of new tokens to generate.\"}\n    )\n\n    # Generation strategy\n    do_sample: Optional[bool] = field(default=False)\n    num_beams: Optional[int] = field(default=1)\n    num_beam_groups: Optional[int] = field(default=1)\n    penalty_alpha: Optional[float] = field(default=None)\n    use_cache: Optional[bool] = field(default=True)\n\n    # Hyperparameters for logit manipulation\n    temperature: Optional[float] = field(default=1.0)\n    top_k: Optional[int] = field(default=50)\n    top_p: Optional[float] = field(default=1.0)\n    typical_p: Optional[float] = field(default=1.0)\n    diversity_penalty: Optional[float] = field(default=0.0)\n    repetition_penalty: Optional[float] = field(default=1.0)\n    length_penalty: Optional[float] = field(default=1.0)\n    no_repeat_ngram_size: Optional[int] = field(default=0)\n\n\n\n\n\ndef get_accelerate_model(args, checkpoint_dir):\n\n\n\n\n    device_map = \"auto\"\n\n    # if we are in a distributed setting, we need to set the device map and max memory per device\n    if os.environ.get('LOCAL_RANK') is not None:\n        local_rank = int(os.environ.get('LOCAL_RANK', '0'))\n        device_map = {'': local_rank}\n\n\n    print(f'loading base model {args.model_name_or_path}...')\n    model = AutoModelForCausalLM.from_pretrained(\n        args.model_name_or_path,\n        device_map=device_map,\n        trust_remote_code=args.trust_remote_code,\n    )\n\n\n\n\n    # Tokenizer\n    tokenizer = AutoTokenizer.from_pretrained(\n        args.model_name_or_path,\n        padding_side=\"right\",\n        use_fast=True, # Fast tokenizer giving issues.\n        trust_remote_code=args.trust_remote_code,\n    )\n    if tokenizer._pad_token is None:\n        special_tokens_dict = dict(pad_token=DEFAULT_PAD_TOKEN)\n        if args.dataset == \"OpenAssistant/oasst_top1_2023-08-25\":\n            chat_special_tokens = [\"<|im_start|>\", \"<|im_end|>\"]\n            special_tokens_dict.update(additional_special_tokens=chat_special_tokens)\n\n        smart_tokenizer_and_embedding_resize(\n            special_tokens_dict=special_tokens_dict,\n            tokenizer=tokenizer,\n            model=model\n        )\n\n    return model, tokenizer\n\ndef print_trainable_parameters(args, model):\n    \"\"\"\n    Prints the number of trainable parameters in the model.\n    \"\"\"\n    trainable_params = 0\n    all_param = 0\n    for _, param in model.named_parameters():\n        all_param += param.numel()\n        if param.requires_grad:\n            trainable_params += param.numel()\n    print(\n        f\"trainable params: {trainable_params} || \"\n        f\"all params: {all_param} || \"\n    )\n\ndef smart_tokenizer_and_embedding_resize(\n    special_tokens_dict: Dict,\n    tokenizer: transformers.PreTrainedTokenizer,\n    model: transformers.PreTrainedModel,\n    non_special_tokens = None,\n):\n    \"\"\"Resize tokenizer and embedding.\n\n    Note: This is the unoptimized version that may make your embedding size not be divisible by 64.\n    \"\"\"\n    num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) + tokenizer.add_tokens(non_special_tokens)\n    model.resize_token_embeddings(len(tokenizer))\n    \n    if num_new_tokens > 0:\n        input_embeddings_data = model.get_input_embeddings().weight.data\n        output_embeddings_data = model.get_output_embeddings().weight.data\n\n        input_embeddings_avg = input_embeddings_data[:-num_new_tokens].mean(dim=0, keepdim=True)\n        output_embeddings_avg = output_embeddings_data[:-num_new_tokens].mean(dim=0, keepdim=True)\n\n        input_embeddings_data[-num_new_tokens:] = input_embeddings_avg\n        output_embeddings_data[-num_new_tokens:] = output_embeddings_avg\n    print(f\"Resized tokenizer and embedding to {len(tokenizer)} tokens.\")\n\n@dataclass\nclass DataCollatorForCausalLM(object):\n    tokenizer: transformers.PreTrainedTokenizer\n    source_max_len: int\n    target_max_len: int\n    train_on_source: bool\n    predict_with_generate: bool\n\n    def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:\n        # Extract elements\n        sources = [f\"{self.tokenizer.bos_token}{example['input']}\" for example in instances]\n        targets = [f\"{example['output']}{self.tokenizer.eos_token}\" for example in instances]\n        # Tokenize\n        tokenized_sources_with_prompt = self.tokenizer(\n            sources,\n            max_length=self.source_max_len,\n            truncation=True,\n            add_special_tokens=False,\n        )\n        tokenized_targets = self.tokenizer(\n            targets,\n            max_length=self.target_max_len,\n            truncation=True,\n            add_special_tokens=False,\n        )\n        # Build the input and labels for causal LM\n        input_ids = []\n        labels = []\n        for tokenized_source, tokenized_target in zip(\n            tokenized_sources_with_prompt['input_ids'],\n            tokenized_targets['input_ids']\n        ):\n            if not self.predict_with_generate:\n                input_ids.append(torch.tensor(tokenized_source + tokenized_target))\n                if not self.train_on_source:\n                    labels.append(\n                        torch.tensor([IGNORE_INDEX for _ in range(len(tokenized_source))] + copy.deepcopy(tokenized_target))\n                    )\n                else:\n                    labels.append(torch.tensor(copy.deepcopy(tokenized_source + tokenized_target)))\n            else:\n                input_ids.append(torch.tensor(tokenized_source))\n        # Apply padding\n        input_ids = pad_sequence(input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id)\n        labels = pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX) if not self.predict_with_generate else None\n        data_dict = {\n            'input_ids': input_ids,\n            'attention_mask':input_ids.ne(self.tokenizer.pad_token_id),\n        }\n        if labels is not None:\n            data_dict['labels'] = labels\n        return data_dict\n\ndef extract_unnatural_instructions_data(examples, extract_reformulations=False):\n    out = {\n        'input': [],\n        'output': [],\n    }\n    for example_instances in examples['instances']:\n        for instance in example_instances:\n            out['input'].append(instance['instruction_with_input'])\n            out['output'].append(instance['output'])\n    if extract_reformulations:\n        for example_reformulations in examples['reformulations']:\n            if example_reformulations is not None:\n                for instance in example_reformulations:\n                    out['input'].append(instance['instruction_with_input'])\n                    out['output'].append(instance['output'])\n    return out\n\nALPACA_PROMPT_DICT = {\n    \"prompt_input\": (\n        \"Below is an instruction that describes a task, paired with an input that provides further context. \"\n        \"Write a response that appropriately completes the request.\\n\\n\"\n        \"### Instruction:\\n{instruction}\\n\\n### Input:\\n{input}\\n\\n### Response: \"\n    ),\n    \"prompt_no_input\": (\n        \"Below is an instruction that describes a task. \"\n        \"Write a response that appropriately completes the request.\\n\\n\"\n        \"### Instruction:\\n{instruction}\\n\\n### Response: \"\n    ),\n}\n\ndef extract_alpaca_dataset(example):\n    if example.get(\"input\", \"\") != \"\":\n        prompt_format = ALPACA_PROMPT_DICT[\"prompt_input\"]\n    else:\n        prompt_format = ALPACA_PROMPT_DICT[\"prompt_no_input\"]\n    return {'input': prompt_format.format(**example)}\n\ndef local_dataset(dataset_name):\n    if dataset_name.endswith('.json') or dataset_name.endswith('.jsonl'):\n        full_dataset = Dataset.from_json(path_or_paths=dataset_name)\n    elif dataset_name.endswith('.csv'):\n        full_dataset = Dataset.from_pandas(pd.read_csv(dataset_name))\n    elif dataset_name.endswith('.tsv'):\n        full_dataset = Dataset.from_pandas(pd.read_csv(dataset_name, delimiter='\\t'))\n    else:\n        raise ValueError(f\"Unsupported dataset format: {dataset_name}\")\n\n    split_dataset = full_dataset.train_test_split(test_size=0.1)\n    return split_dataset\n\ndef make_data_module(tokenizer: transformers.PreTrainedTokenizer, args) -> Dict:\n    \"\"\"\n    Make dataset and collator for supervised fine-tuning.\n    Datasets are expected to have the following columns: { `input`, `output` }\n\n    Available datasets to be selected with `dataset` argument:\n        - alpaca, 52002 examples\n        - alpaca cleaned, 51942 examples\n        - chip2 (OIG), 210289 examples\n        - self-instruct, 82612 examples\n        - hh-rlhf (Anthropic), 160800 examples\n        - longform, 23.7k examples\n        - oasst1 (OpenAssistant) primary message tree only, 9,846 examples\n\n    Coming soon:\n        - unnatural instructions core, 66010 examples\n        - unnatural instructions full, 240670 examples\n        - alpaca-gpt4, 52002 examples\n        - unnatural-instructions-gpt4, 9000 examples\n        - supernatural-instructions, 69624 examples (same as paper with 100 ex/task more can be used)\n        - flan (FLAN v2), up to 20M examples available\n        - vicuna\n\n    \"\"\"\n    def load_data(dataset_name):\n        if dataset_name == 'alpaca':\n            return load_dataset(\"tatsu-lab/alpaca\")\n        elif dataset_name == 'alpaca-clean':\n            return load_dataset(\"yahma/alpaca-cleaned\")\n        elif dataset_name == 'chip2':\n            return load_dataset(\"laion/OIG\", data_files='unified_chip2.jsonl')\n        elif dataset_name == 'hh-rlhf':\n            return load_dataset(\"Anthropic/hh-rlhf\")\n        elif dataset_name == 'longform':\n            return load_dataset(\"akoksal/LongForm\")\n        elif dataset_name == 'oasst1':\n            return load_dataset(\"timdettmers/openassistant-guanaco\")\n        elif dataset_name == \"OpenAssistant/oasst_top1_2023-08-25\":\n            return load_dataset(\"OpenAssistant/oasst_top1_2023-08-25\")\n        elif dataset_name == 'vicuna':\n            raise NotImplementedError(\"Vicuna data was not released.\")\n        else:\n            if os.path.exists(dataset_name):\n                try:\n                    args.dataset_format = args.dataset_format if args.dataset_format else \"input-output\"\n                    full_dataset = local_dataset(dataset_name)\n                    return full_dataset\n                except:\n                    raise ValueError(f\"Error loading dataset from {dataset_name}\")\n            else:\n                raise NotImplementedError(f\"Dataset {dataset_name} not implemented yet.\")\n\n    def format_dataset(dataset, dataset_format):\n        if (\n            dataset_format == 'alpaca' or dataset_format == 'alpaca-clean' or\n            (dataset_format is None and args.dataset in ['alpaca', 'alpaca-clean'])\n        ):\n            dataset = dataset.map(extract_alpaca_dataset, remove_columns=['instruction'])\n        elif dataset_format == 'chip2' or (dataset_format is None and args.dataset == 'chip2'):\n            dataset = dataset.map(lambda x: {\n                'input': x['text'].split('\\n<bot>: ')[0].replace('<human>: ', ''),\n                'output': x['text'].split('\\n<bot>: ')[1],\n            })\n        elif dataset_format == 'self-instruct' or (dataset_format is None and args.dataset == 'self-instruct'):\n            for old, new in [[\"prompt\", \"input\"], [\"completion\", \"output\"]]:\n                dataset = dataset.rename_column(old, new)\n        elif dataset_format == 'hh-rlhf' or (dataset_format is None and args.dataset == 'hh-rlhf'):\n            dataset = dataset.map(lambda x: {\n                'input': '',\n                'output': x['chosen']\n            })\n        elif dataset_format == 'oasst1' or (dataset_format is None and args.dataset == 'oasst1'):\n            dataset = dataset.map(lambda x: {\n                'input': '',\n                'output': x['text'],\n            })\n        elif dataset_format == 'input-output':\n            # leave as is\n            pass\n        # Remove unused columns.\n        dataset = dataset.remove_columns(\n            [col for col in dataset.column_names['train'] if col not in ['input', 'output']]\n        )\n        return dataset\n\n     # Load dataset.\n    dataset = load_data(args.dataset)\n    dataset = format_dataset(dataset, args.dataset_format)\n \n    # Split train/eval, reduce size\n    if args.do_eval or args.do_predict:\n        if 'eval' in dataset:\n            eval_dataset = dataset['eval']\n        else:\n            print('Splitting train dataset in train and validation according to `eval_dataset_size`')\n            dataset = dataset[\"train\"].train_test_split(\n                test_size=args.eval_dataset_size, shuffle=True, seed=42\n            )\n            eval_dataset = dataset['test']\n        if args.max_eval_samples is not None and len(eval_dataset) > args.max_eval_samples:\n            eval_dataset = eval_dataset.select(range(args.max_eval_samples))\n        if args.group_by_length:\n            eval_dataset = eval_dataset.map(lambda x: {'length': len(x['input']) + len(x['output'])})\n    if args.do_train:\n        train_dataset = dataset['train']\n        if args.max_train_samples is not None and len(train_dataset) > args.max_train_samples:\n            train_dataset = train_dataset.select(range(args.max_train_samples))\n        if args.group_by_length:\n            train_dataset = train_dataset.map(lambda x: {'length': len(x['input']) + len(x['output'])})\n\n    data_collator = DataCollatorForCausalLM(\n        tokenizer=tokenizer,\n        source_max_len=args.source_max_len,\n        target_max_len=args.target_max_len,\n        train_on_source=args.train_on_source,\n        predict_with_generate=args.predict_with_generate,\n    )\n    return dict(\n        train_dataset=train_dataset if args.do_train else None,\n        eval_dataset=eval_dataset if args.do_eval else None,\n        predict_dataset=eval_dataset if args.do_predict else None,\n        data_collator=data_collator\n    )\n\ndef get_last_checkpoint(checkpoint_dir):\n    if isdir(checkpoint_dir):\n        is_completed = exists(join(checkpoint_dir, 'completed'))\n        if is_completed: return None, True # already finished\n        max_step = 0\n        for filename in os.listdir(checkpoint_dir):\n            if isdir(join(checkpoint_dir, filename)) and filename.startswith('checkpoint'):\n                max_step = max(max_step, int(filename.replace('checkpoint-', '')))\n        if max_step == 0: return None, is_completed # training started, but no checkpoint\n        checkpoint_dir = join(checkpoint_dir, f'checkpoint-{max_step}')\n        print(f\"Found a previous checkpoint at: {checkpoint_dir}\")\n        return checkpoint_dir, is_completed # checkpoint found!\n    return None, False # first training\n\ndef train():\n    hfparser = transformers.HfArgumentParser((\n        ModelArguments, DataArguments, TrainingArguments, GenerationArguments\n    ))\n    model_args, data_args, training_args, generation_args, extra_args = \\\n        hfparser.parse_args_into_dataclasses(return_remaining_strings=True)\n    training_args.generation_config = transformers.GenerationConfig(**vars(generation_args))\n    args = argparse.Namespace(\n        **vars(model_args), **vars(data_args), **vars(training_args)\n    )\n    print(args)\n    \n    checkpoint_dir, completed_training = get_last_checkpoint(args.output_dir)\n    if completed_training:\n        print('Detected that training was already completed!')\n\n    model, tokenizer = get_accelerate_model(args, checkpoint_dir)\n\n    model.config.use_cache = False\n    print('loaded model')\n    set_seed(args.seed)\n\n    data_module = make_data_module(tokenizer=tokenizer, args=args)\n    \n    trainer = Seq2SeqTrainer(\n        model=model,\n        tokenizer=tokenizer,\n        args=training_args,\n        **{k:v for k,v in data_module.items() if k != 'predict_dataset'},\n    )\n\n\n   \n        \n\n        \n\n    # Verifying the datatypes and parameter counts before training.\n    print_trainable_parameters(args, model)\n    dtypes = {}\n    for _, p in model.named_parameters():\n        dtype = p.dtype\n        if dtype not in dtypes: dtypes[dtype] = 0\n        dtypes[dtype] += p.numel()\n    total = 0\n    for k, v in dtypes.items(): total+= v\n    for k, v in dtypes.items():\n        print(k, v, v/total)\n\n    all_metrics = {\"run_name\": args.run_name}\n    # Training\n    if args.do_train:\n        logger.info(\"*** Train ***\")\n        # Note: `resume_from_checkpoint` not supported for adapter checkpoints by HF.\n        # Currently adapter checkpoint is reloaded as expected but optimizer/scheduler states are not.\n        train_result = trainer.train()\n        metrics = train_result.metrics\n        trainer.log_metrics(\"train\", metrics)\n        trainer.save_metrics(\"train\", metrics)\n        trainer.save_state()\n        all_metrics.update(metrics)\n    # Evaluation\n    if args.do_eval:\n        logger.info(\"*** Evaluate ***\")\n        metrics = trainer.evaluate(metric_key_prefix=\"eval\")\n        trainer.log_metrics(\"eval\", metrics)\n        trainer.save_metrics(\"eval\", metrics)\n        all_metrics.update(metrics)\n    # Prediction\n    if args.do_predict:\n        logger.info(\"*** Predict ***\")\n        prediction_output = trainer.predict(test_dataset=data_module['predict_dataset'],metric_key_prefix=\"predict\")\n        prediction_metrics = prediction_output.metrics\n        predictions = prediction_output.predictions\n        predictions = np.where(predictions != -100, predictions, tokenizer.pad_token_id)\n        predictions = tokenizer.batch_decode(\n            predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True\n        )\n        with open(os.path.join(args.output_dir, 'predictions.jsonl'), 'w') as fout:\n            for i, example in enumerate(data_module['predict_dataset']):\n                example['prediction_with_input'] = predictions[i].strip()\n                example['prediction'] = predictions[i].replace(example['input'], '').strip()\n                fout.write(json.dumps(example) + '\\n')\n        print(prediction_metrics)\n        trainer.log_metrics(\"predict\", prediction_metrics)\n        trainer.save_metrics(\"predict\", prediction_metrics)\n        all_metrics.update(prediction_metrics)\n\n    if (args.do_train or args.do_eval or args.do_predict):\n        with open(os.path.join(args.output_dir, \"metrics.json\"), \"w\") as fout:\n            fout.write(json.dumps(all_metrics))\n\nif __name__ == \"__main__\":\n    train()\n"
  },
  {
    "path": "sft/script.sh",
    "content": "# We include a simple full-parameter finetuning & inference script here. Our V0.1 chat model is finetuned using this script. \n# The FT dataset we use is openassistant-guanaco. For finetuning with less than 4GB RAM, we refer you to the Qlora and bitsandbytes repo.\n# We did not undergone extensive hyperparameter tuning nor choosing more performant FT datasets. \n# We hope the community can explore on finetuning TinyLlama and come up with better chat models. I will include community-finetuned models in this repo.\n\n# V0.1\nCUDA_VISIBLE_DEVICES=4,5,6,7 accelerate launch --multi_gpu --num_processes 4 --main_process_port 1234 finetune.py \\\n    --model_name_or_path PY007/TinyLlama-1.1B-intermediate-step-240k-503b \\\n    --output_dir ./output/503B_FT_lr1e-5_ep5 \\\n    --logging_steps 10 \\\n    --save_strategy epoch \\\n    --data_seed 42 \\\n    --save_total_limit 6 \\\n    --evaluation_strategy epoch \\\n    --eval_dataset_size 512 \\\n    --max_eval_samples 1000 \\\n    --per_device_eval_batch_size 1 \\\n    --max_new_tokens 32 \\\n    --dataloader_num_workers 3 \\\n    --group_by_length=False \\\n    --logging_strategy steps \\\n    --remove_unused_columns False \\\n    --do_train \\\n    --do_eval \\\n    --warmup_ratio 0.05 \\\n    --lr_scheduler_type constant \\\n    --dataset oasst1 \\\n    --source_max_len 16 \\\n    --target_max_len 512 \\\n    --per_device_train_batch_size 4 \\\n    --max_steps 0 \\\n    --num_train_epochs 5 \\\n    --learning_rate 1e-5 \\\n    --adam_beta2 0.999 \\\n    --max_grad_norm 1.0 \\\n    --weight_decay 0.0 \\\n    --seed 0 \\\n    --trust_remote_code \\\n    --report_to wandb \n\n\n# V0.2\nCUDA_VISIBLE_DEVICES=0,1,2,3 accelerate launch --multi_gpu --num_processes 4 --main_process_port 1234 finetune.py \\\n    --model_name_or_path PY007/TinyLlama-1.1B-intermediate-step-480k-1T \\\n    --output_dir ./output/503B_FT_lr1e-5_ep5_top1_2023-08-25 \\\n    --logging_steps 10 \\\n    --save_strategy epoch \\\n    --data_seed 42 \\\n    --save_total_limit 6 \\\n    --evaluation_strategy epoch \\\n    --eval_dataset_size 512 \\\n    --max_eval_samples 1000 \\\n    --per_device_eval_batch_size 1 \\\n    --max_new_tokens 32 \\\n    --dataloader_num_workers 3 \\\n    --group_by_length=False \\\n    --logging_strategy steps \\\n    --remove_unused_columns False \\\n    --do_train \\\n    --do_eval \\\n    --warmup_ratio 0.05 \\\n    --lr_scheduler_type constant \\\n    --dataset OpenAssistant/oasst_top1_2023-08-25 \\\n    --dataset_format oasst1 \\\n    --source_max_len 16 \\\n    --target_max_len 512 \\\n    --per_device_train_batch_size 4 \\\n    --max_steps 0 \\\n    --num_train_epochs 5 \\\n    --learning_rate 1e-5 \\\n    --adam_beta2 0.999 \\\n    --max_grad_norm 1.0 \\\n    --weight_decay 0.0 \\\n    --seed 0 \\\n    --trust_remote_code \\\n    --report_to wandb \n"
  },
  {
    "path": "sft/simple_inference.py",
    "content": "from transformers import AutoTokenizer\nimport transformers \nimport torch\nmodel = \"PY007/TinyLlama-1.1B-Chat-v0.1\"\ntokenizer = AutoTokenizer.from_pretrained(model)\npipeline = transformers.pipeline(\n    \"text-generation\",\n    model=model,\n    torch_dtype=torch.float16,\n    device_map=\"auto\",\n)\n\nprompt = \"Give me detailed info about Jeo Biden.\"\nformatted_prompt = (\n    f\"### Human: {prompt} ### Assistant:\"\n)\n\n\nsequences = pipeline(\n    formatted_prompt,\n    do_sample=True,\n    top_k=50,\n    top_p = 0.9,\n    num_return_sequences=1,\n    repetition_penalty=1.1,\n    max_new_tokens=1024,\n)\nfor seq in sequences:\n    print(f\"Result: {seq['generated_text']}\")\n"
  },
  {
    "path": "sft/simple_inference2.py",
    "content": "\n\nfrom transformers import AutoTokenizer\nimport transformers \nimport torch\nmodel = \"PY007/TinyLlama-1.1B-Chat-v0.2\"\ntokenizer = AutoTokenizer.from_pretrained(model)\npipeline = transformers.pipeline(\n    \"text-generation\",\n    model=model,\n    torch_dtype=torch.float16,\n    device_map=\"auto\",\n)\n\nprompt = \"How to get in a good university?\"\nformatted_prompt = (\n    f\"<|im_start|>user\\n{prompt}<|im_end|>\\n<|im_start|>assistant\\n\"\n)\n\n\nsequences = pipeline(\n    formatted_prompt,\n    do_sample=True,\n    top_k=50,\n    top_p = 0.9,\n    num_return_sequences=1,\n    repetition_penalty=1.1,\n    max_new_tokens=1024,\n)\nfor seq in sequences:\n    print(f\"Result: {seq['generated_text']}\")"
  },
  {
    "path": "speculative_decoding/README.md",
    "content": "## Speculative Decoding\n\n### HuggingFace \"Assisted Generation\"\n\n\n| Large Model | Native Decoding | Assisted Decoding  |\n| ----------- | --------------- | ------------------ |\n| guanaco-7b  | 69  seconds   | 38 seconds      |\n| guanaco-13b | 84 seconds             | 45 seconds                 | \n| guanaco-33b | 109 seconds             | 62 seconds                 | \n\nWe use PY007/TinyLlama-1.1B-Chat-v0.1 as the assistant model and vary the large model from guanaco-7B to 33B. Experiments are done on a single A40 GPU with code inside instruct_hf_assisted_decoding.py. TinyLlama is loaded in fp16 and the large models are loaded in 8 bit to make guanaco-33b fit in memory and also to keep a consistent setup. The prompt used is \"Give me detailed info about Jeo Biden.\". max_new_tokens is set to 512. \n\nYou can read this [article](https://huggingface.co/blog/assisted-generation) for more information about HuggingFace's Assisted Generation.\n\nQuote from HF: \"due to INT8 quantization and the use of causal masking in assisted generation, the output of greedy decoding may differ in rare occasions.\"\n#### TODO\n- [ ] Thouroughly benchmark the average speedup on 52K Alpaca prompts.\n\n### Llama.cpp Speculative Decoding\nWe have continue-pretrained a code tinyllama from the 500B checkpoint with another 7B Python data [here](https://huggingface.co/PY007/TinyLlama-1.1B-python-v0.1).\nThe code for continue-pretraining can be found in pretrain/tinyllama_code.py\n\n```\n./speculative \\\n-m models/CodeLlama-7b-hf/ggml-model-f16.gguf \\\n-md models/TinyLlama-1.1B-500B-python/ggml-model-q4_0.gguf \\\n-p \"# Quick-sort implementation in Python and sample usage:\" \\\n-e -ngl 1 -t 4 -n 256 -s 20 --temp 0 --draft 8\n```\nThis gives:\n\n```\nencoded   12 tokens in    0.247 seconds, speed:   48.638 t/s\ndecoded  265 tokens in    7.909 seconds, speed:   33.507 t/s\n\nn_draft   = 16\nn_predict = 265\nn_drafted = 317\nn_accept  = 195\naccept    = 61.514%\n\ndraft:\n\nllama_print_timings:        load time =    53.14 ms\nllama_print_timings:      sample time =   652.62 ms /     1 runs   (  652.62 ms per token,     1.53 tokens per second)\nllama_print_timings: prompt eval time =    73.81 ms /    12 tokens (    6.15 ms per token,   162.58 tokens per second)\nllama_print_timings:        eval time =  2247.77 ms /   378 runs   (    5.95 ms per token,   168.17 tokens per second)\nllama_print_timings:       total time =  8154.92 ms\n\ntarget:\n\nllama_print_timings:        load time =   534.47 ms\nllama_print_timings:      sample time =   208.12 ms /   265 runs   (    0.79 ms per token,  1273.32 tokens per second)\nllama_print_timings: prompt eval time =  4210.38 ms /   382 tokens (   11.02 ms per token,    90.73 tokens per second)\nllama_print_timings:        eval time =   682.80 ms /    16 runs   (   42.68 ms per token,    23.43 tokens per second)\nllama_print_timings:       total time =  8214.11 ms\nggml_metal_free: deallocating\nggml_metal_free: deallocating\n```\n\nEven though the model is continue-pretrained exclusively on Python, it retains its ability in other languages, such as C:\n```\n./speculative \\\n-m models/CodeLlama-7b-hf/ggml-model-f16.gguf \\\n-md models/TinyLlama-1.1B-500B-python/ggml-model-q4_0.gguf \\\n-p \"// Quick-sort implementation in C (4 spaces indentation + detailed comments) and sample usage:\\n\\n#include\" \\\n-e -ngl 1 -t 4 -n 256 -s 20 --temp 0 --draft 8\n```\n\nThis gives:\n\n```\nencoded   25 tokens in    0.278 seconds, speed:   89.900 t/s\ndecoded  258 tokens in    6.432 seconds, speed:   40.112 t/s\n\nn_draft   = 28\nn_predict = 258\nn_drafted = 278\nn_accept  = 200\naccept    = 71.942%\n\ndraft:\n\nllama_print_timings:        load time =   932.54 ms\nllama_print_timings:      sample time =   583.50 ms /     1 runs   (  583.50 ms per token,     1.71 tokens per second)\nllama_print_timings: prompt eval time =    81.50 ms /    25 tokens (    3.26 ms per token,   306.73 tokens per second)\nllama_print_timings:        eval time =  1834.67 ms /   329 runs   (    5.58 ms per token,   179.32 tokens per second)\nllama_print_timings:       total time =  6710.30 ms\n\ntarget:\n\nllama_print_timings:        load time = 18568.44 ms\nllama_print_timings:      sample time =   208.78 ms /   258 runs   (    0.81 ms per token,  1235.75 tokens per second)\nllama_print_timings: prompt eval time =  3164.84 ms /   342 tokens (    9.25 ms per token,   108.06 tokens per second)\nllama_print_timings:        eval time =   775.43 ms /    18 runs   (   43.08 ms per token,    23.21 tokens per second)\nllama_print_timings:       total time =  7650.67 ms\nggml_metal_free: deallocating\nggml_metal_free: deallocating\n```\n\n\nI have not tried 13B CodeLlama as the large model yet because my Mac memory is not enough :)."
  },
  {
    "path": "speculative_decoding/instruct_hf_assisted_decoding.py",
    "content": "from transformers import AutoModelForCausalLM, AutoTokenizer\nimport torch\nimport time\n\n\nmodel_id = \"huggyllama/llama-13b\"\npeft_model_id = \"timdettmers/guanaco-13b\"\nassistant_checkpoint = \"PY007/TinyLlama-1.1B-Chat-v0.1\"\n\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\ntokenizer = AutoTokenizer.from_pretrained(model_id)\n\n\nprompt = \"Give me detailed info about Jeo Biden.\"\nformatted_prompt = f\"### Human: {prompt}### Assistant:\"\ninputs = tokenizer(formatted_prompt, return_tensors=\"pt\").to(device)\nmodel = AutoModelForCausalLM.from_pretrained(model_id, load_in_8bit=True)\nmodel.load_adapter(peft_model_id)\nprint(\"Large model loaded\")\nmodel.config.use_cache = True\nassistant_model = AutoModelForCausalLM.from_pretrained(assistant_checkpoint).half().to(device)  \nassistant_model.config.use_cache = True\nprint(\"Small model loaded\")\n\n\nprint(\"###Native Decoding Starts...\\n\")\nstart = time.time()\noutputs = model.generate(**inputs, assistant_model=None, max_new_tokens=512)\nend = time.time()\nprint(tokenizer.batch_decode(outputs, skip_special_tokens=True))\nprint(\"Time: \", end - start)\n\nprint(\"###TinyLlama Assisted Decoding Starts...\\n\")\nstart = time.time()\noutputs = model.generate(**inputs, assistant_model=assistant_model,max_new_tokens=512)\nend = time.time()\nprint(tokenizer.batch_decode(outputs, skip_special_tokens=True))\n# print time in seconds\nprint(\"Time: \", end - start)\n\n"
  }
]