IA3¶
1.IA3简述¶
IA3(论文:Few-Shot Parameter-Efficient Fine-Tuning is Better and Cheaper than In-Context Learning),通过学习向量来对激活层加权进行缩放,从而获得更强的性能,同时仅引入相对少量的新参数,如下图左边所示,它的诞生背景是为了改进 LoRA。
为了使微调更有效,IA3(通过抑制和放大内部激活注入适配器)使用学习向量重新调整内部激活。 这些学习到的向量被注入到典型的基于transformer的架构中的attention和feedforward模块中。 原始权重保持冻结,这些学习到的向量是微调期间唯一可训练的参数。 与学习 LoRA 更新低秩权重矩阵不同,处理学习向量可以使可训练参数的数量少得多。
与 LoRA 类似,IA3 具有许多相同的优点:
- IA3 通过大幅减少可训练参数的数量,使微调更加高效。对于 T0 模型,使用 IA3 只有大约 0.01% 的可训练参数,而使用 LoRA 有 > 0.1% 的可训练参数。
- 原始的预训练权重保持冻结状态,这意味着可以拥有多个轻量级、便携式 IA3 模型,用于在其之上构建的各种下游任务。
- 使用 IA3 微调的模型的性能与完全微调的模型的性能相当。
- IA3 不会增加任何推理延迟,因为适配器(adapter)权重可以与基础模型合并。
原则上,IA3 可以应用于神经网络中权重矩阵的任何子集,以减少可训练参数的数量。 根据作者的实现,IA3 权重被添加到 Transformer 模型的 key, value 和 feedforward 层。 给定注入 IA3 参数的目标层,可训练参数的数量可以根据权重矩阵的大小确定。
2.IA3微调实战¶
与 PEFT 支持的其他方法一样,要使用 IA3 微调模型,您只需要以下几步:
- 实例化基本模型。
- 创建一个配置 (IA3Config),在其中定义 IA3 特定的参数。
- 使用 get_peft_model() 包装基础模型以获得可训练的 PeftModel。
- 像平常训练基础模型一样训练 PeftModel。
2.1 引入库¶
from transformers import AutoModelForCausalLM
from peft import get_peft_config, get_peft_model, get_peft_model_state_dict, IA3Config, TaskType
import torch
from datasets import load_dataset
import os
from transformers import AutoTokenizer
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from tqdm import tqdm
from datasets import load_dataset
2.2 创建 IA3 微调方法对应的配置¶
device = "cuda"
model_name_or_path = "/data/nfs/llm/model/bloomz-560m"
tokenizer_name_or_path = "/data/nfs/llm/model/bloomz-560m"
peft_config = IA3Config(task_type=TaskType.CAUSAL_LM,
target_modules=["query_key_value", "mlp.dense_4h_to_h"],
inference_mode=False,
feedforward_modules=["mlp.dense_4h_to_h"])
dataset_name = "twitter_complaints"
checkpoint_name = f"{dataset_name}_{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}_v1.pt".replace("/", "_")
text_column = "Tweet text"
label_column = "text_label"
max_length = 64
lr = 3e-2
num_epochs = 10
batch_size = 8
/home/guodong.li/virtual-venv/peft-venv-py310-cu117/lib/python3.10/site-packages/tqdm/auto.py:21:TqdmWarning:IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
[2023-07-22 15:47:42,177] [INFO] [real_accelerator.py:133:get_accelerator] Setting ds_accelerator to cuda (auto detect)
参数说明:
task_type
:指定任务类型。如:条件生成任务(SEQ_2_SEQ_LM),因果语言建模(CAUSAL_LM)等。inference_mode
:是否在推理模式下使用Peft模型。target_modules
:要替换为 IA3 的模块名称列表或模块名称的正则表达式,例如,注意力块。在 PEFT 中支持的模型中默认的模块名如下所示:
TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING = {
"t5": ["k", "v", "wo"],
"mt5": ["k", "v", "wi_1"],
"gpt2": ["c_attn", "mlp.c_proj"],
"bloom": ["query_key_value", "mlp.dense_4h_to_h"],
"roberta": ["key", "value", "output.dense"],
"opt": ["q_proj", "k_proj", "fc2"],
"gptj": ["q_proj", "v_proj", "fc_out"],
"gpt_neox": ["query_key_value", "dense_4h_to_h"],
"gpt_neo": ["q_proj", "v_proj", "c_proj"],
"bart": ["q_proj", "v_proj", "fc2"],
"gpt_bigcode": ["c_attn", "mlp.c_proj"],
"llama": ["k_proj", "v_proj", "down_proj"],
"bert": ["key", "value", "output.dense"],
"deberta-v2": ["key_proj", "value_proj", "output.dense"],
"deberta": ["in_proj", "output.dense"],
}
feedforward_modules
:target_modules 中被视为前馈(feedforward)层的模块名称列表或模块名称的正则表达式。虽然学习向量与注意力块的输出激活相乘,但向量与经典前馈层的输入相乘。在 PEFT 中支持的模型中默认的前馈层模块名如下所示:
TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING = {
"t5": ["wo"],
"mt5": [],
"gpt2": ["mlp.c_proj"],
"bloom": ["mlp.dense_4h_to_h"],
"roberta": ["output.dense"],
"opt": ["fc2"],
"gptj": ["fc_out"],
"gpt_neox": ["dense_4h_to_h"],
"gpt_neo": ["c_proj"],
"bart": ["fc2"],
"gpt_bigcode": ["mlp.c_proj"],
"llama": ["down_proj"],
"bert": ["output.dense"],
"deberta-v2": ["output.dense"],
"deberta": ["output.dense"],
}
module_to_save
:除了 IA3 层之外要设置为可训练并保存在最终检查点中的模块列表。这些通常包括模型的自定义头(head),该头是为微调任务随机初始化的。例如,在序列分类或Token分类任务中,最后一层classifier/score是随机初始化的,因此需要可训练和保存。
from datasets import load_dataset
# dataset = load_dataset("ought/raft", dataset_name)
dataset = load_dataset("/home/guodong.li/data/peft/raft/raft.py", dataset_name, cache_dir="/home/guodong.li/data/peft/data")
classes = [k.replace("_", " ") for k in dataset["train"].features["Label"].names]
print(classes)
dataset = dataset.map(
lambda x: {"text_label": [classes[label] for label in x["Label"]]},
batched=True,
num_proc=1,
)
print(dataset)
dataset["train"][0]
Found cached dataset raft (/home/guodong.li/data/peft/data/raft/twitter_complaints/1.1.0/79c4de1312c1e3730043f7db07179c914f48403101f7124e2fe336f6f54d9f84) 100%|██████████| 2/2 [00:00<00:00, 732.82it/s] Loading cached processed dataset at /home/guodong.li/data/peft/data/raft/twitter_complaints/1.1.0/79c4de1312c1e3730043f7db07179c914f48403101f7124e2fe336f6f54d9f84/cache-0e20fff6b1d898ca.arrow Loading cached processed dataset at /home/guodong.li/data/peft/data/raft/twitter_complaints/1.1.0/79c4de1312c1e3730043f7db07179c914f48403101f7124e2fe336f6f54d9f84/cache-8d14a62b8a688c19.arrow
['Unlabeled', 'complaint', 'no complaint'] DatasetDict({ train:Dataset({ features:['Tweet text', 'ID', 'Label', 'text_label'], num_rows:50 }) test:Dataset({ features:['Tweet text', 'ID', 'Label', 'text_label'], num_rows:3399 }) })
{'Tweet text':'@HMRCcustomers No this is my first job', 'ID':0, 'Label':2, 'text_label':'no complaint'}
# data preprocessing
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
if tokenizer.pad_token_id is None:
tokenizer.pad_token_id = tokenizer.eos_token_id
target_max_length = max([len(tokenizer(class_label)["input_ids"]) for class_label in classes])
print("target_max_length:", target_max_length)
def preprocess_function(examples):
batch_size = len(examples[text_column])
inputs = [f"{text_column} :{x} Label :" for x in examples[text_column]]
targets = [str(x) for x in examples[label_column]]
model_inputs = tokenizer(inputs)
labels = tokenizer(targets)
for i in range(batch_size):
sample_input_ids = model_inputs["input_ids"][i]
label_input_ids = labels["input_ids"][i] + [tokenizer.pad_token_id]
# print(i, sample_input_ids, label_input_ids)
model_inputs["input_ids"][i] = sample_input_ids + label_input_ids
labels["input_ids"][i] = [-100] * len(sample_input_ids) + label_input_ids
model_inputs["attention_mask"][i] = [1] * len(model_inputs["input_ids"][i])
# print(model_inputs)
for i in range(batch_size):
sample_input_ids = model_inputs["input_ids"][i]
label_input_ids = labels["input_ids"][i]
model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * (
max_length - len(sample_input_ids)
) + sample_input_ids
model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs[
"attention_mask"
][i]
labels["input_ids"][i] = [-100] * (max_length - len(sample_input_ids)) + label_input_ids
model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length])
model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length])
labels["input_ids"][i] = torch.tensor(labels["input_ids"][i][:max_length])
model_inputs["labels"] = labels["input_ids"]
return model_inputs
processed_datasets = dataset.map(
preprocess_function,
batched=True,
num_proc=1,
remove_columns=dataset["train"].column_names,
load_from_cache_file=False,
desc="Running tokenizer on dataset",
)
train_dataset = processed_datasets["train"]
eval_dataset = processed_datasets["train"]
train_dataloader = DataLoader(train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)
eval_dataloader = DataLoader(eval_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)
target_max_length:3
def test_preprocess_function(examples):
batch_size = len(examples[text_column])
inputs = [f"{text_column} :{x} Label :" for x in examples[text_column]]
model_inputs = tokenizer(inputs)
# print(model_inputs)
for i in range(batch_size):
sample_input_ids = model_inputs["input_ids"][i]
model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * (max_length - len(sample_input_ids)) + sample_input_ids
model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs["attention_mask"][i]
model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length])
model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length])
return model_inputs
test_dataset = dataset["test"].map(
test_preprocess_function,
batched=True,
num_proc=1,
remove_columns=dataset["train"].column_names,
load_from_cache_file=False,
desc="Running tokenizer on dataset",
)
test_dataloader = DataLoader(test_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)
next(iter(test_dataloader))
{'input_ids':tensor([[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 227985, 5484, 915, 2566, 74757, 64626, 12384, 44639, 613, 52282, 2670, 79920, 3344, 1002, 368, 17646, 14472, 8348, 664, 718, 4, 19036, 17, 31849, 17, 6312, 76, 44, 62470, 56, 91, 50, 14839, 21, 77658, 915, 210], [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 227985, 5484, 915, 405, 187059, 2256, 664, 2550, 18833, 18607, 162467, 4, 1387, 6199, 3291, 23405, 613, 4657, 17082, 566, 3432, 368, 78851, 1185, 61273, 23181, 1553, 15596, 212, 116057, 77658, 915, 210], [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 227985, 5484, 915, 39762, 2566, 22253, 6201, 75701, 15, 632, 718, 5840, 10006, 6201, 18881, 427, 3804, 19528, 267, 158974, 1320, 368, 10029, 632, 49666, 92, 34, 77658, 915, 210], [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 227985, 5484, 915, 2566, 104565, 8695, 2089, 6140, 109676, 99579, 1369, 512, 368, 4570, 54, 632, 368, 1503, 241485, 132226, 15, 982, 727, 1152, 18100, 861, 32596, 77597, 168154, 1306, 132226, 4346, 87843, 17, 130462, 364, 32923, 89, 53, 8309, 20, 75, 77658, 915, 210], [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 227985, 5484, 915, 2566, 14173, 2960, 29906, 387, 20706, 49337, 1369, 77658, 915, 210], [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 227985, 5484, 915, 2566, 219553, 45736, 36876, 1713, 72, 707, 187205, 13002, 177324, 77658, 915, 210], [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 227985, 5484, 915, 2566, 233938, 28518, 13716, 427, 28146, 1119, 17918, 17, 236706, 368, 214997, 7555, 48659, 5276, 21600, 343, 17, 51416, 22403, 318, 1531, 1306, 1130, 20934, 567, 101161, 184849, 87843, 17, 1594, 15231, 2052, 16642, 20, 7180, 80, 26, 77658, 915, 210], [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 227985, 5484, 915, 2566, 80, 2068, 479, 2566, 80, 1376, 878, 147587, 3904, 632, 368, 6084, 65673, 78851, 11736, 15527, 19082, 33151, 461, 17, 45575, 17887, 632, 5219, 14216, 68870, 5967, 1841, 4346, 87843, 17, 1594, 14512, 27, 71, 8184, 19, 290, 63748, 77658, 915, 210]]), 'attention_mask':tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}
2.3 通过调用 get_peft_model 方法包装基础的 Transformer 模型¶
model = AutoModelForCausalLM.from_pretrained(model_name_or_path)
通过 print_trainable_parameters 方法可以查看到 IA3 可训练参数的数量(仅为172,032)以及占比(仅为0.0307%)。
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
trainable params:172,032 || all params:559,386,624 || trainable%:0.0307536849504646
model
PeftModelForCausalLM( (base_model):IA3Model( (model):BloomForCausalLM( (transformer):BloomModel( (word_embeddings):Embedding(250880, 1024) (word_embeddings_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (h):ModuleList( (0):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (1):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (2):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (3):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (4):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (5):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (6):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (7):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (8):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (9):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (10):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (11):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (12):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (13):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (14):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (15):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (16):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (17):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (18):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (19):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (20):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (21):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (22):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) (23):BloomBlock( (input_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (self_attention):BloomAttention( (query_key_value):Linear( in_features=1024, out_features=3072, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 3072x1]) ) (dense):Linear(in_features=1024, out_features=1024, bias=True) (attention_dropout):Dropout(p=0.0, inplace=False) ) (post_attention_layernorm):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) (mlp):BloomMLP( (dense_h_to_4h):Linear(in_features=1024, out_features=4096, bias=True) (gelu_impl):BloomGelu() (dense_4h_to_h):Linear( in_features=4096, out_features=1024, bias=True (ia3_l):ParameterDict( (default):Parameter containing:[torch.FloatTensor of size 1x4096]) ) ) ) ) (ln_f):LayerNorm((1024,), eps=1e-05, elementwise_affine=True) ) (lm_head):Linear(in_features=1024, out_features=250880, bias=False) ) ) )
model.peft_config
{'default':IA3Config(peft_type=<PeftType.IA3:'IA3'>, auto_mapping=None, base_model_name_or_path='/data/nfs/llm/model/bloomz-560m', revision=None, task_type=<TaskType.CAUSAL_LM:'CAUSAL_LM'>, inference_mode=False, target_modules=['query_key_value', 'mlp.dense_4h_to_h'], feedforward_modules=['mlp.dense_4h_to_h'], fan_in_fan_out=False, modules_to_save=None, init_ia3_weights=True)}
2.4 模型训练¶
模型训练的其余部分均无需更改,当模型训练完成之后,保存高效微调部分的模型权重以供模型推理即可。
# model
# optimizer and lr scheduler
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=0,
num_training_steps=(len(train_dataloader) * num_epochs),
)
# training and evaluation
model = model.to(device)
for epoch in range(num_epochs):
model.train()
total_loss = 0
for step, batch in enumerate(tqdm(train_dataloader)):
batch = {k: v.to(device) for k, v in batch.items()}
# print(batch)
# print(batch["input_ids"].shape)
outputs = model(**batch)
loss = outputs.loss
total_loss += loss.detach().float()
loss.backward()
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
eval_loss = 0
eval_preds = []
for step, batch in enumerate(tqdm(eval_dataloader)):
batch = {k: v.to(device) for k, v in batch.items()}
with torch.no_grad():
outputs = model(**batch)
loss = outputs.loss
eval_loss += loss.detach().float()
eval_preds.extend(
tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(), skip_special_tokens=True)
)
eval_epoch_loss = eval_loss / len(eval_dataloader)
eval_ppl = torch.exp(eval_epoch_loss)
train_epoch_loss = total_loss / len(train_dataloader)
train_ppl = torch.exp(train_epoch_loss)
print(f"{epoch=}:{train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}")
100%|██████████| 7/7 [00:01<00:00, 5.03it/s] 100%|██████████| 7/7 [00:00<00:00, 22.78it/s]
epoch=0:train_ppl=tensor(2.4646e+10, device='cuda:0') train_epoch_loss=tensor(23.9279, device='cuda:0') eval_ppl=tensor(195.1290, device='cuda:0') eval_epoch_loss=tensor(5.2737, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 11.21it/s] 100%|██████████| 7/7 [00:00<00:00, 23.23it/s]
epoch=1:train_ppl=tensor(112.6432, device='cuda:0') train_epoch_loss=tensor(4.7242, device='cuda:0') eval_ppl=tensor(46.6624, device='cuda:0') eval_epoch_loss=tensor(3.8429, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 10.88it/s] 100%|██████████| 7/7 [00:00<00:00, 22.53it/s]
epoch=2:train_ppl=tensor(37.6138, device='cuda:0') train_epoch_loss=tensor(3.6274, device='cuda:0') eval_ppl=tensor(21.8593, device='cuda:0') eval_epoch_loss=tensor(3.0846, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 11.28it/s] 100%|██████████| 7/7 [00:00<00:00, 23.16it/s]
epoch=3:train_ppl=tensor(17.3817, device='cuda:0') train_epoch_loss=tensor(2.8554, device='cuda:0') eval_ppl=tensor(9.3968, device='cuda:0') eval_epoch_loss=tensor(2.2404, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 11.34it/s] 100%|██████████| 7/7 [00:00<00:00, 22.91it/s]
epoch=4:train_ppl=tensor(6.2920, device='cuda:0') train_epoch_loss=tensor(1.8393, device='cuda:0') eval_ppl=tensor(3.8994, device='cuda:0') eval_epoch_loss=tensor(1.3608, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 11.29it/s] 100%|██████████| 7/7 [00:00<00:00, 23.15it/s]
epoch=5:train_ppl=tensor(2.7512, device='cuda:0') train_epoch_loss=tensor(1.0120, device='cuda:0') eval_ppl=tensor(1.8104, device='cuda:0') eval_epoch_loss=tensor(0.5936, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 11.31it/s] 100%|██████████| 7/7 [00:00<00:00, 23.19it/s]
epoch=6:train_ppl=tensor(1.5378, device='cuda:0') train_epoch_loss=tensor(0.4303, device='cuda:0') eval_ppl=tensor(1.2499, device='cuda:0') eval_epoch_loss=tensor(0.2231, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 11.29it/s] 100%|██████████| 7/7 [00:00<00:00, 22.97it/s]
epoch=7:train_ppl=tensor(1.1984, device='cuda:0') train_epoch_loss=tensor(0.1810, device='cuda:0') eval_ppl=tensor(1.1350, device='cuda:0') eval_epoch_loss=tensor(0.1267, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 10.71it/s] 100%|██████████| 7/7 [00:00<00:00, 23.24it/s]
epoch=8:train_ppl=tensor(1.1170, device='cuda:0') train_epoch_loss=tensor(0.1106, device='cuda:0') eval_ppl=tensor(1.0947, device='cuda:0') eval_epoch_loss=tensor(0.0905, device='cuda:0')
100%|██████████| 7/7 [00:00<00:00, 11.29it/s] 100%|██████████| 7/7 [00:00<00:00, 22.97it/s]
epoch=9:train_ppl=tensor(1.0917, device='cuda:0') train_epoch_loss=tensor(0.0877, device='cuda:0') eval_ppl=tensor(1.0843, device='cuda:0') eval_epoch_loss=tensor(0.0809, device='cuda:0')
# 模型评估
model.eval()
i = 16
inputs = tokenizer(f'{text_column} :{dataset["test"][i]["Tweet text"]} Label :', return_tensors="pt")
print(dataset["test"][i]["Tweet text"])
print(inputs)
with torch.no_grad():
inputs = {k: v.to(device) for k, v in inputs.items()}
outputs = model.generate(
input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], max_new_tokens=10, eos_token_id=3
)
print(outputs)
print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))
Hey @nytimes your link to cancel my subscription isn't working and nobody is answering the chat. Please don't play that kind of stupid game. {'input_ids':tensor([[227985, 5484, 915, 54078, 2566, 7782, 24502, 2632, 8989, 427, 36992, 2670, 140711, 21994, 10789, 530, 88399, 632, 183542, 368, 44799, 17, 29901, 5926, 7229, 861, 11596, 461, 78851, 14775, 17, 77658, 915, 210]]), 'attention_mask':tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])} tensor([[227985, 5484, 915, 54078, 2566, 7782, 24502, 2632, 8989, 427, 36992, 2670, 140711, 21994, 10789, 530, 88399, 632, 183542, 368, 44799, 17, 29901, 5926, 7229, 861, 11596, 461, 78851, 14775, 17, 77658, 915, 210, 16449, 5952, 3]], device='cuda:0') ["Tweet text :Hey @nytimes your link to cancel my subscription isn't working and nobody is answering the chat. Please don't play that kind of stupid game. Label :complaint"]
# saving model
peft_model_id = f"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}"
print("model_output:", peft_model_id)
model.save_pretrained(peft_model_id)
model_output:/data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM
输出的模型权重文件如下所示:
/data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM
├── [ 398] adapter_config.json
├── [689K] adapter_model.bin
└── [ 129] README.md
0 directories, 3 files
注意:这里只会保存经过训练的增量 PEFT 权重。其中,adapter_config.json`` 为 IA3 配置文件;
adapter_model.bin`` 为 IA3 权重文件。
ckpt = f"{peft_model_id}/adapter_model.bin"
!du -h $ckpt
print("--------------")
!tree -h $peft_model_id
huggingface/tokenizers:The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) 692K /data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM/adapter_model.bin -------------- huggingface/tokenizers:The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) /data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM ├── [ 398] adapter_config.json ├── [689K] adapter_model.bin └── [ 129] README.md 0 directories, 3 files
2.5 加载微调后的权重文件进行推理¶
from peft import PeftModel, PeftConfig
peft_model_id = f"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}"
print("model_input:", peft_model_id)
config = PeftConfig.from_pretrained(peft_model_id)
model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path)
model = PeftModel.from_pretrained(model, peft_model_id)
model_input:/data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM
model.to(device)
model.eval()
i = 4
inputs = tokenizer(f'{text_column} :{dataset["test"][i]["Tweet text"]} Label :', return_tensors="pt")
print(dataset["test"][i]["Tweet text"])
print(inputs)
with torch.no_grad():
inputs = {k: v.to(device) for k, v in inputs.items()}
outputs = model.generate(
input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], max_new_tokens=10, eos_token_id=3
)
print(outputs)
print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))
@greateranglia Ok thanks... {'input_ids':tensor([[227985, 5484, 915, 2566, 14173, 2960, 29906, 387, 20706, 49337, 1369, 77658, 915, 210]]), 'attention_mask':tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])} tensor([[227985, 5484, 915, 2566, 14173, 2960, 29906, 387, 20706, 49337, 1369, 77658, 915, 210, 1936, 106863, 3]], device='cuda:0') ['Tweet text :@greateranglia Ok thanks... Label :no complaint']