Skip to content
Kanishk.

Your T4 Is Lying to You: is_bf16_supported() and a Free 4x Speed-Up

Notes from fine-tuning a 3B model on free Kaggle GPUs: why torch.cuda.is_bf16_supported() says yes on a T4, how a profiler exposed emulated bf16 matmuls, and the one-line fix that cut training from 9 hours to 2.2.

Kanishk Sagar10 min read

TL;DR: On a T4, torch.cuda.is_bf16_supported() returns True, but the T4 has no bfloat16 hardware. If your training script picks bf16 "when supported", every matrix multiply runs through a slow emulation path. Nothing crashes and the loss curve looks normal. It's just 4 to 5 times slower than it should be. Checking the GPU's compute capability instead took our fine-tuning run from an estimated 9 hours down to 2.2. There's a 30-second check you can run on your own setup in section 5.


In this article, I want to walk through a performance bug we hit while fine-tuning Tiny Aya Global (a 3.35B-parameter multilingual model) into a banking assistant for a hackathon. The bug itself is a one-liner. What makes it worth writing about is that it's silent: no warning, no error, correct results. If you fine-tune on free Kaggle or Colab GPUs, there's a decent chance your script has the same line in it, or one of its cousins (section 6).

I'll go through how we noticed something was off, how a profiler pointed at the cause, the fix, how to check your own setup, and two memory traps we found along the way.

1. The setup

Our training job was a fairly standard LoRA fine-tune: Hugging Face transformers Trainer plus PEFT, rank-16 adapters on all attention and MLP projections, gradient checkpointing on, sequences of about 1,450 tokens. We ran it on Kaggle's free tier, which gives you two NVIDIA T4s (16 GB each) for up to 12 hours per session.

Like many training scripts, ours chose the precision like this:

Python
bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
dtype = torch.bfloat16 if bf16 else torch.float16

A quick refresher on the two 16-bit formats. Both use 16 bits per number, but they spend them differently. float16 (fp16) has 5 exponent bits and 10 mantissa bits: good precision, but a small range (the largest value is 65,504), so gradients can underflow and activations can overflow. That's why fp16 training uses a loss scaler, which multiplies the loss before the backward pass and divides the gradients afterwards. bfloat16 (bf16) keeps float32's 8 exponent bits and only 7 mantissa bits: less precision, but the same range as float32, so it rarely needs a scaler. That's why most modern recipes prefer bf16.

So the line above is reasonable: if the hardware supports bf16, use it. "If the hardware supports it" is the catch.

2. The symptom: slow, and nothing else

The first smoke run on a single T4 took about 51 seconds per optimizer step, with 4 samples per step. That's roughly 13 seconds per training example. For our ~2,000 training conversations over 2 epochs, the estimate came out at about 14 hours on one GPU. Moving to both T4s with DistributedDataParallel brought the estimate down to around 9 hours on real data: barely inside Kaggle's 12-hour session limit, and with no room for a second attempt.

Nothing looked wrong. The loss went down nicely, memory was fine, and there were no warnings. What made me suspicious was a simple sanity check. I timed the model outside the Trainer, on one sequence of the same length, in plain float16:

measurement (one T4, 1,450 tokens)time
forward pass, no gradients0.81 s
forward + backward, LoRA + gradient checkpointing3.0 s
one training step inside our Trainer setup~13 s

A 4x gap between "the model doing the work" and "the training loop doing the same work" is too large to blame on data loading or logging. Something inside the step was doing much more work than it should.

This comparison is the most useful habit I took away from the whole episode. A bare forward and backward pass takes ten lines to time, and it gives you a floor: if your training step is several times above it, something in the loop is wasting time.

3. Profiling it

PyTorch's built-in profiler is the quickest way to see where GPU time goes. We wrapped two training steps in a TrainerCallback:

Python
from transformers import TrainerCallback
import torch

class Profile(TrainerCallback):
    def on_step_begin(self, args, state, control, **kw):
        if state.global_step == 3:  # skip warm-up steps
            self.prof = torch.profiler.profile(
                activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA])
            self.prof.__enter__()

    def on_step_end(self, args, state, control, **kw):
        if state.global_step == 5:
            self.prof.__exit__(None, None, None)
            print(self.prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=10))

# trainer = Trainer(..., callbacks=[Profile()])

The top of the table told the whole story (shortened):

 
Name                                                  Self CUDA %   # of Calls
aten::mm                                                  84.25%         5548
void magma_sgemmEx_kernel<float, __nv_bfloat16, ...>      50.71%         2954
void magma_sgemmEx_kernel<float, __nv_bfloat16, ...>      32.16%         1514
aten::bmm                                                  4.66%          576

Matrix multiplies taking most of the time is expected in a transformer. Which kernel runs them is the clue. On a T4, a fast half-precision matmul runs on the tensor cores, in kernels with names like turing_fp16_s1688gemm or cutlass. Instead, about 83% of GPU time went to magma_sgemmEx<float, __nv_bfloat16>. That's a single-precision (FP32) matmul that reads bfloat16 inputs and converts them on the fly. In other words, bf16 emulated in software, on hardware that's roughly 8 times slower at FP32 than at fp16 with tensor cores.

4. Why is_bf16_supported() said yes

The T4 is a Turing GPU, compute capability 7.5. Native bfloat16 arithmetic arrived with Ampere (compute capability 8.0). So why did PyTorch say bf16 was supported?

Because in recent PyTorch versions the function has a parameter you probably never look at:

Python
def is_bf16_supported(including_emulation: bool = True):
    ...
    if torch.cuda.get_device_properties(device).major >= 8:
        return True
    if not including_emulation:
        return False
    # Finally try to create a bfloat16 device.
    return _check_bf16_tensor_supported(device)

By default it returns True whenever the GPU can create a bfloat16 tensor, even if it can't compute with one efficiently. That answers the question "can I use this dtype?". Our training script was really asking "should I train in this dtype?", and on a T4 the answer to that one is no.

Is your GPU affected? Anything below compute capability 8.0:

GPUwhere you meet itcompute capabilitynative bf16
Tesla T4Kaggle, Colab free tier, many clouds7.5no
V100older clouds and clusters7.0no
P100older Kaggle and clusters6.0no
RTX 20 seriesdesktops7.5no
A100 / A10G / A6000clouds, HF Jobs8.0 / 8.6 / 8.6yes
L4 / RTX 30 & 40 seriesclouds, desktops8.9 / 8.6 / 8.9yes
H100clouds9.0yes

5. The fix, and a 30-second check

Ask about the hardware directly:

Python
def native_bf16() -> bool:
    """True only on GPUs with bf16 hardware (compute capability >= 8, Ampere and newer)."""
    return torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8

(torch.cuda.is_bf16_supported(including_emulation=False) gives you the same answer.) Then make the model's dtype and the Trainer's mixed-precision flag agree:

Python
bf16 = native_bf16()
model = AutoModelForCausalLM.from_pretrained(
    model_id, dtype=torch.bfloat16 if bf16 else torch.float16)   # torch_dtype= on older transformers
args = TrainingArguments(..., bf16=bf16, fp16=not bf16)

On a T4 this loads the model in float16 and trains with fp16 mixed precision. The LoRA weights stay in float32 (PEFT does that by default), and the Trainer's loss scaler handles fp16's small range. We applied the fix in two places, the training script and our inference loader, because the same idiom was in both.

If you want to see the problem on your own machine first, this takes about 30 seconds in a notebook:

Python
import time, torch

print(torch.cuda.get_device_name(), torch.cuda.get_device_capability(),
      "is_bf16_supported:", torch.cuda.is_bf16_supported())

def bench(dtype, n=4096, reps=20):
    a = torch.randn(n, n, device="cuda", dtype=dtype); b = torch.randn(n, n, device="cuda", dtype=dtype)
    a @ b; torch.cuda.synchronize()
    t = time.time()
    for _ in range(reps): a @ b
    torch.cuda.synchronize()
    return 2 * n**3 * reps / (time.time() - t) / 1e12   # TFLOP/s

print(f"fp16 {bench(torch.float16):.1f} TFLOP/s   bf16 {bench(torch.bfloat16):.1f} TFLOP/s")

On a GPU with native bf16 the two numbers are close. On a T4 the bf16 number comes out several times lower, even though the first line just told you bf16 is "supported".

Here's what the fix did to our job, the same 160 training conversations on both T4s, before and after:

Bar chart: same model, same data, one line changed. On two Kaggle T4s, training took 7.8 seconds per episode with emulated bf16 versus 1.86 seconds with fp16, and a 106-episode validation pass took 300 seconds versus 64 seconds.
Figure 1.

The same job before and after the change. Training dropped from 7.8 to 1.86 seconds per example, and a validation pass over 106 examples from 300 to 64 seconds (that one also includes the logits fix from section 7). The loss curves matched: 1.41 → 0.89 in fp16 vs 1.47 → 0.87 in bf16 over the first 10 steps.

That's 4.2x faster training. The full run, 1,937 conversations for 2 epochs, finished in 2.2 hours instead of the projected 9. That left room in Kaggle's free weekly quota for evaluation and experiments we would otherwise have skipped.

One honest caveat about fp16. Many recent models were pretrained in bf16, and some produce activations larger than fp16 can represent. If that happens, you'll see the loss jump to nan or inf within the first few dozen steps, usually with the loss scaler repeatedly skipping steps. Tiny Aya Global trained cleanly in fp16 for us, but it's worth watching the first 50 steps whenever you switch a bf16-pretrained model to fp16. If it does overflow, a GPU with native bf16 is the clean fix.

6. Other ways bf16 sneaks onto a T4

The is_bf16_supported() line wasn't the only way we could have ended up here. Two others are just as quiet:

  • Loading with dtype="auto" (torch_dtype="auto" in older versions). This uses the dtype stored in the checkpoint's config, and many recent checkpoints are stored in bf16. The model then sits in bf16 on your T4 without any line of yours mentioning bf16. Check with next(model.parameters()).dtype after loading.
  • Copying bf16=True from a recipe written for an A100. TrainingArguments(bf16=True) on a T4 runs, it just runs slowly. Set the flag from native_bf16().

A two-line guard right before trainer.train() catches all three:

Python
if not native_bf16():
    assert not args.bf16 and next(model.parameters()).dtype != torch.bfloat16, "bf16 on a GPU without bf16"

7. Two memory traps from the same hunt

While profiling, we found two smaller issues worth knowing about if you fine-tune a model with a large vocabulary. Tiny Aya's vocabulary has 262,144 tokens.

Evaluation was keeping all the logits. Validation had a second problem on top of the precision bug. By default, Trainer.evaluate() keeps the model's logits for every example and gathers them across GPUs so it can pass them to compute_metrics. For a 1,450-token example and a 262k vocabulary, that's about 0.75 GB of float16 per example. We only wanted the loss, so:

Python
TrainingArguments(..., prediction_loss_only=True)

If you do need predictions for a metric, preprocess_logits_for_metrics lets you reduce them (for example to an argmax) before they're stored.

Batch size 2 ran out of memory because of the logits. Since 86% of every training example was the same fixed system prompt, our examples were all about the same length, so batching should have been cheap. Batch size 2 still ran out of memory on a 16 GB T4: the failed allocation was 2.6 to 3.2 GB, which is mostly the vocabulary-sized logits (and their float32 copy for the loss) of the extra sequence. With a vocabulary this size, the output layer sets the memory limit for long sequences. Turning gradient checkpointing off ran out of memory as well. We stayed at batch size 1 with 8 gradient-accumulation steps per GPU, which gives the same effective batch size of 16 across two GPUs.

8. Takeaways

If you fine-tune on a T4 (or any GPU below compute capability 8.0: V100, P100, RTX 20 series):

  1. Don't pick bf16 with is_bf16_supported() alone. Use the compute capability (>= 8), or pass including_emulation=False. On older GPUs, use fp16 with mixed precision.
  2. Make the model dtype and the Trainer flag agree, and check next(model.parameters()).dtype after loading: dtype="auto" can hand you bf16 without asking.
  3. Time a bare forward/backward before you trust a training step. If the loop is several times slower than the model, profile before you buy more GPU time.
  4. Read kernel names in the profiler. magma_sgemmEx<float, __nv_bfloat16> on a T4 means emulated bf16. Tensor-core kernels look different.
  5. Watch the first 50 steps after switching to fp16 for nan losses or skipped steps.
  6. With big vocabularies, set prediction_loss_only=True (or reduce logits with preprocess_logits_for_metrics), and expect the vocabulary-sized logits to set your batch-size limit.

The nice thing about this kind of bug is that fixing it costs nothing and makes every later experiment cheaper. The annoying thing is that nothing tells you it's there.


This came out of Desi Agent, a hackathon project where we fine-tuned Tiny Aya Global into a banking tool-calling agent for English, Hindi, Bengali, Hinglish and Banglish. The project write-up covers the rest.

Filed under machine learning, pytorch, gpu, fine tuning