apex icon indicating copy to clipboard operation
apex copied to clipboard

No speedup on RTX card, how apex affects loss function that uses long float?

Open ulorentz opened this issue 6 years ago • 2 comments

My network is a encoder-decoder type, where the encoder uses resnet blocks (so convolution and batch norm). The decoder uses convtranspose and convolution. I am training on RTX2070super, but the apex training is actually slower than the normal one, what may be the issue since my card has tensorcores? My network requires a custom loss function:

loss = self.loss_func(F.log_softmax(y, 1), yb.long())                                                                                                        

loss1 = self.loss_func(F.log_softmax(y1, 1),                              
                                   F.max_pool2d(yb, kernel_size=2, stride=2,          
                                   padding=0).long())                                                                                                                   
loss2 = self.loss_func(F.log_softmax(y2, 1),                              
                                   F.max_pool2d(yb, kernel_size=4, stride=4,          
                                   padding=0).long())                                                                                                                 

loss3 = self.loss_func(F.log_softmax(y3, 1),                              
                                   F.max_pool2d(yb, kernel_size=8, stride=8,          
                                   padding=0).long())                                                                                                                

loss4 = self.loss_func(F.log_softmax(y4, 1),                              
                                   F.max_pool2d(yb, kernel_size=16, stride=16,        
                                   padding=0).long())                                 
                                                                                 
avg_loss = (loss + (0.9*loss1) + (0.8*loss2) + (0.7*loss3) +              
                    (0.6*loss4))/5   

Where self.loss_func is nn.NLLLoss that appears to require long float as target. My original data target is actually natively float16, may be this conversion a bottleneck? How does apex affect pytorch loss function that use long? Is there any workaround?

ulorentz avatar May 12 '20 16:05 ulorentz

I don't think the target.long() path is something Apex can or should convert to FP16.

nn.NLLLoss with class-index targets expects integer class IDs, not floating-point targets. So in this example, yb.long() is converting the label map to the required integer dtype for the target. AMP primarily affects eligible floating-point ops; non-floating tensors are not candidates for Tensor Core acceleration.

The slowdown is probably not because NLLLoss uses long targets directly. More likely causes are:

  1. F.log_softmax + nll_loss are numerically sensitive loss-side ops, so they are normally kept in FP32 rather than accelerated through FP16 Tensor Cores.
  2. The code repeatedly runs max_pool2d(...).long() for four downsampled targets every step, which adds extra kernels/casts.
  3. Whether AMP gives a net speedup depends on whether the convolution/convtranspose work dominates the step. Small batches, dataloader overhead, target preprocessing, loss computation, or non-Tensor-Core-friendly shapes can erase the gain.

Possible workarounds:

  • Store/load segmentation targets as integer class IDs, preferably torch.long, instead of storing them as FP16 targets.
  • Convert targets once in the dataset/collate path or once per batch, not repeatedly inside each loss call.
  • Precompute the downsampled targets once per batch before calculating the five losses.
  • Consider nn.CrossEntropyLoss on raw logits instead of manually doing F.log_softmax + nn.NLLLoss, unless there is a specific reason to keep them separate.
  • Profile forward, loss, backward, optimizer, and dataloader time separately with CUDA synchronization. AMP only speeds up eligible floating-point compute, mostly conv/matmul-heavy parts of the model.

In short: the target should remain integer/long. Apex will not make class-index targets half precision; the useful optimization is reducing repeated target casts/pooling and checking whether the model compute actually dominates runtime.

LeSingh1 avatar May 14 '26 23:05 LeSingh1

Thanks for the detailed writeup. A few things are worth separating here.

nn.NLLLoss targets should be integer class indices, usually torch.long. Apex AMP should not convert those targets to fp16, because AMP only affects eligible floating-point tensors/ops. So the target being long is expected and not something Tensor Cores would accelerate.

Also, in Apex AMP, log_softmax and nll_loss are fp32-side ops for numerical stability. So the loss path here likely is not where Tensor Core speedup will come from.

The more likely issue is that the step is not dominated by Tensor-Core-eligible convolution work. This loss is computed at 5 scales, and each scale involves log_softmax, NLLLoss, plus target downsampling/casting. If that part of the step is a meaningful fraction of runtime, AMP can easily look slower even on an RTX card with Tensor Cores.

A few things to try:

  1. Convert labels once per batch instead of repeatedly inside every loss call.
  2. If the downsampled label maps are needed, precompute them once per batch and reuse them:
    yb_float = yb.float()
    yb1 = F.max_pool2d(yb_float, kernel_size=2, stride=2).long()
    yb2 = F.max_pool2d(yb_float, kernel_size=4, stride=4).long()
    yb3 = F.max_pool2d(yb_float, kernel_size=8, stride=8).long()
    yb4 = F.max_pool2d(yb_float, kernel_size=16, stride=16).long()
    
    assuming max-pooling class labels is the intended target-downsampling behavior.
  3. Consider using nn.CrossEntropyLoss on raw logits instead of F.log_softmax(...) + nn.NLLLoss(...). It is the standard equivalent formulation and avoids manually splitting the two operations.
  4. Profile the training step with CUDA synchronization and separate forward, loss, backward, optimizer, and dataloader timing. If the loss/target-preprocessing time dominates, AMP will not help much.
  5. Check that Apex was built with the relevant C++/CUDA extensions. For example:
    python -c "from apex.optimizers import FusedAdam; print('ok')"
    

So in short: the long target is correct. Apex should not make class-index targets fp16. The slowdown is more likely from loss-side fp32 work, repeated target preprocessing, non-Tensor-Core-friendly shapes, small batch size, dataloader overhead, or missing Apex extensions.

LeSingh1 avatar May 14 '26 23:05 LeSingh1