Add lora layers to the Attention/BertAttention/Linear/RowLinear/FusedGatedMLP layers to the given model, return the changed model
(model: PretrainedModel,
max_lora_rank: Optional[int],
with_dora: bool = False)
| 1420 | |
| 1421 | |
| 1422 | def add_lora(model: PretrainedModel, |
| 1423 | max_lora_rank: Optional[int], |
| 1424 | with_dora: bool = False) -> PretrainedModel: |
| 1425 | ''' Add lora layers to the Attention/BertAttention/Linear/RowLinear/FusedGatedMLP layers to the given model, return the changed model |
| 1426 | ''' |
| 1427 | for name, layer in model.named_modules(): |
| 1428 | max_rank = max_lora_rank |
| 1429 | if isinstance(layer, (Attention, BertAttention)): |
| 1430 | if max_rank is None: |
| 1431 | max_rank = min( |
| 1432 | layer.hidden_size, |
| 1433 | layer.num_attention_heads * layer.attention_head_size, |
| 1434 | layer.num_attention_kv_heads * layer.attention_head_size) |
| 1435 | layer.qkv_lora = Lora( |
| 1436 | in_hidden_size=layer.hidden_size, |
| 1437 | out_hidden_sizes=[ |
| 1438 | layer.num_attention_heads * layer.attention_head_size, |
| 1439 | layer.num_attention_kv_heads * layer.attention_head_size, |
| 1440 | layer.num_attention_kv_heads * layer.attention_head_size |
| 1441 | ], |
| 1442 | max_low_rank=max_rank, |
| 1443 | ) |
| 1444 | |
| 1445 | if with_dora: |
| 1446 | layer.qkv_dora = Dora(out_hidden_sizes=[ |
| 1447 | layer.num_attention_heads * layer.attention_head_size, |
| 1448 | layer.num_attention_kv_heads * layer.attention_head_size, |
| 1449 | layer.num_attention_kv_heads * layer.attention_head_size |
| 1450 | ], ) |
| 1451 | |
| 1452 | if isinstance(layer, (Linear, RowLinear)): |
| 1453 | if max_rank is None: |
| 1454 | max_rank = min(layer.in_features, layer.out_features) |
| 1455 | layer.lora = Lora( |
| 1456 | in_hidden_size=layer.in_features, |
| 1457 | out_hidden_sizes=[layer.out_features], |
| 1458 | max_low_rank=max_rank, |
| 1459 | ) |
| 1460 | if with_dora: |
| 1461 | layer.dora = Dora(out_hidden_sizes=[layer.out_features]) |
| 1462 | |
| 1463 | if isinstance(layer, (MLP, FusedGatedMLP)): |
| 1464 | if max_rank is None: |
| 1465 | max_rank = min(layer.hidden_size, |
| 1466 | layer.ffn_hidden_size // layer.tp_size) |
| 1467 | layer.lora = Lora( |
| 1468 | in_hidden_size=layer.hidden_size, |
| 1469 | out_hidden_sizes=[ |
| 1470 | layer.ffn_hidden_size // layer.tp_size, |
| 1471 | layer.ffn_hidden_size // layer.tp_size |
| 1472 | ], |
| 1473 | max_low_rank=max_rank, |
| 1474 | ) |
| 1475 | |
| 1476 | if isinstance(layer, FusedGatedMLP): |
| 1477 | layer.fused_gate_up_lora = Lora( |
| 1478 | in_hidden_size=layer.hidden_size, |
| 1479 | out_hidden_sizes=[ |
no test coverage detected