Commit 4d4e01e5 authored by chenych's avatar chenych
Browse files

First commit

parents
Pipeline #2616 failed with stages
in 0 seconds
**LLAMA 4 COMMUNITY LICENSE AGREEMENT**
Llama 4 Version Effective Date: April 5, 2025
"**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 4 distributed by Meta at [https://www.llama.com/docs/overview](https://llama.com/docs/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 4**" 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](https://www.llama.com/llama-downloads).
"**Llama Materials**" means, collectively, Meta’s proprietary Llama 4 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 4 is licensed under the Llama 4 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/llama4/use-policy](https://www.llama.com/llama4/use-policy)), which is hereby incorporated by reference into this Agreement.
  
2\. **Additional Commercial Terms**. If, on the Llama 4 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/](https://about.meta.com/brand/resources/meta/company-brand/)[)](https://en.facebookbrand.com/). 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 4 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.
\ No newline at end of file
# Llama4
## 论文
暂无
## 模型结构
Llama 4模型是Llama系列模型中首批采用混合专家(MoE)架构的模型。这一模型也是DeepSeek系列模型采用的架构,与传统的稠密模型相比,在MoE架构中,单独的token只会激活全部参数中的一小部分,训练和推理的计算效率更高。
- Llama 4 Scout,面向文档摘要与大型代码库推理任务,专为高效信息提取与复杂逻辑推理打造,共有16位“专家”、1090亿参数、170亿激活参数量;
- Llama 4 Maverick,专注于多模态能力,支持视觉和语音输入,具备顶级的多语言支持与编程能力,共有128位“专家”、4000亿参数、170亿激活参数量;
- Llama 4 Behemoth,Meta未来最强大的AI模型之一,具备令人瞩目的超大规模参数架构,具有2880亿激活参数量,总参数高达2万亿。
Llama在长文本能力上也取得了突破,具有超大的上下文窗口长度。Llama 4 Scout模型支持高达1000万token的上下文窗口,刷新了开源模型的纪录,而市场上其他领先模型如GPT-4o也未能达到此规模。超大上下文窗口使Llama 4在处理长文档、复杂对话和多轮推理任务时表现出色。
## 算法原理
<div align=center>
<img src="./doc/method.png"/>
</div>
## 环境配置
`-v 路径``docker_nam`e和`imageID`根据实际情况修改
### Docker(方法一)
```bash
cd docker
docker build --no-cache -t llama-factory:latest .
docker run -it --shm-size 200g --network=host --name {docker_name} --privileged --device=/dev/kfd --device=/dev/dri --device=/dev/mkfd --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -u root -v /path/your_code_data/:/path/your_code_data/ -v /opt/hyhal/:/opt/hyhal/:ro {imageID} bash
cd /your_code_path/llama4_pytorch
pip install git+https://github.com/hiyouga/transformers.git@llama4_train
pip install -r requirements.txt
```
### Dockerfile(方法二)
```bash
cd docker
docker build --no-cache -t llama4:latest .
docker run -it --shm-size 200g --network=host --name {docker_name} --privileged --device=/dev/kfd --device=/dev/dri --device=/dev/mkfd --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -u root -v /path/your_code_data/:/path/your_code_data/ -v /opt/hyhal/:/opt/hyhal/:ro {imageID} bash
cd /your_code_path/llama4_pytorch
pip install git+https://github.com/hiyouga/transformers.git@llama4_train
pip install -r requirements.txt
```
### Anaconda(方法三)
关于本项目DCU显卡所需的特殊深度学习库可从[光合](https://developer.hpccube.com/tool/)开发者社区下载安装。
```bash
DTK: 25.04
python: 3.10
torch: 2.4.1
deepspeed: 0.14.2+das.opt2.dtk2504
vllm: 0.6.2+das.opt3.dtk2504
```
`Tips:以上dtk驱动、python、torch等DCU相关工具版本需要严格一一对应`
## 训练
### Llama Factory 微调方法(推荐)
1. 训练库安装(**非llama4_pytorch目录下**),安装版本大于**v0.9.2**`Llama-Factory`具体安装方法请参考仓库的README。
```
git clone https://developer.sourcefind.cn/codes/OpenDAS/llama-factory
```
2. 通过[预训练权重](#预训练权重)下载预训练模型,当前用例使用[Meta-Llama-3-8B-Instruct](http://113.200.138.88:18080/aimodels/Meta-Llama-3-8B-Instruct)模型。
#### 全参微调
SFT训练脚本示例,参考`llama-factory/train_full`下对应yaml文件。
**参数修改**
--model_name_or_path 修改为待训练模型地址,如 /data/Meta-llama3-models/Meta-Llama-3-8B-Instruct
--dataset 微调训练集名称,可选数据集请参考/LLaMA-Factory-0.6.3/data/dataset_info.json
--template 将 default 修改为 llama3
--output_dir 模型保存地址
--fp16 或 --bf16 开启混合精度,单精度可使用 --pure_bf16
其他参数如:--learning_rate、--save_steps可根据自身硬件及需求进行修改。
#### lora微调
SFT训练脚本示例,参考`llama-factory/train_lora`下对应yaml文件。
参数解释同[#全参微调](#全参微调)
## 推理
### vllm推理方法
#### OpenAI server启动
**参数解释:**
- MODEL_PATH: 待测模型地址
- tp: 为模型并行度,根据模型大小进行设定
- PORT: 端口号
- MAX_MODEL_LEN: 模型最大长度,根据模型大小进行设定
- MODEL_NAME: 模型名称
```bash
vllm serve ${MODEL_PATH} --trust-remote-code --enforce-eager --tensor-parallel-size ${tp} --port ${PORT} --max-model-len ${MAX_MODEL_LEN} --served-model-name ${MODEL_NAME} &
```
访问方法:
```bash
curl http://localhost:${PORT}1/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": ${MODEL_NAME},
"messages": [
{"role": "user", "content": "你好"}
]
}'
```
#### 本地python脚本启动
```bash
python infer_vllm.py
```
### transformers推理方法
```bash
## 必须添加HF_ENDPOINT环境变量
export HF_ENDPOINT=https://hf-mirror.com
python infer_transformers.py --model_id /path_of/model_id
```
## result
### 精度
暂无
## 应用场景
### 算法类别
对话问答
### 热点应用行业
制造,广媒,家居,教育
## 预训练权重
模型目录结构如下:
```bash
├── model_save_path
│ ├── Meta-Llama-3-8B
│ ├── original
│ ├── consolidated.00.pth
│ ├── params.json
│ └── tokenizer.model
│ ├── config.json
│ ├── configuration.json
│ ├── generation_config.json
│ ├── LICENSE
│ ├── model-00001-of-00004.safetensors
│ ├── model-00002-of-00004.safetensors
│ ├── model-00003-of-00004.safetensors
│ ├── model-00004-of-00004.safetensors
│ ├── model.safetensors.index.json
│ ├── README.md
│ ├── special_tokens_map.json
│ ├── tokenizer_config.json
│ ├── tokenizer.json
│ └── USE_POLICY.md
```
## 源码仓库及问题反馈
- https://developer.hpccube.com/codes/modelzoo/llama4_pytorch
## 参考资料
- https://github.com/meta-llama/llama3
- https://github.com/InternLM/xtuner
- https://github.com/meta-llama/llama-recipes
- https://github.com/hiyouga/LLaMA-Factory/tree/v0.6.3
FROM image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.4.1-ubuntu22.04-dtk25.04-py3.10
\ No newline at end of file
import argparse
import torch
from transformers import AutoProcessor, Llama4ForConditionalGeneration
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--model_id", type=str, default="meta-llama/Llama-4-Scout-17B-16E-Instruct")
args = parser.parse_args()
return args
if __name__ == "__main__":
# 获取参数信息
args = get_args()
processor = AutoProcessor.from_pretrained(args.model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
args.model_id,
attn_implementation="flex_attention",
device_map="auto",
torch_dtype=torch.bfloat16,
)
url1 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"
url2 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/cat_style_layout.png"
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": url1},
{"type": "image", "url": url2},
{"type": "text", "text": "Can you describe how these two images are similar, and how they differ?"},
]
},
]
# 模板转换
inputs = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
).to(model.device)
outputs = model.generate(
**inputs,
max_new_tokens=256,
)
response = processor.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])[0]
print(response)
print(outputs[0])
import time
from openai import OpenAI
from transformers import AutoTokenizer
from vllm import LLM, SamplingParams
def infer_llama4_vllm(model_path, message, tp_size=1, max_model_len=4096):
'''vllm 推理 llama4'''
tokenizer = AutoTokenizer.from_pretrained(model_path)
# message = MARKDOWN_TEMPLATE.format(query)
messages = [{"role": "user", "content": message}]
print(f"Prompt: {messages!r}")
sampling_params = SamplingParams(temperature=0.3,
top_p=0.9,
max_tokens=4096,
stop_token_ids=[tokenizer.eos_token_id])
llm = LLM(model=model_path,
max_model_len=max_model_len,
trust_remote_code=True,
enforce_eager=True,
dtype="float16",
tensor_parallel_size=tp_size)
# generate answer
prompt_token_ids = [tokenizer.apply_chat_template(messages, add_generation_prompt=True)]
start_time = time.time()
outputs = llm.generate(prompt_token_ids=prompt_token_ids, sampling_params=sampling_params)
print("total infer time", time.time() - start_time)
# results
for output in outputs:
generated_text = output.outputs[0].text
print(f"Generated text: {generated_text!r}")
def infer_llama4_client(client, messages, model_name='Llama-4-Scout-17B-16E-Instruct'):
print(f"Prompt: {messages!r}")
response = client.chat.completions.create(
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": str(messages)}
],
model=model_name,
stream=False
)
print(f"Response text: {response!r}")
return response
if __name__ == "__main__":
# VLLM 本地推理
infer_llama4_vllm(model_path="meta-llama/Llama-4-Scout-17B-16E-Instruct",
message="你好",
tp_size=1,
max_model_len=4096)
# OpenAI API 推理
# url = "127.0.0.1:8000" # 根据实际情况修改
# client = OpenAI(api_key="EMPTY", base_url=f"http://{url}/v1")
# infer_llama4_client(client=client,
# messages="你好",
# model_name='Llama-4-Scout-17B-16E-Instruct')
\ No newline at end of file
### model
model_name_or_path: meta-llama/meta-llama/Llama-4-Scout-17B-16E-Instruct
trust_remote_code: true
### method
stage: sft
do_train: true
finetuning_type: full
deepspeed: examples/deepspeed/ds_z3_config.json # choices: [ds_z0_config.json, ds_z2_config.json, ds_z3_config.json]
### dataset
dataset: identity,alpaca_en_demo
template: llama4
cutoff_len: 2048
overwrite_cache: true
preprocessing_num_workers: 16
dataloader_num_workers: 4
### output
output_dir: saves/llama4-108b/full/sft
logging_steps: 10
save_steps: 500
plot_loss: true
overwrite_output_dir: true
save_only_model: false
### train
per_device_train_batch_size: 1
gradient_accumulation_steps: 2
learning_rate: 1.0e-5
num_train_epochs: 3.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
resume_from_checkpoint: null
### eval
# eval_dataset: alpaca_en_demo
# val_size: 0.1
# per_device_eval_batch_size: 1
# eval_strategy: steps
# eval_steps: 500
# pip install git+https://github.com/hiyouga/transformers.git@llama4_train
### model
model_name_or_path: meta-llama/Llama-4-Scout-17B-16E-Instruct
trust_remote_code: true
### method
stage: sft
do_train: true
finetuning_type: lora
lora_rank: 8
lora_target: all
deepspeed: examples/deepspeed/ds_z3_config.json # choices: [ds_z0_config.json, ds_z2_config.json, ds_z3_config.json]
### dataset
dataset: mllm_demo,identity,alpaca_en_demo
template: llama4
cutoff_len: 2048
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16
dataloader_num_workers: 4
### output
output_dir: saves/llama4-108b/lora/sft
logging_steps: 10
save_steps: 500
plot_loss: true
overwrite_output_dir: true
save_only_model: false
### train
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
learning_rate: 1.0e-4
num_train_epochs: 3.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
resume_from_checkpoint: null
### eval
# eval_dataset: alpaca_en_demo
# val_size: 0.1
# per_device_eval_batch_size: 1
# eval_strategy: steps
# eval_steps: 500
# 模型唯一标识
modelCode=1481
# 模型名称
modelName=llama4_pytorch
# 模型描述
modelDescription=Meta最新开源模型llama4
# 应用场景
appScenario=推理,训练,对话问答,制造,广媒,家居,教育
# 框架类型
frameType=pytorch
# This file was autogenerated by uv via the following command:
# uv export --frozen --no-hashes --no-emit-project --output-file=requirements.txt
annotated-types==0.7.0
certifi==2025.1.31
charset-normalizer==3.4.1
idna==3.10
jinja2==3.1.6
markupsafe==3.0.2
pillow==11.1.0
pydantic==2.10.6
pydantic-core==2.27.2
pyyaml==6.0.2
regex==2024.11.6
requests==2.32.3
tiktoken==0.8.0
typing-extensions==4.12.2
urllib3==2.3.0
\ No newline at end of file
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