Code Monkey home page Code Monkey logo

textgen's Introduction

🇨🇳中文 | 🌐English | 📖文档/Docs | 🤖模型/Models


TextGen: Implementation of Text Generation models

PyPI version Downloads Contributions welcome License Apache 2.0 python_version GitHub issues Wechat Group

📖 Introduction

TextGen实现了多种文本生成模型,包括:LLaMA、ChatGLM、UDA、GPT2、Seq2Seq、BART、T5、SongNet等模型,开箱即用。

🔥 News

[2023/11/02] v1.1.2版本: GPT模型支持了NEFTune给embedding加噪SFT训练方法,SFT中使用 --neft_alpha 参数启用 NEFTune,例如 --neft_alpha 5。详见Release-v1.1.2

[2023/09/05] v1.1.1版本: 支持多卡推理,推理速度加倍,调库textgen做batch推理,多卡推理更方便、快速。详见Release-v1.1.1

[2023/08/23] v1.1.0版本: 发布基于ShareGPT4数据集微调的中英文Vicuna-13B模型shibing624/vicuna-baichuan-13b-chat,和对应的LoRA模型shibing624/vicuna-baichuan-13b-chat-lora,支持多轮对话,评测效果有提升,详见Release-v1.1.0

[2023/08/02] v1.0.2版本: 新增支持ChatGLM2和LLaMA2模型的SFT微调训练,详见Release-v1.0.2

[2023/06/15] v1.0.0版本: 新增ChatGLM/LLaMA/Bloom模型的多轮对话微调训练,并发布医疗问诊LoRA模型shibing624/ziya-llama-13b-medical-lora。详见Release-v1.0.0

[2023/06/02] v0.2.7版本: 新增ChatGLM/LLaMA/Bloom模型的SFT微调训练,并发布适用于通用对话和中文纠错的LoRA模型。详见Release-v0.2.7

😊 Feature

  • GPT:本项目基于PyTorch实现了 ChatGLM-6B 1,2,3 / Baichuan 1,2 / LLaMA 1,2 / BLOOM / Mistral / QWen 等GPT模型LoRA微调训练和预测,可以用于对话生成任务和领域微调训练
  • UDA/EDA:本项目实现了UDA(非核心词替换)、EDA和Back Translation(回译)算法,基于TF-IDF将句子中部分不重要词替换为同义词,随机词插入、删除、替换等方法,产生新的文本,实现了文本扩增
  • Seq2Seq:本项目基于PyTorch实现了Seq2Seq、ConvSeq2Seq、BART模型的训练和预测,可以用于文本翻译、对话生成、摘要生成等文本生成任务
  • T5:本项目基于PyTorch实现了T5和CopyT5模型训练和预测,可以用于文本翻译、对话生成、对联生成、文案撰写等文本生成任务
  • GPT2:本项目基于PyTorch实现了GTP2模型训练和预测,可以用于文章生成、对联生成等文本生成任务
  • SongNet:本项目基于PyTorch实现了SongNet模型训练和预测,可以用于规范格式的诗词、歌词等文本生成任务
  • TGLS:本项目实现了TGLS无监督相似文本生成模型,是一种“先搜索后学习”的文本生成方法,通过反复迭代学习候选集,最终模型能生成类似候选集的高质量相似文本

Release Models

release基于textgen训练的中文模型,模型已经release到HuggingFace models,指定模型名称textgen会自动下载模型,可直接使用。

Model Arch Introduction Train Script Predict Script
shibing624/t5-chinese-couplet T5 fine-tuned中文对联后的模型 对联生成模型调研 predict script
shibing624/songnet-base-chinese-songci SongNet fine-tuned宋词后的模型 training script predict script
shibing624/songnet-base-chinese-couplet SongNet fine-tuned对联后的模型 training script predict script
shibing624/chatglm-6b-csc-zh-lora ChatGLM-6B 在27万中文拼写纠错数据shibing624/CSC上微调了一版ChatGLM-6B,纠错效果有提升,发布微调后的LoRA权重 training script predict script
shibing624/chatglm-6b-belle-zh-lora ChatGLM-6B 在100万条中文ChatGPT指令Belle数据集BelleGroup/train_1M_CN上微调了一版ChatGLM-6B,问答效果有提升,发布微调后的LoRA权重 training script predict script
shibing624/llama-13b-belle-zh-lora LLaMA-13B 在100万条中文ChatGPT指令Belle数据集BelleGroup/train_1M_CN上微调了一版Llama-13B,问答效果有提升,发布微调后的LoRA权重 training script predict script
shibing624/chinese-alpaca-plus-7b-hf LLaMA-7B 中文LLaMA-Plus, Alpaca-Plus 7B版本,在LLaMA-7B上扩充了中文词表并继续预训练120G文本(通用领域),在4M指令数据集上微调后得到的中文Alpaca-plus模型 training script predict script
shibing624/chinese-alpaca-plus-13b-hf LLaMA-13B 中文LLaMA-Plus, Alpaca-Plus 13B版本,在LLaMA-13B上扩充了中文词表并继续预训练120G文本(通用领域),在4.3M指令数据集上微调后得到的中文Alpaca-plus模型 training script predict script
shibing624/ziya-llama-13b-medical-lora LLaMA-13B 在240万条中英文医疗数据集shibing624/medical上微调了一版Ziya-LLaMA-13B模型,医疗问答效果有提升,发布微调后的LoRA权重 training script predict script
shibing624/vicuna-baichuan-13b-chat Baichuan-13B-Chat 在10万条多语言ShareGPT GPT4多轮对话数据集shibing624/sharegpt_gpt4上SFT微调了一版baichuan-13b-chat多轮问答模型,日常问答和医疗问答效果有提升,发布微调后的完整模型权重 training script predict script

Evaluation

Model Arch Introduction Score
LLaMA-7B-Chinese-Alpaca LLaMA-7B 复用ymcui/Chinese-LLaMA-Alpaca的评估case和得分 4.92
LLaMA-13B-Chinese-Alpaca LLaMA-13B 复用ymcui/Chinese-LLaMA-Alpaca的评估case和得分 7.05
ChatGLM-6B ChatGLM-6B 基于原生THUDM/chatglm-6b评估测试集得分 7.16
ChatGLM-6B-v1.1 ChatGLM-6B 基于原生THUDM/chatglm-6bv1.1英文优化版模型评估测试集得分 7.18
shibing624/chatglm-6b-belle-zh-lora ChatGLM-6B 基于THUDM/chatglm-6b加载shibing624/chatglm-6b-belle-zh-loraLoRA模型后评估测试集得分 7.03
facat/alpaca-lora-cn-13b LLaMA-13B 基于decapoda-research/llama-13b-hf加载facat/alpaca-lora-cn-13bLoRA模型后评估测试集并标注得分 4.13
Chinese-Vicuna/Chinese-Vicuna-lora-13b-belle-and-guanaco LLaMA-13B 基于decapoda-research/llama-13b-hf加载Chinese-Vicuna/Chinese-Vicuna-lora-13b-belle-and-guanacoLoRA模型后评估测试集并标注得分 3.98
shibing624/chinese-alpaca-plus-7b-hf LLaMA-7B 使用ymcui/Chinese-LLaMA-Alpaca 合并模型方法合并HF权重后,评估测试集并标注得分 6.93
shibing624/chinese-alpaca-plus-13b-hf LLaMA-13B 使用ymcui/Chinese-LLaMA-Alpaca 合并模型方法合并HF权重后,评估测试集并标注得分 7.07
TheBloke/vicuna-13B-1.1-HF LLaMA-13B 使用原生vicuna-13B-1.1合并后的模型,评估测试集并标注得分 5.13
IDEA-CCNL/Ziya-LLaMA-13B-v1 LLaMA-13B 使用姜子牙通用大模型V1,评估测试集并标注得分 6.63

说明:

  • 评估case,详见在线文档:中文LLM-benchmark多任务评估集(腾讯文档) https://docs.qq.com/sheet/DUUpsREtWbFBsUVJE?tab=r7io7g 感谢韩俊明、杨家铭等同学的标注
  • 评估任务类型包括:知识问答,开放式问答,数值计算,诗词、音乐、体育,娱乐,写文章,文本翻译,代码编程,伦理、拒答类,多轮问答,Score 评分是前100条(10分制)的平均分数,人工打分,越高越好
  • 评估数量少,任务类型不够全面,评分之间的大小关系有一些参考价值,分数的绝对值没太大参考价值
  • 评估脚本:tests/test_benchmark.py ,使用fp16预测,无int量化处理,运行脚本可复现评估结果,但生成结果具有随机性,受解码超参、随机种子等因素影响。评测并非绝对严谨,测试结果仅供晾晒参考
  • 结论:ChatGLM-6B、LLaMA-13B的中文衍生模型(包括alpaca-plus, vicuna, ziya)的表现属于第一梯队,原版LLaMA-7B的表现整体稍差些
  • LLaMA-13B-Chinese-Alpaca是在原版LLaMA上扩充了中文词表,并融入了约20G的通用中文语料后的指令微调模型,表明了LLaMA的底座优秀,具有强大的语言迁移能力
  • ChatGLM这种原生的中文预训练模型更理解中文语义,且在中文知识问答、开放式问答得分高
  • LLaMA系列模型数值计算、中英翻译、代码编程类得分高
  • 经过中文预训练和SFT微调后的Chinese-LLaMA模型在中文诗词、娱乐、伦理类得分相较原版LLaMA有提升

🚀 Demo

HuggingFace Demo: https://huggingface.co/spaces/shibing624/chinese-couplet-generate

run example: examples/T5/gradio_demo.py to see the demo:

python examples/T5/gradio_demo.py

model trained by examples/t5/T5_Finetune_Chinese_Couplet.ipynb

💾 Install

pip install -U textgen

or

install develop version:

pip install torch # conda install pytorch
git clone https://github.com/shibing624/textgen.git
cd textgen
python setup.py install

▶️ Usage

ChatGLM-6B 模型

使用 ChatGLM-6B 微调后的模型

example: examples/gpt/inference_demo.py

from textgen import GptModel

model = GptModel("chatglm", "THUDM/chatglm-6b", peft_name="shibing624/chatglm-6b-csc-zh-lora")
r = model.predict(["介绍下北京"])
print(r)  # ['北京是**的首都...']

训练 ChatGLM-6B 微调模型

  1. 支持自定义训练数据集和训练参数,数据集格式参考examples/data/sharegpt_zh_100_format.jsonl
  2. 支持QLoRA、AdaLoRA、LoRA、P_Tuning、Prefix_Tuning等部分参数微调方法,也支持全参微调
  3. 支持多卡训练,支持混合精度训练
  4. 支持多卡推理

example: examples/gpt/training_chatglm_demo.py

单卡训练:

cd examples/gpt
CUDA_VISIBLE_DEVICES=0 python training_chatglm_demo.py --do_train --do_predict --num_epochs 1 --output_dir outputs_chatglm_v1

多卡训练:

cd examples/gpt
CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 training_chatglm_demo.py --do_train --do_predict --num_epochs 20 --output_dir outputs_chatglm_v1

多卡推理:

cd examples/gpt
CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 inference_multigpu_demo.py --model_type chatglm --base_model THUDM/chatglm-6b

LLaMA 模型

使用 LLaMA 微调后的模型

example: examples/gpt/inference_demo.py

show code example and result
import sys

sys.path.append('../..')
from textgen import GptModel

model = GptModel("llama", "decapoda-research/llama-7b-hf", peft_name="ziqingyang/chinese-alpaca-lora-7b")
r = model.predict(["用一句话描述地球为什么是独一无二的。"])
print(r)  # ['地球是唯一一颗拥有生命的行星。']

训练 LLaMA 微调模型

  1. 支持自定义训练数据集和训练参数,数据集格式参考examples/data/sharegpt_zh_100_format.jsonl
  2. 支持QLoRA、AdaLoRA、LoRA、P_Tuning、Prefix_Tuning等部分参数微调方法,也支持全参微调
  3. 支持多卡训练,支持混合精度训练,使用方法同上(ChatGLM多卡训练)
  4. 支持多卡推理

example: examples/gpt/training_llama_demo.py

基于微调(LoRA)模型继续训练

如果需要基于Lora模型继续训练,可以使用下面的脚本合并模型为新的base model,再微调训练即可。

执行以下命令:

python -m textgen/gpt/merge_peft_adapter \
    --model_type llama \
    --base_model_name_or_path path/to/llama/model \
    --tokenizer_path path/to/llama/tokenizer \
    --peft_model_path path/to/lora/model \
    --output_dir merged

参数说明:

--model_type:模型类型,目前支持bloom,llama,baichuan和chatglm
--base_model_name_or_path:存放HF格式的底座模型权重和配置文件的目录
--tokenizer_path:存放HF格式的底座模型tokenizer文件的目录
--peft_model_path:中文LLaMA/Alpaca LoRA解压后文件所在目录,也可使用HF上的Lora模型名称,如`ziqingyang/chinese-alpaca-lora-7b`会自动下载对应模型
--output_dir:指定保存全量模型权重的目录,默认为./merged

训练领域模型

Note: 为了全面的介绍训练医疗大模型的过程,把4阶段训练方法(Pretraining, Supervised Finetuning, Reward Modeling and Reinforcement Learning)单独新建了一个repo:shibing624/MedicalGPT,请移步该repo查看训练方法。

ConvSeq2Seq 模型

训练并预测ConvSeq2Seq模型:

example: examples/seq2sesq/training_convseq2seq_model_demo.py

show code example and result
import argparse
from loguru import logger
import sys

sys.path.append('../..')
from textgen.seq2seq.conv_seq2seq_model import ConvSeq2SeqModel


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--train_file', default='../data/zh_dialog.tsv', type=str, help='Training data file')
    parser.add_argument('--do_train', action='store_true', help='Whether to run training.')
    parser.add_argument('--do_predict', action='store_true', help='Whether to run predict.')
    parser.add_argument('--output_dir', default='./outputs/convseq2seq_zh/', type=str, help='Model output directory')
    parser.add_argument('--max_seq_length', default=50, type=int, help='Max sequence length')
    parser.add_argument('--num_epochs', default=200, type=int, help='Number of training epochs')
    parser.add_argument('--batch_size', default=32, type=int, help='Batch size')
    args = parser.parse_args()
    logger.info(args)

    if args.do_train:
        logger.info('Loading data...')
        model = ConvSeq2SeqModel(epochs=args.num_epochs, batch_size=args.batch_size,
                                 model_dir=args.output_dir, max_length=args.max_seq_length)
        model.train_model(args.train_file)
        print(model.eval_model(args.train_file))

    if args.do_predict:
        model = ConvSeq2SeqModel(epochs=args.num_epochs, batch_size=args.batch_size,
                                 model_dir=args.output_dir, max_length=args.max_seq_length)
        sentences = ["什么是ai", "你是什么类型的计算机", "你知道热力学吗"]
        print("inputs:", sentences)
        print('outputs:', model.predict(sentences))


if __name__ == '__main__':
    main()

output:

inputs: ["什么是ai", "你是什么类型的计算机", "你知道热力学吗"]
outputs: ['人工智能是工程和科学的分支,致力于构建思维的机器。', '我的程序运行在python,所以我在任何运脑上工作!', '我不能错热是一个疯狂的人工智能"200年。']

BART 模型

训练并预测BART模型:

example: examples/seq2sesq/training_bartseq2seq_zh_demo.py

output:

inputs: ['什么是ai', '你是什么类型的计算机', '你知道热力学吗']
outputs: ['人工智能是工程和科学的分支,致力于构', '我的程序运行在python,所以我在任何电脑上', '什么是热力学吗?']

T5 模型

example: examples/t5/training_zh_t5_model_demo.py

show code example and result
import argparse
from loguru import logger
import pandas as pd
import sys

sys.path.append('../..')
from textgen.t5 import T5Model


def load_data(file_path):
    data = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip('\n')
            terms = line.split('\t')
            if len(terms) == 2:
                data.append(['QA', terms[0], terms[1]])
            else:
                logger.warning(f'line error: {line}')
    return data


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--train_file', default='../data/zh_dialog.tsv', type=str, help='Training data file')
    parser.add_argument('--model_type', default='t5', type=str, help='Transformers model type')
    parser.add_argument('--model_name', default='Langboat/mengzi-t5-base', type=str, help='Transformers model or path')
    parser.add_argument('--do_train', action='store_true', help='Whether to run training.')
    parser.add_argument('--do_predict', action='store_true', help='Whether to run predict.')
    parser.add_argument('--output_dir', default='./outputs/mengzi_t5_zh/', type=str, help='Model output directory')
    parser.add_argument('--max_seq_length', default=50, type=int, help='Max sequence length')
    parser.add_argument('--num_epochs', default=10, type=int, help='Number of training epochs')
    parser.add_argument('--batch_size', default=32, type=int, help='Batch size')
    args = parser.parse_args()
    logger.info(args)

    if args.do_train:
        logger.info('Loading data...')
        # train_data: Pandas DataFrame containing the 3 columns - `prefix`, `input_text`, `target_text`.
        #   - `prefix`: A string indicating the task to perform. (E.g. `"question"`, `"stsb"`)
        #   - `input_text`: The input text. `prefix` is prepended to form the full input. (<prefix>: <input_text>)
        #   - `target_text`: The target sequence
        train_data = load_data(args.train_file)
        logger.debug('train_data: {}'.format(train_data[:10]))
        train_df = pd.DataFrame(train_data, columns=["prefix", "input_text", "target_text"])

        eval_data = load_data(args.train_file)[:10]
        eval_df = pd.DataFrame(eval_data, columns=["prefix", "input_text", "target_text"])

        model_args = {
            "reprocess_input_data": True,
            "overwrite_output_dir": True,
            "max_seq_length": args.max_seq_length,
            "train_batch_size": args.batch_size,
            "num_train_epochs": args.num_epochs,
            "save_eval_checkpoints": False,
            "save_model_every_epoch": False,
            "evaluate_generated_text": True,
            "evaluate_during_training": True,
            "evaluate_during_training_verbose": True,
            "use_multiprocessing": True,
            "save_best_model": True,
            "output_dir": args.output_dir,
            "use_early_stopping": True,
        }
        # model_type: t5  model_name: Langboat/mengzi-t5-base
        model = T5Model(args.model_type, args.model_name, args=model_args)

        def count_matches(labels, preds):
            logger.debug(f"labels: {labels[:10]}")
            logger.debug(f"preds: {preds[:10]}")
            match = sum([1 if label == pred else 0 for label, pred in zip(labels, preds)])
            logger.debug(f"match: {match}")
            return match

        model.train_model(train_df, eval_data=eval_df, matches=count_matches)
        print(model.eval_model(eval_df, matches=count_matches))

    if args.do_predict:
        model = T5Model(args.model_type, args.output_dir)
        sentences = ["什么是ai", "你是什么类型的计算机", "你知道热力学吗"]
        print("inputs:", sentences)
        print("outputs:", model.predict(sentences))


if __name__ == '__main__':
    main()

output:

inputs: ['什么是ai', '你是什么类型的计算机', '你知道热力学吗']
outputs: ['人工智能有两个广义的定义,任何拟人的机械,如在卡雷尔capeks', '我的程序运行在Python,所以我在任何电脑上工作!', '什么是热力学']

GPT2 模型

中文GPT2 - 文章生成

使用中文数据集(段落格式,\n间隔),训练GPT2模型,可以用于诗歌生成、文章生成等任务。

example: examples/gpt2/training_zh_gpt2_demo.py

中文GPT2 - 对联生成

使用中文对联数据集(tsv格式,\t间隔),自定义数据集读取Dataset,训练GPT2模型,可以用于对联生成、对话生成等任务。

example: examples/gpt2/training_couplet_gpt2_demo.py

GPT2 vs T5:

  1. 都是从Transformer改进来的,T5同时有编码器和解码器,GPT2只有解码器
  2. T5的模型优势是处理给定输入,产出对应输出的任务,如翻译、对话、问答等
  3. GPT2的模型优势是自由创作,如写一篇短文
  4. T5的对联生成效果好于GPT2、GPT2的诗词生成效果好于T5

SongNet 模型

格式控制的文本生成模型,paper见SongNet: Rigid Formats Controlled Text Generation, 适用于强韵律格式要求的诗歌、对联、歌词生成等任务。

example: examples/songnet/training_zh_songnet_demo.py

Keyword Text Augmentation(EDA/UDA)

example: examples/text_augmentation/text_augmentation_demo.py

show code example and result
import sys

sys.path.append('..')
from textgen.augment import TextAugment

if __name__ == '__main__':
    docs = ['主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容',
            '晚上肚子好难受',
            '你会武功吗,我不会',
            '组装标题质量受限于广告主自提物料的片段质量,且表达丰富度有限',
            ]
    m = TextAugment(sentence_list=docs)
    a = docs[0]
    print(a)

    b = m.augment(a, aug_ops='random-0.2')
    print('random-0.2:', b)

    b = m.augment(a, aug_ops='insert-0.2')
    print('insert-0.2:', b)

    b = m.augment(a, aug_ops='delete-0.2')
    print('delete-0.2:', b)

    b = m.augment(a, aug_ops='tfidf-0.2')
    print('tfidf-0.2:', b)

    b = m.augment(a, aug_ops='mix-0.2')
    print('mix-0.2:', b)

output:

主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容
random-0.2: ('主要陪陪机器学习、深度学习主要计算机视觉、智能对话系统受限于内容', [('研究', '陪陪', 2, 4), ('', '主要', 13, 15), ('相关', '受限于', 27, 30)])
insert-0.2: ('主要研究机器机器学习学习、深度深度学习、计算机视觉、智能对话系统相关内容', [('机器', '机器机器', 4, 8), ('学习', '学习学习', 8, 12), ('深度', '深度深度', 13, 17)])
delete-0.2: ('主要研究机器学习、深度学习、计算机视觉、对话系统相关内容', [('智能', '', 20, 20)])
tfidf-0.2: ('一是研究机器学习、深度学习、计算机听觉、智能交谈系统密切相关内容', [('主要', '一是', 0, 2), ('视觉', '听觉', 17, 19), ('对话', '交谈', 22, 24), ('相关', '密切相关', 26, 30)])
mix-0.2: ('主要研究机器学习、深度学、计算机听觉、智能对话软件系统相关内容', [('学习', '', 11, 12), ('视觉', '听觉', 16, 18), ('系统', '软件系统', 23, 27)])

TGLS 模型(无监督相似文本生成模型)

无监督的中文电商评论生成:从电商评论中提取用户表达观点的短句并进行组合来生成仿真评论。

example: examples/unsup_generation/unsup_generation_demo.py

show code example and result
import os
import sys

sys.path.append('..')
from textgen.unsup_generation import TglsModel, load_list

pwd_path = os.path.abspath(os.path.dirname(__file__))

samples = load_list(os.path.join(pwd_path, './data/ecommerce_comments.txt'))
docs_text = [
    ["挺好的,速度很快,也很实惠,不知效果如何",
     "产品没得说,买了以后就降价,心情不美丽。",
     "刚收到,包装很完整,不错",
     "发货速度很快,物流也不错,同一时间买的两个东东,一个先到一个还在路上。这个水水很喜欢,不过盖子真的开了。盖不牢了现在。",
     "包装的很好,是正品",
     "被种草兰蔻粉水三百元一大瓶囤货,希望是正品好用,收到的时候用保鲜膜包裹得严严实实,只敢买考拉自营的护肤品",
     ],
    ['很温和,清洗的也很干净,不油腻,很不错,会考虑回购,第一次考拉买护肤品,满意',
     '这款卸妆油我会无限回购的。即使我是油痘皮,也不会闷痘,同时在脸部按摩时,还能解决白头的脂肪粒的问题。用清水洗完脸后,非常的清爽。',
     '自从用了fancl之后就不用其他卸妆了,卸的舒服又干净',
     '买贵了,大润发才卖79。9。',
     ],
    samples
]
m = TglsModel(docs_text)
r = m.generate(samples[:500])
print('size:', len(r))
for review in r:
    print('\t' + review)

output:

美迪惠尔 N.M.F针剂水库保湿面膜有如下的20句评论,其中有10句是真实用户评论,10句是生成的评论,能看出来么?😂

还不错还不错还不错还不错。
东西到了,不知道好不好用。试用过后再来评价。到时看网评都还可以。
哺乳期唯一使用的护肤品,每天都是素颜,脸面全靠面膜吊着😄补水💦不粘腻一如既往的支持,喜欢💕
搞活动时买的面膜,不知道这个面膜是真是假敷在脸上面膜纸都有小水泡鼓起来。
很不错,非常补水,用过的都知道,性价比之王,好用又不贵,正品,用着放心,物流也很快。
面膜非常好用哦。面膜薄薄的。好像是蚕丝面膜啊。精华很多呢。敷在脸上很舒服。感觉挺保湿的,味道也挺好闻的。就是里面只有单纯的面膜直接敷脸上有点不好弄,哈哈哈
还可以保湿效果不错水润润的每天贴一片脸也不干了用完了在买点,不错还会继续回购的。
快递很快,东西很赞!想要得点考拉豆不容易,还要三十个字。时间宝贵,废话不说!用过了就知道了
挺好用的,朋友推荐来的
挺好用的,淡淡的,虽然不是很浓精华的感觉,但是效果也蛮好的。划算
不得不说美迪惠尔的面膜是我用过的最好的面膜之一😎补水效果非常好,没想到这么便宜的价格竟真的能买到真品。
保湿效果挺好的,面膜很好用。
期待好的产品。
一打开包装里面的精华刚刚好,用了补水补水效果不错,物流非常快。
皮肤很光滑😇比上去速度快三天就到了。
前两天皮肤干燥连续敷了两个晚上感觉还不错😂补水效果明显!可想而知精华液又多充足😍敷上以后凉凉的很舒服。
补水效果一般吧~但是我用的韩国背回来的面膜纸不算薄,希望好用会回购的,敷上脸感觉比较清爽~价格还不便宜。
希望好用,面膜用过了很好用,皮肤水嫩光滑白皙,补水不错,价格也合适。
就是精华液太少了,保湿效果不错。
面膜的补水效果非常好,保湿效果确实很赞,这个面膜相对于胶原蛋白和美白的那两款的面膜纸要厚一些,看着价格合适。

前10句是真实用户评论,后10句是生成的。

📚 Dataset

SFT datasets

Reward Model datasets

✅ Todo

  1. add multiple rounds of dialogue data fine-tuning method
  2. add reward model finetuning, go to shibing624/MeidcalGPT
  3. add rl finetuning, go to shibing624/MeidcalGPT
  4. add medical reward dataset
  5. add llama in4 training, go to shibing624/MeidcalGPT
  6. add all training and predict demo in colab

☎️ Contact

  • Issue(建议) :GitHub issues
  • 邮件我:xuming: [email protected]
  • 微信我: 加我微信号:xuming624, 备注:姓名-公司名-NLP 进NLP交流群。

😇 Citation

如果你在研究中使用了textgen,请按如下格式引用:

@misc{textgen,
  title={textgen: Text Generation Tool},
  author={Ming Xu},
  year={2021},
  howpublished={\url{https://github.com/shibing624/textgen}},
}

🤗 License

This repository is licensed under The Apache License 2.0.

Please follow the Model Card to use the LLaMA model.

Please follow the RAIL License to use the BLOOM & BLOOMZ model.

😍 Contribute

项目代码还很粗糙,如果大家对代码有所改进,欢迎提交回本项目,在提交之前,注意以下两点:

  • tests添加相应的单元测试
  • 使用python -m pytest来运行所有单元测试,确保所有单测都是通过的

之后即可提交PR。

💕 Acknowledgements

Thanks for their great work!

textgen's People

Contributors

shibing624 avatar wiserxin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

textgen's Issues

找不到路径或文件

完整错误信息
2022-07-11 11:25:44.675 | INFO | textgen.unsup_generation.tgls_model:init:36 - docs_text len: 3
Traceback (most recent call last):
File "C:\Downloads\Compressed\textgen-main\examples\unsup_generation_demo.py", line 31, in
m = TglsModel(docs_text)
File "C:\AppData\Roaming\Python\Python310\site-packages\textgen\unsup_generation\tgls_model.py", line 38, in init
self.stopwords = set(load_list(default_stopwords_path))
File "C:\AppData\Roaming\Python\Python310\site-packages\textgen\unsup_generation\phrase.py", line 131, in load_list
return [l for l in open(path, 'r', encoding='utf-8').read().split()]
FileNotFoundError: [Errno 2] No such file or directory: 'C:\AppData\Roaming\Python\Python310\site-packages\textgen\unsup_generation\../data/stopwords.txt'

这个错误是在运行例子的时候出现的,操作系统win10,python版本3.10.5
unsup_generation_demo.py

请问要怎么解决,谢谢

Bart长文本训练问题

我用Bart训练代码,每个训练数据都为:输入文本约1000字符,输出文本长3-5万字符。训练几个epoch后会出错,错误信息如下所示。
但是控制输入和输出的字符长度,比如都为100字符左右,则训练正常,没有报错。

请问一下:Bart模型的输入输出长度有什么要求吗,这应该是内部embedding维度出错了吧。谢谢。

RuntimeError: CUDA error: CUBLAS_STATUS_EXECUTION_FAILED when calling cublasSgemmStridedBatched( handle, opa, opb, m, n, k, &alpha, a, lda, stridea, b, ldb, strideb, &beta, c, ldc, stridec, num_batches)

关于数据集处理

Describe the Question

Please provide a clear and concise description of what the question is.

Describe your attempts

  • [ x] I walked through the tutorials
  • [x ] I checked the documentation
  • [ x] I checked to make sure that this is not a duplicate question

您好。我想尝试微调关于剧本的llama 使用的Lora。我看到指令精调使用数据模板是
{
"instruction": "",
"input": "",
"output": ""
}
我的原始数据类似下面这种:
一些环境描述和背景描述。
旁白:旁白说的话1.
角色1:角色1的话1. (角色情绪和动作)
角色2:角色2的话1. (角色情绪和动作)
xxxx

如果是这样的话,想请教一下应该怎么样处理源数据到模板数据会比较合适。非常感谢

多卡部署

想请问一下,用fastapi多卡部署生成式模型,怎样在不同卡上起服务呢

1. README文档的微信群和几个别的超链接打不开 2. 开始写使用教程(大概更新会比较慢)

大老看了您的微调方式,有点疑问,您的三个阶段是在哪里体现出来的?

大老看了您的微调方式,有点疑问,您的四个阶段是在哪里体现出来的? 如下:

第一阶段:PT(Continue PreTraining)增量预训练,在海量领域文档数据上二次预训练GPT模型,以注入领域知识 [
		
第二阶段:SFT(Supervised Fine-tuning)有监督微调,构造指令微调数据集,在预训练模型基础上做指令精调,以对齐指令意图			

第三阶段:RM(Reward Model)奖励模型建模,构造人类偏好排序数据集,训练奖励模型,用来对齐人类偏好,主要是"HHH"原则

第四阶段:RL(Reinforcement Learning)(RLHF)基于人类反馈的强化学习(RLHF),用奖励模型来训练SFT模型,生成模型使用奖励或惩罚来更新其策略,以便生成更高质量、更符合人类偏好的文本

我没看到例子哪里需要训练4次的呢? https://github.com/shibing624/textgen#%E8%AE%AD%E7%BB%83-chatglm-6b-%E5%BE%AE%E8%B0%83%E6%A8%A1%E5%9E%8B

您好,请教一下语法纠错后的PRF如何计算?

Describe the Question

Please provide a clear and concise description of what the question is.

Describe your attempts

  • I walked through the tutorials
  • I checked the documentation
  • I checked to make sure that this is not a duplicate question

如果我想训练一个细分领域的知识库,请问 训练数据 要按什么格式准备?您的例子给的是 纠正拼写错误,我们 知识库 训练需要改动哪些地方才能正确训练?

1 如果我想训练一个细分领域的知识库,请问 训练数据 要按什么格式准备?您的例子给的是 纠正拼写错误,我们 知识库 训练需要改动哪些地方才能正确训练?

2 为训练的模型给出的结果 我如果想纠正,这个通过训练可以实现么? 纠正的训练标注数据最少需要提供几条?还是 一条就可以?需要训练多少step?

3 我们p-tune 发现 chatGLB污染很严重,整个模型训练后完全不能用了,您的lora训练结果 污染情况如何?需要注意些什么?

非常感谢,希望能深入交流

如何用使用 p40 训练lora

Describe the bug

torch._dynamo.exc.BackendCompilerFailed: debug_wrapper raised RuntimeError: Found Tesla P40 which is too old to be supported by the triton GPU compiler, which is used as the backend. Triton only supports devices of CUDA Capability >= 7.0, but your device is of CUDA capability 6.1

To Reproduce

image

Describe your attempts

  • I checked the documentation and found no answer
  • I checked to make sure that this is not a duplicate issue

按照https://www.reddit.com/r/StableDiffusion/comments/12nh9hn/dreambooth_training_lora_failed_due_to_triton_gpu/ 上说的配置export TORCHDYNAMO_DISABLE=1
重跑后会报

RuntimeError: GET was unable to find an engine to execute this computation

Context

  • OS [CentOS Linux]:
  • Hardware [Tesla P40]:

bart纠错模型训练问题

老师您好,我在尝试您提供的training_bartseq2seq_zh_demo.py训练模型时发现,获取的best_model模型出现语句误纠后,我将'正确句'+‘\t’+'正确句'的数据继续加入模型进行训练,发现有的数据误纠得到改善,但是有的数据依然会出现同样的误纠,加入误纠数据训练完全没有效果,请问这个问题怎么解决呢?
例如:把‘干部’误纠为‘老干部’,我加了多句包含‘干部’的防误纠数据训练后,依然会把‘干部’误纠为‘老干部’
原句:‘目前,按照组织要求,事业干部一般不能担任行政的科室长及副局长,对于事业干部做事的积极性也存在较大影响’————误纠为————‘目前,按照组织要求,事业干部一般不能担任行政的科室长及副局长,对于事业老干部做事的积极性也存在较大影响’

而,原句:‘让我们用阅读来沁润每一颗童心、让阅读来伴随你我成长’原本误纠为‘让我们用阅读来沁润每一颗童心、让阅读带来伴随你我成长’,在加入‘让我们用阅读来沁润每一颗童心、让阅读来伴随你我成长’+‘\t’+‘让我们用阅读来沁润每一颗童心、让阅读来伴随你我成长’以后,误纠消失

请问为什么模型会出现这种不稳定的情况

README中LLaMA模型部分是不是还没有更新+merge_peft_adapter.py的save_pretrained()似乎有问题

我看好像LLaMA模型从llamamodel换成gptmodel了?

一个是LLaMA的代码示例,还有一个模型转换部分,我是直接用Python执行实现的:

python whj_download/githubs/textgen/textgen/gpt/merge_peft_adapter.py \
    --base_model_name_or_path /data/whj/pretrained_model/llama-7b/llama \
    --peft_model_path /data/whj/pretrained_model/chinese-alpaca-lora-7b \
    --output_type huggingface \
    --output_dir /data/whj/pretrained_model/chinese-alpaca-plus-7b-hf \
    --offload_dir /data/whj/cache

whj_download/githubs/textgen/textgen/gpt/merge_peft_adapter.py这个代码原303行AutoModelForCausalLM.save_pretrained(base_model, output_dir)这个是否是transformers版本的问题?我是transformers 4.30.2,需要改成base_model.save_pretrained(output_dir)才能运行,否则会报AttributeError: type object 'AutoModelForCausalLM' has no attribute 'save_pretrained'

lora 训练参数

trainable params: 22021440 || all params: 6195307952 || trainable%: 0.35545351692954874

请教一下,更新之后的lora为啥训练参数占比这么高了,之前只有0.05左右

ChatGLM-6B full parameter fine-tuning loss = 0

Today, when I was doing the full parameter fine-tuning, my loss became 0.0 after the training of batch 17, and then it kept going to 0.0. I changed both the learning rate and batch, but I still failed to solve such problems

1686814220592

c48c3a4aade14a25914550b827a0c3f

请问训练的数据集如何获取啊?

Describe the Question

Please provide a clear and concise description of what the question is.

Describe your attempts

  • I walked through the tutorials
  • I checked the documentation
  • I checked to make sure that this is not a duplicate question

用lora训练chatglm时跑内存

下午我在跑的时候就爆过一次内存,当时没在意,但是刚刚看的时候注意到按道理这个模型应该只占14g多,现在跑到第二个epoch的时候就莫名内存占用变大了。
image
这是跑到第三个epoch时的内存占用
image

请问有没有用于evaluation的代码?

代码里只有train和predict的代码,尝试写了一下evaluate的代码,但是总是不对,train的时候读数据只有input_ids,是不是evaluate的时候要加上labels?之前参照原始chatglm的代码修改了一下,也总是报错,请问作者大大能不能给一下evaluate的代码呀?

shibing624/prompt-t5-base-chinese测试结果和示例结果不一致

这是测试代码:
from textgen import T5Model
model = T5Model("t5", "shibing624/prompt-t5-base-chinese")

while(True):
print('input sentence:')
input_text = input()
print('input:')
print(input_text)
r = model.predict([input_text])
print('output:')
print(r)

测试结果:
input sentence:
意图分类:\n帮我定一个周日上海浦东的房间\n选项:闹钟,文学,酒店,艺术,体育,健康,天气,其他 \n答案:
input:
意图分类:\n帮我定一个周日上海浦东的房间\n选项:闹钟,文学,酒店,艺术,体育,健康,天气,其他 \n答案:
Generating outputs: 100%|███████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 22.28it/s]
output:
['旅游']

和hugging face上您显示的测试结果不一致:
Input:
意图分类:
帮我定一个周日上海浦东的房间
选项:闹钟,文学,酒店,艺术,体育,健康,天气,其他
答案:
Model output:
酒店

数据集格式

想请问一下您bart的数据集应该处理成哪种形式呢

模型结果有问题

使用模型对新闻分类(classify)、目的分类(classify)、摘要(生成)进行测试,和预期结果差异太大,在https://huggingface.co/csebuetnlp/mT5_multilingual_XLSum测试同样如此

-- coding: utf-8 --

from textgen import T5Model
model = T5Model("t5", "shibing624/prompt-t5-base-chinese")
r = model.predict(['''分类任务:
折价率过低遭抛售基金泰和跌7.15%,证券时报记者 朱景锋本报讯 由于折价率在大盘封基中处于最低水平,基金泰和昨日遭到投资者大举抛售,跌幅达到7.15%,远超大盘。盘面显示,基金泰和随大盘高开,之后开始震荡走低,午后开始加速下行,几乎没有像样反弹。截至收盘时,在沪深300指数仅下跌2.56%的情况下,基金泰和收盘跌幅高达7.15%,在所有封基中跌幅最大,而昨日多数封基跌幅在2%左右。
选项:财经,娱乐,时政,股票
答案:'''])
print(r)

结果:['股票价格下降']

安装问题

Describe the Question

每次安装的时候都会自动下载torch==2.0.1,但是我看requirements并没有要求。而且下载的是cpu版本,覆盖我的GPU版本。

chatglm用lora训练完predict出的结果和重新加载模型和lora后输出的结果差异很大

根据https://github.com/THUDM/ChatGLM-6B/tree/main/improve 说的,100条样本足够训练模型,在此基础上实验。
训练样例如下:
{"content": "请给我的美妆店起一个名字。", "summary": "店铺名:柏雅诗BAYEAS。 说明:balmy(温和的)+yearn(思念)+sanguine(快乐的);雅,优雅。 请问您对于名称还有什么特殊要求吗?例如,是否希望名称具有特定的含义或特点?"}
整个训练集100条样本。

training_chatglm_adgen_demo.py 后面做了轻微改动如下:
image
输出结果如下:
image

第一次明显学到了训练样本的一些特征,为何重新加载模型后就完全体现不出来?

单机多卡训练方法

正常从单卡变成双卡,step应该 /2,耗时应该/2,但是在我的机器上并没有体现出来,step和时间和单卡的一样,是不是我指定多卡的方法错了,请问作者大哥,正确的应该怎么指定啊。

怎么指定单GPU


当有多块显卡的时候,默认全部加载,试过了
os.environ["CUDA_VISIBLE_DEVICES"] = '0'

args={'use_lora': True, 'output_dir': args.output_dir, "max_length": args.max_length, 'n_gpu':0},
以及
cuda_device = 0
都没法做到,请教一下,如何设置用单GPU训练或者预测

if use_cuda:
            if torch.cuda.is_available():
                if cuda_device == -1:
                    self.device = torch.device("cuda")
                else:
                    self.device = torch.device(f"cuda:{cuda_device}")
            else:
                raise ValueError(
                    "'use_cuda' set to True when cuda is unavailable."
                    "Make sure CUDA is available or set `use_cuda=False`."
                )
        else:
            self.device = "cpu"
 logger.debug(f"Device: {self.device}")

2023-04-17 02:18:32.967 | DEBUG | chatglm.chatglm_model:init:92 - Device: cuda:0

这里打印结果如上,但是还是会加载多块GPU

model 使用授权问题

微调之后的模型,版权属于谁呢,pclue数据非商用,数据是否需要自己准备才能训练得到自己的模型

torch.load()希望能够增加map_location

  • I checked to make sure that this is not a duplicate issue
  • I'm submitting the request to the correct repository (for model requests, see here)

Is your feature request related to a problem? Please describe.

我遇到的问题是在textgen/gpt/gpt_model.py第359行,因为我保存的设备(双卡)和加载的设备(单卡)不同,我改成adapters_weights = torch.load(checkpoint_name,map_location="cpu")后能够正常运行

Describe the solution you'd like

我的建议是开放一个可以输入设备的接口,或者直接就放CPU上算了

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Additional Information

Other things you want the developers to know.

ChatGLM模型微调问题咨询

image

运行 /ChatGLM-6B/textgen/examples/chatglm$ python predict_demo.py 报错,glm6B模型用的是 原版, lora 微调模型 用的是 git clone https://huggingface.co/shibing624/chatglm-6b-csc-zh-lora

报错

(pt) ubuntu@youran-gpu21:~/ChatGLM-6B/textgen/examples/chatglm$ python predict_demo2.py
2023-04-14 11:47:33.176 | DEBUG | textgen.chatglm.chatglm_model:init:98 - Device: cuda
Explicitly passing a revision is encouraged when loading a configuration with custom code to ensure no malicious code has been contributed in a newer revision.
Explicitly passing a revision is encouraged when loading a model with custom code to ensure no malicious code has been contributed in a newer revision.
Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:12<00:00, 1.58s/it]
Explicitly passing a revision is encouraged when loading a model with custom code to ensure no malicious code has been contributed in a newer revision.
2023-04-14 11:48:08.995 | INFO | textgen.chatglm.chatglm_model:load_lora:342 - Loaded lora model from /home/ubuntu/ChatGLM-6B/textgen/chatglm-6b-csc-zh-lora
Traceback (most recent call last):
File "/home/ubuntu/ChatGLM-6B/textgen/examples/chatglm/predict_demo2.py", line 12, in
r = model.predict(["对下面中文拼写纠错:\n少先队员因该为老人让坐。\n答:"])
File "/home/ubuntu/anaconda3/envs/pt/lib/python3.9/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
return func(*args, **kwargs)
File "/home/ubuntu/anaconda3/envs/pt/lib/python3.9/site-packages/textgen-0.1.9-py3.9.egg/textgen/chatglm/chatglm_model.py", line 385, in predict
self.model.eval()
File "/home/ubuntu/anaconda3/envs/pt/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1930, in eval
return self.train(False)
File "/home/ubuntu/anaconda3/envs/pt/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1911, in train
module.train(mode)
File "/home/ubuntu/anaconda3/envs/pt/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1911, in train
module.train(mode)
File "/home/ubuntu/anaconda3/envs/pt/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1911, in train
module.train(mode)
[Previous line repeated 4 more times]
File "/home/ubuntu/anaconda3/envs/pt/lib/python3.9/site-packages/peft-0.2.0-py3.9.egg/peft/tuners/lora.py", line 417, in train
delta_w = F.conv1d(
RuntimeError: Expected 4-dimensional input for 4-dimensional weight [8192, 8, 1, 1], but got 3-dimensional input of size [1, 16, 4096] instead

保存模型问题

想请教一下,这种保存模型除了 adapter_model.bin 和 adapter_config.json ,其他文件是否都与lora 无关?
如果想像原始6b那种流式输出的时候,这里应该怎么改?有好的建议嘛

Miss Requirement tensorboardX

I've use last code,

from textgen import ChatGlmModel

return a error "No module named 'tensorboardX'"

after install

pip3 install tensorboardX crc32c soundfile

it works without error

我想让TGLS精简些,但一改就会报错

Describe the Question

Please provide a clear and concise description of what the question is.

Describe your attempts

  • I walked through the tutorials
  • I checked the documentation
  • I checked to make sure that this is not a duplicate question
    image
    我这个报错是因为给点数据太少了么???

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.