Commit 67a9a51f authored by dengjb's avatar dengjb
Browse files

update codes

parent 74155287
Pipeline #1298 canceled with stages
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/en/_build/
docs/zh_cn/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.vscode
.idea
.DS_Store
# custom
*.pkl
*.pkl.json
*.log.json
# Pytorch
*.pth
*.py~
*.sh~
\ No newline at end of file
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# codellama_pytorch
# CodeLlama
Codellama模型是一系列7B、13B、34B和70B模型,使用500B-1T的tokens进行训练。
## 论文
`Code Llama: Open Foundation Models for Code`<br>
[CodeLlama](https://scontent-lax3-1.xx.fbcdn.net/v/t39.2365-6/440937359_1249838219330505_1104237120116944930_n.pdf?_nc_cat=109&ccb=1-7&_nc_sid=3c67a6&_nc_ohc=nf68R9-64t8Q7kNvgHxIBjM&_nc_ht=scontent-lax3-1.xx&oh=00_AYBcUILDMCTVXhedseMkIiEnVwAkWPP9xejZllnlBiaK0Q&oe=66893420)
## 模型结构
codellama的模型结构主要基于llama2架构进行训练而来,使用了不同的训练方法得到了基于不同任务目的的代码生成模型。
<div align=center>
<img src="./asserts/model_architecture.png"/>
</div>
code generation models by meta
\ No newline at end of file
## 算法原理
使用GQA模块能够带来更好的速度,使用GQA的head数量不同则会带来速度和性能平衡转换<br>
使用了RoPE位置旋转编码来替代Embedding编码,使得模型获得更好的外推性。<br>
<div align=center>
<img src="./asserts/model_blocks.png"/>
</div>
## 环境配置
-v 路径、docker_name和imageID根据实际情况修改
### Docker(方法一)
```bash
docker pull image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.1.0-centos7.6-dtk24.04-py310
docker run -it -v /path/your_code_data/:/path/your_code_data/ -v /opt/hyhal/:/opt/hyhal/:ro --shm-size=80G --privileged=true --device=/dev/kfd --device=/dev/dri/ --group-add video --name docker_name imageID bash
cd /your_code_path/codellama_pytorch
pip install -r requirements.txt
export HF_ENDPOINT=https://hf-mirror.com
```
### Dockerfile(方法二)
```bash
cd docker
docker build --no-cache -t codellama:latest .
docker run -it -v /path/your_code_data/:/path/your_code_data/ -v /opt/hyhal/:/opt/hyhal/:ro --shm-size=80G --privileged=true --device=/dev/kfd --device=/dev/dri/ --group-add video --name docker_name imageID bash
cd /your_code_path/codellama_pytorch
pip install -r requirements.txt
export HF_ENDPOINT=https://hf-mirror.com
```
### Anaconda(方法三)
关于本项目DCU显卡所需的特殊深度学习库可从[光合](https://developer.hpccube.com/tool/)开发者社区下载安装。
```
DTK驱动: dtk24.04
python: python3.10
torch: 2.1.0
```
`Tips:以上dtk驱动、python、torch等DCU相关工具版本需要严格一一对应`
其它非深度学习库安装方式如下:
```bash
pip install -r requirements.txt -i http://mirrors.huaweicloud.com/repository/pypi/simple
export HF_ENDPOINT=https://hf-mirror.com
```
## 数据集
finetune训练样例数据采用verilog-dataset-v3 [下载地址](https://hf-mirror.com/datasets/emilgoh/verilog-dataset-v3)<br>
```angular2html
.
├── verilog-dataset-v3
│   ├── README.md
│   └── train.csv
......
```
<div align=center>
<img src="./asserts/dataset.png"/>
</div>
## 训练
### 单机两卡
- lora微调
具体参数更改请在train.sh文件中进行,以下为必要参数 <br>
DATA_PATH="{数据集地址}" <br>
MODEL_PATH="{预训练模型加载地址}" <br>
- 全参微调 - 将lora_config地址空字符填充即可
LORA_CONFIG=""
```bash
bash ./train.sh
```
## 推理
基于Huggingface's Transformers进行推理.<br>
模型下载后[模型下载地址](https://hf-mirror.com/meta-llama/CodeLlama-7b-Instruct-hf) 默认需存放至weights文件夹中<br>
也可自行更改 inference.py文件中的 model_name 参数<br>
```bash
HIP_VISIBLE_DEVICES=0 python inference.py
```
## Result
prompt:In Bash, how do I list all text files in the current directory (excluding subdirectories) that have been modified in the last month?",<br>
result:
<div align=center>
<img src="./asserts/result.png"/>
</div>
### 精度
训练集verilog-dataset-v3
| device | lora_train_loss | steps |
|:--------:|:---------------:|:-----:|
| A800*2 | 0.4743 | 2580 |
| K100*2 | 0.4687 | 2580 |
NV:绿色 DCU:红色
<div align=center>
<img src="./asserts/loss.jpg"/>
</div>
## 应用场景
### 算法类别
代码生成
### 热点应用行业
制造,能源,教育
## 预训练权重
模型目录结构如下:
```
.
└── CodeLlama-7b-Instruct-hf
├── config.json
├── generation_config.json
├── LICENSE
├── model-00001-of-00002.safetensors
├── model-00002-of-00002.safetensors
├── model.safetensors.index.json
├── pytorch_model-00001-of-00003.bin
├── pytorch_model-00002-of-00003.bin
├── pytorch_model-00003-of-00003.bin
├── pytorch_model.bin.index.json
├── README.md
├── special_tokens_map.json
├── tokenizer_config.json
├── tokenizer.json
├── tokenizer.model
└── USE_POLICY.md
```
## 源码仓库及问题反馈
- https://developer.hpccube.com/codes/modelzoo/starcoder2_pytorch
## 参考资料
- https://developer.hpccube.com/codes/modelzoo/codellama_pytorch
- https://hf-mirror.com/meta-llama/CodeLlama-7b-Instruct-hf
- https://github.com/meta-llama/codellama
- https://hf-mirror.com/datasets/emilgoh/verilog-dataset-v3
FROM image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.1.0-centos7.6-dtk24.04-py310
\ No newline at end of file
{
"bf16": {
"enabled": "auto"
},
"optimizer": {
"type": "AdamW",
"params": {
"lr": "auto",
"betas": "auto",
"eps": "auto",
"weight_decay": "auto"
}
},
"scheduler": {
"type": "WarmupLR",
"params": {
"warmup_min_lr": "auto",
"warmup_max_lr": "auto",
"warmup_num_steps": "auto"
}
},
"zero_optimization": {
"stage": 3,
"offload_optimizer": {
"device": "cpu",
"pin_memory": true
},
"offload_param": {
"device": "cpu",
"pin_memory": true
},
"overlap_comm": true,
"contiguous_gradients": true,
"sub_group_size": 1e9,
"reduce_bucket_size": "auto",
"stage3_prefetch_bucket_size": "auto",
"stage3_param_persistence_threshold": "auto",
"stage3_max_live_parameters": 1e9,
"stage3_max_reuse_distance": 1e9,
"stage3_gather_16bit_weights_on_model_save": true
},
"gradient_accumulation_steps": "auto",
"gradient_clipping": "auto",
"steps_per_print": 20,
"train_batch_size": "auto",
"train_micro_batch_size_per_gpu": "auto",
"wall_clock_breakdown": false
}
\ No newline at end of file
import copy
import random
from dataclasses import dataclass, field
from typing import Optional, Dict, Sequence
import os
import torch
import torch.distributed
import transformers
from transformers import Trainer
from datasets import load_dataset
IGNORE_INDEX = -100
EOT_TOKEN = "<|EOT|>"
def build_instruction_prompt(instruction: str):
return '''
You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.
### Instruction:
{}
### Response:
'''.format(instruction.strip()).lstrip()
@dataclass
class ModelArguments:
model_name_or_path: Optional[str] = field(default="./weights/CodeLlama-7b-Instruct-hf")
@dataclass
class DataArguments:
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
# training Default Arguments 继承于 Transform.TrainingArguments 的默认参数。
@dataclass
class TrainingArguments(transformers.TrainingArguments):
cache_dir: Optional[str] = field(default=None)
optim: str = field(default="adamw_torch")
model_max_length: int = field(
default=512,
metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
)
lora_config: str = field(default="",
metadata={"help": "lora Finetuning configs path, for use ptft model to finetuning."},
)
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
"""Collects the state dict and dump to disk."""
state_dict = trainer.model.state_dict()
if trainer.args.should_save:
cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
del state_dict
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
"""Tokenize a list of strings."""
tokenized_list = [
tokenizer(
text,
return_tensors="pt",
padding="longest",
max_length=tokenizer.model_max_length,
truncation=True,
)
for text in strings
]
input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
input_ids_lens = labels_lens = [
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
]
return dict(
input_ids=input_ids,
labels=labels,
input_ids_lens=input_ids_lens,
labels_lens=labels_lens,
)
def preprocess(
sources: Sequence[str],
targets: Sequence[str],
tokenizer: transformers.PreTrainedTokenizer,
) -> Dict:
"""Preprocess the data by tokenizing."""
system_prompt = 'I want you to act as an IC designer, and implement the following in Verilog.'
instruction = 'Generate a Verilog module'
examples = [tokenizer.apply_chat_template([
{"role": "system", "content": f"{system_prompt} {instruction}"},
{"role": "user", "content": f"{s}"},
{"role": "assistant", "content": f"{t}"},
], tokenize=False) for s, t in zip(sources, targets)]
examples_tokenized, sources_tokenized = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)]
input_ids = examples_tokenized["input_ids"]
labels = copy.deepcopy(input_ids)
for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]):
label[:source_len] = IGNORE_INDEX
return dict(input_ids=input_ids, labels=labels)
@dataclass
class DataCollatorForSupervisedDataset(object):
"""Collate examples for supervised fine-tuning."""
tokenizer: transformers.PreTrainedTokenizer
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
input_ids = [torch.tensor(x) for x in input_ids]
input_ids = torch.nn.utils.rnn.pad_sequence(
input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id
)
labels = [torch.tensor(x) for x in labels]
labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
return dict(
input_ids=input_ids,
labels=labels,
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
)
# input_ids = torch.tensor(input_ids)
# labels = torch.tensor(labels)
# return dict(
# input_ids=input_ids,
# labels=labels,
# attention_mask=input_ids,
# )
def train_tokenize_function(examples, tokenizer):
sources = [
build_instruction_prompt(instruction)
for instruction in examples['description']
]
targets = [output for output in examples['output']]
data_dict = preprocess(sources, targets, tokenizer)
return data_dict
def train():
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
if training_args.local_rank == 0:
print('=' * 100)
print(training_args)
tokenizer = transformers.AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
model_max_length=training_args.model_max_length,
padding_side="right",
use_fast=True,
trust_remote_code=True
)
tokenizer.pad_token_id = tokenizer.eos_token_id
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "left"
print("PAD Token:", tokenizer.pad_token, tokenizer.pad_token_id)
print("BOS Token", tokenizer.bos_token, tokenizer.bos_token_id)
print("EOS Token", tokenizer.eos_token, tokenizer.eos_token_id)
if training_args.local_rank == 0:
print("Load tokenizer from {} over.".format(model_args.model_name_or_path))
model = transformers.AutoModelForCausalLM.from_pretrained(
model_args.model_name_or_path,
torch_dtype=torch.bfloat16,
# low_cpu_mem_usage=True,
trust_remote_code=True,
)
if training_args.local_rank == 0:
print("Load model from {} over.".format(model_args.model_name_or_path))
raw_train_datasets = load_dataset(
'csv',
data_files=data_args.data_path,
split="train",
cache_dir=training_args.cache_dir
)
if training_args.local_rank > 0:
torch.distributed.barrier()
train_dataset = raw_train_datasets.map(
train_tokenize_function,
batched=True,
batch_size=3000,
num_proc=32,
remove_columns=raw_train_datasets.column_names,
load_from_cache_file=True, # not args.overwrite_cache
desc="Running Encoding",
fn_kwargs={"tokenizer": tokenizer}
)
if training_args.local_rank == 0:
torch.distributed.barrier()
if training_args.local_rank == 0:
print("Training dataset samples:", len(train_dataset))
for index in random.sample(range(len(train_dataset)), 3):
print(
f"Sample {index} of the training set: {train_dataset[index]['input_ids']}, {train_dataset[index]['labels']}.")
print(f"Sample {index} of the training set: {tokenizer.decode(list(train_dataset[index]['input_ids']))}.")
if training_args.lora_config is not None and os.path.exists(training_args.lora_config):
from peft import (
get_peft_model,
LoraConfig,
TaskType,
prepare_model_for_kbit_training,
peft_model,
set_peft_model_state_dict,
)
import json
with open(training_args.lora_config) as f:
lora_config = json.load(f)
petf_lora_config = LoraConfig(
r=lora_config['r'],
lora_alpha=lora_config["lora_alpha"],
target_modules=lora_config["target_modules"],
fan_in_fan_out=False,
lora_dropout=lora_config["lora_dropout"],
bias=lora_config["bias"],
task_type="CAUSAL_LM",
inference_mode=False,
)
model.enable_input_require_grads()
model = get_peft_model(model, peft_config=petf_lora_config)
# if training_args.output_dir:
# if os.path.exists(training_args.output_dir):
# print(f"Restarting from {training_args.output_dir}")
# adapters_weights = torch.load(training_args.output_dir)
# set_peft_model_state_dict(model, adapters_weights)
# else:
# print(f"Checkpoint {training_args.output_dir} not found")
print(("#" * 10 + "\n") * 2 + "\n" + "\n")
print("using lora finetune!")
print("\n" + "\n" + ("#" * 10 + "\n") * 2)
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
data_module = dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
trainer = Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
trainer.train()
trainer.save_state()
safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
if __name__ == "__main__":
train()
icon.png

62.1 KB

import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer
base_model = "./weights/CodeLlama-7b-Instruct-hf"
max_gen_length = 4096
description = "In Bash, how do I list all text files in the current directory (excluding subdirectories) that have been modified in the last month?"
tokenizer = AutoTokenizer.from_pretrained(
base_model,
model_max_length=max_gen_length,
)
chat = [
{"role": "user", "content": f"{description}"},
]
print(tokenizer.apply_chat_template(chat, tokenize=False))
model_input = tokenizer.apply_chat_template(chat,return_tensors="pt",truncation=True,).to("cuda")
model = AutoModelForCausalLM.from_pretrained(
base_model,
torch_dtype=torch.float16,
device_map="auto",
low_cpu_mem_usage=True,
trust_remote_code=True,
)
model.eval()
with torch.no_grad():
print(tokenizer.decode(model.generate(model_input, max_new_tokens=max_gen_length)[0], skip_special_tokens=True))
{
"r":8,
"lora_alpha":16,
"target_modules":["q_proj","v_proj"],
"fan_in_fan_out":"False",
"lora_dropout":0.05,
"bias":"none",
"task_type":"CAUSAL_LM",
"inference_mode":"False"
}
\ No newline at end of file
# 模型唯一标识
modelCode=650
# 模型名称
modelName=codellama_pytorch
# 模型描述
modelDescription=Codellama模型是一系列7B、13B、34B和70B模型,使用500B-1T的tokens进行训练。
# 应用场景
appScenario=推理,训练,代码生成,制造,能源,教育
# 框架类型
frameType=pytorch
#torch>=2.0
#tokenizers>=0.14.0
#transformers==4.35.0
#accelerate
#deepspeed==0.12.2
sympy==1.12
pebble
timeout-decorator
accelerate
attrdict
tqdm
datasets
tensorboardX
peft
#export CUDA_VISIBLE_DEVICES=1,2
DATA_PATH="./data/verilog-dataset-v3/train.csv"
OUTPUT_PATH="./outputs"
MODEL_PATH="./weights/CodeLlama-7b-Instruct-hf"
DEEPSEPPD_CONFIG="./dp_configs/ds_config_stage3.json"
LORA_CONFIG="./lora_config.json"
deepspeed --include="localhost:2,3" --master_port 25923 fintune.py \
--model_name_or_path $MODEL_PATH \
--data_path $DATA_PATH \
--output_dir $OUTPUT_PATH \
--num_train_epochs 3 \
--model_max_length 2048 \
--per_device_train_batch_size 2 \
--per_device_eval_batch_size 1 \
--gradient_accumulation_steps 4 \
--evaluation_strategy "no" \
--save_strategy "steps" \
--save_steps 100 \
--save_total_limit 100 \
--learning_rate 2e-5 \
--warmup_steps 10 \
--logging_steps 1 \
--lr_scheduler_type "cosine" \
--gradient_checkpointing True \
--report_to "all" \
--deepspeed $DEEPSEPPD_CONFIG \
--bf16 True \
--lora_config $LORA_CONFIG
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