(self)
| 474 | |
| 475 | |
| 476 | def quantize(self): |
| 477 | def cast_to(weight, dtype=None, device=None, copy=False): |
| 478 | if device is None or weight.device == device: |
| 479 | if not copy: |
| 480 | if dtype is None or weight.dtype == dtype: |
| 481 | return weight |
| 482 | return weight.to(dtype=dtype, copy=copy) |
| 483 | |
| 484 | r = torch.empty_like(weight, dtype=dtype, device=device) |
| 485 | r.copy_(weight) |
| 486 | return r |
| 487 | |
| 488 | def cast_weight(s, input=None, dtype=None, device=None): |
| 489 | if input is not None: |
| 490 | if dtype is None: |
| 491 | dtype = input.dtype |
| 492 | if device is None: |
| 493 | device = input.device |
| 494 | weight = cast_to(s.weight, dtype, device) |
| 495 | return weight |
| 496 | |
| 497 | def cast_bias_weight(s, input=None, dtype=None, device=None, bias_dtype=None): |
| 498 | if input is not None: |
| 499 | if dtype is None: |
| 500 | dtype = input.dtype |
| 501 | if bias_dtype is None: |
| 502 | bias_dtype = dtype |
| 503 | if device is None: |
| 504 | device = input.device |
| 505 | bias = None |
| 506 | weight = cast_to(s.weight, dtype, device) |
| 507 | bias = cast_to(s.bias, bias_dtype, device) |
| 508 | return weight, bias |
| 509 | |
| 510 | class quantized_layer: |
| 511 | class Linear(torch.nn.Linear): |
| 512 | def __init__(self, *args, **kwargs): |
| 513 | super().__init__(*args, **kwargs) |
| 514 | |
| 515 | def forward(self,input,**kwargs): |
| 516 | weight,bias= cast_bias_weight(self,input) |
| 517 | return torch.nn.functional.linear(input,weight,bias) |
| 518 | |
| 519 | class RMSNorm(torch.nn.Module): |
| 520 | def __init__(self, module): |
| 521 | super().__init__() |
| 522 | self.module = module |
| 523 | |
| 524 | def forward(self,hidden_states,**kwargs): |
| 525 | weight= cast_weight(self.module,hidden_states) |
| 526 | input_dtype = hidden_states.dtype |
| 527 | variance = hidden_states.to(torch.float32).square().mean(-1, keepdim=True) |
| 528 | hidden_states = hidden_states * torch.rsqrt(variance + self.module.eps) |
| 529 | hidden_states = hidden_states.to(input_dtype) * weight |
| 530 | return hidden_states |
| 531 | |
| 532 | def replace_layer(model): |
| 533 | for name, module in model.named_children(): |
nothing calls this directly
no outgoing calls
no test coverage detected