Python / PyTorch Fundamentals Interview Questions
What are tensor data types (dtypes) in PyTorch and why do they matter?
Every tensor has a dtype that determines the numeric type and precision of its elements. Choosing the right dtype affects memory usage, computation speed, and numeric precision — a critical consideration when training on GPUs.
| dtype | Alias | Bits | Use case |
|---|---|---|---|
| torch.float32 | torch.float | 32 | Default for model weights and activations |
| torch.float64 | torch.double | 64 | High-precision numerical work |
| torch.float16 | torch.half | 16 | Mixed-precision training (GPU) |
| torch.bfloat16 | — | 16 | Modern GPUs (A100+); wider exponent than float16 |
| torch.int64 | torch.long | 64 | Indices, class labels, sequence lengths |
| torch.int32 | torch.int | 32 | General integer computation |
| torch.bool | — | 8 | Masks, boolean indexing |
| torch.uint8 | — | 8 | Image pixel values (0–255) |
import torch # Creating tensors with specific dtypes x = torch.tensor([1.0, 2.0], dtype=torch.float32) y = torch.tensor([1, 2, 3], dtype=torch.long) # class labels m = torch.tensor([True, False, True], dtype=torch.bool) # Casting between dtypes print(x.dtype) # torch.float32 x64 = x.double() # â float64 x16 = x.half() # â float16 xi = x.to(torch.int32) # â int32 # Default dtype (float32 for floats, int64 for ints) print(torch.tensor([1.0]).dtype) # torch.float32 print(torch.tensor([1]).dtype) # torch.int64 # Change global default torch.set_default_dtype(torch.float64) # rarely needed # Why dtype matters for loss computation: # CrossEntropyLoss expects: # input: float32 (logits) # target: int64 (class indices) loss_fn = torch.nn.CrossEntropyLoss() logits = torch.randn(4, 10) # float32 targets = torch.randint(0, 10, (4,)) # int64 loss = loss_fn(logits, targets) # works! # targets_wrong = targets.float() # would error!
Most common dtype errors: passing float64 weights into a model expecting float32, or passing float targets to a loss function expecting long (e.g. CrossEntropyLoss).
More Related questions...