# RemoteModule Source: https://www.tensorplay.cn/docs/generated/tensorplay.distributed.nn.RemoteModule.html ```python class tensorplay.distributed.nn.RemoteModule(remote_device: str, module_cls: type[Module], args: tuple[Any, ...] | None = None, kwargs: dict[str, Any] | None = None) ``` ```python compile(*args, **kwargs) ``` Compile this Module’s forward using tensorplay.compile(). This Module’s __call__ method is compiled and all arguments are passed as-is to tensorplay.compile(). See tensorplay.compile() for details on the arguments for this function. ```python forward(*input: Any) → None ``` Define the computation performed at every call. Should be overridden by all subclasses. > **Note** > > Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them. ```python get_buffer(target: str) → Tensor ``` Return the buffer given by target if it exists, otherwise throw an error. See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target. Parameters: target – The fully-qualified string name of the buffer to look for. (See get_submodule for how to specify a fully-qualified string.) Returns: The buffer referenced by target Return type: [tensorplay.Tensor](/docs/generated/tensorplay.Tensor.html#tensorplay.Tensor) Raises: [AttributeError](https://docs.python.org/3/builtins/exceptions.html#AttributeError) – If the target string references an invalid path or resolves to something that is not a buffer ```python get_extra_state() → Any ``` Return any extra state to include in the module’s state_dict. Implement this and a corresponding [set_extra_state()](#tensorplay.distributed.nn.RemoteModule.set_extra_state) for your module if you need to store extra state. This function is called when building the module’s state_dict(). Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes. Returns: Any extra state to store in the module’s state_dict Return type: [object](https://docs.python.org/3/builtins/functions.html#object) ```python get_parameter(target: str) → Parameter ``` Return the parameter given by target if it exists, otherwise throw an error. See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target. Parameters: target – The fully-qualified string name of the Parameter to look for. (See get_submodule for how to specify a fully-qualified string.) Returns: The Parameter referenced by target Return type: tensorplay.nn.Parameter Raises: [AttributeError](https://docs.python.org/3/builtins/exceptions.html#AttributeError) – If the target string references an invalid path or resolves to something that is not an nn.Parameter ```python get_submodule(target: str) → Module ``` Return the submodule given by target if it exists, otherwise throw an error. For example, let’s say you have an nn.Module A that looks like this: ``` A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) ) ``` (The diagram shows an nn.Module A. A which has a nested submodule net_b, which itself has two submodules net_c and linear. net_c then has a submodule conv.) To check whether or not we have the linear submodule, we would call get_submodule("net_b.linear"). To check whether we have the conv submodule, we would call get_submodule("net_b.net_c.conv"). The runtime of get_submodule is bounded by the degree of module nesting in target. A query against named_modules achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists, get_submodule should always be used. Parameters: target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.) Returns: The submodule referenced by target Return type: tensorplay.nn.Module Raises: [AttributeError](https://docs.python.org/3/builtins/exceptions.html#AttributeError) – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of nn.Module. ```python register_full_backward_hook(hook: Callable[[Module, tuple[Tensor, ...] | Tensor, tuple[Tensor, ...] | Tensor], None | tuple[Tensor, ...] | Tensor], prepend: bool = False) → RemovableHandle ``` Register a backward hook on the module. The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows: - Ordinarily, the hook fires when the gradients are computed with respect to the module inputs. - If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs. - If none of the module outputs require gradients, then the hooks will not fire. The hook should have the following signature: ``` hook(module, grad_input, grad_output) -> tuple(Tensor) or None ``` The grad_input and grad_output are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place of grad_input in subsequent computations. grad_input will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries in grad_input and grad_output will be None for all non-Tensor arguments. For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function. > **Warning** > > Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error. Parameters: - hook (Callable) – The user-defined hook to be registered. - prepend ([bool](https://docs.python.org/3/builtins/functions.html#bool)) – If true, the provided hook will be fired before all existing backward hooks on this tensorplay.nn.Module. Otherwise, the provided hook will be fired after all existing backward hooks on this tensorplay.nn.Module. Note that global backward hooks registered with register_module_full_backward_hook() will fire before all hooks registered by this method. Returns: a handle that can be used to remove the added hook by calling handle.remove() Return type: tensorplay.utils.hooks.RemovableHandle ```python register_full_backward_pre_hook(hook: Callable[[Module, tuple[Tensor, ...] | Tensor], None | tuple[Tensor, ...] | Tensor], prepend: bool = False) → RemovableHandle ``` Register a backward pre-hook on the module. The hook will be called every time the gradients for the module are computed. The hook should have the following signature: ``` hook(module, grad_output) -> tuple[Tensor] or None ``` The grad_output is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place of grad_output in subsequent computations. Entries in grad_output will be None for all non-Tensor arguments. For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function. > **Warning** > > Modifying inputs inplace is not allowed when using backward hooks and will raise an error. Parameters: - hook (Callable) – The user-defined hook to be registered. - prepend ([bool](https://docs.python.org/3/builtins/functions.html#bool)) – If true, the provided hook will be fired before all existing backward_pre hooks on this tensorplay.nn.Module. Otherwise, the provided hook will be fired after all existing backward_pre hooks on this tensorplay.nn.Module. Note that global backward_pre hooks registered with register_module_full_backward_pre_hook() will fire before all hooks registered by this method. Returns: a handle that can be used to remove the added hook by calling handle.remove() Return type: tensorplay.utils.hooks.RemovableHandle ```python register_load_state_dict_post_hook(hook) ``` Register a post-hook to be run after module’s load_state_dict() is called. It should have the following signature:: hook(module, incompatible_keys) -> None The module argument is the current module that this hook is registered on, and the incompatible_keys argument is a NamedTuple consisting of attributes missing_keys and unexpected_keys. missing_keys is a list of str containing the missing keys and unexpected_keys is a list of str containing the unexpected keys. The given incompatible_keys can be modified inplace if needed. Note that the checks performed when calling load_state_dict() with strict=True are affected by modifications the hook makes to missing_keys or unexpected_keys, as expected. Additions to either set of keys will result in an error being thrown when strict=True, and clearing out both missing and unexpected keys will avoid an error. Returns: a handle that can be used to remove the added hook by calling handle.remove() Return type: tensorplay.utils.hooks.RemovableHandle ```python register_load_state_dict_pre_hook(hook) ``` Register a pre-hook to be run before module’s load_state_dict() is called. It should have the following signature:: hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950 Parameters: hook (Callable) – Callable hook that will be invoked before loading the state dict. ```python register_module(name: str, module: Module | None) → None ``` Alias for add_module(). ```python register_state_dict_post_hook(hook) ``` Register a post-hook for the state_dict() method. It should have the following signature:: hook(module, state_dict, prefix, local_metadata) -> None The registered hooks can modify the state_dict inplace. ```python register_state_dict_pre_hook(hook) ``` Register a pre-hook for the state_dict() method. It should have the following signature:: hook(module, prefix, keep_vars) -> None The registered hooks can be used to perform pre-processing before the state_dict call is made. ```python set_extra_state(state: Any) → None ``` Set extra state contained in the loaded state_dict. This function is called from load_state_dict() to handle any extra state found within the state_dict. Implement this function and a corresponding [get_extra_state()](#tensorplay.distributed.nn.RemoteModule.get_extra_state) for your module if you need to store extra state within its state_dict. Parameters: state ([dict](https://docs.python.org/3/builtins/stdtypes.html#dict)) – Extra state from the state_dict ```python set_submodule(target: str, module: Module, strict: bool = False) → None ``` Set the submodule given by target if it exists, otherwise throw an error. > **Note** > > If strict is set to False (default), the method will replace an existing submodule or create a new submodule if the parent module exists. If strict is set to True, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist. For example, let’s say you have an nn.Module A that looks like this: ``` A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) ) ``` (The diagram shows an nn.Module A. A has a nested submodule net_b, which itself has two submodules net_c and linear. net_c then has a submodule conv.) To override the Conv2d with a new submodule Linear, you could call set_submodule("net_b.net_c.conv", nn.Linear(1, 1)) where strict could be True or False To add a new submodule Conv2d to the existing net_b module, you would call set_submodule("net_b.conv", nn.Conv2d(1, 1, 1)). In the above if you set strict=True and call set_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised because net_b does not have a submodule named conv. Parameters: - target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.) - module – The module to set the submodule to. - strict – If False, the method will replace an existing submodule or create a new submodule if the parent module exists. If True, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist. Raises: - [ValueError](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the target string is empty or if module is not an instance of nn.Module. - [AttributeError](https://docs.python.org/3/builtins/exceptions.html#AttributeError) – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of nn.Module. ```python to_empty(*, device: str | device | int | None, recurse: bool = True) → Self ``` Move the parameters and buffers to the specified device without copying storage. Parameters: - device ([tensorplay.device](/docs/generated/tensorplay.Device.html#tensorplay.Device)) – The desired device of the parameters and buffers in this module. - recurse ([bool](https://docs.python.org/3/builtins/functions.html#bool)) – Whether parameters and buffers of submodules should be recursively moved to the specified device. Returns: self Return type: Module