Download runtime/inference/mixed_precision.py from hscr/luxfer: direct link, hf CLI and curl.
- Browser
- Download file 915 Bytes
-
https://huggingface.co/hscr/luxfer/resolve/main/runtime/inference/mixed_precision.py
- Command line
-
hf download hf://hscr/luxfer/runtime/inference/mixed_precision.py
-
curl -L -o mixed_precision.py https://huggingface.co/hscr/luxfer/resolve/main/runtime/inference/mixed_precision.py
915 Bytes
| """Opt-in FP32 MLP arithmetic, keeping BF16 inter-layer activations.""" | |
| import torch | |
| from torch import nn | |
| class FP32Linear(nn.Module): | |
| def __init__(self,linear): | |
| super().__init__() | |
| self.weight=nn.Parameter(linear.weight.detach().float(),requires_grad=False) | |
| self.bias=nn.Parameter(linear.bias.detach().float(),requires_grad=False) if linear.bias is not None else None | |
| def forward(self,x): | |
| return torch.nn.functional.linear(x.float(),self.weight,self.bias).to(x.dtype) | |
| def fp32_mlp(model): | |
| if model.training: raise ValueError('Runtime conversion is inference only') | |
| for block in model.model.layers.layers: | |
| for name,child in list(block.mlp.named_children()): | |
| if isinstance(child,nn.Linear): setattr(block.mlp,name,FP32Linear(child)) | |
| else: raise ValueError('FP32 MLP runtime currently requires unfactorized projections') | |
| return model | |