Make FusedLayerNorm cpu compatible
Hello,
I hit an issue with FusedLayerNorm raising error when using cpu only.
RuntimeError: input must be a CUDA tensor (layer_norm_affine at csrc/layer_norm_cuda.cp:148)
The use case is either:
- Run some unit test in cpu
- Load model in cpu for inference
The issue is already reported here but personally I think it would make more sense for apex to make sure the Modules works on both cpu and gpu.
I wasn't the author of the apex FusedLayerNorm, and we intended it purely for GPU-side performance benefits during training. If you must use LayerNorm on the CPU, you should use the built-in Pytorch implementation. I'm not sure if on the CPU, writing our own custom implementation would provide a significant performance gain anyway. Can you special case the usage based on whether you're targeting CPU or GPU?
if cpu_inference:
LayerNorm = apex.normalization.FusedLayerNorm
else:
LayerNorm = torch.nn.LayerNorm
Hello @mcarilli, Yes there are workarounds but it is still very complex to convert models trained on GPU with FusedLayerNorm to a CPU-compatible model with nn.LayerNorm.
So basically as a user I am pretty reluctant to use it since it tie my implementation to run on certain hardware.
I think it would be nice if FusedLayerNorm can follow more closely the vanilla LayerNorm behaviour with possibility to do .cpu() and work on cpu.
Maybe I can propose a MR if it sounds interesting enough?
Our long term plan is to move the FusedLayerNorm code into upstream, so that Pytorch's LayerNorm on the GPU will make use of it automatically. However, that may take a while, because I've got a backlog of other tasks (Amp checkpointing, better support for fused optimizers, making apex pip-installable). I would be happy to accept an MR if that helps relieve code divergence in your script. I think the easiest thing would be to make the .cpu() version of FusedLayerNorm a thin wrapper around the existing upstream CPU LayerNorm. Calling .cpu() on FusedLayerNorm would then copy the buffers from the Cuda implementation to the Pytorch version.