Write a Python class to implement Mixed Precision Training that uses both float32 and float16 data types to optimize memory usage and speed. Your class should have an __init__(self, loss_scale=1024.0) method to initialize with loss scaling factor. Implement forward(self, weights, inputs, targets) to perform the forward pass of a linear model in float16 and return the Mean Squared Error (MSE) loss multiplied by loss_scale as a built-in Python float, and backward(self, gradients) to unscale gradients and check for overflow. Use float16 for computations but float32 for gradient accumulation. Return gradients as float32 and set them to zero if overflow is detected.
forward: cast weights, inputs and targets to float16, compute predictions = inputs @ weights and the MSE against targets in float16, then convert the loss to a Python float and multiply it by loss_scale.backward: overflow means any NaN or Inf in gradients. In that case return an all-zero float32 array of the same shape; otherwise return gradients cast to float32 and divided by loss_scale.Only use NumPy.