Docsity

PyTorch Community Awards PyTorch Problem Solver Practice Exam, Exams of Technology

Toggle sidebar
bg1
PyTorch Community Awards PyTorch
Problem Solver Practice Exam
**Question 1.** Which PyTorch function converts a NumPy array to a tensor without copying
data?
A) `torch.from_numpy()`
B) `torch.tensor()`
C) `torch.as_tensor()`
D) `torch.frombuffer()`
Answer: A
Explanation: `torch.from_numpy()` creates a tensor that shares the same memory with the
NumPy array, avoiding a copy.
**Question 2.** In PyTorch, what does the `requires_grad=False` flag on a tensor indicate?
A) The tensor will be excluded from the computational graph.
B) The tensor’s gradients will be accumulated during backpropagation.
C) The tensor will be moved to the GPU automatically.
D) The tensor will be treated as a leaf node.
Answer: A
Explanation: Setting `requires_grad=False` tells autograd not to track operations on that tensor,
so it is omitted from the graph.
**Question 3.** Which broadcasting rule allows a tensor of shape `(5, 1, 3)` to be added to a
tensor of shape `(1, 4, 3)`?
A) Both tensors must have the same number of dimensions.
B) Dimensions are compared from the trailing end, and a size of 1 can be broadcast.
C) Only the first dimension can be broadcast.
D) Broadcasting is not possible for these shapes.
Answer: B
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download PyTorch Community Awards PyTorch Problem Solver Practice Exam and more Exams Technology in PDF only on Docsity!

Problem Solver Practice Exam

Question 1. Which PyTorch function converts a NumPy array to a tensor without copying data? A) torch.from_numpy() B) torch.tensor() C) torch.as_tensor() D) torch.frombuffer() Answer: A Explanation: torch.from_numpy() creates a tensor that shares the same memory with the NumPy array, avoiding a copy. Question 2. In PyTorch, what does the requires_grad=False flag on a tensor indicate? A) The tensor will be excluded from the computational graph. B) The tensor’s gradients will be accumulated during backpropagation. C) The tensor will be moved to the GPU automatically. D) The tensor will be treated as a leaf node. Answer: A Explanation: Setting requires_grad=False tells autograd not to track operations on that tensor, so it is omitted from the graph. Question 3. Which broadcasting rule allows a tensor of shape (5, 1, 3) to be added to a tensor of shape (1, 4, 3)? A) Both tensors must have the same number of dimensions. B) Dimensions are compared from the trailing end, and a size of 1 can be broadcast. C) Only the first dimension can be broadcast. D) Broadcasting is not possible for these shapes. Answer: B

Problem Solver Practice Exam

Explanation: Starting from the rightmost dimension, 3 matches 3, 1 can broadcast to 4, and 5 can broadcast to 1, yielding a result of shape (5, 4, 3). Question 4. Which method should be used to temporarily disable gradient computation for inference? A) torch.set_grad_enabled(False) B) torch.no_grad() C) torch.inference_mode() D) Both B and C are valid, but C is more performant. Answer: D Explanation: Both torch.no_grad() and torch.inference_mode() disable gradients, but inference_mode() adds extra optimizations for inference. Question 5. When moving a tensor to a GPU device, which statement is true? A) tensor.cuda() always returns a new tensor on the default GPU. B) tensor.to('cpu') moves the tensor back to CPU without copying. C) tensor.to(device) can accept a torch.device object or a string. D) Tensors cannot be moved after creation. Answer: C Explanation: tensor.to(device) accepts either a torch.device instance or a device string such as 'cuda:0'. Question 6. Which of the following correctly clears the CUDA cache to free unused memory? A) torch.cuda.empty_cache() B) torch.cuda.clear_memory()

Problem Solver Practice Exam

Question 9. How does nn.Sequential handle residual connections? A) It automatically adds skip connections. B) It cannot represent residual connections; you need a custom nn.Module. C) You can embed a nn.Identity layer to simulate a residual. D) Residuals are added via the forward method of the sequential container. Answer: B Explanation: nn.Sequential strictly stacks modules linearly; residual connections require explicit definition in a custom module. Question 10. Which container is best for storing a variable number of sub‑modules that need to be indexed by name? A) nn.ModuleList B) nn.ModuleDict C) Python list D) Python dict Answer: B Explanation: nn.ModuleDict holds modules with string keys, allowing name‑based access while registering them as parameters. Question 11. What is the effect of setting pin_memory=True in a DataLoader? A) Data will be copied to GPU memory automatically. B) Data will be allocated in page‑locked host memory, speeding up host‑to‑GPU transfer. C) The loader will use a single worker thread. D) It disables shuffling of the dataset. Answer: B

Problem Solver Practice Exam

Explanation: Pinning memory prevents the OS from swapping it out, enabling faster DMA transfers to the GPU. Question 12. Which of the following is a correct way to implement a custom dataset for time‑series data stored in multiple CSV files? A) Subclass torch.nn.Module and implement __len__ and __getitem__. B) Subclass torch.utils.data.Dataset and implement __len__ and __getitem__. C) Use torchvision.datasets.ImageFolder. D) Use torch.utils.data.DataLoader directly without a dataset class. Answer: B Explanation: Custom datasets inherit from torch.utils.data.Dataset and must define __len__ and __getitem__. Question 13. Which optimizer includes a “bias‑correction” term to counteract the initialization bias of first‑moment estimates? A) SGD B) Adam C) RMSprop D) Adagrad Answer: B Explanation: Adam computes bias‑corrected estimates for both first and second moments, improving early‑training stability. Question 14. In a learning rate scheduler, what does StepLR do? A) Reduces LR when a metric plateaus. B) Decreases LR by a factor every fixed number of epochs.

Problem Solver Practice Exam

A) To trace the model’s execution graph with example inputs. B) To convert Python control flow into TorchScript for deployment. C) To export the model to ONNX format. D) To compress the model weights. Answer: B Explanation: torch.jit.script parses Python code, including conditionals and loops, into TorchScript. Question 18. Which of the following statements about torch.nn.functional (often imported as F) is correct? A) Functions in F maintain state (e.g., learnable parameters). B) F provides stateless operations such as activations and loss functions. C) F is a subclass of nn.Module. D) Using F automatically registers layers in the model. Answer: B Explanation: torch.nn.functional contains pure functions without internal parameters; they operate on tensors directly. Question 19. How can you ensure reproducibility across runs when using CUDA? A) Set torch.backends.cudnn.deterministic = True only. B) Set seeds for random, numpy, and torch, and enable deterministic cuDNN. C) Use torch.set_printoptions to fix printing. D) Reinstall PyTorch each time. Answer: B

Problem Solver Practice Exam

Explanation: Full reproducibility requires seeding all RNGs and setting torch.backends.cudnn.deterministic = True (and optionally torch.backends.cudnn.benchmark = False). Question 20. Which method correctly saves only the model’s parameters to a file? A) torch.save(model, 'model.pth') B) torch.save(model.state_dict(), 'model.pth') C) torch.save(model.parameters(), 'model.pth') D) torch.save(model.modules(), 'model.pth') Answer: B Explanation: state_dict() returns a dictionary of all learnable parameters, which is the recommended way to checkpoint models. Question 21. What is the effect of calling tensor.detach()? A) It creates a new tensor that shares storage but is excluded from the autograd graph. B**) It copies the tensor to CPU memory. C) It clears the tensor’s gradient. D) It moves the tensor to GPU. Answer: A Explanation: detach() returns a tensor with the same data but without gradient tracking. Question 22. Which transform from torchvision.transforms randomly flips an image horizontally with a probability of 0.5? A) RandomVerticalFlip() B) RandomHorizontalFlip(p=0.5) C) RandomResizedCrop()

Problem Solver Practice Exam

B) Only GPU memory usage. C) Both CPU and GPU activities, including kernel execution times. D) Only the loss values per iteration. Answer: C Explanation: The profiler tracks detailed CPU and GPU events, helping identify performance bottlenecks. Question 26. Which loss function is best suited for training a regression model where outliers should have less influence? A) nn.MSELoss B) nn.L1Loss C) nn.SmoothL1Loss D) nn.BCEWithLogitsLoss Answer: C Explanation: SmoothL1Loss (Huber loss) behaves like L2 near zero error and like L1 for large errors, reducing outlier impact. Question 27. How can you convert a PyTorch model to ONNX format? A) torch.onnx.export(model, dummy_input, "model.onnx") B) torch.jit.trace(model, dummy_input).save("model.onnx") C) torch.save(model, "model.onnx") D) model.to_onnx("model.onnx") Answer: A Explanation: torch.onnx.export runs a forward pass with a sample input and writes the ONNX graph to a file.

Problem Solver Practice Exam

Question 28. Which of the following statements about torch.nn.ModuleList is true? A) It automatically registers the contained modules as parameters. B) It behaves like a Python list but does not register its elements. C) It can only contain nn.Linear layers. D) It requires a dictionary of modules as input. Answer: A Explanation: ModuleList is a list‑like container that registers each contained module, making their parameters learnable. Question 29. When using torch.utils.data.DataLoader, what does setting drop_last=True accomplish? A) It discards the last incomplete batch if the dataset size isn’t divisible by batch size. B) It shuffles the dataset before each epoch. C) It forces all batches to have the same size by padding. D) It enables multi‑GPU training. Answer: A Explanation: drop_last=True ensures every batch has exactly batch_size samples, which can be important for certain layers (e.g., BatchNorm). Question 30. What is the purpose of torch.nn.functional.dropout when training=False? A) It applies dropout regardless of mode. B) It becomes a no‑op (passes input unchanged). C) It raises an exception. D) It scales the activations by the dropout probability. Answer: B

Problem Solver Practice Exam

D) model.clip_gradients(2.0) Answer: A Explanation: clip_grad_norm_ rescales gradients so that their global norm does not exceed max_norm. Question 34. In the context of TorchServe, what is an “extra file”? A) A configuration file that defines model handlers. B) Any additional file (e.g., tokenizer, label map) packaged with the model archive. C) A log file generated during inference. D) The Python script that defines the model architecture. Answer: B Explanation: Extra files are bundled with the .mar archive to provide resources needed at inference time. Question 35. Which method is used to convert a model to TorchScript via tracing? A) torch.jit.script(model) B) torch.jit.trace(model, example_input) C) torch.jit.compile(model) D) torch.jit.convert(model) Answer: B Explanation: torch.jit.trace runs the model with a sample input to record the operations, producing a TorchScript graph. Question 36. What does the torch.nn.utils.parameters_to_vector function do? A) Converts a list of tensors into a single concatenated vector. B) Splits a vector into a list of parameters.

Problem Solver Practice Exam

C) Saves parameters to a file. D) Normalizes all parameters. Answer: A Explanation: It flattens and concatenates the parameters of a model into a single 1‑D tensor. Question 37. Which of the following is true about torch.autograd.grad? A) It computes gradients and stores them in tensor.grad. B) It returns the gradients as a tuple without modifying tensor.grad. C) It only works for scalar outputs. D) It cannot compute higher‑order gradients. Answer: B Explanation: torch.autograd.grad returns gradients directly and does not accumulate them in the .grad attribute. Question 38. What is the main advantage of using torch.nn.DataParallel over manually moving data to multiple GPUs? A) It automatically splits the model across GPUs (model parallelism). B) It handles gradient synchronization and device placement for you. C) It reduces memory consumption on each GPU. D) It enables mixed‑precision training automatically. Answer: B Explanation: DataParallel replicates the model on each GPU, splits input batches, and aggregates gradients automatically. Question 39. Which of the following transforms is deterministic and does not introduce randomness?

Problem Solver Practice Exam

Question 42. When using torch.nn.LSTM, what does setting batch_first=True change? A) The hidden state is returned first. B) Input tensors are expected in shape (batch, seq, features). C) The LSTM will process batches in parallel. D) It forces the use of GPU. Answer: B Explanation: batch_first=True expects the batch dimension as the first axis instead of the default (seq, batch, features). Question 43. Which method should be overridden to customize the behavior of a PyTorch Dataset that loads data lazily from disk? A) __init__ only B) __len__ only C) __getitem__ only D) Both __len__ and __getitem__ Answer: D Explanation: __len__ reports dataset size, while __getitem__ defines how each sample is retrieved; both are required. Question 44. In the context of gradient accumulation, why might you set optimizer.zero_grad(set_to_none=True) instead of the default zero_grad()? A) It reduces GPU memory usage by not allocating new tensors. B) It speeds up the backward pass. C) It clears gradients more aggressively, preventing overflow. D) It is required for mixed‑precision training.

Problem Solver Practice Exam

Answer: A Explanation: Setting gradients to None avoids creating zero tensors, saving memory and potentially improving speed. Question 45. Which of the following is a correct way to apply weight decay only to convolutional layers in a model? A) Use a single optimizer with weight_decay=0.01. B) Create parameter groups: one with conv parameters and weight_decay, another without. C) Manually zero out gradients of non‑conv layers. D) Set requires_grad=False for non‑conv layers. Answer: B Explanation: Parameter groups let you assign different hyper‑parameters (like weight decay) to subsets of parameters. Question 46. Which TorchMetrics class would you use to compute the top‑5 accuracy for a classification model? A) Accuracy() with top_k=5 B) TopKAccuracy(k=5) C) Precision() with average='macro' D) Recall() with average='micro' Answer: A Explanation: torchmetrics.Accuracy(top_k=5) computes top‑k accuracy; top_k=5 yields top‑ 5 accuracy. Question 47. What is the effect of calling model.eval() on a PyTorch model? A) It disables gradient computation for all parameters.

Problem Solver Practice Exam

Question 50. Which of the following is true about torch.nn.utils.spectral_norm? A) It adds a regularization term to the loss. B) It constrains the weight matrix’s spectral norm during training. C) It automatically prunes neurons. D) It converts the layer to a convolutional layer. Answer: B Explanation: Spectral normalization reparameterizes the weight matrix to have a bounded spectral norm, stabilizing GAN training. Question 51. What does the torch.backends.cuda.matmul.allow_tf32 flag control? A) Whether TensorFloat‑32 precision is permitted for matrix multiplications on Ampere GPUs. B) Whether TF‑IDF vectors are used in embedding layers. C) Whether the model can be exported to TensorFlow. D) Whether CUDA kernels are compiled at runtime. Answer: A Explanation: Setting this flag enables or disables the use of TF32, which offers speed gains with slight precision loss on supported hardware. Question 52. Which of the following is a correct way to log training metrics using TensorBoard in PyTorch? A) writer = SummaryWriter() then writer.add_scalar('Loss/train', loss, epoch) B) torch.utils.tensorboard.add_scalar('Loss', loss, epoch) C) tensorboard.log('Loss', loss) D) torch.log_scalar('Loss/train', loss, epoch) Answer: A

Problem Solver Practice Exam

Explanation: SummaryWriter from torch.utils.tensorboard provides the add_scalar method for logging. Question 53. When using torch.nn.Conv2d with padding='same' (available in PyTorch 2.0+), what is the effect? A) The output spatial size equals the input size when stride=1. B) The padding value is set to zero automatically. C) It disables bias in the convolution. D) It forces the kernel size to be odd. Answer: A Explanation: 'same' padding adds enough zeros so that, with stride 1, the output height and width match the input. Question 54. Which of the following statements about torch.nn.EmbeddingBag is correct? A) It computes the average of embeddings for each bag without requiring explicit padding. B) It only works with fixed‑size input sequences. C) It is a deprecated API. D) It requires gradients to be manually accumulated. Answer: A Explanation: EmbeddingBag aggregates (sum or mean) embeddings over variable‑length “bags”, handling padding efficiently. Question 55. What is the purpose of torch.nn.utils.clip_grad_value_? A) To clip gradients element‑wise to a maximum absolute value. B) To clip the global norm of gradients. C) To scale gradients by a constant factor.