importwarningsimportcontextlibfromtypingimportAny,Callable,Dict,Iterator,List,TupleimporttorchfromtorchimportTensor__all__=["functional_call"]# We avoid typing module here because module attributes are declared as Union[Parameter, Tensor] by default# and using other types causes mypy errorsdef_change_class(module,params_and_buffers)->None:cls=module.__class__attr_to_path:Dict[str,str]=module._attr_to_pathdef_getattribute(self,name:str)->Any:ifnameinattr_to_path:returnparams_and_buffers[attr_to_path[name]]returncls.__getattribute__(self,name)def_setattr(self,name:str,value:Any)->None:ifnameinattr_to_path:params_and_buffers[attr_to_path[name]]=valueelse:returncls.__setattr__(self,name,value)param_cls=type(f"StatelessReplacer{cls.__name__}",(cls,),{"__getattribute__":_getattribute,"__setattr__":_setattr,},)module.__class__=param_clsmodule._orig_class=clsdef_check_tied_val_already_replaced(old_val,new_val,replaced_tensors_map):ifold_valnotinreplaced_tensors_map:replaced_tensors_map[old_val]=new_valelifreplaced_tensors_map[old_val]isnotnew_val:warnings.warn("functional_call was passed multiple values for tied weights. ""This behavior is deprecated and will be an error in future versions")def_create_swap_params(params_and_buffers,replaced_tensors_map):def_swap_parameters(module,tensor_name:str,full_path:str,tensor:Tensor)->None:# Changes the module class to get a new __getattr__ dunder method# that looks for the reparametrized tensorifhasattr(module,tensor_name):old_val=getattr(module,tensor_name)_check_tied_val_already_replaced(old_val,tensor,replaced_tensors_map)ifhasattr(module,"_attr_to_path"):module._attr_to_path[tensor_name]=full_pathelse:module._attr_to_path={}module._attr_to_path[tensor_name]=full_path_change_class(module,params_and_buffers)return_swap_parametersdef_remove_swap(module,name:str,full_path:str)->None:ifhasattr(module,"_orig_class"):module.__class__=module._orig_classdelattr(module,"_orig_class")delattr(module,"_attr_to_path")@contextlib.contextmanagerdef_reparametrize_module(module:'torch.nn.Module',parameters_and_buffers:Dict[str,Tensor],)->Iterator[None]:orig_tensors_to_replacements:Dict[Tensor,Tensor]={}forname,tensorinparameters_and_buffers.items():_apply_func_submodules(_create_swap_params(parameters_and_buffers,orig_tensors_to_replacements),module,name.split("."),name,(tensor,))try:yieldfinally:fornameinparameters_and_buffers:_apply_func_submodules(_remove_swap,module,name.split("."),name,())def_apply_func_submodules(func:Callable[...,None],module:'torch.nn.Module',path:List[str],full_path:str,args:Tuple,):iflen(path)==1:func(module,path[0],full_path,*args)else:_apply_func_submodules(func,getattr(module,path[0]),path[1:],full_path,args)
[docs]deffunctional_call(module:'torch.nn.Module',parameters_and_buffers:Dict[str,Tensor],args:Tuple,kwargs:Dict[str,Any]=None,):r"""Performs a functional call on the module by replacing the module parameters and buffers with the provided ones. .. note:: If the module has active parametrizations, passing a value in the :attr:`parameters_and_buffers` argument with the name set to the regular parameter name will completely disable the parametrization. If you want to apply the parametrization function to the value passed please set the key as ``{submodule_name}.parametrizations.{parameter_name}.original``. .. note:: If the module performs in-place operations on parameters/buffers, these will be reflected in the `parameters_and_buffers` input. Example:: >>> a = {'foo': torch.zeros(())} >>> # xdoctest: +SKIP >>> mod = Foo() # does self.foo = self.foo + 1 >>> print(mod.foo) # tensor(0.) >>> functional_call(mod, a, torch.ones(())) >>> print(mod.foo) # tensor(0.) >>> print(a['foo']) # tensor(1.) Args: module (torch.nn.Module): the module to call parameters_and_buffers (dict of str and Tensor): the parameters that will be used in the module call. args (tuple): arguments to be passed to the module call kwargs (dict): keyword arguments to be passed to the module call Returns: Any: the result of calling ``module``. """# TODO allow kwargs such as unsafe and others for parametrizationif(torch.jit.is_tracing()ortorch.jit.is_scripting()orisinstance(module,(torch.jit.RecursiveScriptModule,torch.jit.ScriptModule,torch.jit.ScriptFunction))):raiseRuntimeError("The stateless API can't be used with Jitted modules")ifkwargsisNone:kwargs={}with_reparametrize_module(module,parameters_and_buffers):ifisinstance(args,tuple):out=module(*args,**kwargs)else:out=module(args,**kwargs)returnout
Docs
Access comprehensive developer documentation for PyTorch
To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. As the current maintainers of this site, Facebook’s Cookies Policy applies. Learn more, including about available controls: Cookies Policy.