pyvene.models.intervenable_base.IntervenableModel#

class IntervenableModel(config, model, **kwargs)[source]#

Bases: BaseModel

Intervenable model via pyvene native backend (hook-based).

__init__(config, model, **kwargs)[source]#

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Methods

__init__(config, model, **kwargs)

Initialize internal Module state, shared by both nn.Module and ScriptModule.

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

count_parameters([include_model])

Set device of interventions and the model

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

disable_intervention_gradients()

Disable gradient in the trainable intervention

disable_model_gradients()

Disable gradient in the model

double()

Casts all floating point parameters and buffers to double datatype.

enable_model_gradients()

Enable gradient in the model

eval()

Set the module in evaluation mode.

eval_alignment(eval_dataloader, ...)

The method evaluate alignment.

extra_repr()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(base[, sources, unit_locations, ...])

Main forward function that serves a wrapper to actual model forward calls.

generate(base[, sources, unit_locations, ...])

Intervenable generation function that serves a wrapper to regular model generate calls.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_cached_activations()

Return the cached activations with keys

get_cached_hot_activations()

Return the cached hot activations with linked keys

get_device()

Get device of interventions and the model

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

get_trainable_parameters()

Return trainable params as key value pairs

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load(load_directory, model[, ...])

Load interventions from disk or hub

load_intervention(load_directory[, ...])

Instead of creating an new object, this function loads existing weights onto the current object.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([recurse])

The above, but for HuggingFace.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post hook to be run after module's load_state_dict is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

save(save_directory[, save_to_hf_hub, ...])

Save interventions to disk or hub

save_intervention(save_directory[, ...])

Instead of saving the metadata with artifacts, it only saves artifacts such as trainable weights.

set_device(device[, set_model])

Set device of interventions and the model

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_temperature(temp)

Set temperature if needed

set_zero_grad()

Set device of interventions and the model

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

train_alignment(train_dataloader, ...)

The method find alignment.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad()

The above, but for HuggingFace.

Attributes

BACKEND

T_destination

call_super_init

dump_patches

training

eval()[source]#

Set the module in evaluation mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

This is equivalent with self.train(False).

See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.

Returns:

Module: self

eval_alignment(eval_dataloader, compute_metrics, inputs_collator, **kwargs)[source]#

The method evaluate alignment.

forward(base, sources: List | None = None, unit_locations: Dict | None = None, source_representations: Dict | None = None, subspaces: List | None = None, labels: LongTensor | None = None, output_original_output: bool | None = False, return_dict: bool | None = None, use_cache: bool | None = None)[source]#

Main forward function that serves a wrapper to actual model forward calls. It will use forward hooks to do interventions.

In essense, sources will lead to getter hooks to get activations. We will use these activations to intervene on our base example.

Parameters: base: The base example. sources: A list of source examples. unit_locations: The intervention locations. activations_sources: A list of representations. subspace: Subspace interventions.

Return: base_output: the non-intervened output of the base input. counterfactual_outputs: the intervened output of the base input.

Notes:

1) unit_locations unit_locations is a dict where keys are tied with example pairs involved in one intervention as, {

“sources->base” : List[]

}

the shape can be

2 * num_intervention * bs * num_max_unit

OR

2 * num_intervention * num_intervention_level * bs * num_max_unit

if we intervene on h.pos which is a nested intervention location.

2) subspaces subspaces is a list of indices indicating which subspace will this intervention target given an example in the batch.

An intervention could be initialized with subspace parition as, [[… subspace_1 …], [… subspace_2 …], [rest]]

An intervention may be targeting a specific partition.

This input field should look like something like, [

[[subspace indices], [subspace indices]], <- for the first intervention None, <- for the second intervention [[subspace indices], [subspace indices]]

]

Only setter (where do_intervention is called) needs this field.

*We assume base and source targetting the same subspace for now. *We assume only a single space is targeted for now (although 2d list is provided).

Since we now support group-based intervention, the number of sources should be equal to the total number of groups.

generate(base, sources: List | None = None, unit_locations: Dict | None = None, source_representations: Dict | None = None, intervene_on_prompt: bool = False, subspaces: List | None = None, output_original_output: bool | None = False, **kwargs)[source]#

Intervenable generation function that serves a wrapper to regular model generate calls.

Currently, we support basic interventions in the prompt only. We will support generation interventions in the next release.

TODO: Unroll sources and intervene in the generation step.

Parameters: base: The base example. sources: A list of source examples. unit_locations: The intervention locations of

base.

activations_sources: A list of representations. intervene_on_prompt: Whether only intervene on prompt. **kwargs: All other generation parameters.

Return: base_output: the non-intervened output of the base input. counterfactual_outputs: the intervened output of the base input.

static load(load_directory, model, local_directory=None, from_huggingface_hub=False, include_model=False)[source]#

Load interventions from disk or hub

load_intervention(load_directory, include_model=True)[source]#

Instead of creating an new object, this function loads existing weights onto the current object. This is not a static method, and returns nothing.

save(save_directory, save_to_hf_hub=False, hf_repo_name='my-awesome-model', include_model=False)[source]#

Save interventions to disk or hub

save_intervention(save_directory, include_model=True)[source]#

Instead of saving the metadata with artifacts, it only saves artifacts such as trainable weights. This is not a static method, and returns nothing.

train(mode=True)[source]#

Set the module in training mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

Args:
mode (bool): whether to set training mode (True) or evaluation

mode (False). Default: True.

Returns:

Module: self

train_alignment(train_dataloader, compute_loss, compute_metrics, inputs_collator, **kwargs)[source]#

The method find alignment.

a.k.a. training the intervention

Notes: 1) we use Adam, and linear lr scheduling. 2) you can pass in lr or using default 1e-3