--- extra_gated_heading: You need to share contact information with Meta to access this model extra_gated_prompt: >- ## FAIR Noncommercial Research License Last Updated: [October 16th 2024] “Acceptable Use Policy” means the FAIR Acceptable Use Policy, applicable to Research Materials, that is incorporated into this Agreement. “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the Research Materials set forth herein. “Documentation” means the specifications, manuals and documentation accompanying Research Materials distributed by Meta. “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf. “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) and Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland). “Noncommercial Research Uses” means noncommercial research use cases related to research, development, education, processing, or analysis and in each case, is not primarily intended for commercial advantage or monetary compensation to you or others. “Research Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, demonstration materials and other elements of the foregoing distributed by Meta and made available under this Agreement. By clicking “I Accept” below or by using or distributing any portion or element of the Research Materials, you agree to be bound by this Agreement. 1. License Rights and Redistribution. a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the Research Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Research Materials. b. Redistribution and Use. i. You will not use the Research Materials or any outputs or results of the Research Materials in connection with any commercial uses or for any uses other than Noncommercial Research Uses; ii. Distribution of Research Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the Research Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement. You shall also provide a copy of this Agreement to such third party. iii. If you submit for publication the results of research you perform on, using, or otherwise in connection with Research Materials, you must acknowledge the use of Research Materials in your publication. iv. Your use of the Research Materials must comply with applicable laws and regulations (including Trade Control Laws) and adhere to the FAIR Acceptable Use Policy, which is hereby incorporated by reference into this Agreement. 2. User Support. Your Noncommercial Research Use of the Research Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the Research Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind. 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE RESEARCH MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE RESEARCH MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE RESEARCH MATERIALS AND ANY OUTPUT AND RESULTS. 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING. 5. Intellectual Property. a. Subject to Meta’s ownership of Research Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the Research Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications. b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Research Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the Research Materials. 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the Research Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the Research Materials. Sections 5, 6 and 9 shall survive the termination of this Agreement. 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement. 8. Modifications and Amendments. Meta may modify this Agreement from time to time by posting a revised version at https://huggingface.co/facebook/layerskip-llama2-7B/blob/main/LICENSE; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the Research Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta. FAIR Acceptable Use Policy The Fundamental AI Research (FAIR) team at Meta seeks to further understanding of new and existing research domains with the mission of advancing the state-of-the-art in artificial intelligence through open research for the benefit of all. As part of this mission, Meta makes certain research materials available for noncommercial research use. Meta is committed to promoting the safe and responsible use of such research materials. Prohibited Uses You agree you will not use, or allow others to use, Research Materials to: 1.Violate the law or others’ rights, including to: a. Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as: i. Violence or terrorism ii. Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material iii. Human trafficking, exploitation, and sexual violence iv. The illegal distribution of information or materials to minors, including obscene materials, or failure to employ legally required age-gating in connection with such information or materials. v. Sexual solicitation vi. Any other criminal activity b. Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals c. Engage in, promote, incite, or facilitate discrimination or other unlawful or harmful conduct in the provision of employment, employment benefits, credit, housing, other economic benefits, or other essential goods and services d. Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices e. Collect, process, disclose, generate, or infer health, demographic, or other sensitive personal or private information about individuals without rights and consents required by applicable laws f. Engage in or facilitate any action or generate any content that infringes, misappropriates, or otherwise violates any third-party rights, including the outputs or results of any technology using FAIR research materials g. Create, generate, or facilitate the creation of malicious code, malware, computer viruses or do anything else that could disable, overburden, interfere with or impair the proper working, integrity, operation or appearance of a website or computer system 2. Engage in, promote, incite, facilitate, or assist in the planning or development of activities that present a risk of death or bodily harm to individuals, including use of research artifacts related to the following: a. Military, warfare, nuclear industries or applications, espionage, use for materials or activities that are subject to the International Traffic Arms Regulations (ITAR) maintained by the United States Department of State b. Guns and illegal weapons (including weapon development) c. Illegal drugs and regulated/controlled substances d. Operation of critical infrastructure, transportation technologies, or heavy machinery e. Self-harm or harm to others, including suicide, cutting, and eating disorders f. Any content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual 3. Intentionally deceive or mislead others, including use of FAIR Research Materials related to the following: a. Generating, promoting, or furthering fraud or the creation or promotion of disinformation b. Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content c. Generating, promoting, or further distributing spam d. Impersonating another individual without consent, authorization, or legal right e. Representing that outputs of FAIR research materials or outputs from technology using FAIR research materials o are human-generated f. Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement 4. Fail to appropriately disclose to end users any known dangers of your Research Materials. Please report any violation of this Policy or other problems that could lead to a violation of this Policy by submitting a report [here](https://docs.google.com/forms/d/e/1FAIpQLSeb11cryAopJ7LNrC4nxEUXrHY26hfkXQMf_uH-oFgA3WlYZQ/viewform). extra_gated_fields: First Name: text Last Name: text Date of birth: date_picker Country: country Affiliation: text geo: ip_location By clicking Submit below I accept the terms of the license and acknowledge that the information I provide will be collected stored processed and shared in accordance with the Meta Privacy Policy: checkbox extra_gated_description: The information you provide will be collected, stored, processed and shared in accordance with the [Meta Privacy Policy](https://www.facebook.com/privacy/policy/). extra_gated_button_content: Submit language: - en library_name: transformers pipeline_tag: text-generation tags: - facebook - meta - pytorch - llama - llama-2 license: other license_name: fair license_link: LICENSE base_model: meta-llama/Llama-2-7b-hf --- # LayerSkip Llama2 7B Llama2 7B model continually pretrained with LayerSkip as presented in [Layer Skip: Enabling Early Exit Inference and Self-Speculative Decoding ](https://arxiv.org/abs/2404.16710) and is capable of performing self-speculative decoding: decode with earlier layers and verify with remaining layers. ## How to Use We are providing 3 ways to run the model - [HuggingFace](#huggingface) - [LayerSkip Codebase](#layerskip-codebase) - [gpt-fast](#gpt-fast) ### HuggingFace HuggingFace does not yet have self-speculative decoding support. However, we can re-use it's speculative decoding feature by creating a draft model using a subset of the layers of the main model: ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer >>> import torch >>> from copy import deepcopy >>> checkpoint = "facebook/layerskip-llama2-7B" >>> early_exit = 4 >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> prompt = "typing import List\ndef bucket_sort(A: List):" >>> model = AutoModelForCausalLM.from_pretrained(checkpoint) >>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) >>> generation_config = model.generation_config >>> weights_memo = {id(w): w for w in model.parameters()} >>> assistant_model = deepcopy(model, memo=weights_memo) # Clone main model with shared weights >>> assistant_model.model.layers = assistant_model.model.layers[:early_exit] # Apply early exit >>> del assistant_model.model.layers[early_exit:] >>> model.to(device) >>> assistant_model.to(device) >>> inputs = tokenizer(prompt, return_tensors="pt").to(device) >>> outputs = model.generate(**inputs, assistant_model=assistant_model, generation_config=generation_config) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) ``` Please note that this is not an optimal implementation as it requires more memory to save KV cache and activations of duplicated layers. The optimized implementation that re-uses earlier layers is in our [custom implementation](#layerskip-codebase) or in our [gpt-fast implementation](#gpt-fast).
Benchmark If you would like to measure the speedup between self-speculative decoding and autoregressive decoding, we have written this script: ```python from transformers import LlamaForCausalLM, LlamaConfig, LlamaTokenizer, GenerationConfig import torch from copy import deepcopy from time import time from tqdm import tqdm prompt = "typing import List\ndef bucket_sort(A: List):" checkpoint = "facebook/layerskip-llama2-7B" early_exit = 4 device = "cuda" if torch.cuda.is_available() else "cpu" max_new_tokens = 512 do_sample = True top_p = 0.9 temperature = 0.6 warmup = 2 repeat = 10 config = LlamaConfig.from_pretrained(checkpoint) model = LlamaForCausalLM.from_pretrained(checkpoint, config=config, torch_dtype=torch.float16) # Draft model # Clone main model with shared weights weights_memo = {id(w): w for w in model.parameters()} assistant_model = deepcopy(model, memo=weights_memo) # Create early exit version assistant_model.model.layers = assistant_model.model.layers[:early_exit] del assistant_model.model.layers[early_exit:] model.to(device) assistant_model.to(device) tokenizer = LlamaTokenizer.from_pretrained(checkpoint, use_fast=False) inputs = tokenizer(prompt, return_tensors="pt").to(device) generation_config = { "max_new_tokens": max_new_tokens, "do_sample": do_sample, "top_p": top_p, "temperature": temperature, "pad_token_id": tokenizer.eos_token_id, } # Warmup print("Warmup") for i in tqdm(range(warmup)): _ = model.generate(**inputs, **generation_config) _ = model.generate(**inputs, **generation_config, assistant_model=assistant_model) print("Autoregressive Decoding") total_time = 0 total_tokens = 0 for i in tqdm(range(repeat)): start = time() outputs = model.generate(**inputs, **generation_config) total_time += time() - start total_tokens += outputs.numel() print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) print("\n\t=========================") print(f"\tAverage Generation Time: {total_time / repeat:.2f} s") print(f"\tAverage Tokens per Second: {total_tokens / total_time:.2f} tokens per sec\n\n") print("Self-Speculative Decoding") total_time = 0 total_tokens = 0 for i in tqdm(range(repeat)): start = time() outputs = model.generate(**inputs, **generation_config, assistant_model=assistant_model) total_time += time() - start total_tokens += outputs.numel() print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) print("\n\t=========================") print(f"\tAverage Generation Time: {total_time / repeat:.2f} s") print(f"\tAverage Tokens per Second: {total_tokens / total_time:.2f} tokens per sec\n\n") ``` Running this script on a single A100 NVIDIA GPU with `transformers==4.34.1`, `torch==2.2.1`, `triton==2.2.0`, we obtain: ``` Autoregressive Decoding ========================= Average Generation Time: 12.60 s Average Tokens per Second: 34.87 tokens per sec Self-Speculative Decoding ========================= Average Generation Time: 7.38 s Average Tokens per Second: 56.10 tokens per sec ```
### LayerSkip Codebase Our self-speculative decoding implementation at [github.com/facebookresearch/LayerSkip](https://github.com/facebookresearch/LayerSkip) has an optimized version that does not consume extra memory and re-uses the weights and KV cache of earlier layers in both draft and verification stages. To run: ```console > git clone git@github.com:facebookresearch/LayerSkip.git > cd LayerSkip > conda create --name layer_skip python=3.10 > conda activate layer_skip > pip install -r requirements.txt > torchrun generate.py --model facebook/layerskip-llama2-7B --generation_strategy self_speculative --exit_layer 6 --num_speculations 4 ``` You can find more details in the GitHub repo for more options and scripts. ### GPT-Fast We have also implemented self-speculative decoding as a [separatae branch in PyTorch's gpt-fast](https://github.com/pytorch-labs/gpt-fast/tree/LayerSkip) if you would to stack our solution on top of other optimizations like `torch.compile()` and quantization. Our gpt-fast implementation is optimized as it does not consume extra memory and re-uses the weights and KV cache of earlier layers in both draft and verification stages. To run: ```console > git clone git@github.com:pytorch-labs/gpt-fast.git -b LayerSkip > cd gpt-fast > conda create --name gpt_fast python=3.10 > conda activate gpt_fast > # Install PyTorch (check [here](https://pytorch.org/get-started/locally/) for other hardwares and operating systems) > pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 > pip install sentencepiece huggingface_hub tiktoken > mkdir checkpoints > MODEL_REPO=facebook/layerskip-llama2-7B > ./scripts/prepare.sh $MODEL_REPO > python generate.py --compile --checkpoint_path checkpoints/$MODEL_REPO/model.pth --top_k 100 --temperature 0.6 --self_speculative --early_exit 5 --speculate_k 3 ```
Benchmark - Autoregressive decoding: ```console > python generate.py --compile --checkpoint_path checkpoints/$MODEL_REPO/model.pth --top_k 100 --temperature 0.6 ========== Average tokens/sec: 110.50 Memory used: 13.88 GB ``` - Self-speculative decoding: ```console > python generate.py --compile --checkpoint_path checkpoints/$MODEL_REPO/model.pth --top_k 100 --temperature 0.6 --self_speculative --early_exit 5 --speculate_k 3 ========== {'tokens_per_sec': [120.16508373150057, 141.77910376715855, 132.42363092761354, 138.73840444421148, 121.55019835742718], 'accept_counts': [[32, 15, 19, 20], [50, 23, 21, 10], [31, 22, 16, 19], [41, 19, 19, 16], [35, 20, 15, 20], [47, 32, 9, 16]]} Acceptance probs: [0.41622574955908287, 0.2310405643738977, 0.1746031746031746, 0.1781305114638448] Mean Accepted: 1.1146384479717812 Average tokens/sec: 130.93 Memory used: 13.91 GB ```
## Training Our training implementation is work-in-progress. You can check this [pull request](https://github.com/pytorch/torchtune/pull/1076) for details and discussions. ## Issues Please report any software "bug", or other problems with the models through one of the following means: - Reporting issues with the model: [https://github.com/facebookresearch/LayerSkip/issues](https://github.com/facebookresearch/LayerSkip/issues) - Reporting risky content generated by the model: [developers.facebook.com/llama_output_feedback](http://developers.facebook.com/llama_output_feedback) - Reporting bugs and security concerns: [facebook.com/whitehat/info](http://facebook.com/whitehat/info) ## License See the [LICENSE](LICENSE) file.