diff --git a/lit-llama/.github/CODEOWNERS b/lit-llama/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..8349e1320f2e5ff75bc55b7f3b32076cd1895559 --- /dev/null +++ b/lit-llama/.github/CODEOWNERS @@ -0,0 +1 @@ +* @awaelchli @carmocca @lantiga diff --git a/lit-llama/.github/azure-gpu-tests.yml b/lit-llama/.github/azure-gpu-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..944b91beccb593d02bd29e2893101fc217690fbf --- /dev/null +++ b/lit-llama/.github/azure-gpu-tests.yml @@ -0,0 +1,57 @@ +# Python package +# Create and test a Python package on multiple Python versions. +# Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/python + +trigger: + tags: + include: + - '*' + branches: + include: + - "main" + - "refs/tags/*" + +pr: + branches: + include: + - "main" + +jobs: + - job: testing + # how long to run the job before automatically cancelling + timeoutInMinutes: "20" + # how much time to give 'run always even if cancelled tasks' before stopping them + cancelTimeoutInMinutes: "2" + pool: "lit-rtx-3090" + variables: + DEVICES: $( python -c 'print("$(Agent.Name)".split("_")[-1])' ) + container: + image: "pytorchlightning/pytorch_lightning:base-cuda-py3.10-torch2.0-cuda11.7.1" + options: "--gpus=all --shm-size=8gb" + workspace: + clean: all + steps: + + - bash: | + echo "##vso[task.setvariable variable=CUDA_VISIBLE_DEVICES]$(DEVICES)" + cuda_ver=$(python -c "import torch ; print(''.join(map(str, torch.version.cuda.split('.')[:2])))") + echo "##vso[task.setvariable variable=CUDA_VERSION_MM]$cuda_ver" + displayName: 'set env. vars' + + - bash: | + echo $CUDA_VISIBLE_DEVICES + echo $CUDA_VERSION_MM + lspci | egrep 'VGA|3D' + whereis nvidia + nvidia-smi + which python && which pip + python --version && pip --version && pip list + python -c "import torch ; mgpu = torch.cuda.device_count() ; assert mgpu == 2, f'GPU: {mgpu}'" + displayName: 'Image info & NVIDIA' + + - script: pip install pytest -r requirements.txt + displayName: 'Install dependencies' + + - bash: pytest -v --durations=10 --disable-pytest-warnings --strict-markers --color=yes + displayName: 'Testing' diff --git a/lit-llama/.github/workflows/cpu-tests.yml b/lit-llama/.github/workflows/cpu-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..09fcc9300b1dd11a86ba359fe91369e5d28556b7 --- /dev/null +++ b/lit-llama/.github/workflows/cpu-tests.yml @@ -0,0 +1,52 @@ +name: CPU tests + +on: + push: + branches: [main] + pull_request: + branches: [main] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +defaults: + run: + shell: bash + +jobs: + cpu-tests: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - {os: "macOS-11", python-version: "3.10"} + - {os: "ubuntu-20.04", python-version: "3.10"} + - {os: "windows-2022", python-version: "3.10"} + timeout-minutes: 15 + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + cache: 'pip' + cache-dependency-path: | + requirements.txt + setup.py + + - name: Run tests without the package installed + run: | + pip install pytest -r requirements.txt + pip list + + pytest --disable-pytest-warnings --strict-markers --color=yes + + - name: Run tests + run: | + pip install . --no-deps + + pytest -v --durations=10 --disable-pytest-warnings --strict-markers --color=yes diff --git a/lit-llama/.gitignore b/lit-llama/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e84385252ea8e87ab9c4aab5d6dc265e858d50c3 --- /dev/null +++ b/lit-llama/.gitignore @@ -0,0 +1,16 @@ +__pycache__ +.idea +.DS_Store +*.egg-info +build + +# data +data +checkpoints +out +!data/shakespeare/prepare.py +wandb + +# downloaded by our tests +original_model.py +original_adapter.py \ No newline at end of file diff --git a/lit-llama/LICENSE b/lit-llama/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..fe60df99e7ff3db486c7722fe98e7739614e7a0f --- /dev/null +++ b/lit-llama/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2023] Lightning AI + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/lit-llama/README.md b/lit-llama/README.md new file mode 100644 index 0000000000000000000000000000000000000000..058e3fe7344566e02c524100c81865229a30c456 --- /dev/null +++ b/lit-llama/README.md @@ -0,0 +1,193 @@ +
+
+# ⚡ Lit-LLaMA ️
+
+
+
+ [](https://dev.azure.com/Lightning-AI/lit%20Models/_build/latest?definitionId=49&branchName=main) [](https://github.com/Lightning-AI/lit-llama/blob/master/LICENSE) [](https://discord.gg/VptPCZkGNa)
+
+
+
+
+
+Join us and start contributing, especially on the following areas:
+
+- [ ] [Pre-training](https://github.com/Lightning-AI/lit-llama/labels/pre-training)
+- [ ] [Fine-tuning (full and LoRA)](https://github.com/Lightning-AI/lit-llama/labels/fine-tuning)
+- [ ] [Quantization](https://github.com/Lightning-AI/lit-llama/labels/quantization)
+- [ ] [Sparsification](https://github.com/Lightning-AI/lit-llama/labels/sparsification)
+
+Look at `train.py` for a starting point towards pre-training / fine-tuning using [Lightning Fabric](https://lightning.ai/docs/fabric/stable/).
+
+We welcome all individual contributors, regardless of their level of experience or hardware. Your contributions are valuable, and we are excited to see what you can accomplish in this collaborative and supportive environment.
+
+Unsure about contributing? Check out our [Contributing to Lit-LLaMA: A Hitchhiker’s Guide to the Quest for Fully Open-Source AI](https://lightning.ai/pages/community/tutorial/contributing-to-lit-llama-a-hitchhikers-guide-to-the-quest-for-fully-open-source-ai/) guide.
+
+Don't forget to [join our Discord](https://discord.gg/VptPCZkGNa)!
+
+## Acknowledgements
+
+- [@karpathy](https://github.com/karpathy) for [nanoGPT](https://github.com/karpathy/nanoGPT)
+- [@FacebookResearch](https://github.com/facebookresearch) for the original [LLaMA implementation](https://github.com/facebookresearch/llama)
+- [@TimDettmers](https://github.com/TimDettmers) for [bitsandbytes](https://github.com/TimDettmers/bitsandbytes)
+- [@Microsoft](https://github.com/microsoft) for [LoRA](https://github.com/microsoft/LoRA)
+- [@IST-DASLab](https://github.com/IST-DASLab) for [GPTQ](https://github.com/IST-DASLab/gptq)
+
+## License
+
+Lit-LLaMA is released under the [Apache 2.0](https://github.com/Lightning-AI/lightning-llama/blob/main/LICENSE) license.
diff --git a/lit-llama/evaluate/adapter.py b/lit-llama/evaluate/adapter.py
new file mode 100644
index 0000000000000000000000000000000000000000..9aa378279cbb216ac120f9c7da29b14a761947df
--- /dev/null
+++ b/lit-llama/evaluate/adapter.py
@@ -0,0 +1,164 @@
+# This mimics GPTQ's evaluation metrics: https://github.com/IST-DASLab/gptq/
+# Thanks to E. Frantar et al GPTQ: Accurate Post-training Compression for GPT, arXiv:2210.17323
+import math
+import sys
+import time
+from pathlib import Path
+from typing import Optional
+
+import lightning as L
+import torch
+import tqdm
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from lit_llama import Tokenizer
+from lit_llama.adapter import LLaMA
+from lit_llama.utils import EmptyInitOnDevice, lazy_load, llama_model_lookup
+from scripts.prepare_alpaca import generate_prompt
+
+from datasets import load_dataset
+
+instruction_tuning = True
+
+
+def load_eval_data(dataset_name: str) -> str:
+ # this mimics gptq datautils
+ if dataset_name == "wikitext":
+ # traindata = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')
+ testdata = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
+ testdata = "\n\n".join(testdata["text"])
+ elif dataset_name == "ptb":
+ testdata = load_dataset("ptb_text_only", "penn_treebank", split="test")
+ testdata = "\n\n".join(testdata["sentence"])
+ elif dataset_name == "c4":
+ testdata = load_dataset(
+ "allenai/c4",
+ "allenai--c4",
+ data_files={"validation": "en/c4-validation.00000-of-00008.json.gz"},
+ split="validation",
+ )
+ testdata = " ".join(testdata[:1100]["text"])
+
+ else:
+ raise ValueError("invalid dataset name (wikitext, ptb, c4 are allowed)")
+ return testdata
+
+
+@torch.inference_mode()
+def main(
+ datasets: str = "wikitext,ptb,c4",
+ *,
+ # compilation fails as it does not support torch.complex64 for RoPE
+ # compile: bool = False,
+ accelerator: str = "auto",
+ adapter_path: Path = Path("out/adapter/alpaca/lit-llama-adapter-finetuned.pth"),
+ checkpoint_path: Path = Path("checkpoints/lit-llama/7B/lit-llama.pth"),
+ tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"),
+ dtype: str = "float32",
+ quantize: Optional[str] = None,
+) -> None:
+ """Generates text samples based on a pre-trained LLaMA model and tokenizer.
+
+ Args:
+ datasets: The datasets to use as a comma separated string
+ # compile: Whether to compile the model.
+ accelerator: The hardware to run on. Possible choices are:
+ ``"cpu"``, ``"cuda"``, ``"mps"``, ``"gpu"``, ``"tpu"``, ``"auto"``.
+ adapter_path: Path to the checkpoint with trained adapter weights, which are the output of
+ `finetune_adapter.py`.
+ checkpoint_path: The checkpoint path to load.
+ tokenizer_path: The tokenizer path to load.
+ dtype: The tensor dtype for choosing the floating-point precision
+ quantize: Whether to quantize the model and using which method:
+ ``"llm.int8"``: LLM.int8() mode,
+ ``"gptq.int4"``: GPTQ 4-bit mode.
+ """
+ assert adapter_path.is_file()
+ assert checkpoint_path.is_file()
+ assert tokenizer_path.is_file()
+
+ fabric = L.Fabric(accelerator=accelerator, devices=1)
+
+ dt = getattr(torch, dtype, None)
+ if not isinstance(dt, torch.dtype):
+ raise ValueError(f"{dtype} is not a valid dtype.")
+ dtype = dt
+
+ print("Loading model ...", file=sys.stderr)
+ t0 = time.time()
+ with lazy_load(checkpoint_path) as pretrained_checkpoint, lazy_load(adapter_path) as adapter_checkpoint:
+ name = llama_model_lookup(pretrained_checkpoint)
+
+ with EmptyInitOnDevice(
+ device=fabric.device, dtype=dtype, quantization_mode=quantize
+ ):
+ model = LLaMA.from_name(name)
+
+ # 1. Load the pretrained weights
+ model.load_state_dict(pretrained_checkpoint, strict=False)
+ # 2. Load the fine-tuned adapter weights
+ model.load_state_dict(adapter_checkpoint, strict=False)
+
+ print(f"Time to load model: {time.time() - t0:.02f} seconds.", file=sys.stderr)
+
+ model.eval()
+
+ # if compile:
+ # model = torch.compile(model)
+
+ total_toks = 0
+ model = fabric.setup_module(model)
+
+ tokenizer = Tokenizer(tokenizer_path)
+
+ for dsname in datasets.split(","):
+ test_string = load_eval_data(dsname)
+
+ if instruction_tuning:
+ sample = {"instruction": test_string, "input": input}
+ test_string = generate_prompt(sample)
+
+ encoded_text = tokenizer.encode(
+ test_string, bos=True, eos=False, device=fabric.device
+ )
+ encoded_text = encoded_text[
+ None, : 256 * model.config.block_size
+ ] # add batch dimension, trim like gptq implementation
+ t0 = time.perf_counter()
+
+ nlls = 0
+ toks = 0
+ block_size = 2048 # this is for compat with gptq, and indeed we get much worse beyond this (https://github.com/facebookresearch/llama/blob/57b0eb62de0636e75af471e49e2f1862d908d9d8/llama/model.py#L30)
+ for i in tqdm.tqdm(range(0, encoded_text.shape[1], block_size)):
+ inp = encoded_text[:, i : i + block_size]
+ logits = model(inp)[0]
+ nll = torch.nn.functional.cross_entropy(
+ logits[:-1], inp[0, 1:].to(dtype=torch.long), reduction="sum"
+ )
+ toks += inp.size(1) - 1
+ nlls += nll.item()
+
+ print(encoded_text.shape, logits.shape)
+ ppl = math.exp(nlls / toks)
+ print(f"Perplexity on {dsname}: {ppl:.2f}")
+ total_toks += toks
+
+ t = time.perf_counter() - t0
+ print(
+ f"\n\nTime for inference: {t:.02f} sec total, {total_toks / t:.02f} tokens/sec",
+ file=sys.stderr,
+ )
+ print(
+ f"Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB",
+ file=sys.stderr,
+ )
+
+
+if __name__ == "__main__":
+ from jsonargparse import CLI
+
+ torch.set_float32_matmul_precision("high")
+ CLI(main)
diff --git a/lit-llama/evaluate/adapter_v2.py b/lit-llama/evaluate/adapter_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1337a7790d91859bb21fd85717f69161f3a0e97
--- /dev/null
+++ b/lit-llama/evaluate/adapter_v2.py
@@ -0,0 +1,161 @@
+# This mimics GPTQ's evaluation metrics: https://github.com/IST-DASLab/gptq/
+# Thanks to E. Frantar et al GPTQ: Accurate Post-training Compression for GPT, arXiv:2210.17323
+import math
+import sys
+import time
+from pathlib import Path
+from typing import Optional
+
+import lightning as L
+import torch
+import tqdm
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from lit_llama import Tokenizer
+from lit_llama.adapter import LLaMA
+from lit_llama.utils import EmptyInitOnDevice, lazy_load, llama_model_lookup
+from lit_llama.adapter_v2 import add_adapter_v2_parameters_to_linear_layers
+from scripts.prepare_alpaca import generate_prompt
+
+from datasets import load_dataset
+
+
+def load_eval_data(dataset_name: str) -> str:
+ # this mimics gptq datautils
+ if dataset_name == "wikitext":
+ # traindata = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')
+ testdata = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
+ testdata = "\n\n".join(testdata["text"])
+ elif dataset_name == "ptb":
+ testdata = load_dataset("ptb_text_only", "penn_treebank", split="test")
+ testdata = "\n\n".join(testdata["sentence"])
+ elif dataset_name == "c4":
+ testdata = load_dataset(
+ "allenai/c4",
+ "allenai--c4",
+ data_files={"validation": "en/c4-validation.00000-of-00008.json.gz"},
+ split="validation",
+ )
+ testdata = " ".join(testdata[:1100]["text"])
+
+ else:
+ raise ValueError("invalid dataset name (wikitext, ptb, c4 are allowed)")
+ return testdata
+
+
+@torch.inference_mode()
+def main(
+ datasets: str = "wikitext,ptb,c4",
+ *,
+ accelerator: str = "auto",
+ adapter_path: Path = Path("out/adapter_v2/alpaca/lit-llama-adapter-finetuned.pth"),
+ checkpoint_path: Path = Path("checkpoints/lit-llama/7B/lit-llama.pth"),
+ tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"),
+ dtype: str = "float32",
+ quantize: Optional[str] = None,
+) -> None:
+ """Generates text samples based on a pre-trained LLaMA model and tokenizer.
+
+ Args:
+ datasets: The datasets to use as a comma separated string
+ accelerator: The hardware to run on. Possible choices are:
+ ``"cpu"``, ``"cuda"``, ``"mps"``, ``"gpu"``, ``"tpu"``, ``"auto"``.
+ adapter_path: Path to the checkpoint with trained adapter weights, which are the output of
+ `finetune_adapter_v2.py`.
+ checkpoint_path: The checkpoint path to load.
+ tokenizer_path: The tokenizer path to load.
+ dtype: The tensor dtype for choosing the floating-point precision
+ quantize: Whether to quantize the model and using which method:
+ ``"llm.int8"``: LLM.int8() mode,
+ ``"gptq.int4"``: GPTQ 4-bit mode.
+ """
+ assert adapter_path.is_file()
+ assert checkpoint_path.is_file()
+ assert tokenizer_path.is_file()
+
+ fabric = L.Fabric(accelerator=accelerator, devices=1)
+
+ dt = getattr(torch, dtype, None)
+ if not isinstance(dt, torch.dtype):
+ raise ValueError(f"{dtype} is not a valid dtype.")
+ dtype = dt
+
+ print("Loading model ...", file=sys.stderr)
+ t0 = time.time()
+ with lazy_load(checkpoint_path) as pretrained_checkpoint, lazy_load(adapter_path) as adapter_checkpoint:
+ name = llama_model_lookup(pretrained_checkpoint)
+
+ with EmptyInitOnDevice(
+ device=fabric.device, dtype=dtype, quantization_mode=quantize
+ ):
+ model = LLaMA.from_name(name)
+ add_adapter_v2_parameters_to_linear_layers(model)
+
+ # 1. Load the pretrained weights
+ model.load_state_dict(pretrained_checkpoint, strict=False)
+ # 2. Load the fine-tuned adapter weights
+ model.load_state_dict(adapter_checkpoint, strict=False)
+
+ print(f"Time to load model: {time.time() - t0:.02f} seconds.", file=sys.stderr)
+
+ model.eval()
+
+ # if compile:
+ # model = torch.compile(model)
+
+ total_toks = 0
+ model = fabric.setup_module(model)
+
+ tokenizer = Tokenizer(tokenizer_path)
+
+ for dsname in datasets.split(","):
+ test_string = load_eval_data(dsname)
+
+ sample = {"instruction": test_string, "input": input}
+ test_string = generate_prompt(sample)
+
+ encoded_text = tokenizer.encode(
+ test_string, bos=True, eos=False, device=fabric.device
+ )
+ encoded_text = encoded_text[
+ None, : 256 * model.config.block_size
+ ] # add batch dimension, trim like gptq implementation
+ t0 = time.perf_counter()
+
+ nlls = 0
+ toks = 0
+
+ block_size = 2048 # this is for compat with gptq, and indeed we get much worse beyond this (https://github.com/facebookresearch/llama/blob/57b0eb62de0636e75af471e49e2f1862d908d9d8/llama/model.py#L30)
+ for i in tqdm.tqdm(range(0, encoded_text.shape[1], block_size)):
+ inp = encoded_text[:, i : i + block_size]
+ logits = model(inp)[0]
+ nll = torch.nn.functional.cross_entropy(
+ logits[:-1], inp[0, 1:].to(dtype=torch.long), reduction="sum"
+ )
+ toks += inp.size(1) - 1
+ nlls += nll.item()
+
+ print(encoded_text.shape, logits.shape)
+ ppl = math.exp(nlls / toks)
+ print(f"Perplexity on {dsname}: {ppl:.2f}")
+ total_toks += toks
+
+ t = time.perf_counter() - t0
+ print(
+ f"\n\nTime for inference: {t:.02f} sec total, {total_toks / t:.02f} tokens/sec",
+ file=sys.stderr,
+ )
+ print(
+ f"Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB",
+ file=sys.stderr,
+ )
+
+
+if __name__ == "__main__":
+ from jsonargparse import CLI
+
+ torch.set_float32_matmul_precision("high")
+ CLI(main)
diff --git a/lit-llama/evaluate/full.py b/lit-llama/evaluate/full.py
new file mode 100644
index 0000000000000000000000000000000000000000..48d5fb89a9ccfb1ba6be31f2132095a461012726
--- /dev/null
+++ b/lit-llama/evaluate/full.py
@@ -0,0 +1,147 @@
+# This mimics GPTQ's evaluation metrics: https://github.com/IST-DASLab/gptq/
+# Thanks to E. Frantar et al GPTQ: Accurate Post-training Compression for GPT, arXiv:2210.17323
+import math
+import sys
+import time
+from pathlib import Path
+from typing import Optional
+
+import lightning as L
+import torch
+import tqdm
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from lit_llama import LLaMA, Tokenizer
+from lit_llama.utils import EmptyInitOnDevice
+
+from datasets import load_dataset
+
+
+def load_eval_data(dataset_name: str) -> str:
+ # this mimics gptq datautils
+ if dataset_name == "wikitext":
+ # traindata = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')
+ testdata = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
+ testdata = "\n\n".join(testdata["text"])
+ elif dataset_name == "ptb":
+ testdata = load_dataset("ptb_text_only", "penn_treebank", split="test")
+ testdata = "\n\n".join(testdata["sentence"])
+ elif dataset_name == "c4":
+ testdata = load_dataset(
+ "allenai/c4",
+ "allenai--c4",
+ data_files={"validation": "en/c4-validation.00000-of-00008.json.gz"},
+ split="validation",
+ )
+ testdata = " ".join(testdata[:1100]["text"])
+
+ else:
+ raise ValueError("invalid dataset name (wikitext, ptb, c4 are allowed)")
+ return testdata
+
+
+def main(
+ datasets: str = "wikitext,ptb,c4",
+ *,
+ # compilation fails as it does not support torch.complex64 for RoPE
+ # compile: bool = False,
+ accelerator: str = "auto",
+ checkpoint_path: Optional[Path] = None,
+ tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"),
+ model_size: str = "7B",
+ dtype: str = "float32",
+ quantize: Optional[str] = None,
+) -> None:
+ """Generates text samples based on a pre-trained LLaMA model and tokenizer.
+
+ Args:
+ datasets: The datasets to use as a comma separated string
+ # compile: Whether to compile the model.
+ accelerator: The hardware to run on. Possible choices are:
+ ``"cpu"``, ``"cuda"``, ``"mps"``, ``"gpu"``, ``"tpu"``, ``"auto"``.
+ checkpoint_path: The checkpoint path to load.
+ tokenizer_path: The tokenizer path to load.
+ dtype: The tensor dtype for choosing the floating-point precision
+ quantize: Whether to quantize the model and using which method:
+ ``"llm.int8"``: LLM.int8() mode,
+ ``"gptq.int4"``: GPTQ 4-bit mode.
+ """
+ if not checkpoint_path:
+ checkpoint_path = Path(f"checkpoints/lit-llama/{model_size}/lit-llama.pth")
+ assert checkpoint_path.is_file()
+ assert tokenizer_path.is_file()
+
+ fabric = L.Fabric(accelerator=accelerator, devices=1)
+
+ dt = getattr(torch, dtype, None)
+ if not isinstance(dt, torch.dtype):
+ raise ValueError(f"{dtype} is not a valid dtype.")
+ dtype = dt
+
+ with EmptyInitOnDevice(
+ device=fabric.device, dtype=dtype, quantization_mode=quantize
+ ):
+ print("Loading model ...", file=sys.stderr)
+ t0 = time.time()
+ model = LLaMA.from_name(model_size)
+ checkpoint = torch.load(checkpoint_path)
+ model.load_state_dict(checkpoint)
+ print(f"Time to load model: {time.time() - t0:.02f} seconds.", file=sys.stderr)
+
+ model.eval()
+
+ # if compile:
+ # model = torch.compile(model)
+
+ total_toks = 0
+ model = fabric.setup_module(model)
+
+ tokenizer = Tokenizer(tokenizer_path)
+
+ for dsname in datasets.split(","):
+ test_string = load_eval_data(dsname)
+ encoded_text = tokenizer.encode(
+ test_string, bos=True, eos=False, device=fabric.device
+ )
+ encoded_text = encoded_text[
+ None, : 256 * model.config.block_size
+ ] # add batch dimension, trim like gptq implementation
+ t0 = time.perf_counter()
+
+ nlls = 0
+ toks = 0
+ with torch.inference_mode():
+ block_size = 2048 # this is for compat with gptq, and indeed we get much worse beyond this (https://github.com/facebookresearch/llama/blob/57b0eb62de0636e75af471e49e2f1862d908d9d8/llama/model.py#L30)
+ for i in tqdm.tqdm(range(0, encoded_text.shape[1], block_size)):
+ inp = encoded_text[:, i : i + block_size]
+ logits = model(inp)[0]
+ nll = torch.nn.functional.cross_entropy(
+ logits[:-1], inp[0, 1:].to(dtype=torch.long), reduction="sum"
+ )
+ toks += inp.size(1) - 1
+ nlls += nll.item()
+
+ print(encoded_text.shape, logits.shape)
+ ppl = math.exp(nlls / toks)
+ print(f"Perplexity on {dsname}: {ppl:.2f}")
+ total_toks += toks
+
+ t = time.perf_counter() - t0
+ print(
+ f"\n\nTime for inference: {t:.02f} sec total, {total_toks / t:.02f} tokens/sec",
+ file=sys.stderr,
+ )
+ print(
+ f"Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB",
+ file=sys.stderr,
+ )
+
+
+if __name__ == "__main__":
+ from jsonargparse import CLI
+
+ torch.set_float32_matmul_precision("high")
+ CLI(main)
diff --git a/lit-llama/evaluate/lora.py b/lit-llama/evaluate/lora.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c2192b3f8e4e4ed646c32645b47337e88b518c1
--- /dev/null
+++ b/lit-llama/evaluate/lora.py
@@ -0,0 +1,172 @@
+# This mimics GPTQ's evaluation metrics: https://github.com/IST-DASLab/gptq/
+# Thanks to E. Frantar et al GPTQ: Accurate Post-training Compression for GPT, arXiv:2210.17323
+import math
+import sys
+import time
+from pathlib import Path
+from typing import Optional
+
+import lightning as L
+import torch
+import tqdm
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from lit_llama import LLaMA, Tokenizer
+from lit_llama.utils import EmptyInitOnDevice, lazy_load, llama_model_lookup
+from lit_llama.lora import lora
+from scripts.prepare_alpaca import generate_prompt
+
+from datasets import load_dataset
+
+instruction_tuning = True
+lora_r = 8
+lora_alpha = 16
+lora_dropout = 0.05
+
+
+def load_eval_data(dataset_name: str) -> str:
+ # this mimics gptq datautils
+ if dataset_name == "wikitext":
+ # traindata = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')
+ testdata = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
+ testdata = "\n\n".join(testdata["text"])
+ elif dataset_name == "ptb":
+ testdata = load_dataset("ptb_text_only", "penn_treebank", split="test")
+ testdata = "\n\n".join(testdata["sentence"])
+ elif dataset_name == "c4":
+ testdata = load_dataset(
+ "allenai/c4",
+ "allenai--c4",
+ data_files={"validation": "en/c4-validation.00000-of-00008.json.gz"},
+ split="validation",
+ )
+ testdata = " ".join(testdata[:1100]["text"])
+
+ else:
+ raise ValueError("invalid dataset name (wikitext, ptb, c4 are allowed)")
+ return testdata
+
+
+def main(
+ datasets: str = "wikitext,ptb,c4",
+ *,
+ # compilation fails as it does not support torch.complex64 for RoPE
+ # compile: bool = False,
+ accelerator: str = "auto",
+ lora_path: Path = Path("out/lora/alpaca/lit-llama-lora-finetuned.pth"),
+ checkpoint_path: Path = Path("checkpoints/lit-llama/7B/lit-llama.pth"),
+ tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"),
+ dtype: str = "float32",
+ quantize: Optional[str] = None,
+) -> None:
+ """Generates text samples based on a pre-trained LLaMA model and tokenizer
+ finetuned with LoRA.
+
+ Args:
+ datasets: The datasets to use as a comma separated string
+ # compile: Whether to compile the model.
+ accelerator: The hardware to run on. Possible choices are:
+ ``"cpu"``, ``"cuda"``, ``"mps"``, ``"gpu"``, ``"tpu"``, ``"auto"``.
+ lora_path: Path to the checkpoint with trained LoRA weights, which are the output of
+ `finetune_lora.py`.
+ checkpoint_path: The checkpoint path to load.
+ tokenizer_path: The tokenizer path to load.
+ dtype: The tensor dtype for choosing the floating-point precision
+ quantize: Whether to quantize the model and using which method:
+ ``"llm.int8"``: LLM.int8() mode,
+ ``"gptq.int4"``: GPTQ 4-bit mode.
+ """
+ assert lora_path.is_file()
+ assert checkpoint_path.is_file()
+ assert tokenizer_path.is_file()
+
+ if quantize is not None:
+ raise NotImplementedError("Quantization in LoRA is not supported yet")
+
+ fabric = L.Fabric(accelerator=accelerator, devices=1)
+
+ dt = getattr(torch, dtype, None)
+ if not isinstance(dt, torch.dtype):
+ raise ValueError(f"{dtype} is not a valid dtype.")
+ dtype = dt
+
+ print("Loading model ...", file=sys.stderr)
+ t0 = time.time()
+
+ with lazy_load(checkpoint_path) as pretrained_checkpoint, lazy_load(lora_path) as lora_checkpoint:
+ name = llama_model_lookup(pretrained_checkpoint)
+
+ with EmptyInitOnDevice(
+ device=fabric.device, dtype=dtype, quantization_mode=quantize
+ ), lora(r=lora_r, alpha=lora_alpha, dropout=lora_dropout, enabled=True):
+ model = LLaMA.from_name(name)
+
+ # 1. Load the pretrained weights
+ model.load_state_dict(pretrained_checkpoint, strict=False)
+ # 2. Load the fine-tuned lora weights
+ model.load_state_dict(lora_checkpoint, strict=False)
+
+ print(f"Time to load model: {time.time() - t0:.02f} seconds.", file=sys.stderr)
+
+ model.eval()
+
+ # if compile:
+ # model = torch.compile(model)
+
+ total_toks = 0
+ model = fabric.setup_module(model)
+
+ tokenizer = Tokenizer(tokenizer_path)
+
+ for dsname in datasets.split(","):
+ test_string = load_eval_data(dsname)
+
+ if instruction_tuning:
+ sample = {"instruction": test_string, "input": input}
+ test_string = generate_prompt(sample)
+
+ encoded_text = tokenizer.encode(
+ test_string, bos=True, eos=False, device=fabric.device
+ )
+ encoded_text = encoded_text[
+ None, : 256 * model.config.block_size
+ ] # add batch dimension, trim like gptq implementation
+ t0 = time.perf_counter()
+
+ nlls = 0
+ toks = 0
+ with torch.inference_mode():
+ block_size = 2048 # this is for compat with gptq, and indeed we get much worse beyond this (https://github.com/facebookresearch/llama/blob/57b0eb62de0636e75af471e49e2f1862d908d9d8/llama/model.py#L30)
+ for i in tqdm.tqdm(range(0, encoded_text.shape[1], block_size)):
+ inp = encoded_text[:, i : i + block_size]
+ logits = model(inp)[0]
+ nll = torch.nn.functional.cross_entropy(
+ logits[:-1], inp[0, 1:].to(dtype=torch.long), reduction="sum"
+ )
+ toks += inp.size(1) - 1
+ nlls += nll.item()
+
+ print(encoded_text.shape, logits.shape)
+ ppl = math.exp(nlls / toks)
+ print(f"Perplexity on {dsname}: {ppl:.2f}")
+ total_toks += toks
+
+ t = time.perf_counter() - t0
+ print(
+ f"\n\nTime for inference: {t:.02f} sec total, {total_toks / t:.02f} tokens/sec",
+ file=sys.stderr,
+ )
+ print(
+ f"Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB",
+ file=sys.stderr,
+ )
+
+
+if __name__ == "__main__":
+ from jsonargparse import CLI
+
+ torch.set_float32_matmul_precision("high")
+ CLI(main)
diff --git a/lit-llama/finetune/adapter.py b/lit-llama/finetune/adapter.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc815830437cce0a53f3d9d7a80145977d2866a1
--- /dev/null
+++ b/lit-llama/finetune/adapter.py
@@ -0,0 +1,262 @@
+"""
+Instruction-tuning with LLaMA-Adapter on the Alpaca dataset following the paper
+
+LLaMA-Adapter: Efficient Fine-tuning of Language Models with Zero-init Attention
+https://arxiv.org/abs/2303.16199
+
+This script runs on a single GPU by default. You can adjust the `micro_batch_size` to fit your GPU memory.
+You can finetune within 1 hour as done in the original paper using DeepSpeed Zero-2 on 8 A100 GPUs by setting the
+devices variable to `devices = 8` and `micro_batch_size = 8` (or higher).
+
+Note: If you run into a CUDA error "Expected is_sm80 to be true, but got false", uncomment the line
+`torch.backends.cuda.enable_flash_sdp(False)` in the script below (see https://github.com/Lightning-AI/lit-llama/issues/101).
+"""
+import os
+import sys
+import time
+from pathlib import Path
+import shutil
+
+import lightning as L
+import numpy as np
+import torch
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from generate import generate
+from lit_llama.adapter import LLaMA, LLaMAConfig, mark_only_adapter_as_trainable, adapter_state_from_state_dict
+from lit_llama.tokenizer import Tokenizer
+from scripts.prepare_alpaca import generate_prompt
+from lightning.fabric.strategies import DeepSpeedStrategy
+
+
+instruction_tuning = True
+eval_interval = 600
+save_interval = 1000
+eval_iters = 100
+log_interval = 1
+devices = 1
+
+# Hyperparameters
+learning_rate = 9e-3
+batch_size = 64 / devices
+micro_batch_size = 4
+gradient_accumulation_iters = batch_size // micro_batch_size
+assert gradient_accumulation_iters > 0
+epoch_size = 50000 # train dataset size
+num_epochs = 5
+max_iters = num_epochs * (epoch_size // micro_batch_size) // devices
+weight_decay = 0.02
+max_seq_length = 256 # see scripts/prepare_alpaca.py
+warmup_iters = 2 * (epoch_size // micro_batch_size) // devices # 2 epochs
+
+ds_config = {
+ "train_micro_batch_size_per_gpu": micro_batch_size,
+ "gradient_accumulation_steps": gradient_accumulation_iters,
+ "zero_optimization": {"stage": 2},
+}
+
+
+def main(
+ data_dir: str = "data/alpaca",
+ pretrained_path: str = "checkpoints/lit-llama/7B/lit-llama.pth",
+ out_dir: str = "out/adapter/alpaca",
+):
+
+ fabric = L.Fabric(
+ accelerator="cuda",
+ devices=devices,
+ strategy=(DeepSpeedStrategy(config=ds_config) if devices > 1 else "auto"),
+ precision="bf16-true",
+ )
+ fabric.launch()
+ fabric.seed_everything(1337 + fabric.global_rank)
+
+ if fabric.global_rank == 0:
+ os.makedirs(out_dir, exist_ok=True)
+
+ train_data, val_data = load_datasets(data_dir=data_dir)
+
+ config = LLaMAConfig(block_size=max_seq_length)
+
+ if not os.path.isfile(pretrained_path):
+ raise FileNotFoundError(
+ f"Can't find the pretrained weights at {pretrained_path}."
+ " Please follow the instructions in the README to download them."
+ )
+ checkpoint = torch.load(pretrained_path)
+
+ with fabric.init_module():
+ model = LLaMA(config)
+ # strict=False because missing keys due to adapter weights not containted in state dict
+ model.load_state_dict(checkpoint, strict=False)
+
+ mark_only_adapter_as_trainable(model)
+
+ num_params = sum([p.numel() for p in model.parameters() if p.requires_grad])
+ print(f"Number of trainable parameters: {num_params}")
+
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
+ model, optimizer = fabric.setup(model, optimizer)
+ train(fabric, model, optimizer, train_data, val_data, out_dir)
+
+ # Save the final checkpoint at the end of training
+ save_model_checkpoint(fabric, model, os.path.join(out_dir, "lit-llama-adapter-finetuned.pth"))
+
+
+def train(
+ fabric: L.Fabric,
+ model: torch.nn.Module,
+ optimizer: torch.optim.Optimizer,
+ train_data: np.ndarray,
+ val_data: np.ndarray,
+ out_dir: str,
+) -> None:
+ """The training loop.
+
+ Loosely based on the nanoGPT implementation: https://github.com/karpathy/nanoGPT.
+ """
+ step_count = 0
+
+ for iter_num in range(max_iters):
+
+ if step_count <= warmup_iters:
+ # linear warmup
+ lr = learning_rate * step_count / warmup_iters
+ for param_group in optimizer.param_groups:
+ param_group['lr'] = lr
+
+ t0 = time.time()
+
+ input_ids, targets = get_batch(fabric, train_data)
+ with fabric.no_backward_sync(model, enabled=((iter_num + 1) % gradient_accumulation_iters != 0)):
+ logits = model(input_ids)
+ loss = loss_fn(logits, targets)
+ fabric.backward(loss / gradient_accumulation_iters)
+
+ if (iter_num + 1) % gradient_accumulation_iters == 0:
+ optimizer.step()
+ optimizer.zero_grad()
+ step_count += 1
+
+ if step_count % eval_interval == 0:
+ val_loss = validate(fabric, model, val_data)
+ fabric.print(f"step {iter_num}: val loss {val_loss:.4f}")
+ fabric.barrier()
+
+ if step_count % save_interval == 0:
+ print(f"Saving adapter weights to {out_dir}")
+ # TODO: Provide a function/script to merge the adapter weights with pretrained weights
+ save_model_checkpoint(fabric, model, os.path.join(out_dir, f"iter-{iter_num:06d}.pth"))
+
+ dt = time.time() - t0
+ if iter_num % log_interval == 0:
+ fabric.print(f"iter {iter_num}: loss {loss.item():.4f}, time: {dt*1000:.2f}ms")
+
+
+def generate_response(model, instruction, input=""):
+ tokenizer = Tokenizer("checkpoints/lit-llama/tokenizer.model")
+ sample = {"instruction": instruction, "input": input}
+ prompt = instruction
+ if instruction_tuning:
+ prompt = generate_prompt(sample)
+ encoded = tokenizer.encode(prompt, bos=True, eos=False, device=model.device)
+
+ output = generate(
+ model,
+ idx=encoded,
+ max_seq_length=max_seq_length,
+ max_new_tokens=100,
+ temperature=0.8,
+ )
+ output = tokenizer.decode(output)
+ return output # output.split("### Response:")[1].strip()
+
+
+@torch.no_grad()
+def validate(fabric: L.Fabric, model: torch.nn.Module, val_data: np.ndarray) -> torch.Tensor:
+ fabric.print("Validating ...")
+ model.eval()
+ losses = torch.zeros(eval_iters)
+ for k in range(eval_iters):
+ input_ids, targets = get_batch(fabric, val_data)
+ logits = model(input_ids)
+ loss = loss_fn(logits, targets)
+ losses[k] = loss.item()
+ val_loss = losses.mean()
+
+ # produce an example:
+ instruction = "Recommend a movie for me to watch during the weekend and explain the reason."
+ output = generate_response(model, instruction)
+ fabric.print(instruction)
+ fabric.print(output)
+
+ model.train()
+ return val_loss.item()
+
+def loss_fn(logits, targets):
+ # shift the targets such that output n predicts token n+1
+ logits = logits[..., :-1, :].contiguous()
+ targets = targets[..., 1:].contiguous()
+ loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
+ return loss
+
+
+def get_batch(fabric: L.Fabric, data: list):
+ ix = torch.randint(len(data), (micro_batch_size,))
+
+ input_ids = [data[i]["input_ids"].type(torch.int64) for i in ix]
+ labels = [data[i]["labels"].type(torch.int64) for i in ix]
+
+ max_len = max(len(s) for s in input_ids)
+
+ def pad_right(x, pad_id):
+ # pad right based on the longest sequence
+ n = max_len - len(x)
+ return torch.cat((x, torch.full((n,), pad_id, dtype=x.dtype)))
+
+ x = torch.stack([pad_right(x, pad_id=0) for x in input_ids])
+ y = torch.stack([pad_right(x, pad_id=-1) for x in labels])
+ x, y = fabric.to_device((x.pin_memory(), y.pin_memory()))
+ return x, y
+
+
+def load_datasets(data_dir):
+ train_data = torch.load(os.path.join(data_dir, "train.pt"))
+ val_data = torch.load(os.path.join(data_dir, "test.pt"))
+ return train_data, val_data
+
+
+def save_model_checkpoint(fabric, model, file_path):
+ file_path = Path(file_path)
+
+ if isinstance(fabric.strategy, DeepSpeedStrategy):
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
+
+ tmp_path = file_path.with_suffix(".tmp")
+ fabric.save(tmp_path, {"model": model})
+ fabric.barrier()
+ if fabric.global_rank == 0:
+ # Create a consolidated checkpoint with the same name next to the deepspeed checkpoint
+ # and only keep the adapter weights
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(tmp_path)
+ state_dict = adapter_state_from_state_dict(state_dict)
+ torch.save(state_dict, file_path)
+ shutil.rmtree(tmp_path)
+ else:
+ state_dict = adapter_state_from_state_dict(model.state_dict())
+ if fabric.global_rank == 0:
+ torch.save(state_dict, file_path)
+ fabric.barrier()
+
+
+if __name__ == "__main__":
+ # Uncomment this line if you see an error: "Expected is_sm80 to be true, but got false"
+ # torch.backends.cuda.enable_flash_sdp(False)
+ torch.set_float32_matmul_precision("high")
+
+ from jsonargparse.cli import CLI
+
+ CLI(main)
diff --git a/lit-llama/finetune/adapter_v2.py b/lit-llama/finetune/adapter_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..c686cd157c77ac264722579dc9de97b588db564c
--- /dev/null
+++ b/lit-llama/finetune/adapter_v2.py
@@ -0,0 +1,266 @@
+"""
+Instruction-tuning with LLaMA-Adapter v2 on the Alpaca dataset following the paper
+
+LLaMA-Adapter V2: Parameter-Efficient Visual Instruction Model
+https://arxiv.org/abs/2304.15010
+
+This script runs on a single GPU by default. You can adjust the `micro_batch_size` to fit your GPU memory.
+You can finetune within 1 hour as done in the original paper using DeepSpeed Zero-2 on 8 A100 GPUs by setting the
+devices variable to `devices = 8` and `micro_batch_size = 8` (or higher).
+
+Note: If you run into a CUDA error "Expected is_sm80 to be true, but got false", uncomment the line
+`torch.backends.cuda.enable_flash_sdp(False)` in the script below (see https://github.com/Lightning-AI/lit-llama/issues/101).
+"""
+import os
+import sys
+import time
+from pathlib import Path
+import shutil
+
+import lightning as L
+import numpy as np
+import torch
+import torch.nn as nn
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from generate import generate
+from lit_llama.adapter import LLaMA, LLaMAConfig
+from lit_llama.adapter_v2 import (
+ mark_only_adapter_v2_as_trainable,
+ add_adapter_v2_parameters_to_linear_layers,
+ adapter_v2_state_from_state_dict
+ )
+from lit_llama.tokenizer import Tokenizer
+from scripts.prepare_alpaca import generate_prompt
+from lightning.fabric.strategies import DeepSpeedStrategy
+
+
+eval_interval = 600
+save_interval = 1000
+eval_iters = 100
+log_interval = 1
+devices = 1
+
+# Hyperparameters
+learning_rate = 9e-3
+batch_size = 64 / devices
+micro_batch_size = 4
+gradient_accumulation_iters = batch_size // micro_batch_size
+assert gradient_accumulation_iters > 0
+epoch_size = 50000 # train dataset size
+num_epochs = 5
+max_iters = num_epochs * (epoch_size // micro_batch_size) // devices
+weight_decay = 0.02
+max_seq_length = 256 # see scripts/prepare_alpaca.py
+warmup_iters = 2 * (epoch_size // micro_batch_size) // devices # 2 epoch
+
+ds_config = {
+ "train_micro_batch_size_per_gpu": micro_batch_size,
+ "gradient_accumulation_steps": gradient_accumulation_iters,
+ "zero_optimization": {"stage": 2},
+}
+
+
+def main(
+ data_dir: str = "data/alpaca",
+ pretrained_path: str = "checkpoints/lit-llama/7B/lit-llama.pth",
+ out_dir: str = "out/adapter_v2/alpaca",
+):
+
+ fabric = L.Fabric(
+ accelerator="cuda",
+ devices=1,
+ strategy=(DeepSpeedStrategy(config=ds_config) if devices > 1 else "auto"),
+ precision="bf16-true",
+ )
+ fabric.launch()
+ fabric.seed_everything(1337 + fabric.global_rank)
+
+ if fabric.global_rank == 0:
+ os.makedirs(out_dir, exist_ok=True)
+
+ train_data, val_data = load_datasets(data_dir=data_dir)
+
+ config = LLaMAConfig(block_size=max_seq_length)
+
+ if not os.path.isfile(pretrained_path):
+ raise FileNotFoundError(
+ f"Can't find the pretrained weights at {pretrained_path}."
+ " Please follow the instructions in the README to download them."
+ )
+ checkpoint = torch.load(pretrained_path)
+
+ with fabric.init_module():
+ model = LLaMA(config)
+ # strict=False because missing keys due to adapter weights not contained in state dict
+ model.load_state_dict(checkpoint, strict=False)
+
+ add_adapter_v2_parameters_to_linear_layers(model)
+ mark_only_adapter_v2_as_trainable(model)
+
+ num_params = sum([p.numel() for p in model.parameters() if p.requires_grad])
+ print(f"Number of trainable parameters: {num_params}")
+
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
+ model, optimizer = fabric.setup(model, optimizer)
+ train(fabric, model, optimizer, train_data, val_data, out_dir)
+
+ # Save the final checkpoint at the end of training
+ save_model_checkpoint(fabric, model, os.path.join(out_dir, "lit-llama-adapter-finetuned.pth"))
+
+
+def train(
+ fabric: L.Fabric,
+ model: torch.nn.Module,
+ optimizer: torch.optim.Optimizer,
+ train_data: np.ndarray,
+ val_data: np.ndarray,
+ out_dir: str,
+) -> None:
+ """The training loop.
+
+ Loosely based on the nanoGPT implementation: https://github.com/karpathy/nanoGPT.
+ """
+ step_count = 0
+
+ for iter_num in range(max_iters):
+
+ if step_count <= warmup_iters:
+ # linear warmup
+ lr = learning_rate * step_count / warmup_iters
+ for param_group in optimizer.param_groups:
+ param_group['lr'] = lr
+
+ t0 = time.time()
+
+ input_ids, targets = get_batch(fabric, train_data)
+ with fabric.no_backward_sync(model, enabled=((iter_num + 1) % gradient_accumulation_iters != 0)):
+ logits = model(input_ids)
+ loss = loss_fn(logits, targets)
+ fabric.backward(loss / gradient_accumulation_iters)
+
+ if (iter_num + 1) % gradient_accumulation_iters == 0:
+ optimizer.step()
+ optimizer.zero_grad()
+ step_count += 1
+
+ if step_count % eval_interval == 0:
+ val_loss = validate(fabric, model, val_data)
+ fabric.print(f"step {iter_num}: val loss {val_loss:.4f}")
+ fabric.barrier()
+
+ if step_count % save_interval == 0:
+ print(f"Saving adapter weights to {out_dir}")
+ # TODO: Provide a function/script to merge the adapter weights with pretrained weights
+ save_model_checkpoint(fabric, model, os.path.join(out_dir, f"iter-{iter_num:06d}.pth"))
+
+ dt = time.time() - t0
+ if iter_num % log_interval == 0:
+ fabric.print(f"iter {iter_num}: loss {loss.item():.4f}, time: {dt*1000:.2f}ms")
+
+
+def generate_response(model, instruction, input=""):
+ tokenizer = Tokenizer("checkpoints/lit-llama/tokenizer.model")
+ sample = {"instruction": instruction, "input": input}
+ prompt = generate_prompt(sample)
+ encoded = tokenizer.encode(prompt, bos=True, eos=False, device=model.device)
+
+ output = generate(
+ model,
+ idx=encoded,
+ max_seq_length=max_seq_length,
+ max_new_tokens=100,
+ temperature=0.8,
+ )
+ output = tokenizer.decode(output)
+ return output # output.split("### Response:")[1].strip()
+
+
+@torch.no_grad()
+def validate(fabric: L.Fabric, model: torch.nn.Module, val_data: np.ndarray) -> torch.Tensor:
+ fabric.print("Validating ...")
+ model.eval()
+ losses = torch.zeros(eval_iters)
+ for k in range(eval_iters):
+ input_ids, targets = get_batch(fabric, val_data)
+ logits = model(input_ids)
+ loss = loss_fn(logits, targets)
+ losses[k] = loss.item()
+ val_loss = losses.mean()
+
+ # produce an example:
+ instruction = "Recommend a movie for me to watch during the weekend and explain the reason."
+ output = generate_response(model, instruction)
+ fabric.print(instruction)
+ fabric.print(output)
+
+ model.train()
+ return val_loss.item()
+
+def loss_fn(logits, targets):
+ # shift the targets such that output n predicts token n+1
+ logits = logits[..., :-1, :].contiguous()
+ targets = targets[..., 1:].contiguous()
+ loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
+ return loss
+
+
+def get_batch(fabric: L.Fabric, data: list):
+ ix = torch.randint(len(data), (micro_batch_size,))
+
+ input_ids = [data[i]["input_ids"].type(torch.int64) for i in ix]
+ labels = [data[i]["labels"].type(torch.int64) for i in ix]
+
+ max_len = max(len(s) for s in input_ids)
+
+ def pad_right(x, pad_id):
+ # pad right based on the longest sequence
+ n = max_len - len(x)
+ return torch.cat((x, torch.full((n,), pad_id, dtype=x.dtype)))
+
+ x = torch.stack([pad_right(x, pad_id=0) for x in input_ids])
+ y = torch.stack([pad_right(x, pad_id=-1) for x in labels])
+ x, y = fabric.to_device((x.pin_memory(), y.pin_memory()))
+ return x, y
+
+
+def load_datasets(data_dir):
+ train_data = torch.load(os.path.join(data_dir, "train.pt"))
+ val_data = torch.load(os.path.join(data_dir, "test.pt"))
+ return train_data, val_data
+
+
+def save_model_checkpoint(fabric, model, file_path):
+ file_path = Path(file_path)
+
+ if isinstance(fabric.strategy, DeepSpeedStrategy):
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
+
+ tmp_path = file_path.with_suffix(".tmp")
+ fabric.save(tmp_path, {"model": model})
+ fabric.barrier()
+ if fabric.global_rank == 0:
+ # Create a consolidated checkpoint with the same name next to the deepspeed checkpoint
+ # and only keep the adapter weights
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(tmp_path)
+ state_dict = adapter_v2_state_from_state_dict(state_dict)
+ torch.save(state_dict, file_path)
+ shutil.rmtree(tmp_path)
+ else:
+ state_dict = adapter_v2_state_from_state_dict(model.state_dict())
+ if fabric.global_rank == 0:
+ torch.save(state_dict, file_path)
+ fabric.barrier()
+
+
+if __name__ == "__main__":
+ # Uncomment this line if you see an error: "Expected is_sm80 to be true, but got false"
+ # torch.backends.cuda.enable_flash_sdp(False)
+ torch.set_float32_matmul_precision("high")
+
+ from jsonargparse.cli import CLI
+
+ CLI(main)
diff --git a/lit-llama/finetune/full.py b/lit-llama/finetune/full.py
new file mode 100644
index 0000000000000000000000000000000000000000..9248e8de696e4894703cbb5bbe8795dd5d4e71b2
--- /dev/null
+++ b/lit-llama/finetune/full.py
@@ -0,0 +1,224 @@
+"""
+Instruction-tuning on the Alpaca dataset using a regular finetuning procedure (updating all layers).
+
+Note: If you run into a CUDA error "Expected is_sm80 to be true, but got false", uncomment the line
+`torch.backends.cuda.enable_flash_sdp(False)` in the script below (see https://github.com/Lightning-AI/lit-llama/issues/101).
+"""
+import sys
+from pathlib import Path
+import os
+import time
+from functools import partial
+
+import lightning as L
+from lightning.fabric.strategies import FSDPStrategy
+import numpy as np
+import torch
+from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from generate import generate
+from lit_llama.model import Block, LLaMA, LLaMAConfig
+from lit_llama.tokenizer import Tokenizer
+from lit_llama.utils import save_model_checkpoint
+from scripts.prepare_alpaca import generate_prompt
+
+
+instruction_tuning = True
+eval_interval = 1000
+save_interval = 1000
+eval_iters = 100
+log_interval = 100
+devices = 4
+
+# Hyperparameters
+learning_rate = 3e-5
+batch_size = 128 / devices
+micro_batch_size = 4
+gradient_accumulation_iters = batch_size // micro_batch_size
+assert gradient_accumulation_iters > 0
+epoch_size = 50000 # train dataset size
+num_epochs = 5
+max_iters = num_epochs * (epoch_size // micro_batch_size) // devices
+weight_decay = 0.0
+block_size = 512
+warmup_iters = 100
+
+
+def main(
+ data_dir: str = "data/alpaca",
+ pretrained_path: str = "checkpoints/lit-llama/7B/lit-llama.pth",
+ out_dir: str = "out/full/alpaca",
+):
+
+ auto_wrap_policy = partial(transformer_auto_wrap_policy, transformer_layer_cls={Block})
+ strategy = FSDPStrategy(auto_wrap_policy=auto_wrap_policy, activation_checkpointing=Block, limit_all_gathers=True)
+
+ fabric = L.Fabric(accelerator="cuda", devices=devices, precision="bf16-mixed", strategy=strategy)
+ fabric.launch()
+ fabric.seed_everything(1337 + fabric.global_rank)
+
+ if fabric.global_rank == 0:
+ os.makedirs(out_dir, exist_ok=True)
+
+ train_data, val_data = load_datasets(data_dir=data_dir)
+
+ config = LLaMAConfig.from_name("7B")
+ config.block_size = block_size
+
+ checkpoint = torch.load(pretrained_path)
+
+ with fabric.device:
+ torch.set_default_tensor_type(torch.HalfTensor)
+ model = LLaMA(config).bfloat16()
+ torch.set_default_tensor_type(torch.FloatTensor)
+ model.load_state_dict(checkpoint, strict=False)
+
+ model = fabric.setup_module(model)
+
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, foreach=False)
+ optimizer = fabric.setup_optimizers(optimizer)
+
+ train(fabric, model, optimizer, train_data, val_data, out_dir)
+
+ # Save the final checkpoint at the end of training
+ save_model_checkpoint(fabric, model, os.path.join(out_dir, "lit-llama-full-finetuned.pth"))
+
+
+def train(
+ fabric: L.Fabric,
+ model: torch.nn.Module,
+ optimizer: torch.optim.Optimizer,
+ train_data: np.ndarray,
+ val_data: np.ndarray,
+ out_dir: str,
+) -> None:
+ """The training loop.
+
+ Loosely based on the nanoGPT implementation: https://github.com/karpathy/nanoGPT.
+ """
+ step_count = 0
+ model.train()
+
+ for iter_num in range(max_iters):
+
+ is_accumulating = (iter_num + 1) % gradient_accumulation_iters != 0
+
+ if step_count <= warmup_iters:
+ # linear warmup
+ lr = learning_rate * step_count / warmup_iters
+ for param_group in optimizer.param_groups:
+ param_group['lr'] = lr
+
+ t0 = time.time()
+
+ input_ids, targets = get_batch(fabric, train_data)
+ with fabric.no_backward_sync(model, enabled=is_accumulating):
+ logits = model(input_ids)
+ loss = loss_fn(logits, targets)
+ fabric.backward(loss / gradient_accumulation_iters)
+
+ if not is_accumulating:
+ optimizer.step()
+ optimizer.zero_grad()
+ step_count += 1
+
+ if step_count % eval_interval == 0:
+ val_loss = validate(fabric, model, val_data)
+ fabric.print(f"step {iter_num}: val loss {val_loss:.4f}")
+ fabric.barrier()
+
+ if step_count % save_interval == 0:
+ print(f"Saving weights to {out_dir}")
+ save_model_checkpoint(fabric, model, os.path.join(out_dir, f"iter-{iter_num:06d}-ckpt.pth"))
+
+ dt = time.time() - t0
+ if iter_num % log_interval == 0:
+ fabric.print(f"iter {iter_num}: loss {loss.item():.4f}, time: {dt*1000:.2f}ms")
+
+
+def generate_response(model, instruction):
+ tokenizer = Tokenizer("checkpoints/lit-llama/tokenizer.model")
+ sample = {"instruction": instruction, "input": ""}
+ prompt = instruction
+ if instruction_tuning:
+ prompt = generate_prompt(sample)
+ encoded = tokenizer.encode(prompt, bos=True, eos=False, device=model.device)
+
+ output = generate(
+ model,
+ idx=encoded,
+ max_seq_length=block_size,
+ max_new_tokens=100,
+ )
+ output = tokenizer.decode(output)
+ return output # output.split("### Response:")[1].strip()
+
+
+@torch.no_grad()
+def validate(fabric: L.Fabric, model: torch.nn.Module, val_data: np.ndarray) -> torch.Tensor:
+ fabric.print("Validating ...")
+ model.eval()
+ losses = torch.zeros(eval_iters)
+ for k in range(eval_iters):
+ input_ids, targets = get_batch(fabric, val_data)
+ logits = model(input_ids)
+ loss = loss_fn(logits, targets)
+ losses[k] = loss.item()
+ out = losses.mean()
+
+ # produce an example:
+ instruction = "Recommend a movie for me to watch during the weekend and explain the reason."
+
+ output = generate_response(model, instruction)
+ fabric.print(instruction)
+ fabric.print(output)
+
+ model.train()
+ return out.item()
+
+
+def loss_fn(logits, targets):
+ # shift the targets such that output n predicts token n+1
+ logits = logits[..., :-1, :].contiguous()
+ targets = targets[..., 1:].contiguous()
+ loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
+ return loss
+
+
+def get_batch(fabric: L.Fabric, data: list):
+ ix = torch.randint(len(data), (micro_batch_size,))
+
+ input_ids = [data[i]["input_ids"].type(torch.int64) for i in ix]
+ labels = [data[i]["labels"].type(torch.int64) for i in ix]
+
+ max_len = max(len(s) for s in input_ids)
+
+ def pad_right(x, pad_id):
+ # pad right based on the longest sequence
+ n = max_len - len(x)
+ return torch.cat((x, torch.full((n,), pad_id, dtype=x.dtype)))
+
+ x = torch.stack([pad_right(x, pad_id=0) for x in input_ids])
+ y = torch.stack([pad_right(x, pad_id=-1) for x in labels])
+ x, y = fabric.to_device((x.pin_memory(), y.pin_memory()))
+ return x, y
+
+
+def load_datasets(data_dir):
+ train_data = torch.load(os.path.join(data_dir, "train.pt"))
+ val_data = torch.load(os.path.join(data_dir, "test.pt"))
+ return train_data, val_data
+
+
+if __name__ == "__main__":
+ # Uncomment this line if you see an error: "Expected is_sm80 to be true, but got false"
+ # torch.backends.cuda.enable_flash_sdp(False)
+ torch.set_float32_matmul_precision("high")
+
+ from jsonargparse.cli import CLI
+
+ CLI(main)
diff --git a/lit-llama/finetune/lora.py b/lit-llama/finetune/lora.py
new file mode 100644
index 0000000000000000000000000000000000000000..18737015c5d2290406a4558248d8b8b311cb5bf4
--- /dev/null
+++ b/lit-llama/finetune/lora.py
@@ -0,0 +1,218 @@
+"""
+Instruction-tuning with LoRA on the Alpaca dataset.
+
+Note: If you run into a CUDA error "Expected is_sm80 to be true, but got false", uncomment the line
+`torch.backends.cuda.enable_flash_sdp(False)` in the script below (see https://github.com/Lightning-AI/lit-llama/issues/101).
+"""
+import sys
+from pathlib import Path
+import os
+import time
+
+import lightning as L
+import numpy as np
+import torch
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from generate import generate
+from lit_llama.lora import mark_only_lora_as_trainable, lora, lora_state_dict
+from lit_llama.model import LLaMA, LLaMAConfig
+from lit_llama.tokenizer import Tokenizer
+from scripts.prepare_alpaca import generate_prompt
+
+
+instruction_tuning = True
+eval_interval = 100
+save_interval = 100
+eval_iters = 100
+log_interval = 1
+
+# Hyperparameters
+learning_rate = 3e-4
+batch_size = 128
+micro_batch_size = 4
+gradient_accumulation_iters = batch_size // micro_batch_size
+assert gradient_accumulation_iters > 0
+max_iters = 50000 * 3 // micro_batch_size
+weight_decay = 0.0
+max_seq_length = 256 # see scripts/prepare_alpaca.py
+lora_r = 8
+lora_alpha = 16
+lora_dropout = 0.05
+warmup_iters = 100
+
+
+def main(
+ data_dir: str = "data/alpaca",
+ pretrained_path: str = "checkpoints/lit-llama/7B/lit-llama.pth",
+ tokenizer_path: str = "checkpoints/lit-llama/tokenizer.model",
+ out_dir: str = "out/lora/alpaca",
+):
+
+ fabric = L.Fabric(accelerator="cuda", devices=1, precision="bf16-true")
+ fabric.launch()
+ fabric.seed_everything(1337 + fabric.global_rank)
+
+ if fabric.global_rank == 0:
+ os.makedirs(out_dir, exist_ok=True)
+
+ train_data, val_data = load_datasets(data_dir=data_dir)
+
+ config = LLaMAConfig.from_name("7B")
+ config.block_size = max_seq_length
+
+ checkpoint = torch.load(pretrained_path)
+
+ with fabric.init_module(), lora(r=lora_r, alpha=lora_alpha, dropout=lora_dropout, enabled=True):
+ model = LLaMA(config)
+ # strict=False because missing keys due to LoRA weights not contained in checkpoint state
+ model.load_state_dict(checkpoint, strict=False)
+
+ mark_only_lora_as_trainable(model)
+
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
+ model, optimizer = fabric.setup(model, optimizer)
+ train(fabric, model, optimizer, train_data, val_data, tokenizer_path, out_dir)
+
+ # Save the final LoRA checkpoint at the end of training
+ checkpoint = lora_state_dict(model)
+ fabric.save(os.path.join(out_dir, "lit-llama-lora-finetuned.pth"), checkpoint)
+
+
+def train(
+ fabric: L.Fabric,
+ model: torch.nn.Module,
+ optimizer: torch.optim.Optimizer,
+ train_data: np.ndarray,
+ val_data: np.ndarray,
+ tokenizer_path: str,
+ out_dir: str,
+) -> None:
+ """The training loop.
+
+ Loosely based on the nanoGPT implementation: https://github.com/karpathy/nanoGPT.
+ """
+ step_count = 0
+
+ for iter_num in range(max_iters):
+
+ if step_count <= warmup_iters:
+ # linear warmup
+ lr = learning_rate * step_count / warmup_iters
+ for param_group in optimizer.param_groups:
+ param_group['lr'] = lr
+
+ t0 = time.time()
+
+ input_ids, targets = get_batch(fabric, train_data)
+ with fabric.no_backward_sync(model, enabled=((iter_num + 1) % gradient_accumulation_iters != 0)):
+ logits = model(input_ids)
+ loss = loss_fn(logits, targets)
+ fabric.backward(loss / gradient_accumulation_iters)
+
+ if (iter_num + 1) % gradient_accumulation_iters == 0:
+ optimizer.step()
+ optimizer.zero_grad()
+ step_count += 1
+
+ if step_count % eval_interval == 0:
+ val_loss = validate(fabric, model, val_data, tokenizer_path)
+ fabric.print(f"step {iter_num}: val loss {val_loss:.4f}")
+ fabric.barrier()
+
+ if step_count % save_interval == 0:
+ print(f"Saving LoRA weights to {out_dir}")
+ # We are only saving the LoRA weights
+ # TODO: Provide a function/script to merge the LoRA weights with pretrained weights
+ checkpoint = lora_state_dict(model)
+ fabric.save(os.path.join(out_dir, f"iter-{iter_num:06d}-ckpt.pth"), checkpoint)
+
+ dt = time.time() - t0
+ if iter_num % log_interval == 0:
+ fabric.print(f"iter {iter_num}: loss {loss.item():.4f}, time: {dt*1000:.2f}ms")
+
+
+def generate_response(model, instruction, tokenizer_path):
+ tokenizer = Tokenizer(tokenizer_path)
+ sample = {"instruction": instruction, "input": ""}
+ prompt = instruction
+ if instruction_tuning:
+ prompt = generate_prompt(sample)
+ encoded = tokenizer.encode(prompt, bos=True, eos=False, device=model.device)
+
+ output = generate(
+ model,
+ idx=encoded,
+ max_seq_length=max_seq_length,
+ max_new_tokens=100,
+ )
+ output = tokenizer.decode(output)
+ return output # output.split("### Response:")[1].strip()
+
+
+@torch.no_grad()
+def validate(fabric: L.Fabric, model: torch.nn.Module, val_data: np.ndarray, tokenizer_path: str) -> torch.Tensor:
+ fabric.print("Validating ...")
+ model.eval()
+ losses = torch.zeros(eval_iters)
+ for k in range(eval_iters):
+ input_ids, targets = get_batch(fabric, val_data)
+ logits = model(input_ids)
+ loss = loss_fn(logits, targets)
+ losses[k] = loss.item()
+ out = losses.mean()
+
+ # produce an example:
+ instruction = "Recommend a movie for me to watch during the weekend and explain the reason."
+
+ output = generate_response(model, instruction, tokenizer_path)
+ fabric.print(instruction)
+ fabric.print(output)
+
+ model.train()
+ return out.item()
+
+def loss_fn(logits, targets):
+ # shift the targets such that output n predicts token n+1
+ logits = logits[..., :-1, :].contiguous()
+ targets = targets[..., 1:].contiguous()
+ loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
+ return loss
+
+
+def get_batch(fabric: L.Fabric, data: list):
+ ix = torch.randint(len(data), (micro_batch_size,))
+
+ input_ids = [data[i]["input_ids"].type(torch.int64) for i in ix]
+ labels = [data[i]["labels"].type(torch.int64) for i in ix]
+
+ max_len = max(len(s) for s in input_ids)
+
+ def pad_right(x, pad_id):
+ # pad right based on the longest sequence
+ n = max_len - len(x)
+ return torch.cat((x, torch.full((n,), pad_id, dtype=x.dtype)))
+
+ x = torch.stack([pad_right(x, pad_id=0) for x in input_ids])
+ y = torch.stack([pad_right(x, pad_id=-1) for x in labels])
+ x, y = fabric.to_device((x.pin_memory(), y.pin_memory()))
+ return x, y
+
+
+def load_datasets(data_dir):
+ train_data = torch.load(os.path.join(data_dir, "train.pt"))
+ val_data = torch.load(os.path.join(data_dir, "test.pt"))
+ return train_data, val_data
+
+
+if __name__ == "__main__":
+ # Uncomment this line if you see an error: "Expected is_sm80 to be true, but got false"
+ # torch.backends.cuda.enable_flash_sdp(False)
+ torch.set_float32_matmul_precision("high")
+
+ from jsonargparse.cli import CLI
+
+ CLI(main)
diff --git a/lit-llama/generate.py b/lit-llama/generate.py
new file mode 100644
index 0000000000000000000000000000000000000000..91a7a6e4233485b704449bc7ef7421719850bdeb
--- /dev/null
+++ b/lit-llama/generate.py
@@ -0,0 +1,170 @@
+import sys
+import time
+import warnings
+from pathlib import Path
+from typing import Optional
+
+import lightning as L
+import torch
+
+# support running without installing as a package
+wd = Path(__file__).parent.parent.resolve()
+sys.path.append(str(wd))
+
+from lit_llama import LLaMA, Tokenizer
+from lit_llama.utils import lazy_load, llama_model_lookup, quantization
+
+
+@torch.no_grad()
+def generate(
+ model: LLaMA,
+ idx: torch.Tensor,
+ max_new_tokens: int,
+ *,
+ max_seq_length: Optional[int] = None,
+ temperature: float = 1.0,
+ top_k: Optional[int] = None,
+ eos_id: Optional[int] = None,
+) -> torch.Tensor:
+ """Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested.
+
+ The implementation of this function is modified from A. Karpathy's nanoGPT.
+
+ Args:
+ model: The model to use.
+ idx: Tensor of shape (T) with indices of the prompt sequence.
+ max_new_tokens: The number of new tokens to generate.
+ max_seq_length: The maximum sequence length allowed.
+ temperature: Scales the predicted logits by 1 / temperature
+ top_k: If specified, only sample among the tokens with the k highest probabilities
+ eos_id: If specified, stop generating any more token once the self._chunk_size: + part_len = self._chunk_size - self._idx + self._arr[self._idx : self._idx + part_len] = arr[:part_len] + self._write_chunk() + arr = arr[part_len:] + + arr_len = arr.shape[0] + self._arr[self._idx : self._idx + arr_len] = arr + self._idx += arr_len + + def write_reminder(self): + self._write_chunk() + + +class PackedDatasetIterator: + def __init__(self, filenames, n_chunks, block_size, seed, shuffle, wrap): + self._seed = seed + self._shuffle = shuffle + self._rng = np.random.default_rng(seed) if shuffle else None + self._block_idxs = None + + self._wrap = wrap + + # TODO: instead of filenames, we could have a single text stream + # (or text file) with the sequence of all files to be + # fetched/loaded. + self._filenames = filenames + self._file_idx = 0 + + self._n_chunks = n_chunks + + self._dtype = None + self._block_size = block_size + self._n_blocks = None + + self._mmaps = [] + self._buffers = [] + + self._block_idxs = [] + self._curr_idx = 0 + + self._load_n_chunks() + + def _read_header(self, path): + with open(path, "rb") as f: + magic = f.read(len(HDR_MAGIC)) + assert magic == HDR_MAGIC, "File doesn't match expected format." + version = struct.unpack("len(self._filenames[self._file_idx:]): + if not self._wrap: + raise StopIteration + else: + self._file_idx = 0 + + for i in range(self._n_chunks): + filename = self._filenames[self._file_idx + i] + if self._dtype is None: + self._dtype, self._chunk_size = self._read_header( + filename + ) + self._n_blocks = self._chunk_size // self._block_size + # TODO: check header matches with previous files + mmap = np.memmap(filename, mode="r", order="C", offset=HDR_SIZE) + self._mmaps.append(mmap) + self._buffers.append(memoryview(mmap)) + + self._file_idx += self._n_chunks + n_all_blocks = self._n_chunks * self._n_blocks + + self._block_idxs = ( + self._rng.permutation(n_all_blocks) + if self._shuffle + else range(n_all_blocks) + ) + + self._curr_idx = 0 + + def __del__(self): + self._close_mmaps() + del self._mmaps + del self._buffers + + def __iter__(self): + return self + + def __next__(self): + if self._curr_idx >= len(self._block_idxs): + self._load_n_chunks() + # TODO: trigger fetching next next n_chunks if remote + block_idx = self._block_idxs[self._curr_idx] + chunk_id = block_idx // self._n_blocks + buffer = self._buffers[chunk_id] + elem_id = (block_idx % self._n_blocks) * self._block_size + offset = np.dtype(self._dtype).itemsize * elem_id + arr = np.frombuffer( + buffer, dtype=self._dtype, count=self._block_size, offset=offset + ) + self._curr_idx += 1 + return torch.from_numpy(arr.astype(np.int64)) + + +class CombinedDataset(IterableDataset): + def __init__(self, datasets, seed, weights=None): + self._seed = seed + self._datasets = datasets + self._weights = weights + n_datasets = len(datasets) + if weights is None: + self._weights = [1 / n_datasets] * n_datasets + + def __iter__(self): + return CombinedDatasetIterator(self._datasets, self._seed, self._weights) + + +class CombinedDatasetIterator: + def __init__(self, datasets, seed, weights): + self._datasets = [iter(el) for el in datasets] + self._weights = weights + self._rng = random.Random(seed) + + def __next__(self): + dataset, = self._rng.choices(self._datasets, weights=self._weights, k=1) + return next(dataset) diff --git a/lit-llama/lit_llama/quantization.py b/lit-llama/lit_llama/quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6ff5fefa8de948efc9c8ee1bf92fc20039fbe3 --- /dev/null +++ b/lit-llama/lit_llama/quantization.py @@ -0,0 +1,614 @@ +import os +from contextlib import contextmanager +import warnings +import math + +import torch + +# configuration for bitsandbytes before import +os.environ["BITSANDBYTES_NOWELCOME"] = "1" +warnings.filterwarnings( + "ignore", + message="MatMul8bitLt: inputs will be cast from torch.float32 to float16 during quantization", +) +warnings.filterwarnings( + "ignore", + message="MatMul8bitLt: inputs will be cast from torch.bfloat16 to float16 during quantization", +) +warnings.filterwarnings( + "ignore", + message="The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers and GPU quantization are unavailable.", +) + +try: + import bitsandbytes as bnb # noqa: E402 +except: + bnb = None + +try: + import triton # noqa: E402 + import triton.language as tl # noqa: E402 +except: + triton = None + +if bnb is not None: + + class Linear8bitLt(bnb.nn.Linear8bitLt): + """Wraps `bnb.nn.Linear8bitLt` and enables instantiation directly on the device and + re-quantizaton when loading the state dict. + + + This should only be used for inference. For training, use `bnb.nn.Linear8bitLt` directly. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs, has_fp16_weights=False, threshold=6.0) + # We quantize the initial weight here so we don't end up filling the device + # memory with float32 weights which could lead to OOM. + self._quantize_weight(self.weight.data) + + def _load_from_state_dict(self, local_state_dict, *args, **kwargs): + # There is only one key that ends with `*.weight`, the other one is the bias + weight_key = next( + (name for name in local_state_dict.keys() if name.endswith("weight")), + None, + ) + if weight_key is None: + return + + # Load the weight from the state dict and re-quantize it + weight = local_state_dict.pop(weight_key) + self._quantize_weight(weight) + + # If there is a bias, let nn.Module load it + if local_state_dict: + super()._load_from_state_dict(local_state_dict, *args, **kwargs) + + def _quantize_weight(self, weight: torch.Tensor) -> None: + # This code is taken and adapted from `bnb.nn.Int8Params.cuda()` + B = weight.contiguous().half().cuda() + CB, CBt, SCB, SCBt, coo_tensorB = bnb.functional.double_quant(B) + del CBt + del SCBt + self.weight.data = CB + setattr(self.weight, "CB", CB) + setattr(self.weight, "SCB", SCB) + + +if triton is not None: + # This is adapted from the OpenAI Triton matmul example. + @triton.autotune( + configs=[ + triton.Config( + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=3, + num_warps=8, + ), + triton.Config( + { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=3, + num_warps=8, + ), + triton.Config( + { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=4, + num_warps=4, + ), + triton.Config( + { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=4, + num_warps=4, + ), + triton.Config( + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=4, + num_warps=4, + ), + triton.Config( + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=4, + num_warps=4, + ), + triton.Config( + { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=4, + num_warps=4, + ), + triton.Config( + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=4, + num_warps=4, + ), + triton.Config( + { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=5, + num_warps=2, + ), + triton.Config( + { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + }, + num_stages=5, + num_warps=2, + ), + ], + key=["M", "N", "K"], + ) + @triton.jit + def linear_kernel_4bit_weight( + # Pointers to matrices + a_ptr, + b_ptr, + c_ptr, + bscales_ptr, + bzeros_ptr, + # bdequant, + # Matrix dimensions + M, + N, + K, + # The stride variables represent how much to increase the ptr by when moving by 1 + # element in a particular dimension. E.g. stride_am is how much to increase a_ptr + # by to get the element one row down (A has M rows) + stride_am, + stride_ak, + stride_bk, + stride_bn, + stride_cm, + stride_cn, + # Meta-parameters + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + GROUP_SIZE_M: tl.constexpr, + ): + """Kernel for computing the matmul C = A x B.T. + A has shape (M, K), B has shape (N, K) and C has shape (M, N) + """ + # ----------------------------------------------------------- + # Map program ids `pid` to the block of C it should compute. + # This is done in a grouped ordering to promote L2 data reuse + # See above `L2 Cache Optimizations` section for details + pid = tl.program_id(axis=0) + num_pid_m = tl.cdiv(M, BLOCK_SIZE_M) + num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) + num_pid_in_group = GROUP_SIZE_M * num_pid_n + group_id = pid // num_pid_in_group + first_pid_m = group_id * GROUP_SIZE_M + group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) + pid_m = first_pid_m + (pid % group_size_m) + pid_n = (pid % num_pid_in_group) // group_size_m + + # ---------------------------------------------------------- + # Create pointers for the first blocks of A and B. + # We will advance this pointer as we move in the K direction + # and accumulate + # a_ptrs is a block of [BLOCK_SIZE_M, BLOCK_SIZE_K] pointers + # b_ptrs is a block of [BLOCK_SIZE_K, BLOCK_SIZE_n] pointers + # see above `Pointer Arithmetics` section for details + offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + a_mask = offs_am[:, None] < M + b_mask = offs_bn[None, :] < N + offs_k = tl.arange(0, BLOCK_SIZE_K) + a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak) + b_ptrs = b_ptr + ( + (offs_k[:, None] // 2) * stride_bk + offs_bn[None, :] * stride_bn + ) + + bscales_ptrs = bscales_ptr + offs_bn[None, :] + bzeros_ptrs = bzeros_ptr + offs_bn[None, :] + + scale = tl.load(bscales_ptrs) + zero = tl.load(bzeros_ptrs) + # ----------------------------------------------------------- + # Iterate to compute a block of the C matrix + # We accumulate into a `[BLOCK_SIZE_M, BLOCK_SIZE_N]` block + # of fp32 values for higher accuracy. + # `accumulator` will be converted back to fp16 after the loop + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k in range(0, K, BLOCK_SIZE_K): + # wasteful as it is to load everything twice, my attempts at avoiding it lead to slower code + b12 = tl.load(b_ptrs, mask=b_mask) + # Note that for simplicity, we don't apply a mask in K here. + a = tl.load(a_ptrs, mask=a_mask).to(tl.float32) + b = ( + ((b12.to(tl.uint8) >> ((offs_k[:, None] % 2) * 4)) & 0xF).to(tl.float32) + - zero + ) * scale + accumulator += tl.dot(a, b) + + # Advance the ptrs to the next K block + a_ptrs += BLOCK_SIZE_K * stride_ak + b_ptrs += (BLOCK_SIZE_K // 2) * stride_bk + c = accumulator + + # ----------------------------------------------------------- + # Write back the block of the output matrix C + offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + c_ptrs = c_ptr + stride_cm * offs_cm[:, None] + stride_cn * offs_cn[None, :] + c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N) + tl.store(c_ptrs, c, mask=c_mask) + + def qlinear_4bit_weight(inp, weight, scales, zeros): + weight = weight.t().contiguous() + c_shape = inp.shape[:-1] + weight.shape[-1:] + inp = inp.reshape(-1, inp.shape[-1]).contiguous() + # we pad the input to amortize triton compilation cost better + PAD_TO = 256 + if inp.shape[0] % PAD_TO != 0: + c_crop = inp.shape[0] + new_inp_shape0 = inp.shape[0] + PAD_TO - inp.shape[0] % PAD_TO + inp2 = inp.new_empty((new_inp_shape0, inp.shape[1])) + inp2[: inp.shape[0]] = inp + inp2[inp.shape[0] :].zero_() + inp = inp2 + else: + c_crop = None + + assert inp.shape[1] == weight.shape[0] * 2, "incompatible dimensions" + + assert scales.shape == (weight.shape[1], 1) + assert zeros.shape == (weight.shape[1], 1) + scales = scales.contiguous() + zeros = zeros.contiguous() + K, N = weight.shape + M, K = inp.shape + assert ( + K % 32 == 0 + ), "We don't check memory-out-of-bounds with K so K must be divisible by BLOCK_SIZE_K" + # allocates output + c = torch.empty((M, N), device=inp.device, dtype=inp.dtype) + # 1D launch kernel where each block gets its own program. + grid = lambda META: ( + triton.cdiv(M, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]), + ) + linear_kernel_4bit_weight[grid]( + inp, + weight, + c, + scales, + zeros, + M, + N, + K, + inp.stride(0), + inp.stride(1), + weight.stride(0), + weight.stride(1), + c.stride(0), + c.stride(1), + ) + return c[:c_crop].reshape(c_shape) + +else: + qlinear_4bit_weight = None + + +# for correctness but with terrible perf +class ColBlockQuantizedLinear(torch.nn.Module): + def __init__(self, in_features, out_features, bias: bool, *, bits, tile_cols): + super().__init__() + self.in_features = in_features + self.out_features = out_features + self.tile_cols = tile_cols if tile_cols != -1 else self.in_features + self.bits = bits + self.entries_per_byte = 8 // bits + assert self.entries_per_byte > 0 and self.entries_per_byte * self.bits == 8 + assert in_features % self.entries_per_byte == 0 + self.register_buffer( + "quant_weight", + torch.empty( + (self.out_features, self.in_features // self.entries_per_byte), + dtype=torch.uint8, + ) + .t() + .contiguous() + .t(), + ) + self.register_buffer( + "scales", + torch.empty( + ( + self.out_features, + (self.in_features + self.tile_cols - 1) // self.tile_cols, + ) + ), + ) + self.register_buffer("zeros", torch.empty_like(self.scales)) + assert isinstance(bias, bool) + if bias: + self.register_buffer("bias", torch.empty((self.out_features,))) + else: + self.register_buffer("bias", None) + + def pack_weight(self, weight): + weight = weight.to(device=self.quant_weight.device, copy=True) + for j in range(self.scales.size(1)): + weight[:, j * self.tile_cols : (j + 1) * self.tile_cols] /= self.scales[ + :, j : j + 1 + ] + weight[:, j * self.tile_cols : (j + 1) * self.tile_cols] += self.zeros[ + :, j : j + 1 + ] + weight = weight.clamp_(min=0, max=2**self.bits - 1).to(dtype=torch.uint8) + self.quant_weight.zero_() + for nr in range(self.entries_per_byte): + self.quant_weight += weight[:, nr :: self.entries_per_byte] << ( + nr * self.bits + ) + + def get_weight(self, dtype=torch.float): + weight = torch.empty( + (self.out_features, self.in_features), + device=self.quant_weight.device, + dtype=dtype, + ) + mask = (1 << self.bits) - 1 + for nr in range(self.entries_per_byte): + weight[:, nr :: self.entries_per_byte] = ( + (self.quant_weight >> (nr * self.bits)) & mask + ).float() + self.quant_weight.to(dtype) + for j in range(self.scales.size(1)): + weight[:, j * self.tile_cols : (j + 1) * self.tile_cols] -= self.zeros[ + :, j : j + 1 + ] + weight[:, j * self.tile_cols : (j + 1) * self.tile_cols] *= self.scales[ + :, j : j + 1 + ] + return weight + + def forward(self, inp): + if ( + triton is not None + and self.bits == 4 + and self.quant_weight.device.type == "cuda" + and self.zeros.shape[1] == 1 + and self.quant_weight.shape[1] % 32 == 0 + ): + return qlinear_4bit_weight(inp, self.quant_weight, self.scales, self.zeros) + weight = self.get_weight(dtype=inp.dtype) + return torch.nn.functional.linear(inp, weight, self.bias) + + +class GPTQQuantizer: + # The algorithm and code has been taken from https://github.com/IST-DASLab/gptq/ + # E. Frantar et al GPTQ: Accurate Post-training Compression for GPT, arXiv:2210.17323 + # portions copyright by the authors licensed under the Apache License 2.0 + # All errors are our own. + + def __init__( + self, + linear_module, + *, + bits, + perchannel=True, + sym=False, + blocksize=128, + percdamp=0.01, + groupsize=-1, + actorder=False + ): + assert isinstance(linear_module, torch.nn.Linear) + + self.linear_module = linear_module + self.dev = self.linear_module.weight.device + self.rows = linear_module.weight.shape[0] + self.columns = linear_module.weight.shape[1] + self.H = torch.zeros((self.columns, self.columns), device=self.dev) + self.nsamples = 0 + self.bits = bits + self.maxq = 2**bits - 1 + self.perchannel = perchannel + self.sym = sym + self.blocksize = blocksize + self.percdamp = percdamp + self.groupsize = groupsize + self.actorder = actorder + self.tile_cols = self.columns if groupsize == -1 else groupsize + self.scales = torch.zeros( + (self.rows, (self.columns + self.tile_cols - 1) // self.tile_cols), + dtype=self.linear_module.weight.dtype, + device=self.dev, + ) + self.zeros = torch.zeros_like(self.scales) + assert not ( + self.actorder and self.groupsize != -1 + ), "The permutation trick does not work for grouped quantization" + + @staticmethod + def quantize_weight(x, scale, zero, maxq): + q = torch.clamp(torch.round(x / scale) + zero, 0, maxq) + x_rec = scale * (q - zero) + return x_rec + + def find_params_weight(self, x): + dev = x.device + + shape = x.shape + if self.perchannel: + x = x.flatten(1) + else: + x = x.flatten().unsqueeze(0) + + tmp = torch.zeros(x.shape[0], device=dev) + xmin = torch.minimum(x.min(1)[0], tmp) + xmax = torch.maximum(x.max(1)[0], tmp) + + if self.sym: + xmax = torch.maximum(torch.abs(xmin), xmax) + tmp = xmin < 0 + if torch.any(tmp): + xmin[tmp] = -xmax[tmp] + tmp = (xmin == 0) & (xmax == 0) + xmin[tmp] = -1 + xmax[tmp] = +1 + + scale = (xmax - xmin) / self.maxq + if self.sym: + zero = torch.full_like(scale, (self.maxq + 1) / 2) + else: + zero = torch.round(-xmin / scale) + + if not self.perchannel: + tmp = shape[0] + scale = scale.repeat(tmp) + zero = zero.repeat(tmp) + + shape = [-1] + [1] * (len(shape) - 1) + scale = scale.reshape(shape) + zero = zero.reshape(shape) + return scale, zero + + def collect_input_stats(self, _1, inp, _2): + inp = inp[0].detach() + self.last_inp = inp + if len(inp.shape) == 2: + inp = inp.unsqueeze(0) + tmp = inp.shape[0] + if len(inp.shape) == 3: + inp = inp.reshape((-1, inp.shape[-1])) + inp = inp.t() + self.H *= self.nsamples / (self.nsamples + tmp) + self.nsamples += tmp + # inp = inp.float() + inp = math.sqrt(2 / self.nsamples) * inp.float() + # self.H += 2 / self.nsamples * inp.matmul(inp.t()) + self.H += inp.matmul(inp.t()) + + def quantize(self): + W = self.linear_module.weight.detach().to(dtype=torch.float, copy=True) + + scale, zero = self.find_params_weight(W) + self.scales[:] = scale + self.zeros[:] = zero + + H = self.H + del self.H + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + W[:, dead] = 0 + if self.actorder: + perm = torch.argsort(torch.diag(H), descending=True) + W = W[:, perm] + H = H[perm][:, perm] + + Losses = torch.zeros_like(W) + Q = torch.zeros_like(W) + + damp = self.percdamp * torch.mean(torch.diag(H)) + diag = torch.arange(self.columns, device=self.dev) + H[diag, diag] += damp + H = torch.linalg.cholesky(H) + H = torch.cholesky_inverse(H) + H = torch.linalg.cholesky(H, upper=True) + Hinv = H + + for i1 in range(0, self.columns, self.blocksize): + i2 = min(i1 + self.blocksize, self.columns) + count = i2 - i1 + + W1 = W[:, i1:i2].clone() + Q1 = torch.zeros_like(W1) + Err1 = torch.zeros_like(W1) + Losses1 = torch.zeros_like(W1) + Hinv1 = Hinv[i1:i2, i1:i2] + + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + + if self.groupsize != -1: + if (i1 + i) % self.groupsize == 0: + scale, zero = self.find_params_weight( + W[:, (i1 + i) : (i1 + i + self.groupsize)] + ) + self.scales[:, (i1 + i) // self.groupsize] = scale + self.zeros[:, (i1 + i) // self.groupsize] = zero + + q = self.quantize_weight(w.unsqueeze(1), scale, zero, self.maxq) + q = q.squeeze(1) + assert q.dim() == 1 + Q1[:, i] = q + Losses1[:, i] = (w - q) ** 2 / d**2 + + err1 = (w - q) / d + W1[:, i:] -= err1.unsqueeze(1).matmul(Hinv1[i, i:].unsqueeze(0)) + Err1[:, i] = err1 + + Q[:, i1:i2] = Q1 + Losses[:, i1:i2] = Losses1 / 2 + + W[:, i2:] -= Err1.matmul(Hinv[i1:i2, i2:]) + + if self.actorder: + invperm = torch.argsort(perm) + Q = Q[:, invperm] + + weight = Q.reshape(self.linear_module.weight.shape).to( + self.linear_module.weight.data.dtype + ) + error = torch.sum(Losses).item() + + q_module = ColBlockQuantizedLinear( + self.linear_module.in_features, + self.linear_module.out_features, + self.linear_module.bias is not None, + bits=self.bits, + tile_cols=self.groupsize, + ).to(self.dev) + q_module.scales = self.scales + q_module.zeros = self.zeros + q_module.pack_weight(weight) + q_module.bias = self.linear_module.bias + return q_module, error diff --git a/lit-llama/lit_llama/tokenizer.py b/lit-llama/lit_llama/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..fb681e3f51e697902cd3cb0bdcadee4ac3306f2d --- /dev/null +++ b/lit-llama/lit_llama/tokenizer.py @@ -0,0 +1,49 @@ +import os +from pathlib import Path +from typing import Optional + +import torch +from sentencepiece import SentencePieceProcessor, SentencePieceTrainer + + +class Tokenizer: + """Tokenizer for LLaMA.""" + + def __init__(self, model_path: Path) -> None: + self.processor = SentencePieceProcessor(model_file=str(model_path)) + self.bos_id = self.processor.bos_id() + self.eos_id = self.processor.eos_id() + self.pad_id = self.processor.pad_id() + + @property + def vocab_size(self) -> int: + return self.processor.vocab_size() + + def encode( + self, + string: str, + bos: bool = True, + eos: bool = False, + max_length: int = -1, + pad: bool = False, + device: Optional[torch.device] = None + ) -> torch.Tensor: + tokens = self.processor.encode(string) + if bos: + tokens = [self.bos_id] + tokens + if eos: + tokens = tokens + [self.eos_id] + if max_length > 0: + tokens = tokens[:max_length] + if pad and len(tokens) < max_length: + tokens += [self.pad_id] * (max_length - len(tokens)) + + return torch.tensor(tokens, dtype=torch.int, device=device) + + def decode(self, tokens: torch.Tensor) -> str: + return self.processor.decode(tokens.tolist()) + + @staticmethod + def train(input: str, destination: str, vocab_size=32000) -> None: + model_prefix = os.path.join(destination, "tokenizer") + SentencePieceTrainer.Train(input=input, model_prefix=model_prefix, vocab_size=vocab_size) diff --git a/lit-llama/lit_llama/utils.py b/lit-llama/lit_llama/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a09ada20c55c7b49c54f1720d2901b2953f209f9 --- /dev/null +++ b/lit-llama/lit_llama/utils.py @@ -0,0 +1,496 @@ +"""Utility functions for training and inference.""" + +import functools +import pickle +import warnings +from io import BytesIO +from pathlib import Path +from contextlib import contextmanager + +import torch +import torch.utils._device +from lightning.fabric.strategies import DeepSpeedStrategy, FSDPStrategy +from torch.distributed.fsdp import FullStateDictConfig +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.distributed.fsdp import StateDictType +from torch.serialization import normalize_storage_type + +llama_model_sizes = { + 4096: "7B", # 7B n_embd=4096 + 5120: "13B", # 13B n_embd=5120 + 6656: "30B", # 30B n_embd=6656 + 8192: "65B", # 65B n_embd=8192 +} + + +def llama_model_lookup(checkpoint: dict) -> str: + """Returns the LLaMA model name from the checkpoint. + + Checks the width of the lm_head.weight matrix, as these uniquely identify the model. + """ + embedding_size = checkpoint['transformer.wte.weight'].shape[1] + return llama_model_sizes[embedding_size] + + +def find_multiple(n: int, k: int) -> int: + if n % k == 0: + return n + return n + k - (n % k) + + +def save_model_checkpoint(fabric, model, file_path): + """Handles boilerplate logic for retrieving and saving the state_dict. + + This will be upstreamed to Fabric soon. + """ + file_path = Path(file_path) + + if isinstance(fabric.strategy, DeepSpeedStrategy): + from deepspeed.utils.zero_to_fp32 import convert_zero_checkpoint_to_fp32_state_dict + + fabric.save(file_path, {"model": model}) + fabric.barrier() + if fabric.global_rank == 0: + # Create a consolidated checkpoint with the same name next to the deepspeed checkpoint + convert_zero_checkpoint_to_fp32_state_dict(file_path, file_path.with_suffix(".pth")) + return + + if isinstance(fabric.strategy, FSDPStrategy): + save_policy = FullStateDictConfig(offload_to_cpu=(fabric.world_size > 1), rank0_only=True) + with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT, save_policy): + state_dict = model._forward_module.state_dict() + else: + state_dict = model.state_dict() + + if fabric.global_rank == 0: + torch.save(state_dict, file_path) + fabric.barrier() + + +class EmptyInitOnDevice(torch.overrides.TorchFunctionMode): + def __init__(self, device=None, dtype=None, quantization_mode=None): + """ + Create tensors with given device and dtype and don't run initialization + (but instead use "empty tensors", i.e. uninitialized memory). + + device: `torch.device` to work with + dtype: `torch.dtype` to work with + quantization_mode: optional string, quantization mode to work with, default `None`. + Available modes: `llm.int8` bitsnbytes LLM.int8 quantization (only on GPU) + `gptq.int4`, `gptq.int8`: GPTQ pre-quantized models + + Example:: + with EmptyInitOnDevice("cuda", dtype=torch.bfloat16): + model = LLaMA.from_name('7B') + model.load_state_dict(torch.load('llama-lit/7B/lit-llama.pth'))""" + + self.quantization_mode = quantization_mode + self.quantized_linear_cls = None + if self.quantization_mode == 'llm.int8': + if device.type != "cuda": + raise ValueError("Quantization is only supported on the GPU.") + from .quantization import Linear8bitLt + self.quantized_linear_cls = Linear8bitLt + elif self.quantization_mode == 'gptq.int4': + from .quantization import ColBlockQuantizedLinear + self.quantized_linear_cls = functools.partial(ColBlockQuantizedLinear, bits=4, tile_cols=-1) + elif self.quantization_mode == 'gptq.int8': + from .quantization import ColBlockQuantizedLinear + self.quantized_linear_cls = functools.partial(ColBlockQuantizedLinear, bits=8, tile_cols=-1) + elif self.quantization_mode is not None: + raise RuntimeError(f"unknown quantization mode {self.quantization_mode}") + self.device = device + self.dtype = dtype + + def __enter__(self): + if self.quantized_linear_cls != None: + self.torch_linear_cls = torch.nn.Linear + torch.nn.Linear = self.quantized_linear_cls + return super().__enter__() + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.quantized_linear_cls != None: + torch.nn.Linear = self.torch_linear_cls + return super().__exit__(exc_type, exc_val, exc_tb) + + def __torch_function__(self, func, types, args=(), kwargs=None): + kwargs = kwargs or {} + if getattr(func, "__module__", None) == "torch.nn.init": + if "tensor" in kwargs: + return kwargs["tensor"] + else: + return args[0] + if ( + self.device is not None + and func in torch.utils._device._device_constructors() + and kwargs.get("device") is None + ): + kwargs["device"] = self.device + if ( + self.dtype is not None + and func in torch.utils._device._device_constructors() + and kwargs.get("dtype") is None + ): + kwargs["dtype"] = self.dtype + return func(*args, **kwargs) + + +@contextmanager +def quantization(mode: str = None): + quantized_linear_cls = None + if mode == 'llm.int8': + from .quantization import Linear8bitLt + quantized_linear_cls = Linear8bitLt + elif mode == 'gptq.int4': + from .quantization import ColBlockQuantizedLinear + quantized_linear_cls = functools.partial(ColBlockQuantizedLinear, bits=4, tile_cols=-1) + elif mode == 'gptq.int8': + from .quantization import ColBlockQuantizedLinear + quantized_linear_cls = functools.partial(ColBlockQuantizedLinear, bits=8, tile_cols=-1) + elif mode is not None: + raise ValueError(f"Unknown quantization mode: {mode}") + + enabled = mode is not None + torch_linear_cls = torch.nn.Linear + if enabled: + torch.nn.Linear = quantized_linear_cls + yield + if enabled: + torch.nn.Linear = torch_linear_cls + + +# this is taken from torchhacks https://github.com/lernapparat/torchhacks + + +class NotYetLoadedTensor: + def __init__(self, metatensor, archiveinfo, storageinfo, rebuild_args): + self.metatensor = metatensor + self.archiveinfo = archiveinfo + self.storageinfo = storageinfo + self.rebuild_args = rebuild_args + + @classmethod + def rebuild_from_type_v2(cls, func, new_type, args, state, *, archiveinfo=None): + ret = func(*args) + if isinstance(ret, NotYetLoadedTensor): + old_lt = ret._load_tensor + + def _load_tensor(): + t = old_lt() + return torch._tensor._rebuild_from_type_v2( + lambda: t, new_type, (), state + ) + + ret._load_tensor = _load_tensor + return ret + return torch._tensor._rebuild_from_type_v2(func, new_type, args, state) + + @classmethod + def rebuild_parameter( + cls, data, requires_grad, backward_hooks, *, archiveinfo=None + ): + if isinstance(data, NotYetLoadedTensor): + old_lt = data._load_tensor + + def _load_tensor(): + t = old_lt() + return torch._utils._rebuild_parameter(t, requires_grad, backward_hooks) + + data._load_tensor = _load_tensor + return data + return torch._utils._rebuild_parameter(data, requires_grad, backward_hooks) + + @classmethod + def rebuild_tensor_v2( + cls, + storage, + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + metadata=None, + *, + archiveinfo=None, + ): + rebuild_args = ( + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + metadata, + ) + metatensor = torch._utils._rebuild_tensor_v2( + storage, + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + metadata, + ) + storageinfo = storage.archiveinfo + return NotYetLoadedTensor(metatensor, archiveinfo, storageinfo, rebuild_args) + + def _load_tensor(self): + name, storage_cls, fn, device, size = self.storageinfo + dtype = self.metatensor.dtype + + uts = ( + self.archiveinfo.zipfile_context.zf.get_storage_from_record( + f"data/{fn}", + size * torch._utils._element_size(dtype), + torch.UntypedStorage, + ) + ._typed_storage() + ._untyped_storage + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + storage = torch.storage.TypedStorage( + wrap_storage=uts, dtype=self.metatensor.dtype, _internal=True + ) + tensor = torch._utils._rebuild_tensor_v2(storage, *self.rebuild_args) + return tensor + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + loaded_args = [ + (a._load_tensor() if isinstance(a, NotYetLoadedTensor) else a) for a in args + ] + res = func(*loaded_args, **kwargs) + # gc.collect would be costly here, maybe do it optionally + return res + + def __getattr__(self, name): + # properties + ## TODO: device, is_...?? + ## TODO: mH, mT, H, T, data, imag, real + ## name ??? + if name in { + "dtype", + "grad", + "grad_fn", + "layout", + "names", + "ndim", + "output_nr", + "requires_grad", + "retains_grad", + "shape", + "volatile", + }: + return getattr(self.metatensor, name) + if name in {"size"}: + return getattr(self.metatensor, name) + # materializing with contiguous is needed for quantization + if name in {"contiguous"}: + return getattr(self._load_tensor(), name) + + raise AttributeError(f"{type(self)} does not have {name}") + + def __repr__(self): + return f"NotYetLoadedTensor({repr(self.metatensor)})" + + +class LazyLoadingUnpickler(pickle.Unpickler): + def __init__(self, file, zipfile_context): + super().__init__(file) + self.zipfile_context = zipfile_context + + def find_class(self, module, name): + res = super().find_class(module, name) + if module == "torch._utils" and name == "_rebuild_tensor_v2": + return functools.partial( + NotYetLoadedTensor.rebuild_tensor_v2, archiveinfo=self + ) + elif module == "torch._tensor" and name == "_rebuild_from_type_v2": + return functools.partial( + NotYetLoadedTensor.rebuild_from_type_v2, archiveinfo=self + ) + elif module == "torch._utils" and name == "_rebuild_parameter": + return functools.partial( + NotYetLoadedTensor.rebuild_parameter, archiveinfo=self + ) + return res + + def persistent_load(self, pid): + name, cls, fn, device, size = pid + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + s = torch.storage.TypedStorage(dtype=cls().dtype, device="meta") + s.archiveinfo = pid + return s + + +class lazy_load: + def __init__(self, fn): + self.zf = torch._C.PyTorchFileReader(str(fn)) + with BytesIO(self.zf.get_record("data.pkl")) as pkl: + mup = LazyLoadingUnpickler(pkl, self) + self.sd = mup.load() + + def __enter__(self): + return self.sd + + def __exit__(self, exc_type, exc_val, exc_tb): + del self.zf # I don't think there is a way to force closing... + self.zf = None + + +class SavingProxyForStorage: + def __init__(self, obj, saver, protocol_version=5): + self.protocol_version = protocol_version + self.saver = saver + if not (isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj)): + raise TypeError(f"expected storage, not {type(obj)}") + + # this logic is taken from PyTorch 2.0+ torch/serialization.py + if isinstance(obj, torch.storage.TypedStorage): + # PT upstream wants to deprecate this eventually... + storage = obj._untyped_storage + storage_type_str = obj._pickle_storage_type() + storage_type = getattr(torch, storage_type_str) + storage_numel = obj._size() + else: + storage = obj + storage_type = normalize_storage_type(type(obj)) + storage_numel = storage.nbytes() + + storage_key = saver._write_storage_and_return_key(storage) + location = torch.serialization.location_tag(storage) + + self.storage_info = ( + "storage", + storage_type, + storage_key, + location, + storage_numel, + ) + + def __reduce_ex__(self, protocol_version): + assert False, "this should be handled with out of band" + + +class SavingProxyForTensor: + def __init__(self, tensor, saver, protocol_version=5): + self.protocol_version = protocol_version + self.reduce_ret_fn, (storage, *other_reduce_args) = tensor.__reduce_ex__( + protocol_version + ) + assert isinstance( + storage, torch.storage.TypedStorage + ), "Please check for updates" + storage_proxy = SavingProxyForStorage( + storage, saver, protocol_version=protocol_version + ) + self.reduce_args = (storage_proxy, *other_reduce_args) + + def __reduce_ex__(self, protocol_version): + if protocol_version != self.protocol_version: + raise RuntimeError( + f"Unexpected protocol version: expected {self.protocol_version}, got {protocol_version}" + ) + return self.reduce_ret_fn, self.reduce_args + + +class IncrementalPyTorchPickler(pickle.Pickler): + def __init__(self, saver, *args, **kwargs): + super().__init__(*args, **kwargs) + self.storage_dtypes = {} + self.saver = saver + self.id_map = {} + + # this logic is taken from PyTorch 2.0+ torch/serialization.py + def persistent_id(self, obj): + # FIXME: the docs say that persistent_id should only return a string + # but torch store returns tuples. This works only in the binary protocol + # see + # https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-external-objects + # https://github.com/python/cpython/blob/master/Lib/pickle.py#L527-L537 + if isinstance(obj, SavingProxyForStorage): + return obj.storage_info + + if isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj): + if isinstance(obj, torch.storage.TypedStorage): + # TODO: Once we decide to break serialization FC, this case + # can be deleted + storage = obj._untyped_storage + storage_dtype = obj.dtype + storage_type_str = obj._pickle_storage_type() + storage_type = getattr(torch, storage_type_str) + storage_numel = obj._size() + + else: + storage = obj + storage_dtype = torch.uint8 + storage_type = normalize_storage_type(type(obj)) + storage_numel = storage.nbytes() + + # If storage is allocated, ensure that any other saved storages + # pointing to the same data all have the same dtype. If storage is + # not allocated, don't perform this check + if storage.data_ptr() != 0: + if storage.data_ptr() in self.storage_dtypes: + if storage_dtype != self.storage_dtypes[storage.data_ptr()]: + raise RuntimeError( + "Cannot save multiple tensors or storages that " + "view the same data as different types" + ) + else: + self.storage_dtypes[storage.data_ptr()] = storage_dtype + + storage_key = self.id_map.get(storage._cdata) + if storage_key is None: + storage_key = self.saver._write_storage_and_return_key(storage) + self.id_map[storage._cdata] = storage_key + location = torch.serialization.location_tag(storage) + + return ("storage", storage_type, storage_key, location, storage_numel) + + return None + + +class incremental_save: + def __init__(self, name): + self.name = name + self.zipfile = torch._C.PyTorchFileWriter(str(name)) + self.has_saved = False + self.next_key = 0 + + def __enter__(self): + return self + + def store_early(self, tensor): + if isinstance(tensor, torch.Tensor): + return SavingProxyForTensor(tensor, self) + raise TypeError(f"can only store tensors early, not {type(tensor)}") + + def save(self, obj): + if self.has_saved: + raise RuntimeError("have already saved") + # Write the pickle data for `obj` + data_buf = BytesIO() + pickler = IncrementalPyTorchPickler(self, data_buf, protocol=5) + pickler.dump(obj) + data_value = data_buf.getvalue() + self.zipfile.write_record("data.pkl", data_value, len(data_value)) + self.has_saved = True + + def _write_storage_and_return_key(self, storage): + if self.has_saved: + raise RuntimeError("have already saved") + key = self.next_key + self.next_key += 1 + name = f"data/{key}" + if storage.device.type != "cpu": + storage = storage.cpu() + num_bytes = storage.nbytes() + self.zipfile.write_record(name, storage.data_ptr(), num_bytes) + return key + + def __exit__(self, type, value, traceback): + self.zipfile.write_end_of_file() diff --git a/lit-llama/pretrain/redpajama.py b/lit-llama/pretrain/redpajama.py new file mode 100644 index 0000000000000000000000000000000000000000..97ebde284067e49d8a06a7ab80c683542c88c3e2 --- /dev/null +++ b/lit-llama/pretrain/redpajama.py @@ -0,0 +1,321 @@ +import os +import sys +import math +import glob +import time +from functools import partial +from pathlib import Path +from typing import Tuple, Optional + +import lightning as L +from lightning.fabric.strategies import FSDPStrategy + +import torch +from torch.utils.data import DataLoader +from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy + +import numpy as np + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +from lit_llama.model import Block, LLaMA, LLaMAConfig +from lit_llama.packed_dataset import PackedDataset, CombinedDataset +from lit_llama.utils import save_model_checkpoint + + +out_dir = "out/training" +save_interval = 1000 +eval_interval = 1000 +eval_iters = 100 +log_interval = 1 + +# compile = False + +# Hyperparameters +learning_rate = 6e-4 +batch_size = 125 +micro_batch_size = 5 +max_iters = 600000 # num_epochs * (epoch_size // micro_batch_size) // devices +weight_decay = 1e-1 +beta1 = 0.9 +beta2 = 0.95 +grad_clip = 1.0 +decay_lr = True +warmup_iters = 2000 +lr_decay_iters = max_iters +min_lr = 6e-5 + + +# Data proportions from https://arxiv.org/pdf/2302.13971.pdf Table 1 +data_config = [ + ("arxiv", 2.5), + ("book", 4.5), + ("c4", 15.0), + ("cc", 67.0), + ("github", 4.5), + ("stackexchange", 2.0), + ("wikipedia", 4.5), +] + + +def main( + devices: int = 4, + train_data_dir: Path = "data/lit-redpajama", + val_data_dir: Optional[Path] = None, +) -> None: + auto_wrap_policy = partial( + transformer_auto_wrap_policy, transformer_layer_cls={Block} + ) + strategy = FSDPStrategy( + auto_wrap_policy=auto_wrap_policy, activation_checkpointing=Block, limit_all_gathers=True + ) + + fabric = L.Fabric( + accelerator="cuda", devices=devices, precision="bf16-mixed", strategy=strategy + ) + fabric.launch() + fabric.seed_everything(1337) + + if fabric.global_rank == 0: + os.makedirs(out_dir, exist_ok=True) + + config = LLaMAConfig.from_name("7B") + + train_dataloader, val_dataloader = create_dataloaders( + batch_size=micro_batch_size, + block_size=config.block_size, + fabric=fabric, + train_data_dir=train_data_dir, + val_data_dir=val_data_dir, + seed=1338, + ) + if val_dataloader is None: + train_dataloader = fabric.setup_dataloaders(train_dataloader) + else: + train_dataloader, val_dataloader = fabric.setup_dataloaders(train_dataloader, val_dataloader) + + with fabric.device: + torch.set_default_dtype(torch.bfloat16) + model = LLaMA(config) + model.apply(model._init_weights) + torch.set_default_dtype(torch.float32) + + # if compile: + # model = torch.compile(model) + + optimizer = torch.optim.AdamW( + model.parameters(), + lr=learning_rate, + weight_decay=weight_decay, + betas=(beta1, beta2), + foreach=False, + ) + + model, optimizer = fabric.setup(model, optimizer) + + process_batch_size = batch_size // devices + gradient_accumulation_iters = process_batch_size // micro_batch_size + + train(fabric, model, optimizer, train_dataloader, val_dataloader, gradient_accumulation_iters, devices) + + +def train( + fabric: L.Fabric, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + train_dataloader: DataLoader, + val_dataloader: Optional[DataLoader], + grad_accum_steps: int, + devices: int, +) -> None: + """The training loop. + + Loosely based on the nanoGPT implementation: https://github.com/karpathy/nanoGPT. + """ + + step_count = 0 + + step_time = 0.0 + tokens = 0 + tokens_sec = 0.0 + prev_t1 = time.time() + + for iter_num, train_data in enumerate(train_dataloader): + t0 = time.time() + + # determine and set the learning rate for this iteration + lr = get_lr(iter_num) if decay_lr else learning_rate + for param_group in optimizer.param_groups: + param_group["lr"] = lr + + + input_ids = train_data[:, 0 : model.config.block_size].contiguous() + targets = train_data[:, 1 : model.config.block_size + 1].contiguous() + + is_accumulating = (iter_num + 1) % grad_accum_steps != 0 + + with fabric.no_backward_sync(model, enabled=is_accumulating): + logits = model(input_ids) + loss = torch.nn.functional.cross_entropy( + logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1 + ) + fabric.backward(loss / grad_accum_steps) + + t1 = time.time() + + if not is_accumulating: + fabric.clip_gradients(model, optimizer, max_norm=grad_clip) + + optimizer.step() + optimizer.zero_grad() + step_count += 1 + + t1 = time.time() + + if val_dataloader is not None and step_count % eval_interval == 0: + val_loss = validate(fabric, model, val_dataloader) + fabric.print(f"step {iter_num}: val loss {val_loss:.4f}") + fabric.barrier() + fabric.log_dict( + {"iter": iter_num, "val_loss": val_loss, "step": step_count, "lr": lr} + ) + + if step_count % save_interval == 0: + fabric.print(f"Saving checkpoint to {out_dir}") + save_model_checkpoint( + fabric, model, os.path.join(out_dir, f"iter-{iter_num:06d}-ckpt.pth") + ) + + dt = t1 - t0 + + tokens += micro_batch_size * model.config.block_size + step_time += t1 - prev_t1 + prev_t1 = t1 + + if iter_num % log_interval == 0: + tokens_sec_str = f"{tokens / step_time:.0f}" if not is_accumulating else "-" + + fabric.log_dict( + {"iter": iter_num, "train_loss": loss, "step": step_count, "lr": lr} + ) + fabric.print( + f"iter {iter_num}: loss {loss.item():.4f}, time: {dt*1000:.2f}ms, speed: {tokens_sec_str} toks/s/device" + ) + + if not is_accumulating: + tokens = 0 + step_time = 0.0 + + if iter_num > max_iters: + break + + +@torch.no_grad() +def validate( + fabric: L.Fabric, model: torch.nn.Module, val_dataloader: DataLoader +) -> torch.Tensor: + fabric.print("Validating ...") + model.eval() + losses = torch.zeros(eval_iters) + for k, val_data in enumerate(val_dataloader): + input_ids = val_data[:, 0 : model.config.block_size].contiguous() + targets = val_data[:, 1 : model.config.block_size + 1].contiguous() + logits = model(input_ids) + loss = torch.nn.functional.cross_entropy( + logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1 + ) + losses[k] = loss.item() + out = losses.mean() + model.train() + return out + + +def create_dataloader( + batch_size: int, + block_size: int, + data_dir: str, + fabric, + shuffle: bool = True, + seed: int = 12345, +) -> DataLoader: + datasets = [] + for prefix, _ in data_config: + filenames = glob.glob(os.path.join(data_dir, prefix + "*")) + dataset = PackedDataset( + filenames, n_chunks=4, block_size=block_size, shuffle=shuffle, seed=seed, + num_processes=fabric.world_size, process_rank=fabric.global_rank, + ) + datasets.append(dataset) + + if not datasets: + raise RuntimeError( + f"No data found at {data_dir}. Make sure you ran prepare_redpajama.py to create the dataset." + ) + + weights = [weight for _, weight in data_config] + sum_weights = sum(weights) + weights = [el / sum_weights for el in weights] + + combined_dataset = CombinedDataset(datasets=datasets, seed=seed, weights=weights) + + return DataLoader(combined_dataset, batch_size=batch_size, shuffle=False, pin_memory=True) + + +def create_dataloaders( + batch_size: int, + block_size: int, + fabric, + train_data_dir: str = "data/lit-redpajama", + val_data_dir: Optional[str] = None, + seed: int = 12345, +) -> Tuple[DataLoader, DataLoader]: + # Increase by one because we need the next word as well + effective_block_size = block_size + 1 + train_dataloader = create_dataloader( + batch_size=batch_size, + block_size=effective_block_size, + fabric=fabric, + data_dir=train_data_dir, + shuffle=True, + seed=seed, + ) + val_dataloader = ( + create_dataloader( + batch_size=batch_size, + block_size=effective_block_size, + fabric=fabric, + data_dir=val_data_dir, + shuffle=False, + seed=seed, + ) + if val_data_dir + else None + ) + return train_dataloader, val_dataloader + + +# learning rate decay scheduler (cosine with warmup) +def get_lr(it): + # 1) linear warmup for warmup_iters steps + if it < warmup_iters: + return learning_rate * it / warmup_iters + # 2) if it > lr_decay_iters, return min learning rate + if it > lr_decay_iters: + return min_lr + # 3) in between, use cosine decay down to min learning rate + decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters) + assert 0 <= decay_ratio <= 1 + coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1 + return min_lr + coeff * (learning_rate - min_lr) + + +if __name__ == "__main__": + # Uncomment this line if you see an error: "Expected is_sm80 to be true, but got false" + # torch.backends.cuda.enable_flash_sdp(False) + torch.set_float32_matmul_precision("high") + + from jsonargparse.cli import CLI + + CLI(main) diff --git a/lit-llama/pretrain/shakespeare.py b/lit-llama/pretrain/shakespeare.py new file mode 100644 index 0000000000000000000000000000000000000000..9daa064c6a7530a7fd2f5ac7deba63cdd92f38df --- /dev/null +++ b/lit-llama/pretrain/shakespeare.py @@ -0,0 +1,166 @@ +""" +This script is a placeholder for training LLaMA from scratch. +Currently, it just trains on the Shakespeare dataset. +""" +from pathlib import Path +import sys +import os +import time +from functools import partial +from typing import Tuple + +import lightning as L +from lightning.fabric.strategies import FSDPStrategy + +import torch +from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy + +import numpy as np + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +from lit_llama.model import Block, LLaMA, LLaMAConfig +from lit_llama.utils import save_model_checkpoint + + +out_dir = "out/training" +eval_interval = 2000 +eval_iters = 200 +log_interval = 1 +# compilation fails as it does not support torch.complex64 for RoPE +# compile = False + +# Hyperparameters +learning_rate = 6e-4 +batch_size = 2 +max_iters = 600000 +weight_decay = 1e-1 +beta1 = 0.9 +beta2 = 0.95 +grad_clip = 1.0 + +# For shakespeare, choose smaller block size than vanilla LLaMA +block_size = 1024 + + +def main() -> None: + auto_wrap_policy = partial(transformer_auto_wrap_policy, transformer_layer_cls={Block}) + strategy = FSDPStrategy(auto_wrap_policy=auto_wrap_policy, activation_checkpointing=Block, limit_all_gathers=True) + + fabric = L.Fabric(accelerator="cuda", devices=4, precision="bf16-mixed", strategy=strategy) + fabric.launch() + fabric.seed_everything(1337 + fabric.global_rank) + + if fabric.global_rank == 0: + os.makedirs(out_dir, exist_ok=True) + + train_data, val_data = load_datasets() + + config = LLaMAConfig.from_name("7B") + config.block_size = block_size + config.vocab_size = 100 # from prepare_shakespeare.py + + with fabric.device: + model = LLaMA(config) + + # if compile: + # model = torch.compile(model) + + model = fabric.setup_module(model) + + optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2), foreach=False) + optimizer = fabric.setup_optimizers(optimizer) + + train(fabric, model, optimizer, train_data, val_data) + + +def train( + fabric: L.Fabric, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + train_data: np.ndarray, + val_data: np.ndarray, +) -> None: + """The training loop. + + Loosely based on the nanoGPT implementation: https://github.com/karpathy/nanoGPT. + """ + + iter_num = 0 + + while True: + # TODO: add learning rate scheduling + + # evaluate the loss on train/val sets and write checkpoints + if iter_num > 0 and iter_num % eval_interval == 0: + val_loss = validate(fabric, model, val_data) + fabric.print(f"step {iter_num}: val loss {val_loss:.4f}") + fabric.print(f"Saving checkpoint to {out_dir}") + save_model_checkpoint(fabric, model, os.path.join(out_dir, f"iter-{iter_num:06d}-ckpt.pth")) + + t0 = time.time() + + input_ids, targets = get_batch( + fabric, + train_data, + block_size=model.config.block_size, # type: ignore[union-attr,arg-type] + ) + logits = model(input_ids) + loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1) + + fabric.backward(loss) + + # TODO: Gradient clipping + # if grad_clip != 0.0: + # fabric.clip_gradients(model, optimizer, max_norm=grad_clip) + + optimizer.step() + optimizer.zero_grad() + + dt = time.time() - t0 + if iter_num % log_interval == 0: + fabric.print(f"iter {iter_num}: loss {loss.item():.4f}, time: {dt*1000:.2f}ms") + iter_num += 1 + + if iter_num > max_iters: + break + + +@torch.no_grad() +def validate(fabric: L.Fabric, model: torch.nn.Module, val_data: np.ndarray) -> torch.Tensor: + fabric.print("Validating ...") + model.eval() + losses = torch.zeros(eval_iters) + for k in range(eval_iters): + input_ids, targets = get_batch( + fabric, + val_data, + block_size=model.config.block_size, # type: ignore[union-attr,arg-type] + ) + logits = model(input_ids) + loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1) + losses[k] = loss.item() + out = losses.mean() + model.train() + return out + + +def get_batch(fabric: L.Fabric, data: np.ndarray, block_size: int) -> Tuple[torch.Tensor, torch.Tensor]: + ix = torch.randint(len(data) - block_size, (batch_size,)) + x = torch.stack([torch.from_numpy((data[i : i + block_size]).astype(np.int64)) for i in ix]) + y = torch.stack([torch.from_numpy((data[i + 1 : i + 1 + block_size]).astype(np.int64)) for i in ix]) + x, y = fabric.to_device((x.pin_memory(), y.pin_memory())) + return x, y + + +def load_datasets(data_dir: str = "data/shakespeare") -> Tuple[np.ndarray, np.ndarray]: + train_data = np.memmap(os.path.join(data_dir, "train.bin"), dtype=np.uint16, mode="r") + val_data = np.memmap(os.path.join(data_dir, "val.bin"), dtype=np.uint16, mode="r") + return train_data, val_data + + +if __name__ == "__main__": + torch.set_float32_matmul_precision("high") + main() diff --git a/lit-llama/quantize/gptq.py b/lit-llama/quantize/gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..3d646ff04d260f754690e73d280670f077b97d03 --- /dev/null +++ b/lit-llama/quantize/gptq.py @@ -0,0 +1,238 @@ +# This adapts GPTQ's quantization process: https://github.com/IST-DASLab/gptq/ +# E. Frantar et al GPTQ: Accurate Post-training Compression for GPT, arXiv:2210.17323 +# portions copyright by the authors licensed under the Apache License 2.0 +import gc +import sys +import time +from pathlib import Path +from typing import Optional + +import torch +from datasets import load_dataset + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +from lit_llama import LLaMA, Tokenizer +from lit_llama.quantization import GPTQQuantizer +from lit_llama.utils import EmptyInitOnDevice, llama_model_lookup + + +def get_sample_data(): + traindata = load_dataset( + "allenai/c4", + "allenai--c4", + data_files={"train": "en/c4-train.00000-of-01024.json.gz"}, + split="train", + ) + # heuristic for the data size? + txt = "\n".join( + traindata[i]["text"] for i in torch.randperm(len(traindata))[:1000].tolist() + ) + return txt + + +@torch.no_grad() +def llama_blockwise_quantization( + model, sample_inputs, working_device, *, bits=4, groupsize=-1 +): + """ + This is the classic post-training quantization of all linear layers. + We quantize in order, i.e. when observing the inputs, we use the outputs of the previously quantized layers rather + than doing them all at once. + """ + print(model) + print(model.config) + + print("Getting inputs for first block") + model.transformer.wte.to(working_device) + sample_inputs = sample_inputs.to(working_device) + inps = model.transformer.wte(sample_inputs) + model.transformer.wte.to("cpu") + torch.cuda.empty_cache() + + rope_cache = model.build_rope_cache(sample_inputs) + mask_cache = model.build_mask_cache(sample_inputs) + + print("Starting to quantize blocks") + outs = torch.zeros_like(inps) + + # better than relying on enumeration? originally the code bundled + # the two mlp fc layers + # we could automate this with a lot of hooks and another iteration + submodules_to_process = [ + "attn.c_attn", + "attn.c_proj", + "mlp.c_fc1", + "mlp.c_fc2", + "mlp.c_proj", + ] + + for i, block in enumerate(model.transformer.h): + block.to(working_device) + + for name in submodules_to_process: + print(i, name, end=" ") + t0 = time.perf_counter() + print("collecting stats", end=" ") + sys.stdout.flush() + module = block.get_submodule(name) + + gptq = GPTQQuantizer( + module, + bits=bits, + groupsize=groupsize, + actorder=(groupsize == -1), + ) + handle = module.register_forward_hook(gptq.collect_input_stats) + for j in range(inps.size(0)): + outs[j : j + 1], _ = block( + inps[j : j + 1], + rope=rope_cache, + mask=mask_cache, + max_seq_length=model.config.block_size + ) + + handle.remove() + + print("quantizing", end=" ") + sys.stdout.flush() + q_module, error = gptq.quantize() + + # replace the linear module with the quantized module + pname, dname = name.rsplit(".", 1) + setattr(block.get_submodule(pname), dname, q_module) + + # cleanup in an attempt to not run out of memory + del gptq + gc.collect() + torch.cuda.empty_cache() + t1 = time.perf_counter() + print(f"time {int(t1 - t0 + 0.5)}s quantization error {error:.1f}") + + for j in range(inps.size(0)): + outs[j : j + 1], _ = block( + inps[j : j + 1], + rope=rope_cache, + mask=mask_cache, + max_seq_length=model.config.block_size + ) + + block.cpu() + gc.collect() + torch.cuda.empty_cache() + + # the outputs are the next block's inputs and we'll reuse the old inputs + inps, outs = outs, inps + + model.transformer.ln_f.to(working_device) + for j in range(inps.size(0)): + outs[j : j + 1] = model.transformer.ln_f(inps[j : j + 1]) + model.transformer.ln_f.to("cpu") + inps, outs = outs, inps + + model.lm_head.to(working_device) + gptq = GPTQQuantizer( + model.lm_head, + bits=bits, + groupsize=groupsize, + actorder=(groupsize == -1), + ) + handle = model.lm_head.register_forward_hook(gptq.collect_input_stats) + for j in range(inps.size(0)): + model.lm_head(inps[j : j + 1]) + handle.remove() + q_module, error = gptq.quantize() + model.lm_head = q_module + model.lm_head.to("cpu") + + +def main( + *, + checkpoint_path: Path = Path("checkpoints/lit-llama/7B/lit-llama.pth"), + output_path: Optional[Path] = None, + tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"), + n_samples: int = 128, + dtype: str = "float32", + quantize: Optional[str] = None, +) -> None: + """Generates text samples based on a pre-trained LLaMA model and tokenizer. + + Args: + checkpoint_path: The checkpoint path to load. + output_path: Path to write the quantized model's state dict to. + tokenizer_path: The tokenizer path to load. + n_samples: Number of example inputs to use for statistics (default: 128) + dtype: The dtype to use to load the model. + quantize: Mode to quantize the model to: + ``"gptq.int4"``: GPTQ 4-bit mode. + Note that ``"llm.int8"```does not need a quantization step. + """ + assert checkpoint_path.is_file() + assert tokenizer_path.is_file() + if output_path is None: + output_path = checkpoint_path.parent / "llama-gptq.4bit.pth" + assert output_path.parent.is_dir() and (not output_path.exists() or output_path.is_file()) + + device = "cuda" + + dt = getattr(torch, dtype, None) + if not isinstance(dt, torch.dtype): + raise ValueError(f"{dtype} is not a valid dtype.") + dtype = dt + + if quantize == "gptq.int4": + bits = 4 + elif quantize == "gptq.int8": + bits = 8 + else: + raise RuntimeError(f"unknown/unsupported quantization mode {quantize}") + + # we avoid loading the entire model on the GPU and do this block by block + with EmptyInitOnDevice( + device="cpu", + dtype=dtype, + ): + print("Loading model ...", file=sys.stderr) + t0 = time.time() + checkpoint = torch.load(checkpoint_path) + name = llama_model_lookup(checkpoint) + model = LLaMA.from_name(name) + model.load_state_dict(checkpoint) + print(f"Time to load model: {time.time() - t0:.02f} seconds.", file=sys.stderr) + + model.eval() + + tokenizer = Tokenizer(tokenizer_path) + + test_string = get_sample_data() + encoded_text = tokenizer.encode( + test_string, + bos=True, + eos=False, + ) + block_size = 2048 # this is for compat with gptq, and indeed we get much worse beyond this (https://github.com/facebookresearch/llama/blob/57b0eb62de0636e75af471e49e2f1862d908d9d8/llama/model.py#L30) + encoded_text = encoded_text[: n_samples * block_size].reshape(n_samples, block_size) + + t0 = time.perf_counter() + llama_blockwise_quantization(model, encoded_text, device, bits=bits) + t = time.perf_counter() - t0 + + print( + f"\n\nTime for quantization: {t:.02f} sec total", + file=sys.stderr, + ) + print( + f"Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB", + file=sys.stderr, + ) + + torch.save(model.state_dict(), output_path) + + +if __name__ == "__main__": + from jsonargparse import CLI + + torch.set_float32_matmul_precision("high") + CLI(main) diff --git a/lit-llama/requirements.txt b/lit-llama/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8706b998430472e53186da1d281d11e6e755589 --- /dev/null +++ b/lit-llama/requirements.txt @@ -0,0 +1,9 @@ +torch>=2.0.0 +lightning @ git+https://github.com/Lightning-AI/lightning@master +sentencepiece +tqdm # convert_checkpoint.py +numpy # train.py dataset memmap +jsonargparse[signatures] # generate.py, convert_checkpoint.py CLI +bitsandbytes # quantization.py +datasets # evaluate.py +zstandard # prepare_redpajama.py diff --git a/lit-llama/scripts/convert_checkpoint.py b/lit-llama/scripts/convert_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..a7cd157f276f6602a44bbecb9e7c2f126c622102 --- /dev/null +++ b/lit-llama/scripts/convert_checkpoint.py @@ -0,0 +1,141 @@ +import gc +import shutil +from pathlib import Path +from typing import Dict + +import torch +from tqdm import tqdm + +""" +Sample usage: + +```bash +python -m scripts.convert_checkpoint -h + +python -m scripts.convert_checkpoint converted +``` +""" + + +def convert_state_dict(state_dict: Dict[str, torch.Tensor], dtype: torch.dtype = torch.float32) -> Dict[str, torch.Tensor]: + converted = {} + converted["transformer.wte.weight"] = state_dict["tok_embeddings.weight"].to(dtype) + converted["lm_head.weight"] = state_dict["output.weight"].to(dtype) + converted["transformer.ln_f.scale"] = state_dict["norm.weight"].to(dtype) + + for layer_idx in sorted(set([k.split(".")[1] for k in state_dict if k.startswith("layers")])): + # attention + # the wq, wk, wv from the FB model are stacked in our model as c_attn + converted[f"transformer.h.{layer_idx}.attn.c_attn.weight"] = torch.cat( + ( + state_dict[f"layers.{layer_idx}.attention.wq.weight"].to(dtype), + state_dict[f"layers.{layer_idx}.attention.wk.weight"].to(dtype), + state_dict[f"layers.{layer_idx}.attention.wv.weight"].to(dtype), + ) + ) + converted[f"transformer.h.{layer_idx}.attn.c_proj.weight"] = state_dict[ + f"layers.{layer_idx}.attention.wo.weight" + ].to(dtype) + # mlp + converted[f"transformer.h.{layer_idx}.mlp.c_fc1.weight"] = state_dict[ + f"layers.{layer_idx}.feed_forward.w1.weight" + ].to(dtype) + converted[f"transformer.h.{layer_idx}.mlp.c_proj.weight"] = state_dict[ + f"layers.{layer_idx}.feed_forward.w2.weight" + ].to(dtype) + converted[f"transformer.h.{layer_idx}.mlp.c_fc2.weight"] = state_dict[ + f"layers.{layer_idx}.feed_forward.w3.weight" + ].to(dtype) + # rms norm + converted[f"transformer.h.{layer_idx}.rms_1.scale"] = state_dict[f"layers.{layer_idx}.attention_norm.weight"].to(dtype) + converted[f"transformer.h.{layer_idx}.rms_2.scale"] = state_dict[f"layers.{layer_idx}.ffn_norm.weight"].to(dtype) + return converted + + +shard_dims = { + "lm_head.weight": 0, + "wte.weight": 1, + "attn.c_attn.weight": 0, + "attn.c_proj.weight": 1, + "mlp.c_fc1.weight": 0, + "mlp.c_fc2.weight": 0, + "mlp.c_proj.weight": 1 +} + + +def meta_weights_for_nano_model( + *, + output_dir: Path = Path("checkpoints/lit-llama"), + checkpoint_dir: Path = Path("checkpoints/llama/"), + model_size: str = "7B", + dtype: str = "float32", +) -> None: + output_dir = output_dir / model_size + checkpoint_dir = checkpoint_dir / model_size + output_dir.mkdir(parents=True, exist_ok=True) + + # the tokenizer is the same for all model sizes, so we store it in the parent dir + shutil.copy(checkpoint_dir.parent / "tokenizer.model", output_dir.parent) + + dt = getattr(torch, dtype, None) + if not isinstance(dt, torch.dtype): + raise ValueError(f"{dtype} is not a valid dtype.") + dtype = dt + + checkpoint_files = sorted(checkpoint_dir.glob("*.pth")) + checkpoint_files.sort() + n_checkpoints = len(checkpoint_files) + + if n_checkpoints == 0: + raise RuntimeError(f"No checkpoints were found at checkpoint_dir {checkpoint_dir}. `consolidated.0*.pth` files expected at that location.") + + # for the bigger models, there are multiple model-parallel checkpoints + # and we combine them into one single file + combined = None + for file in tqdm(checkpoint_files, total=n_checkpoints): + checkpoint = torch.load(file, map_location="cpu") + converted = convert_state_dict(checkpoint, dtype=dtype) + if combined is None: + combined = converted + continue + for name, param in converted.items(): + dim = None + for k, d in shard_dims.items(): + if k in name: + dim = d + break + if dim is None: + # Extra check: assert that tensors are the same if not sharded + # assert torch.allclose(combined[name], param) + continue + combined[name] = torch.cat((combined[name], param), dim=dim) + + del checkpoint + del converted + gc.collect() + + for name, param in combined.items(): + if "c_attn" not in name: + continue + + # Turn [Q1, K1, V1, Q2, K2, V2, ...] into [Q1, Q2, ..., K1, K2, .., V1, V2, ...] + + src_chunk_len = param.shape[0] // n_checkpoints + mat_len = src_chunk_len // 3 + dst_chunk_len = mat_len * n_checkpoints + attn = torch.clone(param) + for i in range(n_checkpoints): + for j in range(3): + param[j * dst_chunk_len + i * mat_len: j * dst_chunk_len + (i+1) * mat_len] = \ + attn[i * src_chunk_len + j * mat_len: i * src_chunk_len + (j+1) * mat_len] + + del attn + gc.collect() + + torch.save(combined, output_dir / "lit-llama.pth") + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(meta_weights_for_nano_model) diff --git a/lit-llama/scripts/convert_hf_checkpoint.py b/lit-llama/scripts/convert_hf_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..5b262e5e1fc20dbfd5e06ee1828373d4b761f662 --- /dev/null +++ b/lit-llama/scripts/convert_hf_checkpoint.py @@ -0,0 +1,167 @@ +import collections +import contextlib +import gc +import json +import shutil +import sys +from pathlib import Path + +import torch + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +from lit_llama.model import LLaMA, LLaMAConfig +from lit_llama.utils import EmptyInitOnDevice, lazy_load, incremental_save + + +@torch.no_grad() +def convert_hf_checkpoint( + *, + output_dir: Path = Path("checkpoints/lit-llama/7B"), + checkpoint_dir: Path = Path("checkpoints/hf-llama/7B"), + model_size: str = "7B", + dtype: str = "float32", + verify: bool = False, +) -> None: + """ + Perform the reverse operation of: https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py + """ + output_dir.mkdir(parents=True, exist_ok=True) + + # the tokenizer is the same for all model sizes, so we store it in the parent dir + shutil.copy(checkpoint_dir / "tokenizer.model", output_dir.parent) + + dt = getattr(torch, dtype, None) + if not isinstance(dt, torch.dtype): + raise ValueError(f"{dtype} is not a valid dtype.") + dtype = dt + + print("Initializing lit-llama") + config = LLaMAConfig.from_name(model_size) + + with EmptyInitOnDevice(device="meta", dtype=dtype): + model = LLaMA(config) + + qkv_size = model.transformer.h[0].attn.c_attn.weight.shape[0] // 3 + + # initialize a new empty state dict to hold our new weights + sd_meta = model.state_dict() + sd = {} + + # Load the json file containing weight mapping + pytorch_bin_map_json_path = checkpoint_dir / "pytorch_model.bin.index.json" + with open(pytorch_bin_map_json_path) as json_map: + bin_index = json.load(json_map) + bin_files = set(checkpoint_dir / bin for bin in bin_index["weight_map"].values()) + if not bin_files: + raise ValueError(f"Expected {str(checkpoint_dir)!r} to contain .bin files") + + def permute(w): + dim = config.n_embd + w = w._load_tensor().to(dtype) + return ( + w.view(config.n_head, 2, dim // config.n_head // 2, dim) + .transpose(1, 2) + .reshape(dim, dim) + ) + + weight_map = { + "self_attn.o_proj.weight": "attn.c_proj.weight", + "self_attn.q_proj.weight": "attn.c_attn.weight", + "self_attn.k_proj.weight": "attn.c_attn.weight", + "self_attn.v_proj.weight": "attn.c_attn.weight", + "mlp.gate_proj.weight": "mlp.c_fc1.weight", + "mlp.up_proj.weight": "mlp.c_fc2.weight", + "mlp.down_proj.weight": "mlp.c_proj.weight", + "input_layernorm.weight": "rms_1.scale", + "post_attention_layernorm.weight": "rms_2.scale", + "model.embed_tokens.weight": "transformer.wte.weight", + "model.norm.weight": "transformer.ln_f.scale", + "lm_head.weight": "lm_head.weight", + } + + print(f"Saving to disk at {output_dir}") + unprocessed_weights = collections.defaultdict(dict) + + with incremental_save(output_dir / "lit-llama.pth") as saver: + # for checkpoints that split the QKV across several files, we need to keep all the bin files + # open, so we use `ExitStack` to close them all together at the end + with contextlib.ExitStack() as stack: + for bin_file in bin_files: + print("Processing", bin_file) + hf_weights = stack.enter_context(lazy_load(bin_file)) + for name, param in hf_weights.items(): + skip = False + if "rotary_emb.inv_freq" in name: + continue + if "model.layers" in name: + block_id = int(name.split(".")[2]) + from_name = ".".join(name.split(".")[3:]) + to_name = weight_map[from_name] + sd_key = f"transformer.h.{block_id}.{to_name}" + + if "q_proj" in name: + unprocessed_weights[sd_key]["q_proj"] = param + skip = True + elif "k_proj" in name: + unprocessed_weights[sd_key]["k_proj"] = param + skip = True + elif "v_proj" in name: + unprocessed_weights[sd_key]["v_proj"] = param + skip = True + if skip and len(unprocessed_weights[sd_key]) == 3: + w = torch.empty( + sd_meta[sd_key].shape, dtype=sd_meta[sd_key].dtype + ) + w[:qkv_size] = permute(unprocessed_weights[sd_key]["q_proj"]) + w[qkv_size:-qkv_size] = permute( + unprocessed_weights[sd_key]["k_proj"] + ) + w[-qkv_size:] = ( + unprocessed_weights[sd_key]["v_proj"] + ._load_tensor() + .to(dtype) + ) + sd[sd_key] = w + del unprocessed_weights[sd_key] + skip = False + else: + sd[sd_key] = param._load_tensor().to(dtype) + else: + sd_key = weight_map[name] + sd[sd_key] = param._load_tensor().to(dtype) + if not skip: + sd[sd_key] = saver.store_early(sd[sd_key]) + gc.collect() + saver.save(sd) + + assert len(unprocessed_weights) == 0, f"unexpected partial weights {list(unprocessed_weights)}" + if verify: + try: + from transformers import LlamaForCausalLM + except ImportError: + raise ImportError("verify=True requires transformers to be installed, please `pip install transformers`") + print("Verifying...") + + token_sample = torch.randint(0, config.vocab_size, size=(1, config.block_size), dtype=torch.int64) + out = model(token_sample) + del model + gc.collect() + + print("Loading original model for comparison") + model_hf = LlamaForCausalLM.from_pretrained(checkpoint_dir) + out_hf = model_hf(token_sample)["logits"] + + print("Comparing outputs") + assert out.device.type == out_hf.device.type + assert out.dtype == out_hf.dtype + assert torch.testing.assert_close(out, out_hf) + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(convert_hf_checkpoint) + diff --git a/lit-llama/scripts/convert_lora_weights.py b/lit-llama/scripts/convert_lora_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..ad6071e8785973b5ec3d52170fff428355c5cccc --- /dev/null +++ b/lit-llama/scripts/convert_lora_weights.py @@ -0,0 +1,95 @@ +import sys +import time +from pathlib import Path +from typing import Optional + +import lightning as L +import torch +import torch.nn as nn + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +from lit_llama import LLaMA +from lit_llama.utils import EmptyInitOnDevice, lazy_load, llama_model_lookup +from lit_llama.lora import lora + +def del_lora_state_dict(model: nn.Module): + base_model_dict = model.state_dict() + key_to_delete = [k for k in base_model_dict if "lora_" in k] + for del_key in key_to_delete: + del base_model_dict[del_key] + return base_model_dict + + +def lora_model_lookup(checkpoint: dict) -> int: + """Returns the LoRA rank from the adapter checkpoint. + + """ + return checkpoint["transformer.h.0.attn.c_attn.lora_B"].shape[1] + + +def main( + accelerator: str = "auto", + lora_path: Optional[Path] = None, + checkpoint_path: Optional[Path] = None, + dtype: str = "bfloat16", +) -> None: + """Merges lora weights to base model. + + Args: + accelerator: The hardware to run on. Possible choices are: + ``"cpu"``, ``"cuda"``, ``"mps"``, ``"gpu"``, ``"tpu"``, ``"auto"``. + lora_path: Path to the checkpoint with trained LoRA weights, which are the output of + `finetune_lora.py`. + checkpoint_path: The checkpoint path to load. + dtype: `torch.dtype` to work with + """ + if not lora_path: + lora_path = Path("out/lora/alpaca/lit-llama-lora-finetuned.pth") + if not checkpoint_path: + checkpoint_path = Path(f"./checkpoints/lit-llama/7B/lit-llama.pth") + + assert lora_path.is_file() + assert checkpoint_path.is_file() + + fabric = L.Fabric(accelerator=accelerator, devices=1) + + dt = getattr(torch, dtype, None) + if not isinstance(dt, torch.dtype): + raise ValueError(f"{dtype} is not a valid dtype.") + dtype = dt + + print("Loading model ...", file=sys.stderr) + t0 = time.time() + + with (lazy_load(checkpoint_path) as pretrained_checkpoint, + lazy_load(lora_path) as lora_checkpoint): + name = llama_model_lookup(pretrained_checkpoint) + rank = lora_model_lookup(lora_checkpoint) + + with EmptyInitOnDevice( + device=fabric.device, dtype=dtype + ), lora(r=rank, alpha=16, dropout=0.05, enabled=True): + model = LLaMA.from_name(name) + + # 1. Load the pretrained weights + model.load_state_dict(pretrained_checkpoint, strict=False) + # 2. Load the fine-tuned lora weights + model.load_state_dict(lora_checkpoint, strict=False) + + print(f"Time to load model: {time.time() - t0:.02f} seconds.", file=sys.stderr) + + model.eval() + base_model_dict = del_lora_state_dict(model) + save_path = lora_path.with_stem(f"{lora_path.stem}-lora-merged-weights") + print("Saving LoRA to base model weights ...") + torch.save(base_model_dict, save_path) + print(f"Model saved at {save_path}") + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(main) \ No newline at end of file diff --git a/lit-llama/scripts/download.py b/lit-llama/scripts/download.py new file mode 100644 index 0000000000000000000000000000000000000000..bd9eb9e3f12d45812c8601e87387f30c17344d43 --- /dev/null +++ b/lit-llama/scripts/download.py @@ -0,0 +1,34 @@ +import os +from typing import Optional +from urllib.request import urlretrieve + +files = { + "original_model.py": "https://gist.githubusercontent.com/lantiga/fd36849fb1c498da949a0af635318a7b/raw/7dd20f51c2a1ff2886387f0e25c1750a485a08e1/llama_model.py", + "original_adapter.py": "https://gist.githubusercontent.com/awaelchli/546f33fcdb84cc9f1b661ca1ca18418d/raw/e81d8f35fb1fec53af1099349b0c455fc8c9fb01/original_adapter.py", +} + + +def download_original(wd: str) -> None: + for file, url in files.items(): + filepath = os.path.join(wd, file) + if not os.path.isfile(filepath): + print(f"Downloading original implementation to {filepath!r}") + urlretrieve(url=url, filename=file) + print("Done") + else: + print("Original implementation found. Skipping download.") + + +def download_from_hub(repo_id: Optional[str] = None, local_dir: str = "checkpoints/hf-llama/7B") -> None: + if repo_id is None: + raise ValueError("Please pass `--repo_id=...`. You can try googling 'huggingface hub llama' for options.") + + from huggingface_hub import snapshot_download + + snapshot_download(repo_id, local_dir=local_dir, local_dir_use_symlinks=False) + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(download_from_hub) diff --git a/lit-llama/scripts/prepare_alpaca.py b/lit-llama/scripts/prepare_alpaca.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7f78f197c67e9ca20a17a93b52d50f05d7ff46 --- /dev/null +++ b/lit-llama/scripts/prepare_alpaca.py @@ -0,0 +1,131 @@ +"""Implementation derived from https://github.com/tloen/alpaca-lora""" +import sys +from pathlib import Path + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +import torch +import requests +import json +from torch.utils.data import random_split +from lit_llama.tokenizer import Tokenizer +from tqdm import tqdm + + +DATA_FILE = "https://raw.githubusercontent.com/tloen/alpaca-lora/main/alpaca_data_cleaned_archive.json" +DATA_FILE_NAME = "alpaca_data_cleaned_archive.json" +IGNORE_INDEX = -1 + + +def prepare( + destination_path: Path = Path("data/alpaca"), + tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"), + test_split_size: int = 2000, + max_seq_length: int = 256, + seed: int = 42, + mask_inputs: bool = False, # as in alpaca-lora + data_file_name: str = DATA_FILE_NAME +) -> None: + """Prepare the Alpaca dataset for instruction tuning. + + The output is a training and validation dataset saved as `train.pt` and `val.pt`, + which stores the preprocessed and tokenized prompts and labels. + """ + + destination_path.mkdir(parents=True, exist_ok=True) + file_path = destination_path / data_file_name + download(file_path) + + # TODO: If we don't have the Meta weights, where do we get the tokenizer from? + tokenizer = Tokenizer(tokenizer_path) + + with open(file_path, "r") as file: + data = json.load(file) + + # Partition the dataset into train and test + train_split_size = len(data) - test_split_size + train_set, test_set = random_split( + data, + lengths=(train_split_size, test_split_size), + generator=torch.Generator().manual_seed(seed), + ) + train_set, test_set = list(train_set), list(test_set) + + print(f"train has {len(train_set):,} samples") + print(f"val has {len(test_set):,} samples") + + print("Processing train split ...") + train_set = [prepare_sample(sample, tokenizer, max_seq_length, mask_inputs) for sample in tqdm(train_set)] + torch.save(train_set, file_path.parent / "train.pt") + + print("Processing test split ...") + test_set = [prepare_sample(sample, tokenizer, max_seq_length, mask_inputs) for sample in tqdm(test_set)] + torch.save(test_set, file_path.parent / "test.pt") + + +def download(file_path: Path): + """Downloads the raw json data file and saves it in the given destination.""" + if file_path.exists(): + return + with open(file_path, "w") as f: + f.write(requests.get(DATA_FILE).text) + + +def prepare_sample(example: dict, tokenizer: Tokenizer, max_length: int, mask_inputs: bool = True): + """Processes a single sample. + + Each sample in the dataset consists of: + - instruction: A string describing the task + - input: A string holding a special input value for the instruction. + This only applies to some samples, and in others this is empty. + - output: The response string + + This function processes this data to produce a prompt text and a label for + supervised training. The input text is formed as a single message including all + the instruction, the input (optional) and the response. + The label/target is the same message but can optionally have the instruction + input text + masked out (mask_inputs=True). + + Finally, both the prompt and the label get tokenized. If desired, all tokens + in the label that correspond to the original input prompt get masked out (default). + """ + full_prompt = generate_prompt(example) + full_prompt_and_response = full_prompt + example["output"] + encoded_full_prompt = tokenize(tokenizer, full_prompt, max_length=max_length, eos=False) + encoded_full_prompt_and_response = tokenize(tokenizer, full_prompt_and_response, eos=True, max_length=max_length) + + # The labels are the full prompt with response, but with the prompt masked out + labels = encoded_full_prompt_and_response.clone() + if mask_inputs: + labels[:len(encoded_full_prompt)] = IGNORE_INDEX + + return {**example, "input_ids": encoded_full_prompt_and_response, "input_ids_no_response": encoded_full_prompt, "labels": labels} + + +def tokenize(tokenizer: Tokenizer, string: str, max_length: int, eos=True) -> torch.Tensor: + return tokenizer.encode(string, bos=True, eos=eos, max_length=max_length) + + +def generate_prompt(example): + """Generates a standardized message to prompt the model with an instruction, optional input and a + 'response' field.""" + + if example["input"]: + return ( + "Below is an instruction that describes a task, paired with an input that provides further context. " + "Write a response that appropriately completes the request.\n\n" + f"### Instruction:\n{example['instruction']}\n\n### Input:\n{example['input']}\n\n### Response:" + ) + return ( + "Below is an instruction that describes a task. " + "Write a response that appropriately completes the request.\n\n" + f"### Instruction:\n{example['instruction']}\n\n### Response:" + ) + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(prepare) diff --git a/lit-llama/scripts/prepare_any_text.py b/lit-llama/scripts/prepare_any_text.py new file mode 100644 index 0000000000000000000000000000000000000000..9377da6a063c3544e6d163c158a06311aea111cf --- /dev/null +++ b/lit-llama/scripts/prepare_any_text.py @@ -0,0 +1,97 @@ +"""Implementation derived from https://github.com/tloen/alpaca-lora""" +import sys +from pathlib import Path + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +import torch +import requests +import json +from torch.utils.data import random_split +from lit_llama.tokenizer import Tokenizer +from tqdm import tqdm + + +IGNORE_INDEX = -1 + +DATA_FILE_NAME = "input.txt" + + +def prepare( + destination_path: Path = Path("data/any"), + tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"), + test_split_ratio: float = 0.9, # default 90% train, 10% validation + max_seq_length: int = 256, + seed: int = 42, + data_file_name: str = DATA_FILE_NAME, +) -> None: + """Prepare any dataset for finetuning (akin to Shakespheare full tuning). + + The output is a training and validation dataset saved as `train.pt` and `val.pt`, + which stores the preprocessed and tokenized prompts and labels. + """ + + destination_path.mkdir(parents=True, exist_ok=True) + file_path = destination_path / data_file_name + if not file_path.exists(): + raise AssertionError(f"{data_file_name} is provided by the user") + + # TODO: If we don't have the Meta weights, where do we get the tokenizer from? + tokenizer = Tokenizer(tokenizer_path) + + data = [] + + with open(file_path, "r") as input_file: + for line in input_file.readlines(): + data.append(line) + + # Partition the dataset into train and test + train_split_size = int(len(data) * test_split_ratio) + test_split_size = len(data) - train_split_size + train_set, test_set = random_split( + data, + lengths=(train_split_size, test_split_size), + generator=torch.Generator().manual_seed(seed), + ) + train_set, test_set = list(train_set), list(test_set) + + print(f"train has {len(train_set):,} samples") + print(f"val has {len(test_set):,} samples") + + print("Processing train split ...") + train_set = [ + prepare_line(line, tokenizer, max_seq_length) for line in tqdm(train_set) + ] + torch.save(train_set, file_path.parent / "train.pt") + + print("Processing test split ...") + test_set = [ + prepare_line(line, tokenizer, max_seq_length) for line in tqdm(test_set) + ] + torch.save(test_set, file_path.parent / "test.pt") + + +def prepare_line(line: str, tokenizer: Tokenizer, max_length: int): + """Processes a single sample. + + This function processes the line to produce the tokenized version of it. + """ + encoded_full_prompt = tokenize(tokenizer, line, max_length=max_length, eos=False) + return { + "input_ids": encoded_full_prompt, + "labels": encoded_full_prompt, + } + + +def tokenize( + tokenizer: Tokenizer, string: str, max_length: int, eos=True +) -> torch.Tensor: + return tokenizer.encode(string, bos=True, eos=eos, max_length=max_length) + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(prepare) diff --git a/lit-llama/scripts/prepare_dolly.py b/lit-llama/scripts/prepare_dolly.py new file mode 100644 index 0000000000000000000000000000000000000000..a40fa8ddc11aab95490107e419ed21603e3e2d9e --- /dev/null +++ b/lit-llama/scripts/prepare_dolly.py @@ -0,0 +1,133 @@ +"""Implementation derived from https://github.com/tloen/alpaca-lora""" +import sys +from pathlib import Path + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +import torch +import requests +import json +from torch.utils.data import random_split +from lit_llama.tokenizer import Tokenizer +from tqdm import tqdm + + +DATA_FILE = "https://huggingface.co/datasets/databricks/databricks-dolly-15k/resolve/main/databricks-dolly-15k.jsonl" +DATA_FILE_NAME = "dolly_data_cleaned.json" +IGNORE_INDEX = -1 + + +def prepare( + destination_path: Path = Path("data/dolly"), + tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"), + test_split_size: int = 2000, + max_seq_length: int = 1024, + seed: int = 42, + mask_inputs: bool = False, # as in alpaca-lora +) -> None: + """Prepare the Dolly dataset for instruction tuning. + + The output is a training and validation dataset saved as `train.pt` and `val.pt`, + which stores the preprocessed and tokenized prompts and labels. + """ + + destination_path.mkdir(parents=True, exist_ok=True) + file_path = destination_path / DATA_FILE_NAME + download(file_path) + + # TODO: If we don't have the Meta weights, where do we get the tokenizer from? + tokenizer = Tokenizer(tokenizer_path) + + with open(file_path, "r") as file: + data = file.readlines() + data = [json.loads(line) for line in data] + for item in data: + item["input"] = item.pop("context") + item["output"] = item.pop("response") + + # Partition the dataset into train and test + train_split_size = len(data) - test_split_size + train_set, test_set = random_split( + data, + lengths=(train_split_size, test_split_size), + generator=torch.Generator().manual_seed(seed), + ) + train_set, test_set = list(train_set), list(test_set) + + print(f"train has {len(train_set):,} samples") + print(f"val has {len(test_set):,} samples") + + print("Processing train split ...") + train_set = [prepare_sample(sample, tokenizer, max_seq_length, mask_inputs) for sample in tqdm(train_set)] + torch.save(train_set, file_path.parent / "train.pt") + + print("Processing test split ...") + test_set = [prepare_sample(sample, tokenizer, max_seq_length, mask_inputs) for sample in tqdm(test_set)] + torch.save(test_set, file_path.parent / "test.pt") + + +def download(file_path: Path): + """Downloads the raw json data file and saves it in the given destination.""" + if file_path.exists(): + return + with open(file_path, "w") as f: + f.write(requests.get(DATA_FILE).text) + + +def prepare_sample(example: dict, tokenizer: Tokenizer, max_length: int, mask_inputs: bool = True): + """Processes a single sample. + + Each sample in the dataset consists of: + - instruction: A string describing the task + - input: A string holding a special input value for the instruction. + This only applies to some samples, and in others this is empty. + - output: The response string + + This function processes this data to produce a prompt text and a label for + supervised training. The prompt text is formed as a single message including both + the instruction and the input. The label/target is the same message but with the + response attached. + + Finally, both the prompt and the label get tokenized. If desired, all tokens + in the label that correspond to the original input prompt get masked out (default). + """ + full_prompt = generate_prompt(example) + full_prompt_and_response = full_prompt + example["output"] + encoded_full_prompt = tokenize(tokenizer, full_prompt, max_length=max_length, eos=False) + encoded_full_prompt_and_response = tokenize(tokenizer, full_prompt_and_response, eos=True, max_length=max_length) + + # The labels are the full prompt with response, but with the prompt masked out + labels = encoded_full_prompt_and_response.clone() + if mask_inputs: + labels[:len(encoded_full_prompt)] = IGNORE_INDEX + + return {**example, "input_ids": encoded_full_prompt_and_response, "input_ids_no_response": encoded_full_prompt, "labels": labels} + + +def tokenize(tokenizer: Tokenizer, string: str, max_length: int, eos=True) -> torch.Tensor: + return tokenizer.encode(string, bos=True, eos=eos, max_length=max_length) + + +def generate_prompt(example): + """Generates a standardized message to prompt the model with an instruction, optional input and a + 'response' field.""" + + if example["input"]: + return ( + f"Below is an instruction that describes a task, paired with an input that provides further context. " + "Write a response that appropriately completes the request.\n\n" + f"### Instruction:\n{example['instruction']}\n\n### Input:\n{example['input']}\n\n### Response:" + ) + return ( + f"Below is an instruction that describes a task. " + "Write a response that appropriately completes the request.\n\n" + f"### Instruction:\n{example['instruction']}\n\n### Response:" + ) + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(prepare) diff --git a/lit-llama/scripts/prepare_redpajama.py b/lit-llama/scripts/prepare_redpajama.py new file mode 100644 index 0000000000000000000000000000000000000000..8da1c1b4e5525e43268e2c2b0c59be99109894ed --- /dev/null +++ b/lit-llama/scripts/prepare_redpajama.py @@ -0,0 +1,181 @@ +import json +import glob +import os +from pathlib import Path +import sys + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +import numpy as np +from tqdm import tqdm + +from lit_llama import Tokenizer +import lit_llama.packed_dataset as packed_dataset + + +filenames_sample = [ + "arxiv_sample.jsonl", + "book_sample.jsonl", + "c4_sample.jsonl", + "cc_2019-30_sample.jsonl", + "cc_2020-05_sample.jsonl", + "cc_2021-04_sample.jsonl", + "cc_2022-05_sample.jsonl", + "cc_2023-06_sample.jsonl", + "github_sample.jsonl", + "stackexchange_sample.jsonl", + "wikipedia_sample.jsonl", +] + +filename_sets = { + "arxiv": "arxiv/arxiv*", + "book": "book/book*", + "c4": "c4/c4-train*", + "common_crawl": "common_crawl/*", + "github": "github/filtered*", + "stackexchange": "stackexchange/stackexchange*", + "wikipedia": "wikipedia/wiki*", +} + + +def prepare_sample( + source_path: Path, + tokenizer_path: Path, + destination_path: Path, + chunk_size: int, + match = "" +) -> None: + """Prepare the "Red Pajama" dataset. We assume tokenizer has been trained (i.e. we reuse LLaMA's tokenizer model).""" + destination_path.mkdir(parents=True, exist_ok=True) + + tokenizer = Tokenizer(tokenizer_path) + + for name in filenames_sample: + if match and match not in name: + continue + + filepath = source_path / name + + if not filepath.is_file(): + raise RuntimeError( + f"Input file not found at {filepath}. \n" + "Make sure you download the data, e.g. wget -i https://data.together.xyz/redpajama-data-1T/v1.0.0/urls.txt or through \n" + "https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T \n" + "https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T-Sample \n" + ) + + prefix, _ = os.path.splitext(name) + + builder = packed_dataset.PackedDatasetBuilder( + outdir=destination_path, + prefix=prefix, + chunk_size=chunk_size, + sep_token=tokenizer.bos_id, + dtype="auto", + vocab_size=tokenizer.vocab_size, + ) + + print(f"Processing {name}") + + with open(filepath, encoding="utf-8") as f: + for row in tqdm(f): + text = json.loads(row)["text"] + text_ids = tokenizer.encode(text) + builder.add_array(np.array(text_ids, dtype=builder.dtype)) + + builder.write_reminder() + + +def prepare_full( + source_path: Path, + tokenizer_path: Path, + destination_path: Path, + chunk_size: int, + match: str = "" +) -> None: + """Prepare the "Red Pajama" dataset. We assume tokenizer has been trained (i.e. we reuse LLaMA's tokenizer model).""" + import zstandard as zstd + + destination_path.mkdir(parents=True, exist_ok=True) + + tokenizer = Tokenizer(tokenizer_path) + + for set_name, pattern in filename_sets.items(): + if match and match not in set_name: + continue + + is_cc = set_name == "common_crawl" + + filenames = glob.glob(os.path.join(source_path, pattern), recursive=True) + + if not filenames: + raise RuntimeError( + f"No files matching {pattern} found at {source_path}. \n" + "Make sure you download the data, e.g. wget -i https://data.together.xyz/redpajama-data-1T/v1.0.0/urls.txt or through \n" + "https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T \n" + "https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T-Sample \n" + ) + + builder = packed_dataset.PackedDatasetBuilder( + outdir=destination_path, + prefix=set_name, + chunk_size=chunk_size, + sep_token=tokenizer.bos_id, + dtype="auto", + vocab_size=tokenizer.vocab_size, + ) + + for name in filenames: + filepath = source_path / name + + print(f"Processing {name}") + + if is_cc: + with zstd.open(open(filepath, "rb"), "rt", encoding="utf-8") as f: + for row in tqdm(f): + text = json.loads(row)["text"] + text_ids = tokenizer.encode(text) + builder.add_array(np.array(text_ids, dtype=builder.dtype)) + else: + with open(filepath, encoding="utf-8") as f: + for row in tqdm(f): + text = json.loads(row)["text"] + text_ids = tokenizer.encode(text) + builder.add_array(np.array(text_ids, dtype=builder.dtype)) + + builder.write_reminder() + + +def prepare( + source_path: Path = Path("data/RedPajama-Data-1T-Sample"), + tokenizer_path: Path = Path("checkpoints/lit-llama/tokenizer.model"), + destination_path: Path = Path("data/red_pajama_sample"), + chunk_size: int = 2049 * 1024, # 2048 block size + 1 for causal (from LLama), 1024 blocks + sample: bool = False, + match: str = "", +) -> None: + """Prepare the "Red Pajama" dataset. We assume tokenizer has been trained (i.e. we reuse LLaMA's tokenizer model).""" + if sample: + prepare_sample( + source_path=source_path, + tokenizer_path=tokenizer_path, + destination_path=destination_path, + chunk_size=chunk_size, + match=match, + ) + else: + prepare_full( + source_path=source_path, + tokenizer_path=tokenizer_path, + destination_path=destination_path, + chunk_size=chunk_size, + match=match, + ) + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(prepare) diff --git a/lit-llama/scripts/prepare_shakespeare.py b/lit-llama/scripts/prepare_shakespeare.py new file mode 100644 index 0000000000000000000000000000000000000000..01a4079e37019bed4221c1a245a764772d1bef4d --- /dev/null +++ b/lit-llama/scripts/prepare_shakespeare.py @@ -0,0 +1,69 @@ +# MIT License + +# Copyright (c) 2022 Andrej Karpathy + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +import sys +from pathlib import Path + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +import numpy as np +import requests + + +def prepare(destination_path: Path = Path("data/shakespeare")) -> None: + """Prepare the "Tiny Shakespeare" dataset.""" + destination_path.mkdir(parents=True, exist_ok=True) + + # download the tiny shakespeare dataset + input_file_path = destination_path / "input.txt" + if not input_file_path.exists(): + data_url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt" + with open(input_file_path, "w") as f: + f.write(requests.get(data_url).text) + + with open(input_file_path) as f: + data = f.read() + n = len(data) + train_data = data[: int(n * 0.9)] + val_data = data[int(n * 0.9) :] + + from lit_llama import Tokenizer + + Tokenizer.train(input=input_file_path, destination=destination_path, vocab_size=100) + tokenizer = Tokenizer(destination_path / "tokenizer.model") + train_ids = tokenizer.encode(train_data) + val_ids = tokenizer.encode(val_data) + print(f"train has {len(train_ids):,} tokens") + print(f"val has {len(val_ids):,} tokens") + + # export to bin files + train_ids = np.array(train_ids, dtype=np.uint16) + val_ids = np.array(val_ids, dtype=np.uint16) + train_ids.tofile(destination_path / "train.bin") + val_ids.tofile(destination_path / "val.bin") + + +if __name__ == "__main__": + from jsonargparse import CLI + + CLI(prepare) diff --git a/lit-llama/setup.py b/lit-llama/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..94f723632e289a4de853f4e87f8d11841ee7f700 --- /dev/null +++ b/lit-llama/setup.py @@ -0,0 +1,26 @@ +import os + +from setuptools import setup, find_packages + + +_PATH_ROOT = os.path.dirname(__file__) + +with open(os.path.join(_PATH_ROOT, "README.md"), encoding="utf-8") as fo: + readme = fo.read() + +setup( + name='lit-llama', + version='0.1.0', + description='Implementation of the LLaMA language model', + author='Lightning AI', + url='https://github.com/lightning-AI/lit-llama', + install_requires=[ + "torch>=2.0.0", + "lightning @ git+https://github.com/Lightning-AI/lightning@master", + "sentencepiece", + "bitsandbytes", + ], + packages=find_packages(), + long_description=readme, + long_description_content_type="text/markdown", +) diff --git a/lit-llama/tests/conftest.py b/lit-llama/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..ab19c77e17e9e5836a114058453ec75dab203864 --- /dev/null +++ b/lit-llama/tests/conftest.py @@ -0,0 +1,42 @@ +import sys +from pathlib import Path + +import pytest + +wd = Path(__file__).parent.parent.absolute() + + +@pytest.fixture() +def orig_llama(): + sys.path.append(str(wd)) + + from scripts.download import download_original + + download_original(wd) + + import original_model + + return original_model + + +@pytest.fixture() +def orig_llama_adapter(): + sys.path.append(str(wd)) + + from scripts.download import download_original + + download_original(wd) + + import original_adapter + + return original_adapter + + +@pytest.fixture() +def lit_llama(): + # this adds support for running tests without the package installed + sys.path.append(str(wd)) + + import lit_llama + + return lit_llama diff --git a/lit-llama/tests/test_adapter.py b/lit-llama/tests/test_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..f61c67667321ad36af708452554a293694a0d0f3 --- /dev/null +++ b/lit-llama/tests/test_adapter.py @@ -0,0 +1,55 @@ +from dataclasses import asdict +import pytest +import sys +import torch + + +@pytest.mark.skipif(sys.platform == "win32", reason="EmptyInitOnDevice on CPU not working for Windows.") +@pytest.mark.parametrize("model_size", ["7B", "13B", "30B", "65B"]) +def test_config_identical(model_size, lit_llama): + import lit_llama.adapter as llama_adapter + import lit_llama.model as llama + from lit_llama.utils import EmptyInitOnDevice + + llama_config = asdict(llama.LLaMAConfig.from_name(model_size)) + adapter_config = asdict(llama_adapter.LLaMAConfig.from_name(model_size)) + + del adapter_config["adapter_prompt_length"] + del adapter_config["adapter_start_layer"] + assert adapter_config == llama_config + + with EmptyInitOnDevice(): + llama_model = llama.LLaMA.from_name(model_size) + adapter_model = llama_adapter.LLaMA.from_name(model_size) + assert llama_model.lm_head.weight.shape == adapter_model.lm_head.weight.shape + + +def test_adapter_load_gating_factor(lit_llama): + """Tests backward-compatible loading of checkpoints after the `gating_factor` was extended per-head + in PR #297. + """ + import lit_llama.adapter as llama_adapter + from lit_llama.utils import lazy_load + + config = llama_adapter.LLaMAConfig(n_head=4, block_size=100, n_embd=16) + attn = llama_adapter.CausalSelfAttention(config=config, block_idx=3) + + # Old checkpoint format + state_dict={ + "gating_factor": torch.tensor(0.42), # in old checkpoints, this was a scalar + "c_attn.weight": torch.zeros(3 * 16, 16), + "c_proj.weight": torch.zeros(16, 16), + "adapter_wte.weight": torch.zeros(10, 16), + } + attn.load_state_dict(state_dict=state_dict) + assert torch.equal(attn.gating_factor, torch.full((1, 4, 1, 1), 0.42)) + + # New checkpoint format + state_dict={ + "gating_factor": torch.tensor([0.42, 0.42, 0.42, 0.42]).reshape(1, 4, 1, 1), + "c_attn.weight": torch.zeros(3 * 16, 16), + "c_proj.weight": torch.zeros(16, 16), + "adapter_wte.weight": torch.zeros(10, 16), + } + attn.load_state_dict(state_dict=state_dict) + assert torch.equal(attn.gating_factor, torch.full((1, 4, 1, 1), 0.42)) diff --git a/lit-llama/tests/test_adapter_v2.py b/lit-llama/tests/test_adapter_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..2a594a7322a177faac5b520f59c5f0e7dadfa110 --- /dev/null +++ b/lit-llama/tests/test_adapter_v2.py @@ -0,0 +1,26 @@ +import pytest +import sys + + +@pytest.mark.skipif(sys.platform == "win32", reason="EmptyInitOnDevice on CPU not working for Windows.") +@pytest.mark.parametrize("model_size", ["7B", "13B", "30B", "65B"]) +def test_config_identical(model_size, lit_llama): + import torch.nn as nn + import lit_llama.adapter as llama_adapter + from lit_llama.adapter_v2 import adapter_v2_linear_with_bias_and_scale + import lit_llama.model as llama + from lit_llama.utils import EmptyInitOnDevice + + with EmptyInitOnDevice(): + llama_model = llama.LLaMA.from_name(model_size) + adapter_model = llama_adapter.LLaMA.from_name(model_size) + + for module in adapter_model.modules(): + if isinstance(module, nn.Linear): + adapter_v2_linear_with_bias_and_scale(module) + + print(adapter_model.transformer.h[2].attn.c_attn.adapter_bias) + assert not hasattr(llama_model.transformer.h[2].attn.c_attn, 'adapter_bias') + assert not hasattr(llama_model.transformer.h[2].attn.c_attn, 'adapter_scale') + assert hasattr(adapter_model.transformer.h[2].attn.c_attn, 'adapter_bias') + assert hasattr(adapter_model.transformer.h[2].attn.c_attn, 'adapter_scale') \ No newline at end of file diff --git a/lit-llama/tests/test_generate.py b/lit-llama/tests/test_generate.py new file mode 100644 index 0000000000000000000000000000000000000000..ecbd6afd1188265d657be30d8a8140ed39375d71 --- /dev/null +++ b/lit-llama/tests/test_generate.py @@ -0,0 +1,117 @@ +import functools +import subprocess +import sys +from contextlib import contextmanager, redirect_stdout +from io import StringIO +from pathlib import Path +from unittest import mock +from unittest.mock import Mock, call, ANY + +import torch + +wd = Path(__file__).parent.parent.absolute() + + +@functools.lru_cache(maxsize=1) +def load_generate_script(): + sys.path.append(str(wd)) + + import generate as generate + + return generate + + +def test_generate(): + generate = load_generate_script() + + from lit_llama.model import LLaMA, LLaMAConfig + + T, C = 5, 3 + logits = torch.randn(T, C) + input_idx = torch.randint(10, size=(T,)) + + config = LLaMAConfig(block_size=128, vocab_size=16, n_layer=1, n_head=4, n_embd=8) + model = LLaMA(config) + max_new_tokens = 20 + + multinomial_results = [] + original_multinomial = torch.multinomial + + def multinomial(*args, **kwargs): + out = original_multinomial(*args, **kwargs) + multinomial_results.append(out) + return out + + with mock.patch("torch.multinomial", multinomial): + out = generate.generate(model, input_idx, max_new_tokens, max_seq_length=10, top_k=4) + + assert out.size(0) == T + max_new_tokens + multinomial_results = torch.hstack(multinomial_results) + expected = torch.cat((input_idx, multinomial_results)) + assert out.shape == expected.shape + torch.testing.assert_close(out, expected) + + +@mock.patch("torch.cuda.is_bf16_supported", return_value=False) +def test_main(tmp_path, monkeypatch): + generate = load_generate_script() + + checkpoint_path = tmp_path / "ckpt" + checkpoint_path.touch() + tokenizer_path = tmp_path / "tokenizer" + tokenizer_path.touch() + + class FabricMock(Mock): + @property + def device(self): + return torch.device("cpu") + + @contextmanager + def init_module(self, empty_init): + yield + + monkeypatch.setattr(generate.L, "Fabric", FabricMock) + model_mock = Mock() + monkeypatch.setattr(generate.LLaMA, "from_name", model_mock) + lookup_mock = Mock(return_value="1T") + monkeypatch.setattr(generate, "llama_model_lookup", lookup_mock) + load_mock = Mock() + load_mock.return_value = load_mock + load_mock.__enter__ = Mock() + load_mock.__exit__ = Mock() + monkeypatch.setattr(generate.torch, "load", load_mock) + monkeypatch.setattr(generate, "lazy_load", load_mock) + tokenizer_mock = Mock() + tokenizer_mock.return_value.encode.return_value = torch.tensor([[1, 2, 3]]) + tokenizer_mock.return_value.decode.return_value = "foo bar baz" + monkeypatch.setattr(generate, "Tokenizer", tokenizer_mock) + generate_mock = Mock() + generate_mock.return_value = torch.tensor([[3, 2, 1]]) + monkeypatch.setattr(generate, "generate", generate_mock) + + num_samples = 2 + out = StringIO() + with redirect_stdout(out): + generate.main( + checkpoint_path=checkpoint_path, + tokenizer_path=tokenizer_path, + temperature=2.0, + top_k=2, + num_samples=num_samples, + ) + + model_mock.assert_called_once_with("1T") + load_mock.assert_called_once_with(checkpoint_path) + tokenizer_mock.assert_called_once_with(tokenizer_path) + assert len(tokenizer_mock.return_value.decode.mock_calls) == num_samples + assert torch.allclose(tokenizer_mock.return_value.decode.call_args[0][0], generate_mock.return_value) + assert generate_mock.mock_calls == [call(ANY, ANY, 50, temperature=2.0, top_k=2)] * num_samples + # only the generated result is printed to stdout + assert out.getvalue() == "foo bar baz\n" * num_samples + + +def test_cli(): + cli_path = wd / "generate.py" + output = subprocess.check_output([sys.executable, cli_path, "-h"]) + output = str(output.decode()) + assert "Generates text samples" in output diff --git a/lit-llama/tests/test_lora.py b/lit-llama/tests/test_lora.py new file mode 100644 index 0000000000000000000000000000000000000000..2d9e3e8089defb6c1a19629b90c636f4dfa94f0a --- /dev/null +++ b/lit-llama/tests/test_lora.py @@ -0,0 +1,64 @@ +import torch + + +def test_lora_layer_replacement(lit_llama): + from lit_llama.lora import lora, CausalSelfAttention as LoRACausalSelfAttention + from lit_llama.model import LLaMA, LLaMAConfig + + config = LLaMAConfig() + config.n_layer = 2 + config.n_head = 4 + config.n_embd = 8 + config.block_size = 8 + config.vocab_size = 8 + + with lora(r=8, alpha=8, dropout=0.1): + model = LLaMA(config) + + assert isinstance(model.transformer.h[0].attn, LoRACausalSelfAttention) + assert isinstance(model.transformer.h[1].attn, LoRACausalSelfAttention) + + +def test_lora_merge_unmerge(lit_llama): + from lit_llama.lora import lora, mark_only_lora_as_trainable + from lit_llama.model import LLaMA, LLaMAConfig + + config = LLaMAConfig(n_layer=1, n_head=2, n_embd=8, block_size=8, vocab_size=8) + + with lora(r=8, alpha=8, dropout=0.1): + model = LLaMA(config) + + initial_weight = model.transformer.h[0].attn.c_attn.weight.clone() + model.train() + assert torch.equal(model.transformer.h[0].attn.c_attn.weight, initial_weight) + + # perform an update to the LoRA weights + mark_only_lora_as_trainable(model) + optimizer = torch.optim.SGD(model.parameters(), lr=1.0) + model(torch.randint(0, 8, size=(2, 4), dtype=torch.int64)).sum().backward() + optimizer.step() + optimizer.zero_grad() + # the weight remains unchanged (only lora A and B change) + assert torch.equal(model.transformer.h[0].attn.c_attn.weight, initial_weight) + + # 'merge' and then 'unmerge' should neutralize themselves + weight_before = model.transformer.h[0].attn.c_attn.weight.clone() + model.eval() + assert not torch.equal(model.transformer.h[0].attn.c_attn.weight, weight_before) + model.train() + # note: numerically, `W + (A * B) - (A * B) == W` does not hold exactly + assert torch.allclose(model.transformer.h[0].attn.c_attn.weight, weight_before) + + # calling eval/train multiple times in a row should not merge/unmerge multiple times + model.eval() + assert model.transformer.h[0].attn.c_attn.merged + weight_after = model.transformer.h[0].attn.c_attn.weight.clone() + model.eval() + model.eval() + assert torch.equal(model.transformer.h[0].attn.c_attn.weight, weight_after) + model.train() + assert not model.transformer.h[0].attn.c_attn.merged + weight_after = model.transformer.h[0].attn.c_attn.weight.clone() + model.train() + model.train() + assert torch.equal(model.transformer.h[0].attn.c_attn.weight, weight_after) diff --git a/lit-llama/tests/test_model.py b/lit-llama/tests/test_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3abc48434bc02409c6af6740f7014307643864d5 --- /dev/null +++ b/lit-llama/tests/test_model.py @@ -0,0 +1,226 @@ +import torch +import pytest +import sys + + +def copy_mlp(llama_mlp, orig_llama_mlp) -> None: + orig_llama_mlp.w1.weight.copy_(llama_mlp.c_fc1.weight) + orig_llama_mlp.w3.weight.copy_(llama_mlp.c_fc2.weight) + orig_llama_mlp.w2.weight.copy_(llama_mlp.c_proj.weight) + + +def copy_attention(llama_attn, orig_llama_attn) -> None: + n_embd = llama_attn.c_attn.weight.shape[1] + orig_llama_attn.wq.weight.copy_(llama_attn.c_attn.weight[:n_embd]) + orig_llama_attn.wk.weight.copy_(llama_attn.c_attn.weight[n_embd:-n_embd]) + orig_llama_attn.wv.weight.copy_(llama_attn.c_attn.weight[-n_embd:]) + orig_llama_attn.wo.weight.copy_(llama_attn.c_proj.weight) + + +def copy_block(llama_block, orig_llama_block) -> None: + orig_llama_block.attention_norm.weight.copy_(llama_block.rms_1.scale) + copy_attention(llama_block.attn, orig_llama_block.attention) + orig_llama_block.ffn_norm.weight.copy_(llama_block.rms_2.scale) + copy_mlp(llama_block.mlp, orig_llama_block.feed_forward) + + +def copy_weights(llama_model, orig_llama_model) -> None: + orig_llama_model.tok_embeddings.weight.copy_(llama_model.transformer.wte.weight) + for llama_block, orig_llama_block in zip(llama_model.transformer.h, orig_llama_model.layers): + copy_block(llama_block, orig_llama_block) + orig_llama_model.norm.weight.copy_(llama_model.transformer.ln_f.scale) + orig_llama_model.output.weight.copy_(llama_model.lm_head.weight) + + +@torch.no_grad() +@pytest.mark.parametrize("kv_cache", (False, True)) +def test_to_orig_llama(lit_llama, orig_llama, kv_cache) -> None: + block_size = 64 + vocab_size = 32000 + n_layer = 16 + n_head = 16 + n_embd = 32 + batch_size = 3 + + llama_config = lit_llama.LLaMAConfig( + block_size=block_size, vocab_size=vocab_size, n_layer=n_layer, n_head=n_head, n_embd=n_embd + ) + orig_llama_config = orig_llama.ModelArgs( + dim=n_embd, + n_layers=n_layer, + n_heads=n_head, + vocab_size=vocab_size, + norm_eps=1e-5, + max_seq_len=block_size, + max_batch_size=batch_size, + ) + + seq_len = orig_llama_config.max_seq_len + token_sample = torch.randint(0, orig_llama_config.vocab_size, size=(batch_size, seq_len), dtype=torch.int64) + + llama_model = lit_llama.LLaMA(llama_config) + llama_model.apply(llama_model._init_weights) + orig_llama_model = orig_llama.Transformer(orig_llama_config) + + copy_weights(llama_model, orig_llama_model) + + orig_llama_embed = orig_llama_model.tok_embeddings(token_sample) + llama_embed = llama_model.transformer.wte(token_sample) + assert torch.allclose(orig_llama_embed, llama_embed) + + llama_rope = llama_model.build_rope_cache(token_sample) + llama_mask = llama_model.build_mask_cache(token_sample) + orig_llama_mask = torch.full((1, 1, seq_len, seq_len), float("-inf")) + orig_llama_mask = torch.triu(orig_llama_mask, diagonal=1) + if kv_cache: + orig_llama_block_out = orig_llama_model.layers[0]( + orig_llama_embed, 0, orig_llama_model.freqs_cis[:seq_len], orig_llama_mask + ) + theirs_k_cache = orig_llama_model.layers[0].attention.cache_k + theirs_v_cache = orig_llama_model.layers[0].attention.cache_v + head_size = n_embd // n_head + kv_cache_shape = (batch_size, n_head, block_size, head_size) + ours_kv_cache = torch.zeros(kv_cache_shape), torch.zeros(kv_cache_shape) + (llama_block_out, ours_kv_cache) = llama_model.transformer.h[0]( + llama_embed, llama_rope, llama_mask, seq_len, torch.arange(block_size), ours_kv_cache + ) + ours_k_cache = ours_kv_cache[0].permute(0, 2, 1, 3) + ours_v_cache = ours_kv_cache[1].permute(0, 2, 1, 3) + torch.testing.assert_close(ours_k_cache, theirs_k_cache) + torch.testing.assert_close(ours_v_cache, theirs_v_cache) + else: + orig_llama_block_out = orig_llama_model.layers[0]( + orig_llama_embed, 0, orig_llama_model.freqs_cis[:seq_len], orig_llama_mask + ) + (llama_block_out, _) = llama_model.transformer.h[0](llama_embed, llama_rope, llama_mask, seq_len) + assert torch.allclose(orig_llama_block_out, llama_block_out) + + expected = orig_llama_model(token_sample, 0) + out = llama_model(token_sample) + assert torch.allclose(out, expected) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA") +@torch.no_grad() +def test_bfloat16_llama_init(lit_llama, orig_llama) -> None: + from lit_llama.utils import EmptyInitOnDevice + + block_size = 64 + vocab_size = 32000 + n_layer = 16 + n_head = 16 + n_embd = 32 + + llama_config = lit_llama.LLaMAConfig( + block_size=block_size, vocab_size=vocab_size, n_layer=n_layer, n_head=n_head, n_embd=n_embd + ) + llama_model = lit_llama.LLaMA(llama_config) + llama_model.apply(llama_model._init_weights) + + batch_size = 3 + + token_sample = torch.randint(0, vocab_size, size=(batch_size, block_size), dtype=torch.int64) + + expected = llama_model(token_sample) + + with EmptyInitOnDevice(device="cuda", dtype=torch.bfloat16): + llama_model2 = lit_llama.LLaMA(llama_config) + llama_model2.load_state_dict(llama_model.state_dict(keep_vars=True)) + + out = llama_model2(token_sample.cuda()).float().cpu() + torch.testing.assert_close(out, expected, atol=5e-3, rtol=1e-3) + + +def copy_adapter_weights(llama_model, orig_llama_model) -> None: + # copy the gating parameter + for llama_block, orig_llama_block in zip(llama_model.transformer.h, orig_llama_model.layers): + if hasattr(llama_block.attn, "gating_factor"): + llama_block.attn.gating_factor.copy_(orig_llama_block.attention.gate) + + # In the original model, there is one embedding layer for all blocks combined + orig_adapter_wte = orig_llama_model.adapter_query.weight.reshape( + orig_llama_model.params.adapter_layer, orig_llama_model.params.adapter_len, orig_llama_model.params.dim + ) + + # In ours, the embedding layer is split across the individual attention layers + index = 0 + for llama_block in llama_model.transformer.h: + if hasattr(llama_block.attn, "adapter_wte"): + llama_block.attn.adapter_wte.weight.copy_(orig_adapter_wte[index]) + index += 1 + + +def enable_gate(model): + for name, param in model.named_parameters(): + if "gating_factor" in name or "gate" in name: + param.fill_(1) + + +@torch.no_grad() +def test_adapter_parity(orig_llama_adapter): + """Test parity between our implementation of LLaMA-Adapter and the reference code.""" + import lit_llama.adapter as lit_llama + + orig_llama = orig_llama_adapter + + block_size = 32 + vocab_size = 100 + n_layer = 2 + n_head = 4 + n_embd = 16 + adapter_prompt_length: int = 10 + adapter_start_layer: int = 0 + + llama_config = lit_llama.LLaMAConfig( + block_size=block_size, + vocab_size=vocab_size, + n_layer=n_layer, + n_head=n_head, + n_embd=n_embd, + adapter_prompt_length=adapter_prompt_length, + adapter_start_layer=adapter_start_layer, + ) + orig_llama_config = orig_llama.ModelArgs( + dim=n_embd, + n_layers=n_layer, + n_heads=n_head, + vocab_size=vocab_size, + norm_eps=1e-5, + max_seq_len=block_size, + adapter_len=adapter_prompt_length, + adapter_layer=(n_layer - adapter_start_layer), + ) + + batch_size = 3 + token_sample = torch.randint( + 0, orig_llama_config.vocab_size, size=(batch_size, orig_llama_config.max_seq_len), dtype=torch.int64 + ) + + llama_model = lit_llama.LLaMA(llama_config) + llama_model.apply(llama_model._init_weights) + orig_llama_model = orig_llama.Transformer(orig_llama_config) + + copy_weights(llama_model, orig_llama_model) + copy_adapter_weights(llama_model, orig_llama_model) + + # make the gate non-zero, otherwise the adapter is disabled and the model + # identical to regular LLaMA + enable_gate(llama_model) + enable_gate(orig_llama_model) + + expected = orig_llama_model(token_sample, 0) + out = llama_model(token_sample) + assert torch.allclose(out, expected) + + +@pytest.mark.skipif(sys.platform in ("win32", "darwin"), reason="torch.compile not supported on this platform") +def test_model_compile(lit_llama): + llama_config = lit_llama.LLaMAConfig(block_size=8, vocab_size=8, n_layer=2, n_head=2, n_embd=4) + model = lit_llama.LLaMA(llama_config) + model.apply(model._init_weights) + + model = torch.compile(model) + + sample = torch.randint(model.config.vocab_size, size=(2, model.config.block_size), dtype=torch.int64) + for _ in range(3): + _ = model(sample) diff --git a/lit-llama/tests/test_packed_dataset.py b/lit-llama/tests/test_packed_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..3b91fb4a7e8e48ed2af8e436a1c25df083a05154 --- /dev/null +++ b/lit-llama/tests/test_packed_dataset.py @@ -0,0 +1,203 @@ +import os +from unittest.mock import MagicMock +import requests + +from torch.utils.data import IterableDataset + + +def train_tokenizer(destination_path): + destination_path.mkdir(parents=True, exist_ok=True) + + # download the tiny shakespeare dataset + input_file_path = destination_path / "input.txt" + if not input_file_path.exists(): + data_url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt" + with open(input_file_path, "w") as f: + f.write(requests.get(data_url).text) + + from lit_llama import Tokenizer + Tokenizer.train( + input=input_file_path, + destination=destination_path, + vocab_size=100, + ) + + return destination_path / "tokenizer.model" + + +def test_packed_dataset(tmp_path): + tokenizer_path = train_tokenizer(tmp_path) + + from lit_llama import Tokenizer + tokenizer = Tokenizer(tokenizer_path) + + texts = [ + "The moment of truth is upon us.", + "Time to open the fridge." + ] + + from lit_llama.packed_dataset import PackedDatasetBuilder, PackedDataset, HDR_SIZE + + block_size = 10 + n_blocks = 2 + chunk_size = block_size * n_blocks + + builder = PackedDatasetBuilder( + outdir=tmp_path, + prefix="packed_dataset", + chunk_size=chunk_size, + sep_token=tokenizer.bos_id, + dtype="auto", + vocab_size=100, + ) + + text_ids = [] + + for text in texts: + text_ids = tokenizer.encode(text) + assert text_ids[0] == tokenizer.bos_id + builder.add_array(text_ids) + + filenames = builder.filenames + + assert len(filenames) == 2 + assert os.path.basename(filenames[0]) == "packed_dataset_0000000000.bin" + assert os.path.basename(filenames[1]) == "packed_dataset_0000000001.bin" + + import numpy as np + + ex_tokenized = [ + tokenizer.encode(text).numpy().astype(builder.dtype) + for text in texts + ] + ex_tokenized = np.concatenate(ex_tokenized) + ex_tokenized = ex_tokenized[:2 * chunk_size] + + for filename, el in zip(filenames, np.array_split(ex_tokenized, 2)): + mmap = np.memmap(filename, mode="r", order="C", offset=HDR_SIZE) + count = len(mmap) // np.dtype(builder.dtype).itemsize + arr = np.frombuffer( + mmap, dtype=builder.dtype, count=count, offset=0 + ) + where_bos = np.where(arr == tokenizer.bos_id) + # we expect two BOS tokens, one per file + assert len(where_bos) == 1 + assert np.array_equal(arr, el) + + dataset = PackedDataset(filenames=filenames, n_chunks=2, block_size=block_size, shuffle=False) + + ex_split = np.array_split(ex_tokenized, ex_tokenized.shape[0] // block_size) + + for item, el in zip(dataset, ex_split): + assert np.array_equal(item, el) + + dataset = PackedDataset(filenames=filenames, n_chunks=2, block_size=block_size, seed=12345) + + for i, item in enumerate(dataset): + block_idxs = iter(dataset)._block_idxs + assert np.array_equal(item, ex_split[block_idxs[i]]) + + dataset = PackedDataset(filenames=filenames, n_chunks=2, block_size=block_size, seed=12345, wrap=True) + + for i, item in enumerate(dataset): + if i > 24: + break + + dataset = PackedDataset(filenames=filenames, n_chunks=1, block_size=block_size, seed=12345) + + for i, item in enumerate(dataset): + block_idxs = iter(dataset)._block_idxs + chunk_idx = i // n_blocks * n_blocks + assert np.array_equal(item, ex_split[chunk_idx + block_idxs[i % n_blocks]]) + + block_size_ = block_size // 2 + ex_split = np.array_split(ex_tokenized, ex_tokenized.shape[0] // block_size_) + dataset = PackedDataset(filenames=filenames, n_chunks=2, block_size=block_size_, seed=12345) + + for i, item in enumerate(dataset): + block_idxs = iter(dataset)._block_idxs + assert np.array_equal(item, ex_split[block_idxs[i]]) + + block_size_ = block_size // 3 + n_chunks = 2 + ex_chunks = np.split(ex_tokenized, n_chunks) + n_splits = ex_tokenized.shape[0] // n_chunks // block_size_ + ex_splits = [np.split(el[:n_splits * block_size_], n_splits) for el in ex_chunks] + ex_split = sum(ex_splits, []) + + dataset = PackedDataset(filenames=filenames, n_chunks=n_chunks, block_size=block_size_, seed=12345) + + for i, item in enumerate(dataset): + block_idxs = iter(dataset)._block_idxs + assert np.array_equal(item, ex_split[block_idxs[i]]) + + +class SimpleDataset(IterableDataset): + def __init__(self, start, end): + super().__init__() + self._start = start + self._end = end + + def __iter__(self): + return iter(range(self._start, self._end)) + + +def test_combined_dataset(tmp_path): + from lit_llama.packed_dataset import CombinedDataset + + dataset1 = SimpleDataset(0, 10) + dataset2 = SimpleDataset(10, 20) + dataset = CombinedDataset(datasets=[dataset1, dataset2], weights=[1.0, 0.0], seed=12345) + + res = [el for el in dataset] + assert res == list(range(0, 10)) + + dataset1 = SimpleDataset(0, 10) + dataset2 = SimpleDataset(10, 20) + dataset = CombinedDataset(datasets=[dataset1, dataset2], weights=[0.0, 1.0], seed=12345) + + res = [el for el in dataset] + assert res == list(range(10, 20)) + + dataset1 = SimpleDataset(0, 10) + dataset2 = SimpleDataset(10, 20) + dataset = CombinedDataset(datasets=[dataset1, dataset2], weights=[0.5, 0.5], seed=12345) + + res = [el for el in dataset] + assert 9 in res or 19 in res + if len(res) > 10: + assert 0 in res and 10 in res + + +def test_sharded_packed_dataset(monkeypatch): + import lit_llama.packed_dataset + from lit_llama.packed_dataset import PackedDataset + + dataset_iterator_mock = MagicMock() + monkeypatch.setattr(lit_llama.packed_dataset, "PackedDatasetIterator", dataset_iterator_mock) + filenames = [str(i) for i in range(10)] + + # world_size = 1, rank = 0 + iter(PackedDataset(filenames=filenames, n_chunks=2, block_size=2)) + assert dataset_iterator_mock.call_args[1]["filenames"] == filenames + dataset_iterator_mock.reset_mock() + # world_size = 2, rank = 0 + iter(PackedDataset(filenames=filenames, n_chunks=2, block_size=2, num_processes=2, process_rank=0)) + assert dataset_iterator_mock.call_args[1]["filenames"] == ["0", "2", "4", "6", "8"] + dataset_iterator_mock.reset_mock() + # world_size = 2, rank = 1 + iter(PackedDataset(filenames=filenames, n_chunks=2, block_size=2, num_processes=2, process_rank=1)) + assert dataset_iterator_mock.call_args[1]["filenames"] == ["1", "3", "5", "7", "9"] + dataset_iterator_mock.reset_mock() + + # world_size = 3, rank = 0 (dataset size not cleanly divisible by world size) + iter(PackedDataset(filenames=filenames, n_chunks=2, block_size=2, num_processes=3, process_rank=0)) + assert dataset_iterator_mock.call_args[1]["filenames"] == ["0", "3", "6"] + dataset_iterator_mock.reset_mock() + # world_size = 3, rank = 1 (dataset size not cleanly divisible by world size) + iter(PackedDataset(filenames=filenames, n_chunks=2, block_size=2, num_processes=3, process_rank=1)) + assert dataset_iterator_mock.call_args[1]["filenames"] == ["1", "4", "7"] + dataset_iterator_mock.reset_mock() + # world_size = 3, rank = 2 (dataset size not cleanly divisible by world size) + iter(PackedDataset(filenames=filenames, n_chunks=2, block_size=2, num_processes=3, process_rank=2)) + assert dataset_iterator_mock.call_args[1]["filenames"] == ["2", "5", "8"] diff --git a/lit-llama/tests/test_prepare_redpajama.py b/lit-llama/tests/test_prepare_redpajama.py new file mode 100644 index 0000000000000000000000000000000000000000..a3e68a15b354138d67bf8049c929ba3aab8536fd --- /dev/null +++ b/lit-llama/tests/test_prepare_redpajama.py @@ -0,0 +1,142 @@ +import json +import os +import subprocess +import sys +from pathlib import Path +from unittest import mock +from unittest.mock import Mock, call, ANY + +wd = (Path(__file__).parent.parent / "scripts").absolute() + +import requests + + +def train_tokenizer(destination_path): + destination_path.mkdir(parents=True, exist_ok=True) + + # download the tiny shakespeare dataset + input_file_path = destination_path / "input.txt" + if not input_file_path.exists(): + data_url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt" + with open(input_file_path, "w") as f: + f.write(requests.get(data_url).text) + + from lit_llama import Tokenizer + Tokenizer.train(input=input_file_path, destination=destination_path, vocab_size=100) + + return destination_path / "tokenizer.model" + + +def test_prepare_sample(tmp_path): + sys.path.append(str(wd)) + + tokenizer_path = train_tokenizer(tmp_path) + + sample_path = tmp_path / "sample" + source_path = sample_path / "source" + dest_path = sample_path / "dest" + + source_path.mkdir(parents=True, exist_ok=True) + + sample = { + "meta": {"some": "info"}, + "text": "some text" + } + + jsonl_sample = "\n".join([json.dumps(el) for el in [sample] * 2]) + + import prepare_redpajama + + for filename in prepare_redpajama.filenames_sample: + with open(source_path / filename, "w") as f: + f.write(jsonl_sample) + + prepare_redpajama.prepare(source_path=source_path, tokenizer_path=tokenizer_path, destination_path=dest_path, sample=True) + + bin_files = [el.replace(".jsonl", "_0000000000.bin") for el in prepare_redpajama.filenames_sample] + + assert set(os.listdir(dest_path)) == set(bin_files) + + from lit_llama import Tokenizer + from lit_llama.packed_dataset import PackedDataset + + tokenizer = Tokenizer(tokenizer_path) + + # artificially set block_size to fit the text + block_size = len(tokenizer.encode("some text")) + + for filename in bin_files: + filenames = [os.path.join(dest_path, filename)] + dataset = PackedDataset(filenames=filenames, n_chunks=1, block_size=block_size, shuffle=False) + dataset_iter = iter(dataset) + assert tokenizer.decode(next(dataset_iter)) == "some text" + assert tokenizer.decode(next(dataset_iter)) == "some text" + + +def test_prepare_full(tmp_path): + sys.path.append(str(wd)) + + tokenizer_path = train_tokenizer(tmp_path) + + full_path = tmp_path / "full" + source_path = full_path / "source" + dest_path = full_path / "dest" + + source_path.mkdir(parents=True, exist_ok=True) + + sample = { + "meta": {"some": "info"}, + "text": "some text" + } + + jsonl_sample = "\n".join([json.dumps(el) for el in [sample] * 2]) + + import prepare_redpajama + + arxiv_file = source_path / "arxiv" / "arxiv_0.jsonl" + arxiv_file.parent.mkdir(parents=True, exist_ok=True) + with open(arxiv_file, "w") as f: + f.write(jsonl_sample) + + import zstandard as zstd + + cc_file = source_path / "common_crawl" / "cc_0.jsonl" + cc_file.parent.mkdir(parents=True, exist_ok=True) + with zstd.open(cc_file, "wt", encoding="utf-8") as f: + f.write(jsonl_sample) + + filename_sets = { + "arxiv": "arxiv/arxiv*", + "common_crawl": "common_crawl/*", + } + + with mock.patch("prepare_redpajama.filename_sets", filename_sets): + prepare_redpajama.prepare(source_path=source_path, tokenizer_path=tokenizer_path, destination_path=dest_path, sample=False) + + all_names = prepare_redpajama.filename_sets.keys() + bin_files = [el + "_0000000000.bin" for el in all_names] + + assert set(os.listdir(dest_path)) == set(bin_files) + + from lit_llama import Tokenizer + from lit_llama.packed_dataset import PackedDataset + + tokenizer = Tokenizer(tokenizer_path) + + # artificially set block_size to fit the text + block_size = len(tokenizer.encode("some text")) + + filenames = [os.path.join(dest_path, el) for el in bin_files] + + for filename in filenames: + dataset = PackedDataset(filenames=[filename], n_chunks=1, block_size=block_size, shuffle=False) + dataset_iter = iter(dataset) + assert tokenizer.decode(next(dataset_iter)) == "some text" + assert tokenizer.decode(next(dataset_iter)) == "some text" + + +def test_cli(): + cli_path = wd / "prepare_redpajama.py" + output = subprocess.check_output([sys.executable, cli_path, "-h"]) + output = str(output.decode()) + assert 'Prepare the "Red Pajama"' in output diff --git a/lit-llama/tests/test_prepare_shakespeare.py b/lit-llama/tests/test_prepare_shakespeare.py new file mode 100644 index 0000000000000000000000000000000000000000..ef6a80aaaad1e0bef1bc6b2865861f630d28be29 --- /dev/null +++ b/lit-llama/tests/test_prepare_shakespeare.py @@ -0,0 +1,23 @@ +import os +import subprocess +import sys +from pathlib import Path + +wd = (Path(__file__).parent.parent / "scripts").absolute() + + +def test_prepare(tmp_path): + sys.path.append(str(wd)) + + import prepare_shakespeare + + prepare_shakespeare.prepare(tmp_path) + + assert set(os.listdir(tmp_path)) == {"train.bin", "tokenizer.model", "tokenizer.vocab", "input.txt", "val.bin"} + + +def test_cli(): + cli_path = wd / "prepare_shakespeare.py" + output = subprocess.check_output([sys.executable, cli_path, "-h"]) + output = str(output.decode()) + assert 'Prepare the "Tiny Shakespeare"' in output diff --git a/lit-llama/tests/test_rmsnorm.py b/lit-llama/tests/test_rmsnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..e88dc859a583262aac7b0900333da7d225f83187 --- /dev/null +++ b/lit-llama/tests/test_rmsnorm.py @@ -0,0 +1,15 @@ +import torch + + +@torch.no_grad() +def test_rmsnorm(lit_llama, orig_llama) -> None: + block_size = 16 + vocab_size = 16 + + sample = torch.rand(size=(2, block_size, vocab_size), dtype=torch.float32) + + eps = 1e-6 + orig_llama_rmsnorm = orig_llama.RMSNorm(vocab_size, eps=eps)(sample) + llama_rmsnorm = lit_llama.RMSNorm(vocab_size, eps=eps)(sample) + + assert torch.allclose(orig_llama_rmsnorm, llama_rmsnorm) diff --git a/lit-llama/tests/test_rope.py b/lit-llama/tests/test_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..37e993ab5471cebc1f02b9b96b4762762a2bd648 --- /dev/null +++ b/lit-llama/tests/test_rope.py @@ -0,0 +1,17 @@ +import torch + + +@torch.no_grad() +def test_rope(lit_llama, orig_llama) -> None: + torch.manual_seed(1) + + bs, seq_len, n_head, n_embed = 1, 6, 2, 8 + x = torch.randint(0, 10000, size=(bs, seq_len, n_head, n_embed // n_head)).float() + + freqs_cis = orig_llama.precompute_freqs_cis(n_embed // n_head, seq_len) + llama_rope_cache = lit_llama.build_rope_cache(seq_len, n_embed // n_head, dtype=x.dtype, device=x.device) + torch.testing.assert_close(freqs_cis, torch.view_as_complex(llama_rope_cache)) + + llama_x_rope = lit_llama.apply_rope(x, llama_rope_cache) + orig_llama_x_rope, _ = orig_llama.apply_rotary_emb(x, x, freqs_cis) + torch.testing.assert_close(llama_x_rope, orig_llama_x_rope) diff --git a/lit-llama/tests/test_utils.py b/lit-llama/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..97101b12d69beec710ccaeb468cfcf26ee4283c9 --- /dev/null +++ b/lit-llama/tests/test_utils.py @@ -0,0 +1,73 @@ +import tempfile +import pathlib + +import torch + + +class ATensor(torch.Tensor): + pass + + +def test_lazy_load_basic(lit_llama): + import lit_llama.utils + + with tempfile.TemporaryDirectory() as tmpdirname: + m = torch.nn.Linear(5, 3) + path = pathlib.Path(tmpdirname) + fn = str(path / "test.pt") + torch.save(m.state_dict(), fn) + with lit_llama.utils.lazy_load(fn) as sd_lazy: + assert "NotYetLoadedTensor" in str(next(iter(sd_lazy.values()))) + m2 = torch.nn.Linear(5, 3) + m2.load_state_dict(sd_lazy) + + x = torch.randn(2, 5) + actual = m2(x) + expected = m(x) + torch.testing.assert_close(actual, expected) + + +def test_lazy_load_subclass(lit_llama): + import lit_llama.utils + + with tempfile.TemporaryDirectory() as tmpdirname: + path = pathlib.Path(tmpdirname) + fn = str(path / "test.pt") + t = torch.randn(2, 3)[:, 1:] + sd = { + 1: t, + 2: torch.nn.Parameter(t), + 3: torch.Tensor._make_subclass(ATensor, t), + } + torch.save(sd, fn) + with lit_llama.utils.lazy_load(fn) as sd_lazy: + for k in sd.keys(): + actual = sd_lazy[k] + expected = sd[k] + torch.testing.assert_close(actual._load_tensor(), expected) + + +def test_incremental_write(tmp_path, lit_llama): + import lit_llama.utils + + sd = {str(k): torch.randn(5, 10) for k in range(3)} + sd_expected = {k: v.clone() for k, v in sd.items()} + fn = str(tmp_path / "test.pt") + with lit_llama.utils.incremental_save(fn) as f: + sd["0"] = f.store_early(sd["0"]) + sd["2"] = f.store_early(sd["2"]) + f.save(sd) + sd_actual = torch.load(fn) + assert sd_actual.keys() == sd_expected.keys() + for k, v_expected in sd_expected.items(): + v_actual = sd_actual[k] + torch.testing.assert_close(v_expected, v_actual) + + +def test_find_multiple(lit_llama): + from lit_llama.utils import find_multiple + + assert find_multiple(17, 5) == 20 + assert find_multiple(30, 7) == 35 + assert find_multiple(10, 2) == 10 + assert find_multiple(5, 10) == 10