大模型的参数高效微调方法
时间: 2025-02-25 07:16:32 浏览: 54
### 大模型参数高效微调方法
#### BitFit 方法
BitFit 是一种简单有效的参数高效微调策略,仅调整每层中的偏置项。这种方法显著减少了需要更新的参数数量,从而降低了计算成本并提高了效率。尽管只修改少量参数,实验表明该方法仍能保持良好的性能提升效果[^1]。
```python
for layer in model.layers:
for param_name, param in layer.named_parameters():
if "bias" in param_name:
param.requires_grad = True
else:
param.requires_grad = False
```
#### Prefix Tuning 方法
Prefix Tuning 通过引入一组可训练的前缀向量来增强预训练模型的能力。这些前缀向量位于输入序列之前,在整个训练期间唯一允许更新的部分就是这部分新增加的前缀向量权重。此方式使得大部分原有网络结构得以保留不变的同时实现了特定任务的学习能力迁移[^4]。
```python
class PrefixTuning(nn.Module):
def __init__(self, config):
super().__init__()
self.prefix_length = config.prefix_length
self.embedding_size = config.hidden_size
# Initialize prefix embeddings randomly or from a small pre-trained model.
self.prefix_embeddings = nn.Parameter(torch.randn(self.prefix_length, self.embedding_size))
def forward(self, input_ids=None, attention_mask=None, **kwargs):
batch_size = input_ids.shape[0]
# Repeat the same prefix across all examples in the batch.
prefixes = self.prefix_embeddings.unsqueeze(0).expand(batch_size, -1, -1)
inputs_embeds = torch.cat([prefixes, kwargs['inputs_embeds']], dim=1)
extended_attention_mask = torch.cat(
[
torch.ones((batch_size, self.prefix_length), device=input_ids.device),
attention_mask,
],
dim=-1,
)
return {"inputs_embeds": inputs_embeds, "attention_mask": extended_attention_mask}
```
#### Prompt Tuning 方法
Prompt Tuning 则专注于设计特殊的提示模板,并让模型学习如何填充这些空白处的内容以完成指定的任务。这种方式不仅能够有效利用大规模预训练的优势,而且还能灵活应对多种不同的应用场景需求。
```python
def create_prompt_template(task_description, placeholder_token="[MASK]", num_blanks=3):
prompt_parts = task_description.split()
blank_positions = np.linspace(0, len(prompt_parts)-1, num=num_blanks, dtype=int)
for pos in reversed(blank_positions): # Insert blanks backwards to avoid index shifting issues.
prompt_parts.insert(pos, placeholder_token)
return ' '.join(prompt_parts)
task_desc = "Translate English sentence into French."
prompt_with_placeholders = create_prompt_template(task_desc)
print(f"Generated Prompt Template: {prompt_with_placeholders}")
```
阅读全文
相关推荐


















