11"""Setter functions for virtual params such as ``optimizer__lr``."""
22import re
33
4+ # param names can be arbitrarily long, keep the verbose message bounded
5+ MAX_PARAM_GROUP_MSG_LEN = 200
6+
7+
8+ def format_param_group_msg (group_config , param_names ):
9+ """Message for which module params a param group config applies to."""
10+ if not param_names :
11+ msg = (
12+ "Setting param group {} for parameters that are not among the "
13+ "module's learnable parameters (this may be unintended)." .format (
14+ group_config ,
15+ )
16+ )
17+ else :
18+ msg = "Setting param group {} for {}." .format (
19+ group_config ,
20+ ', ' .join (param_names ),
21+ )
22+ if len (msg ) > MAX_PARAM_GROUP_MSG_LEN :
23+ msg = msg [:MAX_PARAM_GROUP_MSG_LEN - 3 ] + '...'
24+ return msg
25+
26+
27+ def _param_names_for_tensors (net , tensors ):
28+ """Map optimizer tensors back to module parameter names when possible."""
29+ tensor_ids = {id (t ) for t in tensors }
30+ names = []
31+ get_params = getattr (net , 'get_all_learnable_params' , None )
32+ if get_params is None :
33+ return names
34+ for name , p in get_params ():
35+ if id (p ) in tensor_ids :
36+ names .append (name )
37+ return names
38+
439
540def _extract_optimizer_param_name_and_group (optimizer_name , param ):
641 """Extract param group and param name from the given parameter name.
@@ -44,6 +79,8 @@ def _set_optimizer_param(optimizer, param_group, param_name, value):
4479 for group in groups :
4580 group [param_name ] = value
4681
82+ return groups
83+
4784
4885def optimizer_setter (
4986 net , param , value , optimizer_attr = 'optimizer_' , optimizer_name = 'optimizer'
@@ -62,9 +99,18 @@ def optimizer_setter(
6299 param_group , param_name = _extract_optimizer_param_name_and_group (
63100 optimizer_name , param )
64101
65- _set_optimizer_param (
102+ groups = _set_optimizer_param (
66103 optimizer = getattr (net , optimizer_attr ),
67104 param_group = param_group ,
68105 param_name = param_name ,
69106 value = value
70107 )
108+
109+ # only report for a specific param group; a global set (e.g. optimizer__lr)
110+ # touches every param and is not what #291 asks to surface
111+ if getattr (net , 'verbose' , 0 ) and param_group != 'all' :
112+ tensors = []
113+ for group in groups :
114+ tensors .extend (group .get ('params' , []))
115+ param_names = _param_names_for_tensors (net , tensors )
116+ print (format_param_group_msg ({param_name : value }, param_names ))
0 commit comments