Is Transformers using GPU by default?

I’m instantiating a model with this

tokenizer = AutoTokenizer.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
model = AutoModelForSequenceClassification.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")

Then running a for loop to get prediction over 10k sentences on a G4 instance (T4 GPU). GPU usage (averaged by minute) is a flat 0.0%. What is wrong? How to use GPU with Transformers?

This like with every PyTorch model, you need to put it on the GPU, as well as your batches of inputs.

You can take a look at this issue How to make transformers examples use GPU? · Issue #2704 · huggingface/transformers · GitHub It includes an example for how to put your model on GPU.

device = "cuda:0" if torch.cuda.is_available() else "cpu"
sentence  = 'Hello World!'
tokenizer = AutoTokenizer.from_pretrained('bert-large-uncased')
model     = BertModel.from_pretrained('bert-large-uncased')

inputs    = tokenizer(sentence, return_tensors="pt").to(device)
model     = model.to(device)
outputs   = model(**inputs)

@sgugger

Are there any samples of how Huggingface Transformer finetuning should be done using GPU please?

Hi @sgugger were you able to figure this out?

I had the same issue - to answer this question, if pytorch + cuda is installed, an e.g. transformers.Trainer class using pytorch will automatically use the cuda (GPU) version without any additional specification.

(You can check if pytorch + cuda is installed by checking if the pytorch-cuda package is installed.)

Is there a way to explicitly disable the trainer from using the GPU? I see something about place_model_on_device on Trainer but it is unclear how to set it to False.

EDIT: Oh, I see I can set use_cpu in TrainingArguments to False.

With AutoModelForSequenceClassification.from_pretrained() as shown above, the model starts on the CPU. Move it to cuda:0 once, then move each batch of tokenized inputs to the same device.

For 10,000 sentences, I’d start with batches of 32 and measure sentences per second. Short, one-at-a-time predictions can make a one-minute GPU utilization average hard to interpret. Hugging Face

import torchmodel = model.to("cuda:0").eval()batch_size = 32predictions = []with torch.inference_mode():    for start in range(0, len(sentences), batch_size):        batch = sentences[start : start + batch_size]        inputs = tokenizer(            batch, padding=True, truncation=True, return_tensors="pt"        ).to(model.device)        label_ids = model(**inputs).logits.argmax(dim=-1).cpu().tolist()        predictions.extend(model.config.id2label[i] for i in label_ids)

If utilization still looks low, print model.device and inputs["input_ids"].device inside the loop. Both should show cuda:0.