Hi,
In that case, you can register the hook directly on self.linear.weight. See the sample below:
import torch
from torch import nn

l = nn.Linear(5, 5)

inp = torch.rand(3, 5)

print("original weights")
print(l.weight)

opt = torch.optim.SGD(l.parameters(), lr=0.01)

mask = torch.rand(5, 5).gt(0.5)
print("our mask")
print(mask)
def hook_fn(grad):
    # You are not allowed to modify inplace what is given !
    out = grad.clone()
    out[mask] = 0
    return out

# Registering the hook only once. This can be done in
# MaskedLinear's __init__ function
l.weight.register_hook(hook_fn)

print("Loss goes down")
for _ in range(50):
    loss = l(inp).abs().sum()
    opt.zero_grad()
    loss.backward()
    opt.step()
    print(loss)
print("only some weights have changed")
print(l.weight)