                                Model Immunization from a Condition Number Perspective

C.3. Pseudo-code of the dummy layer
We provide the Pseudo-code for implementing the dummy layer in Fig. 4 below. The DummyLinear layer extends
torch.nn.Linear and incorporates an optional preconditioning mechanism in the backward pass using the inverse
feature covariance matrix. The LinearFunction class defines the forward and backward computations, where the
forward pass applies a standard linear transformation XW ⊤ + b and stores the input, weight, and bias for gradient
computation. In the backward pass, the input gradient is computed normally, while the weight gradient is modified based
on whether preconditioning is enabled (use precond=True). If enabled, the weight gradient is adjusted by solving
a regularized least-squares system using the inverse of the feature covariance matrix X ⊤ X + ϵI, improving numerical
stability.

class LinearFunction:
    @staticmethod
    def forward(ctx, input, weight, bias, lambda_reg, use_precond):
        # Save input tensors for backward
        ctx.save_for_backward(input, weight, bias)
        ctx.lambda_reg = lambda_reg
        ctx.use_precond = use_precond

         # Compute output
         output = input.mm(weight.t())
         if bias is not None:
             output += bias.unsqueeze(0).expand_as(output)
         return output

    @staticmethod
    def backward(ctx, grad_output):
        # Retrieve saved tensors
        input, weight, bias = ctx.saved_tensors
        lambda_reg = ctx.lambda_reg
        use_precond = ctx.use_precond

         # Initialize gradients
         grad_input = grad_weight = grad_bias = None

         if ctx.needs_input_grad[0]:
             grad_input = grad_output.mm(weight)

         if ctx.needs_input_grad[1]:
             base_grad_weight = grad_output.t().mm(input)
             if use_precond:
                 XtX = input.t().mm(input)
                 lambda_eye = lambda_reg * torch.eye(XtX.size(0), device=XtX.device)
                 XtX_reg = XtX + lambda_eye
                 grad_weight = torch.linalg.solve(XtX_reg, base_grad_weight)
             else:
                 grad_weight = base_grad_weight

         if bias is not None and ctx.needs_input_grad[2]:
             grad_bias = grad_output.sum(0)

         return grad_input, grad_weight, grad_bias, None, None


class DummyLinear(nn.Linear):
    def forward(self, input, lambda_reg, use_precond):
        # Dynamically decide whether to use the covariance inversion as the preconditioner
        return LinearFunction.apply(input, self.weight, self.bias, lambda_reg, use_precond)



                  Figure 4. Dummy layer with selective inverse feature covariance matrix in backward function.




                                                              26
