apex icon indicating copy to clipboard operation
apex copied to clipboard

Make FusedLayerNorm cpu compatible

Open LamDang opened this issue 7 years ago • 3 comments

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.

LamDang avatar Apr 03 '19 15:04 LamDang

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

mcarilli avatar Apr 04 '19 04:04 mcarilli

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?

LamDang avatar Apr 04 '19 09:04 LamDang

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.

mcarilli avatar Apr 04 '19 23:04 mcarilli