(*args, **kwargs)
| 179 | return hash(tuple([map_scalar_to_tuple(t._tuple_shape) for t in tensors])) |
| 180 | |
| 181 | def wrapped_func(*args, **kwargs): |
| 182 | from ..traced_module.pytree import tree_flatten |
| 183 | from ..core.autodiff.grad import Grad |
| 184 | from ..autodiff.grad_manager import get_backwarding_grad_manager |
| 185 | |
| 186 | nonlocal traced |
| 187 | nonlocal custom_autodiff |
| 188 | nonlocal outdef |
| 189 | nonlocal shape_hash |
| 190 | nonlocal unexpected_shape_hash |
| 191 | nonlocal inp_grad_maps, out_grad_maps |
| 192 | trace_obj.convert_optimizer_state_to_tensor(*args, **kwargs) |
| 193 | if not traced: |
| 194 | traced = True |
| 195 | fargs = trace_obj.flatten_inputs(*args, **kwargs) |
| 196 | shape_hash = get_shape_hash(*fargs) if check_shape else None |
| 197 | # we want to construct map like {inp_hid: inp_grad_hid, ...}. but the |
| 198 | # backward() is not called now and the grad is unknown. so we record the |
| 199 | # grad_slot here and then use grad_slot to get the grad hid when exiting |
| 200 | # trace |
| 201 | # **The grad grad_slot returned is the orginal grad, that means it is |
| 202 | # not been processed by gradmanager attach callback, eg., the grad |
| 203 | # before allreduce when distributed training** |
| 204 | inp_grad_maps = {get_handle_id(t): get_grad_slot(t) for t in fargs} |
| 205 | del fargs |
| 206 | |
| 207 | def exit_trace(): |
| 208 | backward_trace_obj._trace.exit() |
| 209 | backward_trace_obj.unset_env() |
| 210 | for k, v in inp_grad_maps.items(): |
| 211 | inp_grad_maps[k] = ( |
| 212 | get_handle_id(v.grad) if v is not None else -1 |
| 213 | ) |
| 214 | |
| 215 | # if we want to trace the gradmanager attach callback, we will replace |
| 216 | # the original grad by the grad processed the gradmanger attach callback |
| 217 | if trace_gmcallback: |
| 218 | |
| 219 | def cb_wrapper(cb): |
| 220 | def wrapper(param, grad): |
| 221 | return ( |
| 222 | grad |
| 223 | if grad._is_external_value() |
| 224 | else cb(param, grad) |
| 225 | ) |
| 226 | |
| 227 | return wrapper |
| 228 | |
| 229 | current_gm = get_backwarding_grad_manager() |
| 230 | for _attached_tensor_id, grad in current_gm._gradients.items(): |
| 231 | spec = current_gm._attach_specs.get(_attached_tensor_id) |
| 232 | _attached_tensor = spec and spec.tensor() |
| 233 | if _attached_tensor is None: |
| 234 | continue |
| 235 | inp_hid = get_handle_id(_attached_tensor) |
| 236 | if inp_hid in inp_grad_maps: |
| 237 | spec.callbacks = list(map(cb_wrapper, spec.callbacks)) |
| 238 | inp_grad_maps[inp_hid] = get_handle_id(grad) |
nothing calls this directly
no test coverage detected