1: from typing import Any, Optional
2: 
3: import torch
4: import torch.nn as nn
5: import torch.nn.functional as F
6: 
7: 
8: class SparseLinear(nn.Linear):
9:     def __init__(self, base: nn.Module, mode: str) -> None:
10:         super().__init__(base.in_features, base.out_features, bias=base.bias is not None)
11:         self.weight = base.weight
12:         self.mode = mode
13: 
14:     def forward(self, x: torch.Tensor, sparse_indices: Optional[torch.Tensor] = None, **kwargs: Any) -> torch.Tensor:
15:         x = x.contiguous()
16:         if sparse_indices is None or self.mode is None:
17:             return F.linear(x, self.weight)
18: 
19:         if self.mode == "in_gather":
20:             idx = sparse_indices.unsqueeze(0).unsqueeze(0).expand(x.shape[0], x.shape[1], -1)
21:             with torch.no_grad():
22:                 x = torch.gather(x, 2, idx).contiguous()
23: 
24:         if self.mode.startswith("in"):
25:             w = self.weight[:, sparse_indices].contiguous()
26:         else:
27:             w = self.weight[sparse_indices].contiguous()
28:         x = F.linear(x, w)
29: 
30:         if self.mode == "out_scatter" and x.shape[-1] != self.weight.shape[0]:
31:             with torch.no_grad():
32:                 out = torch.zeros(
33:                     x.shape[0],
34:                     x.shape[1],
35:                     self.weight.shape[0],
36:                     dtype=x.dtype,
37:                     device=x.device,
38:                 )
39:                 idx = sparse_indices.unsqueeze(0).unsqueeze(0).expand(x.shape[0], x.shape[1], -1)
40:                 x = out.scatter_add(2, idx, x).contiguous()
41: 
42:         return x
43: 
44: 
45: def lora_forward(
46:     self, x: torch.Tensor, indices: Optional[torch.Tensor] = None, *args: Any, **kwargs: Any
47: ) -> torch.Tensor:
48:     """Patched LoRA Linear forward that passes sparse indices through."""
49:     self._check_forward_args(x, *args, **kwargs)
50: 
51:     result = self.base_layer(x, indices, *args, **kwargs)
52:     result_dtype = result.dtype
53: 
54:     for active_adapter in self.active_adapters:
55:         if active_adapter not in self.lora_A.keys():
56:             continue
57: 
58:         lora_A = self.lora_A[active_adapter]
59:         lora_B = self.lora_B[active_adapter]
60:         scaling = self.scaling[active_adapter]
61: 
62:         lora_dropout = getattr(self, "lora_dropout", None)
63:         if lora_dropout is not None and active_adapter in lora_dropout:
64:             x_in = lora_dropout[active_adapter](x)
65:         else:
66:             x_in = x
67: 
68:         x_in = x_in.to(lora_A.weight.dtype)
69:         lora_out = lora_B(lora_A(x_in, indices, *args, **kwargs), indices, *args, **kwargs)
70:         lora_out = lora_out.to(result_dtype)
71:         result = torch.add(result, lora_out, alpha=scaling)
72: 
73:     return result