Module for utility functions and classes used throughout the package.

class nnsight.util.WrapperModule(*args, **kwargs)[source]#

Simple torch module which passes it’s input through. Useful for hooking. If there is only one argument, returns the first element.

forward(*args, **kwargs)[source]#

Defines the computation performed at every call.

Should be overridden by all subclasses.


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.

nnsight.util.apply(data: Collection, fn: Callable, cls: Type) Collection[source]#

Applies some function to all members of a collection of a give type (or types)

  • data (Collection) – Collection to apply function to.

  • fn (Callable) – Function to apply.

  • cls (type) – Type or Types to apply function to.


Same kind of collection as data, after then fn has been applied to members of given type.

Return type:


nnsight.util.fetch_attr(object: object, target: str) Any[source]#

Retrieves an attribute from an object hierarchy given an attribute path. Levels are separated by ‘.’ e.x (transformer.h.1)

  • object (object) – Root object to get attribute from.

  • target (str) – Attribute path as ‘.’ separated string.


Fetched attribute.

Return type:


nnsight.util.wrap(object: object, wrapper: Type, *args, **kwargs) object[source]#

Wraps some object given some wrapper type. Updates the __class__ attribute of the object and calls the wrapper type’s __init__ method.

  • object (object) – Object to wrap.

  • wrapper (Type) – Type to wrap the object in.


Wrapped object.

Return type: