drop in replacement of nn.Linear
| 15 | |
| 16 | |
| 17 | class ActLinear(nn.Module): |
| 18 | """ |
| 19 | drop in replacement of nn.Linear |
| 20 | """ |
| 21 | |
| 22 | def __init__(self, base: nn.Linear): |
| 23 | super().__init__() |
| 24 | self.base = base |
| 25 | self.activation_norms = [] # offload to CPU |
| 26 | self.record_activation = True |
| 27 | |
| 28 | def clear_act_buffer(self): |
| 29 | self.activation_norms = [] |
| 30 | |
| 31 | def forward(self, x): |
| 32 | if self.record_activation: |
| 33 | if hasattr(self, "mask") and self.mask is not None: |
| 34 | x_ = x[self.mask] # num * dim |
| 35 | else: |
| 36 | x_ = x # bs * seq_len * dim |
| 37 | self.activation_norms.append( |
| 38 | x_.view(-1, x_.shape[-1]).cpu() |
| 39 | ) # offload to CPU. |
| 40 | |
| 41 | out = self.base(x) |
| 42 | return out |
| 43 | |
| 44 | |
| 45 | class no_act_recording: |