Elffuss BraidHub

kikocis/SpatialLM public

main · 2.9 KiBRawPermalink
1# Copyright 2025 the LlamaFactory team.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15from typing import TYPE_CHECKING, Set
16
17import torch
18
19from ..framework import logging
20
21
22if TYPE_CHECKING:
23 from transformers import PreTrainedModel
24
25 from ..hparams import FinetuningArguments
26
27
28logger = logging.get_logger(__name__)
29
30
31def get_forbidden_modules(finetuning_args: "FinetuningArguments") -> Set[str]:
32 r"""
33 Freezes network modules for tuning.
34 """
35 forbidden_modules = set()
36 if finetuning_args.train_proj_only:
37 forbidden_modules.update({"point_backbone", "model", "lm_head"})
38 elif finetuning_args.freeze_point_tower:
39 forbidden_modules.add("point_backbone")
40 elif finetuning_args.freeze_language_tower:
41 forbidden_modules.update({"model", "lm_head"})
42
43 return forbidden_modules
44
45
46def _setup_full_tuning(
47 model: "PreTrainedModel",
48 finetuning_args: "FinetuningArguments",
49 is_trainable: bool,
50 cast_trainable_params_to_fp32: bool,
51) -> None:
52 if not is_trainable:
53 return
54
55 logger.info_rank0("Fine-tuning method: Full")
56 forbidden_modules = get_forbidden_modules(finetuning_args)
57 for name, param in model.named_parameters():
58 if not any(forbidden_module in name for forbidden_module in forbidden_modules):
59 if cast_trainable_params_to_fp32:
60 param.data = param.data.to(torch.float32)
61 else:
62 param.data = param.data.to(torch.float32)
63 param.requires_grad_(False)
64
65 # force point_backbone to have float32
66 model.set_point_backbone_dtype(torch.float32)
67
68
69def init_adapter(
70 model: "PreTrainedModel",
71 finetuning_args: "FinetuningArguments",
72 is_trainable: bool,
73) -> "PreTrainedModel":
74 r"""Initialize the adapters.
75
76 Support only full-parameter training for now.
77
78 Note that the trainable parameters must be cast to float32.
79 """
80
81 # cast trainable parameters to float32 if:
82 # 1. is_trainable and not pure_bf16
83 cast_trainable_params_to_fp32 = False
84 if not is_trainable:
85 pass
86 elif finetuning_args.pure_bf16:
87 logger.info_rank0(
88 "Pure bf16 detected, remaining trainable params in half precision."
89 )
90 else:
91 logger.info_rank0("Upcasting trainable params to float32.")
92 cast_trainable_params_to_fp32 = True
93
94 _setup_full_tuning(
95 model, finetuning_args, is_trainable, cast_trainable_params_to_fp32
96 )
97
98 return model