这是一个金融领域大模型微调的具体代码执行过程,具体代码可以详见git仓库。
model_args,data_args,train_args,finetuning_args,generating_args = get_train_args()
tokenizer = AutoTokenizer.from_pretrained(model_path)
config = AutoConfig.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrainded(model_path,config)
配置lora的参数,尽可能微调模型较少的参数。
model = init_adapter(model,args)
配置模型为训练模式
model = model.train()
trianer = SftTrainer(model,args,tokenizer)
model_name_or_path = "your_LLM_model_path"
adapter_name_or_path = "your_lora_model_path"
save_path = "save_model_path"
tokenizer = AutoTokenizer.from_pretrained(
model_name_or_path,
trust_remote_code=True
)
model = AutoModelForCausalLM.from_pretrained(
model_name_or_path,
trust_remote_code=True,
low_cpu_mem_usage=True,
torch_dtype=torch.float16,
device_map="auto"
)
model = PeftModel.from_pretrained(model, adapter_name_or_path)
model = model.merge_and_unload()
tokenizer.save_pretrained(save_path)
model.save_pretrained(save_path)
全部代码
https://gitee.com/iwuzhichao/sft.git
损失函数
大语言模型中有监督微调(SFT)的损失函数是什么?它是怎么进行梯度下降来训练的?针对这类问题,查阅相关资料并没有解释。下面谈点自己的理解:在SFT阶段,其本质是微调一个GPT模型(生成式模型),它的原理是根据上文生成下文,更通俗的解释是根据上文所有内容到一个大的“词表”中寻找下一个词(计算概率),选择概率较大的词作为输出。用到的损失函数是交叉熵损失,比如这个大“词表”真实值为[1,0,0,0,0]而预测值为[0.7,0.1,0.05,0.1,0.05],那么它的计算公式为loss=-1/5(1log(0.7)+0log(0.1)+0log(0.05)+0log(0.1)+0*log(0.05)),这就相当于我要拉进预测概率与真实概率之间的距离。