You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Now lets say we want to update linear1 to offset its output by 100. How can we do this?
The Good Way
The first way is to create a new type that inherits from Linear and override its __call__ method to perform the new behavior. We also override the constructor to be able to easily create it from an existing instance by copying all its attributes. Then we simply swap model.linear1 with its new value.
Another way of doing this is to create a patch_method function that can take any object and overrides any given method with a new provided method. It does so by 1) programmatically creating a new type that inherits from the existing type and overrides the target method with the new method, and 2) updates the object type in place‼️
Then you can simply define the new method and use patch_method to update the __call__ method for model.linear1.
defpatch_method(obj, name, new_method):
# create new type and change object's type 😈obj.__class__=type(
obj.__class__.__name__,
(obj.__class__,),
{name: new_method},
)
defcrazy_linear_call(self, x):
returnnnx.Linear.__call__(self, x) +100patch_method(model.linear1, '__call__', crazy_linear_call)
y=model(x)
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Here we will show two ways to monkey patch an object to get new behavior. As inspiration lets first create a simple model.
Now lets say we want to update
linear1
to offset its output by100
. How can we do this?The Good Way
The first way is to create a new type that inherits from
Linear
and override its__call__
method to perform the new behavior. We also override the constructor to be able to easily create it from an existing instance by copying all its attributes. Then we simply swapmodel.linear1
with its new value.The Evil Way
Another way of doing this is to create a‼️
patch_method
function that can take any object and overrides any given method with a new provided method. It does so by 1) programmatically creating a new type that inherits from the existing type and overrides the target method with the new method, and 2) updates the object type in placeThen you can simply define the new method and use
patch_method
to update the__call__
method formodel.linear1
.Warning: use with care.
Beta Was this translation helpful? Give feedback.
All reactions