Sometimes you need to set an environment variable before importing a package, for example:
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "4"
os.environ["WORLD_SIZE"] = "1"
import torch
See: https://discuss.pytorch.org/t/runtimeerror-device-0-device-num-gpus-internal-assert-failed/178118/6
My suggestion is to ignore E402 module-import-not-at-top-of-file if it comes after a os.environ statement, similar to #9047