Commit 0371621a authored by chenzk's avatar chenzk
Browse files

v1.0

parents
Pipeline #1989 canceled with stages
import numpy as np
import tiktoken
def encode_file(input_file_path, output_file_path, tokenizer_name):
tokenizer = tiktoken.get_encoding(tokenizer_name)
print(tokenizer)
with open(input_file_path, 'r') as f:
data = f.read()
enc_data = tokenizer.encode(data)
enc_data = np.array(enc_data, dtype=np.uint32)
enc_data.tofile(output_file_path)
encode_file('input.txt', 'train.bin', 'cl100k_base')
---
language:
- en
- de
- fr
- it
- pt
- hi
- es
- th
library_name: transformers
pipeline_tag: text-generation
tags:
- facebook
- meta
- pytorch
- llama
- llama-3
license: llama3.2
extra_gated_prompt: >-
### LLAMA 3.2 COMMUNITY LICENSE AGREEMENT
Llama 3.2 Version Release Date: September 25, 2024
“Agreement” means the terms and conditions for use, reproduction, distribution
and modification of the Llama Materials set forth herein.
“Documentation” means the specifications, manuals and documentation accompanying Llama 3.2
distributed by Meta at https://llama.meta.com/doc/overview.
“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.
“Llama 3.2” means the foundational large language models and software and algorithms, including
machine-learning model code, trained model weights, inference-enabling code, training-enabling code,
fine-tuning enabling code and other elements of the foregoing distributed by Meta at
https://www.llama.com/llama-downloads.
“Llama Materials” means, collectively, Meta’s proprietary Llama 3.2 and Documentation (and
any portion thereof) made available under this Agreement.
“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).
By clicking “I Accept” below or by using or distributing any portion or element of the Llama 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 Llama Materials to use, reproduce, distribute, copy, create derivative works
of, and make modifications to the Llama Materials.
b. Redistribution and Use.
i. If you distribute or make available the Llama Materials (or any derivative works thereof),
or a product or service (including another AI model) that contains any of them, you shall (A) provide
a copy of this Agreement with any such Llama Materials; and (B) prominently display “Built with Llama”
on a related website, user interface, blogpost, about page, or product documentation. If you use the
Llama Materials or any outputs or results of the Llama Materials to create, train, fine tune, or
otherwise improve an AI model, which is distributed or made available, you shall also include “Llama”
at the beginning of any such AI model name.
ii. If you receive Llama Materials, or any derivative works thereof, from a Licensee as part
of an integrated end user product, then Section 2 of this Agreement will not apply to you.
iii. You must retain in all copies of the Llama Materials that you distribute the
following attribution notice within a “Notice” text file distributed as a part of such copies:
“Llama 3.2 is licensed under the Llama 3.2 Community License, Copyright © Meta Platforms,
Inc. All Rights Reserved.”
iv. Your use of the Llama Materials must comply with applicable laws and regulations
(including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for
the Llama Materials (available at https://www.llama.com/llama3_2/use-policy), which is hereby
incorporated by reference into this Agreement.
2. Additional Commercial Terms. If, on the Llama 3.2 version release date, the monthly active users
of the products or services made available by or for Licensee, or Licensee’s affiliates,
is greater than 700 million monthly active users in the preceding calendar month, you must request
a license from Meta, which Meta may grant to you in its sole discretion, and you are not authorized to
exercise any of the rights under this Agreement unless or until Meta otherwise expressly grants you such rights.
3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE LLAMA 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 LLAMA MATERIALS AND ASSUME ANY RISKS ASSOCIATED
WITH YOUR USE OF THE LLAMA 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 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. No trademark licenses are granted under this Agreement, and in connection with the Llama Materials,
neither Meta nor Licensee may use any name or mark owned by or associated with the other or any of its affiliates,
except as required for reasonable and customary use in describing and redistributing the Llama Materials or as
set forth in this Section 5(a). Meta hereby grants you a license to use “Llama” (the “Mark”) solely as required
to comply with the last sentence of Section 1.b.i. You will comply with Meta’s brand guidelines (currently accessible
at https://about.meta.com/brand/resources/meta/company-brand/). All goodwill arising out of your use of the Mark
will inure to the benefit of Meta.
b. Subject to Meta’s ownership of Llama Materials and derivatives made by or for Meta, with respect to any
derivative works and modifications of the Llama Materials that are made by you, as between you and Meta,
you are and will be the owner of such derivative works and modifications.
c. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or
counterclaim in a lawsuit) alleging that the Llama Materials or Llama 3.2 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 Llama Materials.
6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access
to the Llama 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 Llama Materials. Sections 3,
4 and 7 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.
### Llama 3.2 Acceptable Use Policy
Meta is committed to promoting safe and fair use of its tools and features, including Llama 3.2.
If you access or use Llama 3.2, you agree to this Acceptable Use Policy (“**Policy**”).
The most recent copy of this policy can be found at
[https://www.llama.com/llama3_2/use-policy](https://www.llama.com/llama3_2/use-policy).
#### Prohibited Uses
We want everyone to use Llama 3.2 safely and responsibly. You agree you will not use, or allow others to use, Llama 3.2 to:
1. Violate the law or others’ rights, including to:
1. Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:
1. Violence or terrorism
2. Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material
3. Human trafficking, exploitation, and sexual violence
4. 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.
5. Sexual solicitation
6. Any other criminal activity
1. Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
2. 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
3. Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
4. Collect, process, disclose, generate, or infer private or sensitive information about individuals, including information about individuals’ identity, health, or demographic information, unless you have obtained the right to do so in accordance with applicable law
5. 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 products or services using the Llama Materials
6. 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
7. Engage in any action, or facilitate any action, to intentionally circumvent or remove usage restrictions or other safety measures, or to enable functionality disabled by Meta 
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 Llama 3.2 related to the following:
8. 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 or to the U.S. Biological Weapons Anti-Terrorism Act of 1989 or the Chemical Weapons Convention Implementation Act of 1997
9. Guns and illegal weapons (including weapon development)
10. Illegal drugs and regulated/controlled substances
11. Operation of critical infrastructure, transportation technologies, or heavy machinery
12. Self-harm or harm to others, including suicide, cutting, and eating disorders
13. 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 Llama 3.2 related to the following:
14. Generating, promoting, or furthering fraud or the creation or promotion of disinformation
15. Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
16. Generating, promoting, or further distributing spam
17. Impersonating another individual without consent, authorization, or legal right
18. Representing that the use of Llama 3.2 or outputs are human-generated
19. 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 AI system
5. Interact with third party tools, models, or software designed to generate unlawful content or engage in unlawful or harmful conduct and/or represent that the outputs of such tools, models, or software are associated with Meta or Llama 3.2
With respect to any multimodal models included in Llama 3.2, the rights granted under Section 1(a) of the Llama 3.2 Community License Agreement are not being granted to you if you are an individual domiciled in, or a company with a principal place of business in, the European Union. This restriction does not apply to end users of a product or service that incorporates any such multimodal models.
Please report any violation of this Policy, software “bug,” or other problems that could lead to a violation of this Policy through one of the following means:
* Reporting issues with the model: [https://github.com/meta-llama/llama-models/issues](https://l.workplace.com/l.php?u=https%3A%2F%2Fgithub.com%2Fmeta-llama%2Fllama-models%2Fissues&h=AT0qV8W9BFT6NwihiOHRuKYQM_UnkzN_NmHMy91OT55gkLpgi4kQupHUl0ssR4dQsIQ8n3tfd0vtkobvsEvt1l4Ic6GXI2EeuHV8N08OG2WnbAmm0FL4ObkazC6G_256vN0lN9DsykCvCqGZ)
* 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)
* Reporting violations of the Acceptable Use Policy or unlicensed uses of Llama 3.2: LlamaUseReport@meta.com
extra_gated_fields:
First Name: text
Last Name: text
Date of birth: date_picker
Country: country
Affiliation: text
Job title:
type: select
options:
- Student
- Research Graduate
- AI researcher
- AI developer/engineer
- Reporter
- Other
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
---
## Model Information
The Meta Llama 3.2 collection of multilingual large language models (LLMs) is a collection of pretrained and instruction-tuned generative models in 1B and 3B sizes (text in/text out). The Llama 3.2 instruction-tuned text only models are optimized for multilingual dialogue use cases, including agentic retrieval and summarization tasks. They outperform many of the available open source and closed chat models on common industry benchmarks.
**Model Developer:** Meta
**Model Architecture:** Llama 3.2 is an auto-regressive language model that uses an optimized transformer architecture. The tuned versions use supervised fine-tuning (SFT) and reinforcement learning with human feedback (RLHF) to align with human preferences for helpfulness and safety.
| | Training Data | Params | Input modalities | Output modalities | Context Length | GQA | Shared Embeddings | Token count | Knowledge cutoff |
| :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
| Llama 3.2 (text only) | A new mix of publicly available online data. | 1B (1.23B) | Multilingual Text | Multilingual Text and code | 128k | Yes | Yes | Up to 9T tokens | December 2023 |
| | | 3B (3.21B) | Multilingual Text | Multilingual Text and code | | | | | |
**Supported Languages:** English, German, French, Italian, Portuguese, Hindi, Spanish, and Thai are officially supported. Llama 3.2 has been trained on a broader collection of languages than these 8 supported languages. Developers may fine-tune Llama 3.2 models for languages beyond these supported languages, provided they comply with the Llama 3.2 Community License and the Acceptable Use Policy. Developers are always expected to ensure that their deployments, including those that involve additional languages, are completed safely and responsibly.
**Llama 3.2 Model Family:** Token counts refer to pretraining data only. All model versions use Grouped-Query Attention (GQA) for improved inference scalability.
**Model Release Date:** Sept 25, 2024
**Status:** This is a static model trained on an offline dataset. Future versions may be released that improve model capabilities and safety.
**License:** Use of Llama 3.2 is governed by the [Llama 3.2 Community License](https://github.com/meta-llama/llama-models/blob/main/models/llama3_2/LICENSE) (a custom, commercial license agreement).
**Feedback:** Where to send questions or comments about the model Instructions on how to provide feedback or comments on the model can be found in the model [README](https://github.com/meta-llama/llama-models/tree/main/models/llama3_2). For more technical information about generation parameters and recipes for how to use Llama 3.2 in applications, please go [here](https://github.com/meta-llama/llama-recipes).
## Intended Use
**Intended Use Cases:** Llama 3.2 is intended for commercial and research use in multiple languages. Instruction tuned text only models are intended for assistant-like chat and agentic applications like knowledge retrieval and summarization, mobile AI powered writing assistants and query and prompt rewriting. Pretrained models can be adapted for a variety of additional natural language generation tasks.
**Out of Scope:** Use in any manner that violates applicable laws or regulations (including trade compliance laws). Use in any other way that is prohibited by the Acceptable Use Policy and Llama 3.2 Community License. Use in languages beyond those explicitly referenced as supported in this model card.
## How to use
This repository contains two versions of Llama-3.2-3B, for use with transformers and with the original `llama` codebase.
### Use with transformers
Starting with transformers >= 4.43.0 onward, you can run conversational inference using the Transformers pipeline abstraction or by leveraging the Auto classes with the generate() function.
Make sure to update your transformers installation via pip install --upgrade transformers.
```python
import torch
from transformers import pipeline
model_id = "meta-llama/Llama-3.2-3B"
pipe = pipeline(
"text-generation",
model=model_id,
torch_dtype=torch.bfloat16,
device_map="auto"
)
pipe("The key to life is")
```
### Use with `llama`
Please, follow the instructions in the [repository](https://github.com/meta-llama/llama).
To download Original checkpoints, see the example command below leveraging `huggingface-cli`:
```
huggingface-cli download meta-llama/Llama-3.2-3B --include "original/*" --local-dir Llama-3.2-3B
```
## Hardware and Software
**Training Factors:** We used custom training libraries, Meta's custom built GPU cluster, and production infrastructure for pretraining. Fine-tuning, annotation, and evaluation were also performed on production infrastructure.
**Training Energy Use:** Training utilized a cumulative of **916k** GPU hours of computation on H100-80GB (TDP of 700W) type hardware, per the table below. Training time is the total GPU time required for training each model and power consumption is the peak power capacity per GPU device used, adjusted for power usage efficiency.
##
**Training Greenhouse Gas Emissions:** Estimated total location-based greenhouse gas emissions were **240** tons CO2eq for training. Since 2020, Meta has maintained net zero greenhouse gas emissions in its global operations and matched 100% of its electricity use with renewable energy; therefore, the total market-based greenhouse gas emissions for training were 0 tons CO2eq.
| | Training Time (GPU hours) | Logit Generation Time (GPU Hours) | Training Power Consumption (W) | Training Location-Based Greenhouse Gas Emissions (tons CO2eq) | Training Market-Based Greenhouse Gas Emissions (tons CO2eq) |
| :---- | :---: | ----- | :---: | :---: | :---: |
| Llama 3.2 1B | 370k | \- | 700 | 107 | 0 |
| Llama 3.2 3B | 460k | \- | 700 | 133 | 0 |
| Total | 830k | 86k | | 240 | 0 |
The methodology used to determine training energy use and greenhouse gas emissions can be found [here](https://arxiv.org/pdf/2204.05149). Since Meta is openly releasing these models, the training energy use and greenhouse gas emissions will not be incurred by others.
## Training Data
**Overview:** Llama 3.2 was pretrained on up to 9 trillion tokens of data from publicly available sources. For the 1B and 3B Llama 3.2 models, we incorporated logits from the Llama 3.1 8B and 70B models into the pretraining stage of the model development, where outputs (logits) from these larger models were used as token-level targets. Knowledge distillation was used after pruning to recover performance. In post-training we used a similar recipe as Llama 3.1 and produced final chat models by doing several rounds of alignment on top of the pre-trained model. Each round involved Supervised Fine-Tuning (SFT), Rejection Sampling (RS), and Direct Preference Optimization (DPO).
**Data Freshness:** The pretraining data has a cutoff of December 2023\.
## Benchmarks \- English Text
In this section, we report the results for Llama 3.2 models on standard automatic benchmarks. For all these evaluations, we used our internal evaluations library.
### Base Pretrained Models
| Category | Benchmark | \# Shots | Metric | Llama 3.2 1B | Llama 3.2 3B | Llama 3.1 8B |
| ----- | ----- | :---: | :---: | :---: | :---: | :---: |
| General | MMLU | 5 | macro\_avg/acc\_char | 32.2 | 58 | 66.7 |
| | AGIEval English | 3-5 | average/acc\_char | 23.3 | 39.2 | 47.8 |
| | ARC-Challenge | 25 | acc\_char | 32.8 | 69.1 | 79.7 |
| Reading comprehension | SQuAD | 1 | em | 49.2 | 67.7 | 77 |
| | QuAC (F1) | 1 | f1 | 37.9 | 42.9 | 44.9 |
| | DROP (F1) | 3 | f1 | 28.0 | 45.2 | 59.5 |
| Long Context | Needle in Haystack | 0 | em | 96.8 | 1 | 1 |
### Instruction Tuned Models
| Capability | | Benchmark | \# Shots | Metric | Llama 3.2 1B | Llama 3.2 3B | Llama 3.1 8B |
| :---: | ----- | :---: | :---: | :---: | :---: | :---: | :---: |
| General | | MMLU | 5 | macro\_avg/acc | 49.3 | 63.4 | 69.4 |
| Re-writing | | Open-rewrite eval | 0 | micro\_avg/rougeL | 41.6 | 40.1 | 40.9 |
| Summarization | | TLDR9+ (test) | 1 | rougeL | 16.8 | 19.0 | 17.2 |
| Instruction following | | IFEval | 0 | avg(prompt/instruction acc loose/strict) | 59.5 | 77.4 | 80.4 |
| Math | | GSM8K (CoT) | 8 | em\_maj1@1 | 44.4 | 77.7 | 84.5 |
| | | MATH (CoT) | 0 | final\_em | 30.6 | 47.3 | 51.9 |
| Reasoning | | ARC-C | 0 | acc | 59.4 | 78.6 | 83.4 |
| | | GPQA | 0 | acc | 27.2 | 32.8 | 32.8 |
| | | Hellaswag | 0 | acc | 41.2 | 69.8 | 78.7 |
| Tool Use | | BFCL V2 | 0 | acc | 25.7 | 67.0 | 70.9 |
| | | Nexus | 0 | macro\_avg/acc | 13.5 | 34.3 | 38.5 |
| Long Context | | InfiniteBench/En.QA | 0 | longbook\_qa/f1 | 20.3 | 19.8 | 27.3 |
| | | InfiniteBench/En.MC | 0 | longbook\_choice/acc | 38.0 | 63.3 | 72.2 |
| | | NIH/Multi-needle | 0 | recall | 75.0 | 84.7 | 98.8 |
| Multilingual | | MGSM (CoT) | 0 | em | 24.5 | 58.2 | 68.9 |
### Multilingual Benchmarks
| Category | Benchmark | Language | Llama 3.2 1B | Llama 3.2 3B | Llama 3.1 8B |
| :---: | :---: | :---: | :---: | :---: | :---: |
| General | MMLU (5-shot, macro\_avg/acc) | Portuguese | 39.82 | 54.48 | 62.12 |
| | | Spanish | 41.5 | 55.1 | 62.5 |
| | | Italian | 39.8 | 53.8 | 61.6 |
| | | German | 39.2 | 53.3 | 60.6 |
| | | French | 40.5 | 54.6 | 62.3 |
| | | Hindi | 33.5 | 43.3 | 50.9 |
| | | Thai | 34.7 | 44.5 | 50.3 |
## Responsibility & Safety
As part of our Responsible release approach, we followed a three-pronged strategy to managing trust & safety risks:
1. Enable developers to deploy helpful, safe and flexible experiences for their target audience and for the use cases supported by Llama
2. Protect developers against adversarial users aiming to exploit Llama capabilities to potentially cause harm
3. Provide protections for the community to help prevent the misuse of our models
### Responsible Deployment
**Approach:** Llama is a foundational technology designed to be used in a variety of use cases. Examples on how Meta’s Llama models have been responsibly deployed can be found in our [Community Stories webpage](https://llama.meta.com/community-stories/). Our approach is to build the most helpful models, enabling the world to benefit from the technology power, by aligning our model safety for generic use cases and addressing a standard set of harms. Developers are then in the driver’s seat to tailor safety for their use cases, defining their own policies and deploying the models with the necessary safeguards in their Llama systems. Llama 3.2 was developed following the best practices outlined in our [Responsible Use Guide](https://llama.meta.com/responsible-use-guide/).
#### Llama 3.2 Instruct
**Objective:** Our main objectives for conducting safety fine-tuning are to provide the research community with a valuable resource for studying the robustness of safety fine-tuning, as well as to offer developers a readily available, safe, and powerful model for various applications to reduce the developer workload to deploy safe AI systems. We implemented the same set of safety mitigations as in Llama 3, and you can learn more about these in the Llama 3 [paper](https://ai.meta.com/research/publications/the-llama-3-herd-of-models/).
**Fine-Tuning Data:** We employ a multi-faceted approach to data collection, combining human-generated data from our vendors with synthetic data to mitigate potential safety risks. We’ve developed many large language model (LLM)-based classifiers that enable us to thoughtfully select high-quality prompts and responses, enhancing data quality control.
**Refusals and Tone:** Building on the work we started with Llama 3, we put a great emphasis on model refusals to benign prompts as well as refusal tone. We included both borderline and adversarial prompts in our safety data strategy, and modified our safety data responses to follow tone guidelines.
#### Llama 3.2 Systems
**Safety as a System:** Large language models, including Llama 3.2, **are not designed to be deployed in isolation** but instead should be deployed as part of an overall AI system with additional safety guardrails as required. Developers are expected to deploy system safeguards when building agentic systems. Safeguards are key to achieve the right helpfulness-safety alignment as well as mitigating safety and security risks inherent to the system and any integration of the model or system with external tools. As part of our responsible release approach, we provide the community with [safeguards](https://llama.meta.com/trust-and-safety/) that developers should deploy with Llama models or other LLMs, including Llama Guard, Prompt Guard and Code Shield. All our [reference implementations](https://github.com/meta-llama/llama-agentic-system) demos contain these safeguards by default so developers can benefit from system-level safety out-of-the-box.
### New Capabilities and Use Cases
**Technological Advancement:** Llama releases usually introduce new capabilities that require specific considerations in addition to the best practices that generally apply across all Generative AI use cases. For prior release capabilities also supported by Llama 3.2, see [Llama 3.1 Model Card](https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/MODEL_CARD.md), as the same considerations apply here as well.
**Constrained Environments:** Llama 3.2 1B and 3B models are expected to be deployed in highly constrained environments, such as mobile devices. LLM Systems using smaller models will have a different alignment profile and safety/helpfulness tradeoff than more complex, larger systems. Developers should ensure the safety of their system meets the requirements of their use case. We recommend using lighter system safeguards for such use cases, like Llama Guard 3-1B or its mobile-optimized version.
### Evaluations
**Scaled Evaluations:** We built dedicated, adversarial evaluation datasets and evaluated systems composed of Llama models and Purple Llama safeguards to filter input prompt and output response. It is important to evaluate applications in context, and we recommend building dedicated evaluation dataset for your use case.
**Red Teaming:** We conducted recurring red teaming exercises with the goal of discovering risks via adversarial prompting and we used the learnings to improve our benchmarks and safety tuning datasets. We partnered early with subject-matter experts in critical risk areas to understand the nature of these real-world harms and how such models may lead to unintended harm for society. Based on these conversations, we derived a set of adversarial goals for the red team to attempt to achieve, such as extracting harmful information or reprogramming the model to act in a potentially harmful capacity. The red team consisted of experts in cybersecurity, adversarial machine learning, responsible AI, and integrity in addition to multilingual content specialists with background in integrity issues in specific geographic markets.
### Critical Risks
In addition to our safety work above, we took extra care on measuring and/or mitigating the following critical risk areas:
**1\. CBRNE (Chemical, Biological, Radiological, Nuclear, and Explosive Weapons):** Llama 3.2 1B and 3B models are smaller and less capable derivatives of Llama 3.1. For Llama 3.1 70B and 405B, to assess risks related to proliferation of chemical and biological weapons, we performed uplift testing designed to assess whether use of Llama 3.1 models could meaningfully increase the capabilities of malicious actors to plan or carry out attacks using these types of weapons and have determined that such testing also applies to the smaller 1B and 3B models.
**2\. Child Safety:** Child Safety risk assessments were conducted using a team of experts, to assess the model’s capability to produce outputs that could result in Child Safety risks and inform on any necessary and appropriate risk mitigations via fine tuning. We leveraged those expert red teaming sessions to expand the coverage of our evaluation benchmarks through Llama 3 model development. For Llama 3, we conducted new in-depth sessions using objective based methodologies to assess the model risks along multiple attack vectors including the additional languages Llama 3 is trained on. We also partnered with content specialists to perform red teaming exercises assessing potentially violating content while taking account of market specific nuances or experiences.
**3\. Cyber Attacks:** For Llama 3.1 405B, our cyber attack uplift study investigated whether LLMs can enhance human capabilities in hacking tasks, both in terms of skill level and speed.
Our attack automation study focused on evaluating the capabilities of LLMs when used as autonomous agents in cyber offensive operations, specifically in the context of ransomware attacks. This evaluation was distinct from previous studies that considered LLMs as interactive assistants. The primary objective was to assess whether these models could effectively function as independent agents in executing complex cyber-attacks without human intervention. Because Llama 3.2’s 1B and 3B models are smaller and less capable models than Llama 3.1 405B, we broadly believe that the testing conducted for the 405B model also applies to Llama 3.2 models.
### Community
**Industry Partnerships:** Generative AI safety requires expertise and tooling, and we believe in the strength of the open community to accelerate its progress. We are active members of open consortiums, including the AI Alliance, Partnership on AI and MLCommons, actively contributing to safety standardization and transparency. We encourage the community to adopt taxonomies like the MLCommons Proof of Concept evaluation to facilitate collaboration and transparency on safety and content evaluations. Our Purple Llama tools are open sourced for the community to use and widely distributed across ecosystem partners including cloud service providers. We encourage community contributions to our [Github repository](https://github.com/meta-llama/PurpleLlama).
**Grants:** We also set up the [Llama Impact Grants](https://llama.meta.com/llama-impact-grants/) program to identify and support the most compelling applications of Meta’s Llama model for societal benefit across three categories: education, climate and open innovation. The 20 finalists from the hundreds of applications can be found [here](https://llama.meta.com/llama-impact-grants/#finalists).
**Reporting:** Finally, we put in place a set of resources including an [output reporting mechanism](https://developers.facebook.com/llama_output_feedback) and [bug bounty program](https://www.facebook.com/whitehat) to continuously improve the Llama technology with the help of the community.
## Ethical Considerations and Limitations
**Values:** The core values of Llama 3.2 are openness, inclusivity and helpfulness. It is meant to serve everyone, and to work for a wide range of use cases. It is thus designed to be accessible to people across many different backgrounds, experiences and perspectives. Llama 3.2 addresses users and their needs as they are, without insertion unnecessary judgment or normativity, while reflecting the understanding that even content that may appear problematic in some cases can serve valuable purposes in others. It respects the dignity and autonomy of all users, especially in terms of the values of free thought and expression that power innovation and progress.
**Testing:** Llama 3.2 is a new technology, and like any new technology, there are risks associated with its use. Testing conducted to date has not covered, nor could it cover, all scenarios. For these reasons, as with all LLMs, Llama 3.2’s potential outputs cannot be predicted in advance, and the model may in some instances produce inaccurate, biased or other objectionable responses to user prompts. Therefore, before deploying any applications of Llama 3.2 models, developers should perform safety testing and tuning tailored to their specific applications of the model. Please refer to available resources including our [Responsible Use Guide](https://llama.meta.com/responsible-use-guide), [Trust and Safety](https://llama.meta.com/trust-and-safety/) solutions, and other [resources](https://llama.meta.com/docs/get-started/) to learn more about responsible development.
---
language:
- en
- de
- fr
- it
- pt
- hi
- es
- th
pipeline_tag: text-generation
tags:
- facebook
- meta
- pytorch
- llama
- llama-3
license: llama3.1
extra_gated_prompt: >-
### LLAMA 3.1 COMMUNITY LICENSE AGREEMENT
Llama 3.1 Version Release Date: July 23, 2024
"Agreement" means the terms and conditions for use, reproduction, distribution
and modification of the Llama Materials set forth herein.
"Documentation" means the specifications, manuals and documentation
accompanying Llama 3.1 distributed by Meta at
https://llama.meta.com/doc/overview.
"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.
"Llama 3.1" means the foundational large language models and software and
algorithms, including machine-learning model code, trained model weights,
inference-enabling code, training-enabling code, fine-tuning enabling code and
other elements of the foregoing distributed by Meta at
https://llama.meta.com/llama-downloads.
"Llama Materials" means, collectively, Meta’s proprietary Llama 3.1 and
Documentation (and any portion thereof) made available under this Agreement.
"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).
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 Llama Materials to use,
reproduce, distribute, copy, create derivative works of, and make
modifications to the Llama Materials.
b. Redistribution and Use.
i. If you distribute or make available the Llama Materials (or any derivative
works thereof), or a product or service (including another AI model) that
contains any of them, you shall (A) provide a copy of this Agreement with any
such Llama Materials; and (B) prominently display “Built with Llama” on a
related website, user interface, blogpost, about page, or product
documentation. If you use the Llama Materials or any outputs or results of the
Llama Materials to create, train, fine tune, or otherwise improve an AI model,
which is distributed or made available, you shall also include “Llama” at the
beginning of any such AI model name.
ii. If you receive Llama Materials, or any derivative works thereof, from a
Licensee as part of an integrated end user product, then Section 2 of this
Agreement will not apply to you.
iii. You must retain in all copies of the Llama Materials that you distribute
the following attribution notice within a “Notice” text file distributed as a
part of such copies: “Llama 3.1 is licensed under the Llama 3.1 Community
License, Copyright © Meta Platforms, Inc. All Rights Reserved.”
iv. Your use of the Llama Materials must comply with applicable laws and
regulations (including trade compliance laws and regulations) and adhere to
the Acceptable Use Policy for the Llama Materials (available at
https://llama.meta.com/llama3_1/use-policy), which is hereby incorporated by
reference into this Agreement.
2. Additional Commercial Terms. If, on the Llama 3.1 version release date, the
monthly active users of the products or services made available by or for
Licensee, or Licensee’s affiliates, is greater than 700 million monthly active
users in the preceding calendar month, you must request a license from Meta,
which Meta may grant to you in its sole discretion, and you are not authorized
to exercise any of the rights under this Agreement unless or until Meta
otherwise expressly grants you such rights.
3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE LLAMA
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 LLAMA MATERIALS AND ASSUME ANY
RISKS ASSOCIATED WITH YOUR USE OF THE LLAMA 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 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. No trademark licenses are granted under this Agreement, and in connection
with the Llama Materials, neither Meta nor Licensee may use any name or mark
owned by or associated with the other or any of its affiliates, except as
required for reasonable and customary use in describing and redistributing the
Llama Materials or as set forth in this Section 5(a). Meta hereby grants you a
license to use “Llama” (the “Mark”) solely as required to comply with the last
sentence of Section 1.b.i. You will comply with Meta’s brand guidelines
(currently accessible at
https://about.meta.com/brand/resources/meta/company-brand/ ). All goodwill
arising out of your use of the Mark will inure to the benefit of Meta.
b. Subject to Meta’s ownership of Llama Materials and derivatives made by or
for Meta, with respect to any derivative works and modifications of the Llama
Materials that are made by you, as between you and Meta, you are and will be
the owner of such derivative works and modifications.
c. If you institute litigation or other proceedings against Meta or any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the Llama
Materials or Llama 3.1 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 Llama Materials.
6. Term and Termination. The term of this Agreement will commence upon your
acceptance of this Agreement or access to the Llama 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 Llama Materials. Sections 3,
4 and 7 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.
### Llama 3.1 Acceptable Use Policy
Meta is committed to promoting safe and fair use of its tools and features,
including Llama 3.1. If you access or use Llama 3.1, you agree to this
Acceptable Use Policy (“Policy”). The most recent copy of this policy can be
found at
[https://llama.meta.com/llama3_1/use-policy](https://llama.meta.com/llama3_1/use-policy)
#### Prohibited Uses
We want everyone to use Llama 3.1 safely and responsibly. You agree you will
not use, or allow others to use, Llama 3.1 to:
1. Violate the law or others’ rights, including to:
1. Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:
1. Violence or terrorism
2. Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material
3. Human trafficking, exploitation, and sexual violence
4. 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.
5. Sexual solicitation
6. Any other criminal activity
3. Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
4. 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
5. Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
6. 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
7. 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 products or services using the Llama Materials
8. 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 Llama 3.1 related to the following:
1. 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
2. Guns and illegal weapons (including weapon development)
3. Illegal drugs and regulated/controlled substances
4. Operation of critical infrastructure, transportation technologies, or heavy machinery
5. Self-harm or harm to others, including suicide, cutting, and eating disorders
6. 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 Llama 3.1 related
to the following:
1. Generating, promoting, or furthering fraud or the creation or promotion of disinformation
2. Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
3. Generating, promoting, or further distributing spam
4. Impersonating another individual without consent, authorization, or legal right
5. Representing that the use of Llama 3.1 or outputs are human-generated
6. 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 AI
system
Please report any violation of this Policy, software “bug,” or other problems
that could lead to a violation of this Policy through one of the following
means:
* Reporting issues with the model: [https://github.com/meta-llama/llama-models/issues](https://github.com/meta-llama/llama-models/issues)
* Reporting risky content generated by the model:
developers.facebook.com/llama_output_feedback
* Reporting bugs and security concerns: facebook.com/whitehat/info
* Reporting violations of the Acceptable Use Policy or unlicensed uses of Meta Llama 3: LlamaUseReport@meta.com
extra_gated_fields:
First Name: text
Last Name: text
Date of birth: date_picker
Country: country
Affiliation: text
Job title:
type: select
options:
- Student
- Research Graduate
- AI researcher
- AI developer/engineer
- Reporter
- Other
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
library_name: transformers
---
## Model Information
The Meta Llama 3.1 collection of multilingual large language models (LLMs) is a collection of pretrained and instruction tuned generative models in 8B, 70B and 405B sizes (text in/text out). The Llama 3.1 instruction tuned text only models (8B, 70B, 405B) are optimized for multilingual dialogue use cases and outperform many of the available open source and closed chat models on common industry benchmarks.
**Model developer**: Meta
**Model Architecture:** Llama 3.1 is an auto-regressive language model that uses an optimized transformer architecture. The tuned versions use supervised fine-tuning (SFT) and reinforcement learning with human feedback (RLHF) to align with human preferences for helpfulness and safety.
<table>
<tr>
<td>
</td>
<td><strong>Training Data</strong>
</td>
<td><strong>Params</strong>
</td>
<td><strong>Input modalities</strong>
</td>
<td><strong>Output modalities</strong>
</td>
<td><strong>Context length</strong>
</td>
<td><strong>GQA</strong>
</td>
<td><strong>Token count</strong>
</td>
<td><strong>Knowledge cutoff</strong>
</td>
</tr>
<tr>
<td rowspan="3" >Llama 3.1 (text only)
</td>
<td rowspan="3" >A new mix of publicly available online data.
</td>
<td>8B
</td>
<td>Multilingual Text
</td>
<td>Multilingual Text and code
</td>
<td>128k
</td>
<td>Yes
</td>
<td rowspan="3" >15T+
</td>
<td rowspan="3" >December 2023
</td>
</tr>
<tr>
<td>70B
</td>
<td>Multilingual Text
</td>
<td>Multilingual Text and code
</td>
<td>128k
</td>
<td>Yes
</td>
</tr>
<tr>
<td>405B
</td>
<td>Multilingual Text
</td>
<td>Multilingual Text and code
</td>
<td>128k
</td>
<td>Yes
</td>
</tr>
</table>
**Supported languages:** English, German, French, Italian, Portuguese, Hindi, Spanish, and Thai.
**Llama 3.1 family of models**. Token counts refer to pretraining data only. All model versions use Grouped-Query Attention (GQA) for improved inference scalability.
**Model Release Date:** July 23, 2024.
**Status:** This is a static model trained on an offline dataset. Future versions of the tuned models will be released as we improve model safety with community feedback.
**License:** A custom commercial license, the Llama 3.1 Community License, is available at: [https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/LICENSE](https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/LICENSE)
Where to send questions or comments about the model Instructions on how to provide feedback or comments on the model can be found in the model [README](https://github.com/meta-llama/llama3). For more technical information about generation parameters and recipes for how to use Llama 3.1 in applications, please go [here](https://github.com/meta-llama/llama-recipes).
## Intended Use
**Intended Use Cases** Llama 3.1 is intended for commercial and research use in multiple languages. Instruction tuned text only models are intended for assistant-like chat, whereas pretrained models can be adapted for a variety of natural language generation tasks. The Llama 3.1 model collection also supports the ability to leverage the outputs of its models to improve other models including synthetic data generation and distillation. The Llama 3.1 Community License allows for these use cases.
**Out-of-scope** Use in any manner that violates applicable laws or regulations (including trade compliance laws). Use in any other way that is prohibited by the Acceptable Use Policy and Llama 3.1 Community License. Use in languages beyond those explicitly referenced as supported in this model card**.
**<span style="text-decoration:underline;">Note</span>: Llama 3.1 has been trained on a broader collection of languages than the 8 supported languages. Developers may fine-tune Llama 3.1 models for languages beyond the 8 supported languages provided they comply with the Llama 3.1 Community License and the Acceptable Use Policy and in such cases are responsible for ensuring that any uses of Llama 3.1 in additional languages is done in a safe and responsible manner.
## How to use
This repository contains two versions of Meta-Llama-3.1-8B, for use with transformers and with the original `llama` codebase.
### Use with transformers
Starting with transformers >= 4.43.0 onward, you can run conversational inference using the Transformers pipeline abstraction or by leveraging the Auto classes with the generate() function.
Make sure to update your transformers installation via pip install --upgrade transformers.
```python
import transformers
import torch
model_id = "meta-llama/Meta-Llama-3.1-8B"
pipeline = transformers.pipeline(
"text-generation", model=model_id, model_kwargs={"torch_dtype": torch.bfloat16}, device_map="auto"
)
pipeline("Hey how are you doing today?")
```
### Use with `llama`
Please, follow the instructions in the [repository](https://github.com/meta-llama/llama).
To download Original checkpoints, see the example command below leveraging `huggingface-cli`:
```
huggingface-cli download meta-llama/Meta-Llama-3.1-8B --include "original/*" --local-dir Meta-Llama-3.1-8B
```
## Hardware and Software
**Training Factors** We used custom training libraries, Meta's custom built GPU cluster, and production infrastructure for pretraining. Fine-tuning, annotation, and evaluation were also performed on production infrastructure.
**Training utilized a cumulative of** 39.3M GPU hours of computation on H100-80GB (TDP of 700W) type hardware, per the table below. Training time is the total GPU time required for training each model and power consumption is the peak power capacity per GPU device used, adjusted for power usage efficiency.
**Training Greenhouse Gas Emissions** Estimated total location-based greenhouse gas emissions were **11,390** tons CO2eq for training. Since 2020, Meta has maintained net zero greenhouse gas emissions in its global operations and matched 100% of its electricity use with renewable energy, therefore the total market-based greenhouse gas emissions for training were 0 tons CO2eq.
<table>
<tr>
<td>
</td>
<td><strong>Training Time (GPU hours)</strong>
</td>
<td><strong>Training Power Consumption (W)</strong>
</td>
<td><strong>Training Location-Based Greenhouse Gas Emissions</strong>
<p>
<strong>(tons CO2eq)</strong>
</td>
<td><strong>Training Market-Based Greenhouse Gas Emissions</strong>
<p>
<strong>(tons CO2eq)</strong>
</td>
</tr>
<tr>
<td>Llama 3.1 8B
</td>
<td>1.46M
</td>
<td>700
</td>
<td>420
</td>
<td>0
</td>
</tr>
<tr>
<td>Llama 3.1 70B
</td>
<td>7.0M
</td>
<td>700
</td>
<td>2,040
</td>
<td>0
</td>
</tr>
<tr>
<td>Llama 3.1 405B
</td>
<td>30.84M
</td>
<td>700
</td>
<td>8,930
</td>
<td>0
</td>
</tr>
<tr>
<td>Total
</td>
<td>39.3M
<td>
<ul>
</ul>
</td>
<td>11,390
</td>
<td>0
</td>
</tr>
</table>
The methodology used to determine training energy use and greenhouse gas emissions can be found [here](https://arxiv.org/pdf/2204.05149). Since Meta is openly releasing these models, the training energy use and greenhouse gas emissions will not be incurred by others.
## Training Data
**Overview:** Llama 3.1 was pretrained on ~15 trillion tokens of data from publicly available sources. The fine-tuning data includes publicly available instruction datasets, as well as over 25M synthetically generated examples.
**Data Freshness:** The pretraining data has a cutoff of December 2023.
## Benchmark scores
In this section, we report the results for Llama 3.1 models on standard automatic benchmarks. For all the evaluations, we use our internal evaluations library.
### Base pretrained models
<table>
<tr>
<td><strong>Category</strong>
</td>
<td><strong>Benchmark</strong>
</td>
<td><strong># Shots</strong>
</td>
<td><strong>Metric</strong>
</td>
<td><strong>Llama 3 8B</strong>
</td>
<td><strong>Llama 3.1 8B</strong>
</td>
<td><strong>Llama 3 70B</strong>
</td>
<td><strong>Llama 3.1 70B</strong>
</td>
<td><strong>Llama 3.1 405B</strong>
</td>
</tr>
<tr>
<td rowspan="7" >General
</td>
<td>MMLU
</td>
<td>5
</td>
<td>macro_avg/acc_char
</td>
<td>66.7
</td>
<td>66.7
</td>
<td>79.5
</td>
<td>79.3
</td>
<td>85.2
</td>
</tr>
<tr>
<td>MMLU-Pro (CoT)
</td>
<td>5
</td>
<td>macro_avg/acc_char
</td>
<td>36.2
</td>
<td>37.1
</td>
<td>55.0
</td>
<td>53.8
</td>
<td>61.6
</td>
</tr>
<tr>
<td>AGIEval English
</td>
<td>3-5
</td>
<td>average/acc_char
</td>
<td>47.1
</td>
<td>47.8
</td>
<td>63.0
</td>
<td>64.6
</td>
<td>71.6
</td>
</tr>
<tr>
<td>CommonSenseQA
</td>
<td>7
</td>
<td>acc_char
</td>
<td>72.6
</td>
<td>75.0
</td>
<td>83.8
</td>
<td>84.1
</td>
<td>85.8
</td>
</tr>
<tr>
<td>Winogrande
</td>
<td>5
</td>
<td>acc_char
</td>
<td>-
</td>
<td>60.5
</td>
<td>-
</td>
<td>83.3
</td>
<td>86.7
</td>
</tr>
<tr>
<td>BIG-Bench Hard (CoT)
</td>
<td>3
</td>
<td>average/em
</td>
<td>61.1
</td>
<td>64.2
</td>
<td>81.3
</td>
<td>81.6
</td>
<td>85.9
</td>
</tr>
<tr>
<td>ARC-Challenge
</td>
<td>25
</td>
<td>acc_char
</td>
<td>79.4
</td>
<td>79.7
</td>
<td>93.1
</td>
<td>92.9
</td>
<td>96.1
</td>
</tr>
<tr>
<td>Knowledge reasoning
</td>
<td>TriviaQA-Wiki
</td>
<td>5
</td>
<td>em
</td>
<td>78.5
</td>
<td>77.6
</td>
<td>89.7
</td>
<td>89.8
</td>
<td>91.8
</td>
</tr>
<tr>
<td rowspan="4" >Reading comprehension
</td>
<td>SQuAD
</td>
<td>1
</td>
<td>em
</td>
<td>76.4
</td>
<td>77.0
</td>
<td>85.6
</td>
<td>81.8
</td>
<td>89.3
</td>
</tr>
<tr>
<td>QuAC (F1)
</td>
<td>1
</td>
<td>f1
</td>
<td>44.4
</td>
<td>44.9
</td>
<td>51.1
</td>
<td>51.1
</td>
<td>53.6
</td>
</tr>
<tr>
<td>BoolQ
</td>
<td>0
</td>
<td>acc_char
</td>
<td>75.7
</td>
<td>75.0
</td>
<td>79.0
</td>
<td>79.4
</td>
<td>80.0
</td>
</tr>
<tr>
<td>DROP (F1)
</td>
<td>3
</td>
<td>f1
</td>
<td>58.4
</td>
<td>59.5
</td>
<td>79.7
</td>
<td>79.6
</td>
<td>84.8
</td>
</tr>
</table>
### Instruction tuned models
<table>
<tr>
<td><strong>Category</strong>
</td>
<td><strong>Benchmark</strong>
</td>
<td><strong># Shots</strong>
</td>
<td><strong>Metric</strong>
</td>
<td><strong>Llama 3 8B Instruct</strong>
</td>
<td><strong>Llama 3.1 8B Instruct</strong>
</td>
<td><strong>Llama 3 70B Instruct</strong>
</td>
<td><strong>Llama 3.1 70B Instruct</strong>
</td>
<td><strong>Llama 3.1 405B Instruct</strong>
</td>
</tr>
<tr>
<td rowspan="4" >General
</td>
<td>MMLU
</td>
<td>5
</td>
<td>macro_avg/acc
</td>
<td>68.5
</td>
<td>69.4
</td>
<td>82.0
</td>
<td>83.6
</td>
<td>87.3
</td>
</tr>
<tr>
<td>MMLU (CoT)
</td>
<td>0
</td>
<td>macro_avg/acc
</td>
<td>65.3
</td>
<td>73.0
</td>
<td>80.9
</td>
<td>86.0
</td>
<td>88.6
</td>
</tr>
<tr>
<td>MMLU-Pro (CoT)
</td>
<td>5
</td>
<td>micro_avg/acc_char
</td>
<td>45.5
</td>
<td>48.3
</td>
<td>63.4
</td>
<td>66.4
</td>
<td>73.3
</td>
</tr>
<tr>
<td>IFEval
</td>
<td>
</td>
<td>
</td>
<td>76.8
</td>
<td>80.4
</td>
<td>82.9
</td>
<td>87.5
</td>
<td>88.6
</td>
</tr>
<tr>
<td rowspan="2" >Reasoning
</td>
<td>ARC-C
</td>
<td>0
</td>
<td>acc
</td>
<td>82.4
</td>
<td>83.4
</td>
<td>94.4
</td>
<td>94.8
</td>
<td>96.9
</td>
</tr>
<tr>
<td>GPQA
</td>
<td>0
</td>
<td>em
</td>
<td>34.6
</td>
<td>30.4
</td>
<td>39.5
</td>
<td>41.7
</td>
<td>50.7
</td>
</tr>
<tr>
<td rowspan="4" >Code
</td>
<td>HumanEval
</td>
<td>0
</td>
<td>pass@1
</td>
<td>60.4
</td>
<td>72.6
</td>
<td>81.7
</td>
<td>80.5
</td>
<td>89.0
</td>
</tr>
<tr>
<td>MBPP ++ base version
</td>
<td>0
</td>
<td>pass@1
</td>
<td>70.6
</td>
<td>72.8
</td>
<td>82.5
</td>
<td>86.0
</td>
<td>88.6
</td>
</tr>
<tr>
<td>Multipl-E HumanEval
</td>
<td>0
</td>
<td>pass@1
</td>
<td>-
</td>
<td>50.8
</td>
<td>-
</td>
<td>65.5
</td>
<td>75.2
</td>
</tr>
<tr>
<td>Multipl-E MBPP
</td>
<td>0
</td>
<td>pass@1
</td>
<td>-
</td>
<td>52.4
</td>
<td>-
</td>
<td>62.0
</td>
<td>65.7
</td>
</tr>
<tr>
<td rowspan="2" >Math
</td>
<td>GSM-8K (CoT)
</td>
<td>8
</td>
<td>em_maj1@1
</td>
<td>80.6
</td>
<td>84.5
</td>
<td>93.0
</td>
<td>95.1
</td>
<td>96.8
</td>
</tr>
<tr>
<td>MATH (CoT)
</td>
<td>0
</td>
<td>final_em
</td>
<td>29.1
</td>
<td>51.9
</td>
<td>51.0
</td>
<td>68.0
</td>
<td>73.8
</td>
</tr>
<tr>
<td rowspan="4" >Tool Use
</td>
<td>API-Bank
</td>
<td>0
</td>
<td>acc
</td>
<td>48.3
</td>
<td>82.6
</td>
<td>85.1
</td>
<td>90.0
</td>
<td>92.0
</td>
</tr>
<tr>
<td>BFCL
</td>
<td>0
</td>
<td>acc
</td>
<td>60.3
</td>
<td>76.1
</td>
<td>83.0
</td>
<td>84.8
</td>
<td>88.5
</td>
</tr>
<tr>
<td>Gorilla Benchmark API Bench
</td>
<td>0
</td>
<td>acc
</td>
<td>1.7
</td>
<td>8.2
</td>
<td>14.7
</td>
<td>29.7
</td>
<td>35.3
</td>
</tr>
<tr>
<td>Nexus (0-shot)
</td>
<td>0
</td>
<td>macro_avg/acc
</td>
<td>18.1
</td>
<td>38.5
</td>
<td>47.8
</td>
<td>56.7
</td>
<td>58.7
</td>
</tr>
<tr>
<td>Multilingual
</td>
<td>Multilingual MGSM (CoT)
</td>
<td>0
</td>
<td>em
</td>
<td>-
</td>
<td>68.9
</td>
<td>-
</td>
<td>86.9
</td>
<td>91.6
</td>
</tr>
</table>
#### Multilingual benchmarks
<table>
<tr>
<td><strong>Category</strong>
</td>
<td><strong>Benchmark</strong>
</td>
<td><strong>Language</strong>
</td>
<td><strong>Llama 3.1 8B</strong>
</td>
<td><strong>Llama 3.1 70B</strong>
</td>
<td><strong>Llama 3.1 405B</strong>
</td>
</tr>
<tr>
<td rowspan="9" ><strong>General</strong>
</td>
<td rowspan="9" ><strong>MMLU (5-shot, macro_avg/acc)</strong>
</td>
<td>Portuguese
</td>
<td>62.12
</td>
<td>80.13
</td>
<td>84.95
</td>
</tr>
<tr>
<td>Spanish
</td>
<td>62.45
</td>
<td>80.05
</td>
<td>85.08
</td>
</tr>
<tr>
<td>Italian
</td>
<td>61.63
</td>
<td>80.4
</td>
<td>85.04
</td>
</tr>
<tr>
<td>German
</td>
<td>60.59
</td>
<td>79.27
</td>
<td>84.36
</td>
</tr>
<tr>
<td>French
</td>
<td>62.34
</td>
<td>79.82
</td>
<td>84.66
</td>
</tr>
<tr>
<td>Hindi
</td>
<td>50.88
</td>
<td>74.52
</td>
<td>80.31
</td>
</tr>
<tr>
<td>Thai
</td>
<td>50.32
</td>
<td>72.95
</td>
<td>78.21
</td>
</tr>
</table>
## Responsibility & Safety
As part of our Responsible release approach, we followed a three-pronged strategy to managing trust & safety risks:
* Enable developers to deploy helpful, safe and flexible experiences for their target audience and for the use cases supported by Llama.
* Protect developers against adversarial users aiming to exploit Llama capabilities to potentially cause harm.
* Provide protections for the community to help prevent the misuse of our models.
### Responsible deployment
Llama is a foundational technology designed to be used in a variety of use cases, examples on how Meta’s Llama models have been responsibly deployed can be found in our [Community Stories webpage](https://llama.meta.com/community-stories/). Our approach is to build the most helpful models enabling the world to benefit from the technology power, by aligning our model safety for the generic use cases addressing a standard set of harms. Developers are then in the driver seat to tailor safety for their use case, defining their own policy and deploying the models with the necessary safeguards in their Llama systems. Llama 3.1 was developed following the best practices outlined in our Responsible Use Guide, you can refer to the [Responsible Use Guide](https://llama.meta.com/responsible-use-guide/) to learn more.
#### Llama 3.1 instruct
Our main objectives for conducting safety fine-tuning are to provide the research community with a valuable resource for studying the robustness of safety fine-tuning, as well as to offer developers a readily available, safe, and powerful model for various applications to reduce the developer workload to deploy safe AI systems. For more details on the safety mitigations implemented please read the Llama 3 paper.
**Fine-tuning data**
We employ a multi-faceted approach to data collection, combining human-generated data from our vendors with synthetic data to mitigate potential safety risks. We’ve developed many large language model (LLM)-based classifiers that enable us to thoughtfully select high-quality prompts and responses, enhancing data quality control.
**Refusals and Tone**
Building on the work we started with Llama 3, we put a great emphasis on model refusals to benign prompts as well as refusal tone. We included both borderline and adversarial prompts in our safety data strategy, and modified our safety data responses to follow tone guidelines.
#### Llama 3.1 systems
**Large language models, including Llama 3.1, are not designed to be deployed in isolation but instead should be deployed as part of an overall AI system with additional safety guardrails as required.** Developers are expected to deploy system safeguards when building agentic systems. Safeguards are key to achieve the right helpfulness-safety alignment as well as mitigating safety and security risks inherent to the system and any integration of the model or system with external tools.
As part of our responsible release approach, we provide the community with [safeguards](https://llama.meta.com/trust-and-safety/) that developers should deploy with Llama models or other LLMs, including Llama Guard 3, Prompt Guard and Code Shield. All our [reference implementations](https://github.com/meta-llama/llama-agentic-system) demos contain these safeguards by default so developers can benefit from system-level safety out-of-the-box.
#### New capabilities
Note that this release introduces new capabilities, including a longer context window, multilingual inputs and outputs and possible integrations by developers with third party tools. Building with these new capabilities requires specific considerations in addition to the best practices that generally apply across all Generative AI use cases.
**Tool-use**: Just like in standard software development, developers are responsible for the integration of the LLM with the tools and services of their choice. They should define a clear policy for their use case and assess the integrity of the third party services they use to be aware of the safety and security limitations when using this capability. Refer to the Responsible Use Guide for best practices on the safe deployment of the third party safeguards.
**Multilinguality**: Llama 3.1 supports 7 languages in addition to English: French, German, Hindi, Italian, Portuguese, Spanish, and Thai. Llama may be able to output text in other languages than those that meet performance thresholds for safety and helpfulness. We strongly discourage developers from using this model to converse in non-supported languages without implementing finetuning and system controls in alignment with their policies and the best practices shared in the Responsible Use Guide.
### Evaluations
We evaluated Llama models for common use cases as well as specific capabilities. Common use cases evaluations measure safety risks of systems for most commonly built applications including chat bot, coding assistant, tool calls. We built dedicated, adversarial evaluation datasets and evaluated systems composed of Llama models and Llama Guard 3 to filter input prompt and output response. It is important to evaluate applications in context, and we recommend building dedicated evaluation dataset for your use case. Prompt Guard and Code Shield are also available if relevant to the application.
Capability evaluations measure vulnerabilities of Llama models inherent to specific capabilities, for which were crafted dedicated benchmarks including long context, multilingual, tools calls, coding or memorization.
**Red teaming**
For both scenarios, we conducted recurring red teaming exercises with the goal of discovering risks via adversarial prompting and we used the learnings to improve our benchmarks and safety tuning datasets.
We partnered early with subject-matter experts in critical risk areas to understand the nature of these real-world harms and how such models may lead to unintended harm for society. Based on these conversations, we derived a set of adversarial goals for the red team to attempt to achieve, such as extracting harmful information or reprogramming the model to act in a potentially harmful capacity. The red team consisted of experts in cybersecurity, adversarial machine learning, responsible AI, and integrity in addition to multilingual content specialists with background in integrity issues in specific geographic markets.
### Critical and other risks
We specifically focused our efforts on mitigating the following critical risk areas:
**1- CBRNE (Chemical, Biological, Radiological, Nuclear, and Explosive materials) helpfulness**
To assess risks related to proliferation of chemical and biological weapons, we performed uplift testing designed to assess whether use of Llama 3.1 models could meaningfully increase the capabilities of malicious actors to plan or carry out attacks using these types of weapons.
**2. Child Safety**
Child Safety risk assessments were conducted using a team of experts, to assess the model’s capability to produce outputs that could result in Child Safety risks and inform on any necessary and appropriate risk mitigations via fine tuning. We leveraged those expert red teaming sessions to expand the coverage of our evaluation benchmarks through Llama 3 model development. For Llama 3, we conducted new in-depth sessions using objective based methodologies to assess the model risks along multiple attack vectors including the additional languages Llama 3 is trained on. We also partnered with content specialists to perform red teaming exercises assessing potentially violating content while taking account of market specific nuances or experiences.
**3. Cyber attack enablement**
Our cyber attack uplift study investigated whether LLMs can enhance human capabilities in hacking tasks, both in terms of skill level and speed.
Our attack automation study focused on evaluating the capabilities of LLMs when used as autonomous agents in cyber offensive operations, specifically in the context of ransomware attacks. This evaluation was distinct from previous studies that considered LLMs as interactive assistants. The primary objective was to assess whether these models could effectively function as independent agents in executing complex cyber-attacks without human intervention.
Our study of Llama-3.1-405B’s social engineering uplift for cyber attackers was conducted to assess the effectiveness of AI models in aiding cyber threat actors in spear phishing campaigns. Please read our Llama 3.1 Cyber security whitepaper to learn more.
### Community
Generative AI safety requires expertise and tooling, and we believe in the strength of the open community to accelerate its progress. We are active members of open consortiums, including the AI Alliance, Partnership on AI and MLCommons, actively contributing to safety standardization and transparency. We encourage the community to adopt taxonomies like the MLCommons Proof of Concept evaluation to facilitate collaboration and transparency on safety and content evaluations. Our Purple Llama tools are open sourced for the community to use and widely distributed across ecosystem partners including cloud service providers. We encourage community contributions to our [Github repository](https://github.com/meta-llama/PurpleLlama).
We also set up the [Llama Impact Grants](https://llama.meta.com/llama-impact-grants/) program to identify and support the most compelling applications of Meta’s Llama model for societal benefit across three categories: education, climate and open innovation. The 20 finalists from the hundreds of applications can be found [here](https://llama.meta.com/llama-impact-grants/#finalists).
Finally, we put in place a set of resources including an [output reporting mechanism](https://developers.facebook.com/llama_output_feedback) and [bug bounty program](https://www.facebook.com/whitehat) to continuously improve the Llama technology with the help of the community.
## Ethical Considerations and Limitations
The core values of Llama 3.1 are openness, inclusivity and helpfulness. It is meant to serve everyone, and to work for a wide range of use cases. It is thus designed to be accessible to people across many different backgrounds, experiences and perspectives. Llama 3.1 addresses users and their needs as they are, without insertion unnecessary judgment or normativity, while reflecting the understanding that even content that may appear problematic in some cases can serve valuable purposes in others. It respects the dignity and autonomy of all users, especially in terms of the values of free thought and expression that power innovation and progress.
But Llama 3.1 is a new technology, and like any new technology, there are risks associated with its use. Testing conducted to date has not covered, nor could it cover, all scenarios. For these reasons, as with all LLMs, Llama 3.1’s potential outputs cannot be predicted in advance, and the model may in some instances produce inaccurate, biased or other objectionable responses to user prompts. Therefore, before deploying any applications of Llama 3.1 models, developers should perform safety testing and tuning tailored to their specific applications of the model. Please refer to available resources including our [Responsible Use Guide](https://llama.meta.com/responsible-use-guide), [Trust and Safety](https://llama.meta.com/trust-and-safety/) solutions, and other [resources](https://llama.meta.com/docs/get-started/) to learn more about responsible development.
\ No newline at end of file
"""
This script is designed to replace the tokenizer of a given model along with its embeddings.
It allows for swapping out the existing tokenizer and embedding layer with new ones,
which can be useful for fine-tuning models on specific domains or languages,
or for experimenting with different tokenization strategies.
"""
import argparse
import json
import os
import torch
import torch.nn as nn
from transformers import AutoTokenizer
from tqdm import tqdm
from allamo.logging import configure_logger, logger
from allamo.train_utils import (
get_model_checkpoint_path,
get_config_checkpoint_path,
)
def copy_layer(model_checkpoint, state_dict, src_layer_idx, dest_layer_idx):
logger.info(f"copying weights from layer {src_layer_idx} to layer {dest_layer_idx}")
state_dict[f"layers.{dest_layer_idx}.attention.q_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention.q_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.attention.k_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention.k_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.attention.v_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention.v_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.attention.c_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention.c_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.feed_forward.gate_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.feed_forward.gate_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.feed_forward.down_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.feed_forward.down_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.feed_forward.up_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.feed_forward.up_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.attention_norm.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention_norm.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.ffn_norm.weight"] = model_checkpoint[f"layers.{src_layer_idx}.ffn_norm.weight"].clone()
def adjust_model(input_dir_path, input_checkpoint_name_base, output_dir_path, output_checkpoint_name_base, add_first_layer, add_last_layer, source_tokenizer_path, target_tokenizer_path):
os.makedirs(output_dir_path, exist_ok=True)
logger.info(f"loading checkpoint from {input_dir_path}...")
with open(get_config_checkpoint_path(input_checkpoint_name_base, input_dir_path), "r", encoding="utf-8") as f:
config_checkpoint = json.load(f)
model_checkpoint = torch.load(get_model_checkpoint_path(input_checkpoint_name_base, input_dir_path), map_location='cpu')
unwanted_prefix = '_orig_mod.'
for k,v in list(model_checkpoint.items()):
if k.startswith(unwanted_prefix):
model_checkpoint[k[len(unwanted_prefix):]] = model_checkpoint.pop(k)
if source_tokenizer_path and target_tokenizer_path:
logger.info(f"swapping embeddings for the new tokenizer")
source_tokenizer = AutoTokenizer.from_pretrained(source_tokenizer_path)
target_tokenizer = AutoTokenizer.from_pretrained(target_tokenizer_path)
new_embs = nn.Embedding(len(target_tokenizer), config_checkpoint['model_args']['n_embd']).weight.data
new_lm_head = nn.Linear(config_checkpoint['model_args']['n_embd'], len(target_tokenizer), bias=False).weight.data
existing_token_count = 0
new_token_count = 0
stats = {}
for token, token_id in tqdm(target_tokenizer.get_vocab().items()):
if token in source_tokenizer.get_vocab():
existing_token_count += 1
src_token_id = source_tokenizer.get_vocab()[token]
new_embs[token_id] = model_checkpoint["tok_embeddings.weight"][src_token_id]
new_lm_head[token_id] = model_checkpoint["lm_head.weight"][src_token_id]
stats[1] = stats.get(1, 0) + 1
else:
new_token_count += 1
src_token_ids = source_tokenizer(token, add_special_tokens=False).input_ids
new_embs[token_id] = model_checkpoint["tok_embeddings.weight"][src_token_ids[-1]]
new_lm_head[token_id] = model_checkpoint["lm_head.weight"][src_token_ids[-1]]
stats[len(src_token_ids)] = stats.get(len(src_token_ids), 0) + 1
logger.info(f"Embeddings adjusted. Prev vocab size: {len(source_tokenizer)}. New vocab size: {len(target_tokenizer)}. Reused tokens: {existing_token_count}. New tokens: {new_token_count}")
logger.info(f"Prev tokens to new token counts: {stats}")
model_checkpoint["tok_embeddings.weight"] = new_embs
model_checkpoint["lm_head.weight"] = new_lm_head
state_dict = {
"tok_embeddings.weight": model_checkpoint["tok_embeddings.weight"],
"norm.weight": model_checkpoint["norm.weight"],
"lm_head.weight": model_checkpoint["lm_head.weight"],
}
expected_num_layers = config_checkpoint['model_args']['n_layer']
if add_first_layer:
expected_num_layers += 1
if add_last_layer:
expected_num_layers += 1
for src_layer_idx in range(config_checkpoint['model_args']['n_layer']):
if add_first_layer:
if src_layer_idx == 0:
copy_layer(model_checkpoint, state_dict, src_layer_idx, src_layer_idx)
copy_layer(model_checkpoint, state_dict, src_layer_idx, src_layer_idx+1)
else:
copy_layer(model_checkpoint, state_dict, src_layer_idx, src_layer_idx)
if add_last_layer:
copy_layer(model_checkpoint, state_dict, config_checkpoint['model_args']['n_layer']-1, expected_num_layers-1)
param_count = 0
param_bytes = 0
for k, v in state_dict.items():
param_count += v.numel()
param_bytes += v.numel() * v.element_size()
config_checkpoint['model_args']['n_layer'] = expected_num_layers
param_count /= 1e6
param_bytes /= 1024**2
logger.info(f"New model layers: {config_checkpoint['model_args']['n_layer']}. Model parameters: {param_count:.2f}M. Est. Size: {param_bytes:.3f}MB")
ckpt_file_path = get_config_checkpoint_path(output_checkpoint_name_base, output_dir_path)
logger.info(f"saving config checkpoint to {ckpt_file_path}")
with open(ckpt_file_path, "w", encoding="utf-8") as f:
json.dump(config_checkpoint, f, indent=4, ensure_ascii=False)
ckpt_file_path = get_model_checkpoint_path(output_checkpoint_name_base, output_dir_path)
logger.info(f"saving model checkpoint to {ckpt_file_path}")
torch.save(state_dict, ckpt_file_path)
logger.info(f"checkpoint files saved in {output_dir_path}")
if __name__ == "__main__":
configure_logger()
parser = argparse.ArgumentParser()
parser.add_argument(
"--input_dir",
help="Location of ALLaMo weights, which contains a checkpoint file",
)
parser.add_argument(
"--input_checkpoint_name_base",
default='ckpt',
help="Source checkpoint file name base",
)
parser.add_argument(
"--output_dir",
help="Location to write up-scaled model",
)
parser.add_argument(
"--output_checkpoint_name_base",
default='ckpt',
help="Output checkpoint file name base",
)
parser.add_argument(
"--add_first_layer", action='store_true',
help="Duplicate first layer",
)
parser.add_argument(
"--add_last_layer", action='store_true',
help="Duplicate last layer",
)
parser.add_argument(
"--source_tokenizer",
help="Source/original tokenizer",
)
parser.add_argument(
"--target_tokenizer",
help="Target/new tokenizer",
)
args = parser.parse_args()
adjust_model(
input_dir_path=args.input_dir,
input_checkpoint_name_base=args.input_checkpoint_name_base,
output_dir_path=args.output_dir,
output_checkpoint_name_base=args.output_checkpoint_name_base,
add_first_layer=args.add_first_layer,
add_last_layer=args.add_last_layer,
source_tokenizer_path=args.source_tokenizer,
target_tokenizer_path=args.target_tokenizer
)
{
"model_args": {
"block_size": 131072,
"vocab_size": 128256,
"rope_freq_base": 10000,
"rope_freq_scale": 1.0,
"n_layer": 32,
"num_kv_heads": 8,
"head_size": 128,
"n_head": 32,
"n_embd": 4096,
"intermediate_size": 14336,
"dropout": 0.0,
"bias": false,
"multiple_of": 256,
"norm_eps": 1e-05,
"sliding_window": null,
"gradient_checkpointing": false
}
}
\ No newline at end of file
{
"model_args": {
"block_size": 131072,
"vocab_size": 128256,
"rope_freq_base": 10000,
"rope_freq_scale": 1.0,
"n_layer": 28,
"num_kv_heads": 8,
"head_size": 128,
"n_head": 24,
"n_embd": 3072,
"intermediate_size": 8192,
"dropout": 0.0,
"bias": false,
"multiple_of": 256,
"norm_eps": 1e-05,
"sliding_window": null,
"gradient_checkpointing": false
}
}
\ No newline at end of file
import argparse
import os
from enum import Enum
from typing import Union
import torch
from torch.distributed.checkpoint import FileSystemReader, FileSystemWriter
from torch.distributed.checkpoint.format_utils import _EmptyStateDictLoadPlanner
from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
from torch.distributed.checkpoint.state_dict_loader import _load_state_dict
from torch.distributed.checkpoint.state_dict_saver import _save_state_dict
from allamo.logging import configure_logger, logger
from allamo.train_utils import remove_unwanted_prefix_from_model_state_dict
def add_prefix_to_model_state_dict(state_dict, prefix):
for k, _ in list(state_dict.items()):
state_dict[prefix + k] = state_dict.pop(k)
def dcp_to_torch_save(dcp_checkpoint_dir: Union[str, os.PathLike], torch_save_path: Union[str, os.PathLike], state_key: str):
state_dict: STATE_DICT_TYPE = {}
_load_state_dict(
state_dict,
storage_reader=FileSystemReader(dcp_checkpoint_dir),
planner=_EmptyStateDictLoadPlanner(),
no_dist=True,
)
if state_key:
if state_key in state_dict:
state_dict = state_dict[state_key]
else:
logger.warning(f"Key '{state_key}' not found. Using full state dict with the following keys: {', '.join(state_dict.keys())}")
torch.save(state_dict, torch_save_path)
logger.info(f"Conversion completed. New model saved in {torch_save_path}")
def torch_save_to_dcp(torch_save_path: Union[str, os.PathLike], dcp_checkpoint_dir: Union[str, os.PathLike], state_key: str):
state_dict = torch.load(torch_save_path)
remove_unwanted_prefix_from_model_state_dict(state_dict)
if state_key:
add_prefix_to_model_state_dict(state_dict, state_key + ".")
logger.info(f"Prefixed model state dict with '{state_key}.'")
# we don't need stateful behavior here because the expectation is anything loaded by
# torch.load would not contain stateful objects.
_save_state_dict(
state_dict, storage_writer=FileSystemWriter(dcp_checkpoint_dir), no_dist=True
)
logger.info(f"Conversion completed. New model saved in {dcp_checkpoint_dir}")
if __name__ == "__main__":
class FormatMode(Enum):
TORCH_TO_DCP = "torch_to_dcp"
DCP_TO_TORCH = "dcp_to_torch"
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mode', type=str, required=True, choices=[m.value for m in FormatMode], help="Conversion mode")
parser.add_argument('-s', '--src', type=str, required=True, help="Path to the source model")
parser.add_argument('-d', '--dst', type=str, required=True, help="Path to the target model")
parser.add_argument('-k', '--state_key', type=str, help="Dictionary key with desired state")
args = parser.parse_args()
configure_logger()
logger.info(f"Converting checkpoint from {args.src} to {args.dst} using method: '{args.mode}'")
checkpoint_missing_warning = (
f"No checkpoint found at {args.src}. Skipping conversion."
)
if args.mode == FormatMode.TORCH_TO_DCP.value:
if os.path.isfile(args.src):
os.makedirs(args.dst, exist_ok=True)
torch_save_to_dcp(args.src, args.dst, args.state_key)
else:
logger.warning(checkpoint_missing_warning)
elif args.mode == FormatMode.DCP_TO_TORCH.value:
if os.path.isdir(args.src):
dcp_to_torch_save(args.src, args.dst, args.state_key)
else:
logger.warning(checkpoint_missing_warning)
import argparse
import shutil
import torch
import torch.distributed as dist
from allamo.checkpoint.checkpoint_manager import CheckpointManager
from allamo.configuration import AllamoConfiguration
from allamo.logging import configure_logger, logger
from allamo.model.model import AllamoTransformer
from allamo.torch_utils import init_torch
from allamo.train_utils import (
get_config_checkpoint_path,
create_model_config,
)
from allamo.training_context import TrainingContext
from allamo.parallelisms.fsdp2_utils import build_world_mesh, parallelize_model_with_fsdp2
def parallelize_dcp(args):
train_ctx = TrainingContext(
tp = args.tp_size,
)
if train_ctx.master_process:
configure_logger()
config = AllamoConfiguration(
load_configuration = False,
device=args.device,
backend=args.backend,
tensor_parallel_degree = args.tp_size,
out_dir = args.dst,
compile = False,
)
init_torch(train_ctx, config)
logger.info(f"Torch initialized")
config_ckpt_file_path = get_config_checkpoint_path(args.checkpoint_name, args.src)
checkpoint_manager = CheckpointManager(config, train_ctx, None)
checkpoint_manager.load_config_checkpoint(config_ckpt_file_path)
logger.info("Config checkpoint loaded")
world_mesh = build_world_mesh(train_ctx, args.device)
model_config = create_model_config(config)
with torch.device('meta'):
model = AllamoTransformer(model_config)
logger.info("Model initialized on meta device")
model.to_empty(device=args.device)
model.init_model_weights()
logger.info(f"Model weights initialized on {args.device} device")
checkpoint_manager.load_distributed_model_checkpoint_from(model, args.src, args.checkpoint_name)
logger.info("Model checkpoint loaded")
model = parallelize_model_with_fsdp2(model, world_mesh, config, False)
checkpoint_manager.save_distributed_model_checkpoint_to(model, args.dst, args.checkpoint_name)
shutil.copy(config_ckpt_file_path, get_config_checkpoint_path(args.checkpoint_name, args.dst))
dist.barrier()
dist.destroy_process_group()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--src', type=str, required=True, help="Path to source checkpoint directory")
parser.add_argument('-d', '--dst', type=str, required=True, help="Path to target checkpoint directory")
parser.add_argument('-n', '--checkpoint_name', type=str, required=True, help="Checkpoint name")
parser.add_argument('-t', '--tp_size', type=int, required=True, help="Tensor parallel degree")
parser.add_argument('--device', type=str, choices=['cpu', 'cuda'], default='cpu', help="Device type to run conversion on")
parser.add_argument('--backend', type=str, choices=['gloo', 'mpi', 'nccl'], default='gloo', help="Specifies one of three built-in backends")
args = parser.parse_args()
parallelize_dcp(args)
logger.info(f"Distributed checkpoint parallelized with TP={args.tp_size}")
"""
Use this file to convert config checkpoint from PyTorch to JSON format
"""
import argparse
import dataclasses
import json
import torch
from allamo.logging import configure_logger, logger
def convert_ckpt(config_ckpt):
config_checkpoint = torch.load(config_ckpt, map_location='cpu')
json_checkpoint = {}
if 'model_args' in config_checkpoint:
json_checkpoint['model_args'] = dataclasses.asdict(config_checkpoint['model_args'])
if 'iter_num' in config_checkpoint:
json_checkpoint['iter_num'] = config_checkpoint['iter_num']
if 'best_train_loss' in config_checkpoint:
json_checkpoint['best_train_loss'] = config_checkpoint['best_train_loss']
if isinstance(json_checkpoint['best_train_loss'], torch.Tensor):
json_checkpoint['best_train_loss'] = json_checkpoint['best_train_loss'].item()
if 'best_val_loss' in config_checkpoint:
json_checkpoint['best_val_loss'] = config_checkpoint['best_val_loss']
if isinstance(json_checkpoint['best_val_loss'], torch.Tensor):
json_checkpoint['best_val_loss'] = json_checkpoint['best_val_loss'].item()
if 'processed_tokens' in config_checkpoint:
json_checkpoint['processed_tokens'] = config_checkpoint['processed_tokens']
if 'config' in config_checkpoint:
json_checkpoint['config'] = config_checkpoint['config']
data_loader_ckpt = {}
if 'allamo_dataloader_train_processed_files' in config_checkpoint:
data_loader_ckpt['train_processed_files'] = config_checkpoint['allamo_dataloader_train_processed_files']
if 'allamo_dataloader_dataset_offset' in config_checkpoint:
data_loader_ckpt['dataset_offset'] = config_checkpoint['allamo_dataloader_dataset_offset']
if 'allamo_dataloader_epoch' in config_checkpoint:
data_loader_ckpt['epoch'] = config_checkpoint['allamo_dataloader_epoch']
if data_loader_ckpt:
json_checkpoint['allamo_dataloader'] = data_loader_ckpt
output_file = config_ckpt[:-3] + '.json'
with open(output_file, "w", encoding="utf-8") as f:
json.dump(json_checkpoint, f, indent=4, ensure_ascii=False)
logger.info(f"Conversion completed! New config saved in {output_file}")
if __name__ == '__main__':
configure_logger()
parser = argparse.ArgumentParser(description='Convert config checkpoint to JSON format')
parser.add_argument(
"--config_ckpt",
help="Path to config checkpoint in PyTorch format",
)
args = parser.parse_args()
convert_ckpt(args.config_ckpt)
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
"""
Use this file for scaling your model with a method called depth up-scaling (DUS).
More details: https://arxiv.org/abs/2312.15166
"""
import argparse
import json
import os
import torch
from allamo.logging import configure_logger, logger
from allamo.train_utils import (
get_model_checkpoint_path,
get_config_checkpoint_path,
)
def prepare_layer_keys_mapping(n_layers, last_layers_to_drop, first_layers_to_drop):
mapping_pairs = []
bottom_layers = n_layers - last_layers_to_drop
top_layers = n_layers - first_layers_to_drop
# bottom layers
for layer_i in range(bottom_layers):
mapping_pairs.append((layer_i, layer_i))
# top layers
for layer_i in range(top_layers):
src_layer_idx = first_layers_to_drop + layer_i
dest_layer_idx = bottom_layers + layer_i
mapping_pairs.append((dest_layer_idx, src_layer_idx))
return mapping_pairs
def depth_up_scale_model(input_dir_path, input_checkpoint_name_base, output_dir_path, output_checkpoint_name_base, last_layers_to_drop, first_layers_to_drop, bfloat16):
os.makedirs(output_dir_path, exist_ok=True)
logger.info(f"loading checkpoint from {input_dir_path}...")
with open(get_config_checkpoint_path(input_checkpoint_name_base, input_dir_path), "r", encoding="utf-8") as f:
config_checkpoint = json.load(f)
model_checkpoint = torch.load(get_model_checkpoint_path(input_checkpoint_name_base, input_dir_path), map_location='cpu')
unwanted_prefix = '_orig_mod.'
for k,v in list(model_checkpoint.items()):
if k.startswith(unwanted_prefix):
model_checkpoint[k[len(unwanted_prefix):]] = model_checkpoint.pop(k)
state_dict = {
"tok_embeddings.weight": model_checkpoint["tok_embeddings.weight"],
"norm.weight": model_checkpoint["norm.weight"],
"lm_head.weight": model_checkpoint["lm_head.weight"],
}
layer_mapping_pairs = prepare_layer_keys_mapping(config_checkpoint['model_args']['n_layer'], last_layers_to_drop, first_layers_to_drop)
# you can customize the mapping here, e.g., replace some layers with others
for dest_layer_idx, src_layer_idx in layer_mapping_pairs:
logger.info(f"copying weights from layer {src_layer_idx} to layer {dest_layer_idx}")
state_dict[f"layers.{dest_layer_idx}.attention.q_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention.q_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.attention.k_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention.k_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.attention.v_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention.v_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.attention.c_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention.c_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.feed_forward.gate_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.feed_forward.gate_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.feed_forward.down_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.feed_forward.down_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.feed_forward.up_proj.weight"] = model_checkpoint[f"layers.{src_layer_idx}.feed_forward.up_proj.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.attention_norm.weight"] = model_checkpoint[f"layers.{src_layer_idx}.attention_norm.weight"].clone()
state_dict[f"layers.{dest_layer_idx}.ffn_norm.weight"] = model_checkpoint[f"layers.{src_layer_idx}.ffn_norm.weight"].clone()
if bfloat16:
logger.info("converting weights to bfloat16")
param_count = 0
param_bytes = 0
for k, v in state_dict.items():
if bfloat16:
v = v.to(torch.bfloat16)
state_dict[k] = v
param_count += v.numel()
param_bytes += v.numel() * v.element_size()
config_checkpoint['model_args']['n_layer'] = len(layer_mapping_pairs)
param_count /= 1e6
param_bytes /= 1024**2
logger.info(f"New model layers: {config_checkpoint['model_args']['n_layer']}. Model parameters: {param_count:.2f}M. Est. Size: {param_bytes:.3f}MB")
ckpt_file_path = get_config_checkpoint_path(output_checkpoint_name_base, output_dir_path)
logger.info(f"saving config checkpoint to {ckpt_file_path}")
with open(ckpt_file_path, "w", encoding="utf-8") as f:
json.dump(config_checkpoint, f, indent=4, ensure_ascii=False)
ckpt_file_path = get_model_checkpoint_path(output_checkpoint_name_base, output_dir_path)
logger.info(f"saving model checkpoint to {ckpt_file_path}")
torch.save(state_dict, ckpt_file_path)
logger.info(f"checkpoint files saved in {output_dir_path}")
def main():
configure_logger()
parser = argparse.ArgumentParser()
parser.add_argument(
"--input_dir",
help="Location of ALLaMo weights, which contains a checkpoint file",
)
parser.add_argument(
"--input_checkpoint_name_base",
default='ckpt',
help="Source checkpoint file name base",
)
parser.add_argument(
"--output_dir",
help="Location to write up-scaled model",
)
parser.add_argument(
"--output_checkpoint_name_base",
default='up-scaled_ckpt',
help="Output checkpoint file name base",
)
parser.add_argument(
"--last_layers_to_drop", type=int,
help="Number of last layers to drop from the bottom copy of the model",
)
parser.add_argument(
"--first_layers_to_drop", type=int,
help="Number of first layers to drop from the top copy of the model",
)
parser.add_argument(
"--bfloat16", type=bool,
help="Convert weights to bfloaf16",
)
args = parser.parse_args()
depth_up_scale_model(
input_dir_path=args.input_dir,
input_checkpoint_name_base=args.input_checkpoint_name_base,
output_dir_path=args.output_dir,
output_checkpoint_name_base=args.output_checkpoint_name_base,
last_layers_to_drop=args.last_layers_to_drop,
first_layers_to_drop=args.first_layers_to_drop,
bfloat16=args.bfloat16
)
if __name__ == "__main__":
main()
import dataclasses
import gc
import torch
from allamo.logging import configure_logger, logger
from allamo.model.model import AllamoTransformerConfig, AllamoTransformer
from allamo.configuration import AllamoConfiguration
configure_logger()
config = AllamoConfiguration()
if config.dtype == 'bfloat16-true':
torch.set_default_dtype(torch.bfloat16)
transformer_config_fields = [f.name for f in dataclasses.fields(AllamoTransformerConfig)]
model_args = {k: getattr(config, k) for k in transformer_config_fields if hasattr(config, k)}
modelConf = AllamoTransformerConfig(**model_args)
model = AllamoTransformer(modelConf)
optimizer = 'Adam'
if 'cuda' in config.device:
torch.cuda.set_device(config.device)
gc.collect()
torch.cuda.empty_cache()
model_input = torch.randint(0, config.vocab_size, (config.block_size,), dtype=torch.int64).unsqueeze(0).repeat(config.batch_size, 1)
logger.info(f"Max Sequence size: {(model_input.numel() * model_input.element_size())/(1024*1024)}")
a = torch.cuda.memory_allocated(config.device)
model.to(device=config.device)
b = torch.cuda.memory_allocated(config.device)
with torch.no_grad():
output = model(model_input.to(config.device))[0].sum() # Taking the sum here just to get a scalar output
c = torch.cuda.memory_allocated(config.device)
model_memory = b - a
inference_memory = c - b
logger.info(f"Memory allocated by the model (precision: {config.dtype}): {model_memory/(1024*1024)}")
logger.info(f"Inference Maximum Memory Estimate: {inference_memory/(1024*1024)}")
if optimizer is not None:
gc.collect()
torch.cuda.empty_cache()
b = torch.cuda.memory_allocated(config.device)
output = model(model_input.to(config.device))[0].sum() # Taking the sum here just to get a scalar output
c = torch.cuda.memory_allocated(config.device)
amp_multiplier = .5 if config.dtype == 'float16' or config.dtype == 'bfloat16' else 1
# More details: https://stackoverflow.com/a/76994670
activations = 32 * config.n_layer * (34 * config.block_size * config.n_embd + 5 * config.n_head * config.block_size^2) / 2
if config.dtype == 'bfloat16-true':
activations /= 2
forward_pass_memory = activations #(c - b)*amp_multiplier
logger.info(f"Forward pass memory: {forward_pass_memory/(1024*1024)}")
gradient_memory = model_memory
if optimizer == 'Adam':
o = 2
elif optimizer == 'RMSprop':
o = 1
elif optimizer == 'SGD':
o = 0
elif optimizer == 'Adagrad':
o = 1
else:
raise ValueError("Unsupported optimizer. Look up how many moments are stored by your optimizer and add a case to the optimizer checker.")
gradient_moment_memory = o*gradient_memory
total_memory = model_memory + forward_pass_memory + gradient_memory + gradient_moment_memory
logger.info(f"Training Maximum Memory Estimate: {total_memory/(1024*1024)}")
logger.info(f"* model: {model_memory/(1024*1024)}")
logger.info(f"* forward pass: {forward_pass_memory/(1024*1024)}")
logger.info(f"* gradient: {gradient_memory/(1024*1024)}")
logger.info(f"* gradient moments: {gradient_moment_memory/(1024*1024)}")
"""
Use this file to export ALLaMo weights to HuggingFace formats
"""
import argparse
import gc
import json
import os
import shutil
import torch
from transformers import LlamaConfig, LlamaForCausalLM, MistralConfig, MistralForCausalLM
from allamo.logging import configure_logger, logger
from allamo.model.model import AllamoTransformerConfig
from allamo.train_utils import (
get_model_checkpoint_path,
get_config_checkpoint_path,
)
def compute_intermediate_size(config):
return config.multiple_of * ((int(config.n_embd * 8 / 3) + config.multiple_of - 1) // config.multiple_of)
def read_json(path):
with open(path, "r") as f:
return json.load(f)
def write_json(text, path):
with open(path, "w") as f:
json.dump(text, f)
def write_model(checkpoint_dir_path, checkpoint_name_base, hf_model_path, hf_model_type, hf_model_dtype=None, hf_model_max_position_embeddings=None):
assert hf_model_type == "llama" or hf_model_type == "mistral", "Only llama and mistral architectures are supported"
os.makedirs(hf_model_path, exist_ok=True)
tmp_model_path = os.path.join(hf_model_path, "tmp")
os.makedirs(tmp_model_path, exist_ok=True)
logger.info(f"loading checkpoint from {checkpoint_dir_path}...")
with open(get_config_checkpoint_path(checkpoint_name_base, checkpoint_dir_path), "r", encoding="utf-8") as f:
config_checkpoint = json.load(f)
model_checkpoint = torch.load(get_model_checkpoint_path(checkpoint_name_base, checkpoint_dir_path), map_location='cpu')
allamo_transformer_config = AllamoTransformerConfig(**config_checkpoint['model_args'])
n_layers = allamo_transformer_config.n_layer
intermediate_size = allamo_transformer_config.intermediate_size if hasattr(allamo_transformer_config, 'intermediate_size') else compute_intermediate_size(allamo_transformer_config)
max_position_embeddings = allamo_transformer_config.block_size if hf_model_max_position_embeddings is None else hf_model_max_position_embeddings
logger.info(f"converting all parameters from the checkpoint model")
unwanted_prefix = '_orig_mod.'
for k,v in list(model_checkpoint.items()):
if k.startswith(unwanted_prefix):
model_checkpoint[k[len(unwanted_prefix):]] = model_checkpoint.pop(k)
param_count = 0
index_dict = {"weight_map": {}}
for layer_i in range(n_layers):
logger.info(f"converting weights in layer {layer_i}")
filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
state_dict = {
f"model.layers.{layer_i}.self_attn.q_proj.weight": model_checkpoint[f"layers.{layer_i}.attention.q_proj.weight"],
f"model.layers.{layer_i}.self_attn.k_proj.weight": model_checkpoint[f"layers.{layer_i}.attention.k_proj.weight"],
f"model.layers.{layer_i}.self_attn.v_proj.weight": model_checkpoint[f"layers.{layer_i}.attention.v_proj.weight"],
f"model.layers.{layer_i}.self_attn.o_proj.weight": model_checkpoint[f"layers.{layer_i}.attention.c_proj.weight"],
f"model.layers.{layer_i}.mlp.gate_proj.weight": model_checkpoint[f"layers.{layer_i}.feed_forward.gate_proj.weight"],
f"model.layers.{layer_i}.mlp.down_proj.weight": model_checkpoint[f"layers.{layer_i}.feed_forward.down_proj.weight"],
f"model.layers.{layer_i}.mlp.up_proj.weight": model_checkpoint[f"layers.{layer_i}.feed_forward.up_proj.weight"],
f"model.layers.{layer_i}.input_layernorm.weight": model_checkpoint[f"layers.{layer_i}.attention_norm.weight"],
f"model.layers.{layer_i}.post_attention_layernorm.weight": model_checkpoint[f"layers.{layer_i}.ffn_norm.weight"]
}
if allamo_transformer_config.bias:
state_dict[f"model.layers.{layer_i}.self_attn.q_proj.bias"] = model_checkpoint[f"layers.{layer_i}.attention.q_proj.bias"]
state_dict[f"model.layers.{layer_i}.self_attn.k_proj.bias"] = model_checkpoint[f"layers.{layer_i}.attention.k_proj.bias"]
state_dict[f"model.layers.{layer_i}.self_attn.v_proj.bias"] = model_checkpoint[f"layers.{layer_i}.attention.v_proj.bias"]
state_dict[f"model.layers.{layer_i}.self_attn.o_proj.bias"] = model_checkpoint[f"layers.{layer_i}.attention.c_proj.bias"]
state_dict[f"model.layers.{layer_i}.mlp.gate_proj.bias"] = model_checkpoint[f"layers.{layer_i}.feed_forward.gate_proj.bias"]
state_dict[f"model.layers.{layer_i}.mlp.down_proj.bias"] = model_checkpoint[f"layers.{layer_i}.feed_forward.down_proj.bias"]
state_dict[f"model.layers.{layer_i}.mlp.up_proj.bias"] = model_checkpoint[f"layers.{layer_i}.feed_forward.up_proj.bias"]
for k, v in state_dict.items():
index_dict["weight_map"][k] = filename
param_count += v.numel()
torch.save(state_dict, os.path.join(tmp_model_path, filename))
filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
state_dict = {
"model.embed_tokens.weight": model_checkpoint["tok_embeddings.weight"],
"model.norm.weight": model_checkpoint["norm.weight"],
"lm_head.weight": model_checkpoint["lm_head.weight"],
}
if hf_model_dtype:
torch_dtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[hf_model_dtype]
param_size_bytes = {'float32': 4, 'bfloat16': 2, 'float16': 2}[hf_model_dtype]
else:
# resolve model params dtype, e.g. torch.float16
torch_dtype = model_checkpoint["lm_head.weight"].dtype
param_size_bytes = 4 if torch_dtype == torch.float32 else 2
for k, v in state_dict.items():
index_dict["weight_map"][k] = filename
param_count += v.numel()
torch.save(state_dict, os.path.join(tmp_model_path, filename))
logger.info(f"{param_count} params converted to HF LLaMA model")
# Write configs
index_dict["metadata"] = {"total_size": param_count * param_size_bytes}
write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
if hf_model_type == "llama":
config = LlamaConfig(
vocab_size=allamo_transformer_config.vocab_size,
max_position_embeddings=max_position_embeddings,
hidden_size=allamo_transformer_config.n_embd,
intermediate_size=intermediate_size,
num_attention_heads=allamo_transformer_config.n_head,
num_key_value_heads=allamo_transformer_config.num_kv_heads,
num_hidden_layers=n_layers,
rms_norm_eps=allamo_transformer_config.norm_eps,
rope_theta=allamo_transformer_config.rope_freq_base,
attention_bias=allamo_transformer_config.bias,
mlp_bias=allamo_transformer_config.bias,
)
elif hf_model_type == "mistral":
assert not allamo_transformer_config.bias, "Mistral models don't support bias"
config = MistralConfig(
vocab_size=allamo_transformer_config.vocab_size,
max_position_embeddings=max_position_embeddings,
hidden_size=allamo_transformer_config.n_embd,
intermediate_size=intermediate_size,
num_attention_heads=allamo_transformer_config.n_head,
num_key_value_heads=allamo_transformer_config.num_kv_heads,
num_hidden_layers=n_layers,
rms_norm_eps=allamo_transformer_config.norm_eps,
rope_theta=allamo_transformer_config.rope_freq_base,
sliding_window=allamo_transformer_config.sliding_window,
)
config.save_pretrained(tmp_model_path)
logger.info(f"configuration for the HF LLaMA model saved")
# Make space so we can load the model properly now.
del state_dict
del config_checkpoint
del model_checkpoint
gc.collect()
logger.info(f"loading the checkpoint in a LLaMA model with {torch_dtype} dtype")
if hf_model_type == "llama":
model = LlamaForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch_dtype, low_cpu_mem_usage=True)
elif hf_model_type == "mistral":
model = MistralForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch_dtype, low_cpu_mem_usage=True)
# Avoid saving this as part of the config.
del model.config._name_or_path
logger.info(f"saving in the Transformers format")
model.save_pretrained(hf_model_path)
shutil.rmtree(tmp_model_path)
logger.info(f"conversion completed!")
if __name__ == "__main__":
configure_logger()
parser = argparse.ArgumentParser()
parser.add_argument(
"--input_dir",
help="Location of ALLaMo weights, which contains a checkpoint file",
)
parser.add_argument(
"--checkpoint_name_base",
default='ckpt',
help="Checkpoint file name base",
)
parser.add_argument(
"--output_dir",
help="Location to write HF model",
)
parser.add_argument(
"--model_type",
choices=['llama', 'mistral'],
default='llama',
help="Determine model type",
)
parser.add_argument(
"--output_dtype",
choices=['float32', 'bfloat16', 'float16'],
help="Override model dtype and save the model under a specific dtype",
)
parser.add_argument(
"--max_position_embeddings",
help="Overwrite max_position_embeddings with this value",
)
args = parser.parse_args()
write_model(
checkpoint_dir_path=args.input_dir,
checkpoint_name_base=args.checkpoint_name_base,
hf_model_path=args.output_dir,
hf_model_type=args.model_type,
hf_model_dtype=args.output_dtype,
hf_model_max_position_embeddings=args.max_position_embeddings,
)
python export_to_hf.py --input_dir="/home/data/llama3/" --output_dir="/home/data/llama-hf/"
"""
Use this file to add reference log probabilities to your DPO (Direct Preference Optimization) dataset
"""
import argparse
import concurrent.futures
import joblib
import json
import os
import time
import torch
from itertools import chain
from tqdm import tqdm
from transformers import AutoModelForCausalLM
from allamo.logging import configure_logger, logger
from allamo.trainer.dpo_fsdp_trainer import get_log_prob
def format_seconds_as_time(seconds):
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{int(hours)}:{int(minutes):02}:{int(seconds):02}"
def get_dtype(dtype_str):
return {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype_str]
def get_batch(sample, device, pin_memory):
chosen_input_ids = torch.stack([torch.from_numpy(sample['chosen_input_ids'])]).to(torch.int64)
chosen_target_ids = torch.stack([torch.from_numpy(sample['chosen_target_ids'])]).to(torch.int64)
rejected_input_ids = torch.stack([torch.from_numpy(sample['rejected_input_ids'])]).to(torch.int64)
rejected_target_ids = torch.stack([torch.from_numpy(sample['rejected_target_ids'])]).to(torch.int64)
if 'cuda' in device and pin_memory:
chosen_input_ids = chosen_input_ids.pin_memory().to(device, non_blocking=True)
chosen_target_ids = chosen_target_ids.pin_memory().to(device, non_blocking=True)
rejected_input_ids = rejected_input_ids.pin_memory().to(device, non_blocking=True)
rejected_target_ids = rejected_target_ids.pin_memory().to(device, non_blocking=True)
else:
chosen_input_ids = chosen_input_ids.to(device)
chosen_target_ids = chosen_target_ids.to(device)
rejected_input_ids = rejected_input_ids.to(device)
rejected_target_ids = rejected_target_ids.to(device)
return {
"chosen_input_ids": chosen_input_ids,
"chosen_target_ids": chosen_target_ids,
"rejected_input_ids": rejected_input_ids,
"rejected_target_ids": rejected_target_ids
}
def calculate_sample_stats(samples):
sum_reference_chosen_logps = sum(sample["reference_chosen_logps"] for sample in samples)
sum_reference_rejected_logps = sum(sample["reference_rejected_logps"] for sample in samples)
return {
'min_reference_chosen_logps': min(sample["reference_chosen_logps"] for sample in samples),
'max_reference_chosen_logps': max(sample["reference_chosen_logps"] for sample in samples),
'sum_reference_chosen_logps': sum_reference_chosen_logps,
'avg_reference_chosen_logps': sum_reference_chosen_logps / len(samples),
'min_reference_rejected_logps': min(sample["reference_rejected_logps"] for sample in samples),
'max_reference_rejected_logps': max(sample["reference_rejected_logps"] for sample in samples),
'sum_reference_rejected_logps': sum_reference_rejected_logps,
'avg_reference_rejected_logps': sum_reference_rejected_logps / len(samples)
}
def process_file(input_file, model, device, pin_memory, ignore_index, disable_logging=True):
samples = joblib.load(input_file)
with torch.no_grad():
for sample in tqdm(samples, disable=disable_logging):
batch = get_batch(sample, device, pin_memory)
reference_chosen_output = model(input_ids=batch["chosen_input_ids"])
reference_rejected_output = model(input_ids=batch["rejected_input_ids"])
sample["reference_chosen_loss"] = reference_chosen_output.loss
sample["reference_chosen_logps"] = get_log_prob(reference_chosen_output.logits, batch["chosen_target_ids"], ignore_index).item()
sample["reference_rejected_loss"] = reference_rejected_output.loss
sample["reference_rejected_logps"] = get_log_prob(reference_rejected_output.logits, batch["rejected_target_ids"], ignore_index).item()
with open(input_file, 'wb') as f:
joblib.dump(samples, f)
return samples
def process_chunk(args):
input_file, hf_model_path, hf_model_dtype, device, pin_memory, ignore_index = args
model = AutoModelForCausalLM.from_pretrained(hf_model_path, torch_dtype=get_dtype(hf_model_dtype), device_map=device)
process_file(input_file, model, device, pin_memory, ignore_index)
def save_samples(samples, input_file, args):
if args.save_samples > 0:
logger.info(f"Saving samples")
samples_file = os.path.join(args.output_dir, os.path.basename(input_file) + "-samples.jsonl")
with open(samples_file, 'w') as f:
for sample in samples[:args.save_samples]:
chosen_input_ids = sample["chosen_input_ids"].tolist()
rejected_input_ids = sample["rejected_input_ids"].tolist()
new_sample = {
"chosen_len": len(chosen_input_ids),
"rejected_len": len(rejected_input_ids),
"batch_len": len(chosen_input_ids)+len(rejected_input_ids),
"chosen_input_ids": chosen_input_ids,
"chosen_target_ids": sample["chosen_target_ids"].tolist(),
"rejected_input_ids": rejected_input_ids,
"rejected_target_ids": sample["rejected_target_ids"].tolist(),
"reference_chosen_logps": sample["reference_chosen_logps"],
"reference_rejected_logps": sample["reference_rejected_logps"]
}
f.write(json.dumps(new_sample, ensure_ascii=False))
f.write('\n')
logger.info(f"Samples saved in {samples_file}")
if __name__ == "__main__":
configure_logger()
parser = argparse.ArgumentParser(description='Tokenize dialogues for DPO training')
parser.add_argument("-f", "--input_file", help="Input file in the ALM format")
parser.add_argument("-i", "--input_dir", help="Directory with input files in the ALM format")
parser.add_argument("-o", "--output_dir", required=True, help="Output dir")
parser.add_argument("--hf_model_path", required=True, help="Model path in HF format")
parser.add_argument("--hf_model_dtype", required=True, help="HF model dtype")
parser.add_argument("--hf_model_device", required=True, help="Device to load the HF model on")
parser.add_argument("--hf_model_copies", type=int, default=1, help="Number of model copies to run on separate devices")
parser.add_argument("--pin_memory", type=bool, default=True, help="Specifies if the tensor is copied to pinned memory")
parser.add_argument("--ignore_index", type=int, default=-100, help="Specifies a target value that is ignored in loss computation. Default is -100")
parser.add_argument('--save_samples', type=int, default=-1, help='Save this number of samples if positive')
parser.add_argument('--verbose', action='store_true', help='Be verbose')
args = parser.parse_args()
input_files = []
if args.input_file:
input_files.append(args.input_file)
if args.input_dir:
for root, dirs, files in os.walk(args.input_dir):
for f in files:
if f.endswith('.alm'):
input_files.append(os.path.join(root, f))
logger.info(f"Initialized with {len(input_files)} input file(s)")
os.makedirs(args.output_dir, exist_ok=True)
timer = time.time()
if args.hf_model_copies > 1:
assert args.hf_model_device.startswith("cuda"), "Only CUDA devices are supported in parallel mode"
for input_file in input_files:
logger.info(f'Loading data from {input_file}')
samples = joblib.load(input_file)
logger.info(f'Loaded {len(samples)} samples. Start generating log probabilities')
logger.info(f"Chunking {len(samples):,} samples into {args.hf_model_copies} files")
chunk_files = []
for rank in tqdm(range(args.hf_model_copies), total=args.hf_model_copies, desc="Chunking", disable=(not args.verbose)):
chunk_file = os.path.join(args.output_dir, f"chunk_{rank:05}.tmp")
with open(chunk_file, 'wb') as f:
joblib.dump(samples[rank::args.hf_model_copies], f)
chunk_files.append(chunk_file)
del samples
logger.info(f"Saved {len(chunk_files)} chunks in {args.output_dir}")
logger.info(f"Start generating log probabilities for {len(chunk_files)} chunks")
max_workers = min(len(chunk_files), args.hf_model_copies)
chunk_batches = list((chunk_file, args.hf_model_path, args.hf_model_dtype, f"cuda:{rank}", args.pin_memory, args.ignore_index) for rank, chunk_file in enumerate(chunk_files))
with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor:
for _ in executor.map(process_chunk, chunk_batches):
pass
del executor
logger.info(f"Log probabilities generated in {len(chunk_files)} chunks")
logger.info(f"Merging {len(chunk_files)} chunks")
chunks = joblib.Parallel(n_jobs=len(chunk_files))(joblib.delayed(joblib.load)(f) for f in chunk_files)
samples = list(chain.from_iterable(chunks))
logger.info(f"{len(samples):,} samples merged")
output_file = os.path.join(args.output_dir, os.path.basename(input_file))
with open(output_file, 'wb') as f:
joblib.dump(samples, f)
logger.info(f"Saved ({len(samples)}) samples in {output_file}")
save_samples(samples, input_file, args)
stats = calculate_sample_stats(samples)
stats_str = json.dumps(stats, indent=4, ensure_ascii=False)
logger.info(f"Stats for {input_file}:\n{stats_str}")
# cleanup
for chunk_file in chunk_files:
os.remove(chunk_file)
else:
device = args.hf_model_device
model = AutoModelForCausalLM.from_pretrained(args.hf_model_path, torch_dtype=get_dtype(args.hf_model_dtype), device_map=device)
logger.info(f"Model loaded")
for input_file in input_files:
logger.info(f'Processing {input_file}')
samples = process_file(input_file, model, device, args.pin_memory, args.ignore_index, disable_logging=(not args.verbose))
save_samples(samples, input_file, args)
stats = calculate_sample_stats(samples)
stats_str = json.dumps(stats, indent=4, ensure_ascii=False)
logger.info(f"Stats for {input_file}:\n{stats_str}")
logger.info(f"Generated log probabilities for {len(input_files)} file(s) in {format_seconds_as_time(time.time()-timer)}")
wget https://mirror.ghproxy.com/https://github.com/git-lfs/git-lfs/releases/download/v3.5.1/git-lfs-linux-amd64-v3.5.1.tar.gz
tar -xzvf git-lfs-linux-amd64-v3.5.1.tar.gz
./git-lfs-3.5.1/install.sh
rm -rf git-lfs-3.5.1 git-lfs-linux-amd64-v3.5.1.tar.gz
"""
Use this file to import Huggingface LlamaForCausalLM weights to ALLaMo format.
"""
import argparse
import dataclasses
import json
import os
import torch
from transformers import LlamaForCausalLM
from allamo.logging import configure_logger, logger
from allamo.model.model import AllamoTransformerConfig, AllamoTransformer
def import_model(hf_model_path, output_model_path):
logger.info(f"Importing Huggingface LlamaForCausalLM weights")
hf_model = LlamaForCausalLM.from_pretrained(hf_model_path, torch_dtype=torch.float32, low_cpu_mem_usage=True)
logger.info(f"Huggingface LlamaForCausalLM model loaded")
assert hf_model.config.hidden_act == "silu"
config = AllamoTransformerConfig()
config.block_size = hf_model.config.max_position_embeddings
config.vocab_size = hf_model.config.vocab_size
config.n_layer = hf_model.config.num_hidden_layers
config.n_head = hf_model.config.num_attention_heads
config.n_embd = hf_model.config.hidden_size
config.intermediate_size = hf_model.config.intermediate_size
config.head_size = config.n_embd // config.n_head
config.num_kv_heads = hf_model.config.num_key_value_heads
config.dropout = 0.0
config.bias = False
config.norm_eps = hf_model.config.rms_norm_eps
logger.info(f"initializing vanilla ALLaMo model")
model = AllamoTransformer(config)
logger.info(f"preparing weights")
state_dicts_map = {}
sd_hf_model = hf_model.state_dict()
model_sd = model.state_dict()
for layer_i in range(config.n_layer):
state_dicts_map[f"layers.{layer_i}.attention.q_proj.weight"] = f"model.layers.{layer_i}.self_attn.q_proj.weight"
state_dicts_map[f"layers.{layer_i}.attention.k_proj.weight"] = f"model.layers.{layer_i}.self_attn.k_proj.weight"
state_dicts_map[f"layers.{layer_i}.attention.v_proj.weight"] = f"model.layers.{layer_i}.self_attn.v_proj.weight"
state_dicts_map[f"layers.{layer_i}.attention.c_proj.weight"] = f"model.layers.{layer_i}.self_attn.o_proj.weight"
state_dicts_map[f"layers.{layer_i}.attention.rotary_emb.inv_freq"] = f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"
state_dicts_map[f"layers.{layer_i}.feed_forward.gate_proj.weight"] = f"model.layers.{layer_i}.mlp.gate_proj.weight"
state_dicts_map[f"layers.{layer_i}.feed_forward.down_proj.weight"] = f"model.layers.{layer_i}.mlp.down_proj.weight"
state_dicts_map[f"layers.{layer_i}.feed_forward.up_proj.weight"] = f"model.layers.{layer_i}.mlp.up_proj.weight"
state_dicts_map[f"layers.{layer_i}.attention_norm.weight"] = f"model.layers.{layer_i}.input_layernorm.weight"
state_dicts_map[f"layers.{layer_i}.ffn_norm.weight"] = f"model.layers.{layer_i}.post_attention_layernorm.weight"
state_dicts_map["tok_embeddings.weight"] = "model.embed_tokens.weight"
state_dicts_map["norm.weight"] = "model.norm.weight"
state_dicts_map["lm_head.weight"] = "lm_head.weight"
logger.info(f"checking params coverage")
for k, v in model_sd.items():
if k not in state_dicts_map:
logger.info(f"{k} param won't be updated in the ALLaMo model!")
for k, v in sd_hf_model.items():
if k not in state_dicts_map.values():
logger.info(f"{k} param won't be copied to the ALLaMo model!")
logger.info(f"copying params to the ALLaMo model")
param_count = 0
for k, v in state_dicts_map.items():
if not k.endswith('rotary_emb.inv_freq'):
assert sd_hf_model[v].shape == model_sd[k].shape
with torch.no_grad():
model_sd[k].copy_(sd_hf_model[v])
param_count += model_sd[k].numel()
logger.info(f"{param_count} params copied to the ALLaMo model")
for k, _ in model_sd.items():
if not torch.all(torch.eq(model_sd[k], sd_hf_model[state_dicts_map[k]])):
logger.info(f"{k} param in the ALLaMo model is not the same as {state_dicts_map[k]} param in the source model!")
logger.info(f"params verified")
ckpt_file_name = 'import_ckpt'
config_checkpoint = {
'model_args': dataclasses.asdict(config)
}
ckpt_file_path = os.path.join(output_model_path, f'config_{ckpt_file_name}.json')
logger.info(f"saving config checkpoint to {ckpt_file_path}")
with open(ckpt_file_path, "w", encoding="utf-8") as f:
json.dump(config_checkpoint, f, indent=4, ensure_ascii=False)
ckpt_file_path = os.path.join(output_model_path, f'model_{ckpt_file_name}.pt')
logger.info(f"saving model checkpoint to {ckpt_file_path}")
torch.save(model_sd, ckpt_file_path)
logger.info(f"checkpoint files saved in {output_model_path}")
if __name__ == '__main__':
configure_logger()
parser = argparse.ArgumentParser(description='Import Huggingface LlamaForCausalLM weights to ALLaMo model')
parser.add_argument(
"--huggingface_model",
help="Huggingface model path",
)
parser.add_argument(
"--output_dir",
help="Path to output directory",
)
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
import_model(
hf_model_path=args.huggingface_model,
output_model_path=args.output_dir,
)
logger.info("import completed")
python import_hf_llama_weights.py --huggingface_model Meta-Llama-3.1-8B --output_dir allamo-llama-3.1-8b
# python import_hf_llama_weights.py --huggingface_model Llama-3.2-3B --output_dir allamo-llama-3.2-3B
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment