1414# See the License for the specific language governing permissions and
1515# limitations under the License.
1616""" ConfigMixinuration base class and utilities."""
17-
18-
19- import copy
2017import inspect
2118import json
2219import os
2320import re
21+ from collections import OrderedDict
2422from typing import Any , Dict , Tuple , Union
2523
2624from huggingface_hub import hf_hub_download
@@ -63,10 +61,14 @@ def register_to_config(self, **kwargs):
6361 logger .error (f"Can't set { key } with value { value } for { self } " )
6462 raise err
6563
66- if not hasattr (self , "_dict_to_save" ):
67- self ._dict_to_save = {}
64+ if not hasattr (self , "_internal_dict" ):
65+ internal_dict = kwargs
66+ else :
67+ previous_dict = dict (self ._internal_dict )
68+ internal_dict = {** self ._internal_dict , ** kwargs }
69+ logger .debug (f"Updating config from { previous_dict } to { internal_dict } " )
6870
69- self ._dict_to_save . update ( kwargs )
71+ self ._internal_dict = FrozenDict ( internal_dict )
7072
7173 def save_config (self , save_directory : Union [str , os .PathLike ], push_to_hub : bool = False , ** kwargs ):
7274 """
@@ -230,8 +232,7 @@ def __repr__(self):
230232
231233 @property
232234 def config (self ) -> Dict [str , Any ]:
233- output = copy .deepcopy (self ._dict_to_save )
234- return output
235+ return self ._internal_dict
235236
236237 def to_json_string (self ) -> str :
237238 """
@@ -240,7 +241,7 @@ def to_json_string(self) -> str:
240241 Returns:
241242 `str`: String containing all the attributes that make up this configuration instance in JSON format.
242243 """
243- config_dict = self ._dict_to_save
244+ config_dict = self ._internal_dict
244245 return json .dumps (config_dict , indent = 2 , sort_keys = True ) + "\n "
245246
246247 def to_json_file (self , json_file_path : Union [str , os .PathLike ]):
@@ -253,3 +254,39 @@ def to_json_file(self, json_file_path: Union[str, os.PathLike]):
253254 """
254255 with open (json_file_path , "w" , encoding = "utf-8" ) as writer :
255256 writer .write (self .to_json_string ())
257+
258+
259+ class FrozenDict (OrderedDict ):
260+ def __init__ (self , * args , ** kwargs ):
261+ # remove `None`
262+ args = (a for a in args if a is not None )
263+ kwargs = {k : v for k , v in kwargs if v is not None }
264+
265+ super ().__init__ (* args , ** kwargs )
266+
267+ for key , value in self .items ():
268+ setattr (self , key , value )
269+
270+ self .__frozen = True
271+
272+ def __delitem__ (self , * args , ** kwargs ):
273+ raise Exception (f"You cannot use ``__delitem__`` on a { self .__class__ .__name__ } instance." )
274+
275+ def setdefault (self , * args , ** kwargs ):
276+ raise Exception (f"You cannot use ``setdefault`` on a { self .__class__ .__name__ } instance." )
277+
278+ def pop (self , * args , ** kwargs ):
279+ raise Exception (f"You cannot use ``pop`` on a { self .__class__ .__name__ } instance." )
280+
281+ def update (self , * args , ** kwargs ):
282+ raise Exception (f"You cannot use ``update`` on a { self .__class__ .__name__ } instance." )
283+
284+ def __setattr__ (self , name , value ):
285+ if hasattr (self , "__frozen" ) and self .__frozen :
286+ raise Exception (f"You cannot use ``__setattr__`` on a { self .__class__ .__name__ } instance." )
287+ super ().__setattr__ (name , value )
288+
289+ def __setitem__ (self , name , value ):
290+ if hasattr (self , "__frozen" ) and self .__frozen :
291+ raise Exception (f"You cannot use ``__setattr__`` on a { self .__class__ .__name__ } instance." )
292+ super ().__setitem__ (name , value )
0 commit comments