luxfer / runtime /inference /mixed_precision.py
mdxss's picture
Publish Luxfer early beta with runnable weights and language metadata
7b6f2cc verified
Raw History Blame Contribute Delete
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