PyTorch 实现与追问

题集来源:Alireza Dirafzoon(alirezadir)收录项目:AIMLInterviews查看原题集

题目来源
Devinterview 其中第 85—146 题的题目索引来自 Devinterview,答案由 AIMLInterviews 重新撰写;原文的 50 题补充部分在此收录为 62 道,含拆分追问。

题目目录

156 道原题
  1. Implement the following function without Python loops: ```python def normalize_rows(x: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: """Standardize each row to zero mean and unit variance.""" ... ``` Requirements: - x has shape [batch_size, num_features]. - Preserve x's device and dtype. - Avoid division by zero. - Do not modify x in place.

    原题
  2. What should happen when a row has zero variance?

    原题
  3. How would this change for [B, C, H, W]?

    原题

    此追问承接前面的逐行标准化函数;四维输入未指定归一化的维度。

  4. view, reshape, squeeze, and unsqueeze?

    原题
  5. When can broadcasting be wrong?

    原题
  6. Write a reusable preprocessing component that replaces non-finite values, standardizes features using training statistics, works on CPU or GPU, saves its state, and prevents validation leakage.

    原题
  7. Implement binary precision, recall, and F1 from logits. Inputs may be on GPU, targets may contain only one class, no autograd graph should be created, and the result should contain Python floats.

    原题
  8. Implement one training epoch and a complete evaluation pass with correct modes, gradient handling, device placement, sample-weighted loss, empty-loader behavior, and final predictions.

    原题
  9. Review the following code: ```python def evaluate(model, loader): model.train() losses = [] for x, y in loader: prediction = model(x) loss = torch.nn.CrossEntropyLoss()(prediction, y) losses.append(loss) return torch.tensor(losses).mean().item() ```

    原题
  10. Write a function that splits a sequence into batches while optionally retaining the final incomplete batch.

    原题
  11. Implement a reproducible train/validation split without scikit-learn.

    原题
  12. Write a generator that lazily reads and transforms records from a large dataset.

    原题
  13. Flatten a nested dictionary while preserving a reversible mapping.

    原题
  14. Merge metric dictionaries and compute weighted averages.

    原题
  15. Implement an execution-time decorator.

    原题
  16. Design a registry for losses, optimizers, or preprocessing functions.

    原题
  17. Refactor a monolithic training script into testable modules.

    原题
  18. Define a typed configuration object.

    原题
  19. Make a utility deterministic without mutable global state.

    原题
  20. When should you use a dataclass, function, class, or abstract base class?

    原题
  21. What is wrong with mutable default arguments?

    原题
  22. Explain shallow versus deep copies with an ML configuration.

    原题
  23. Design errors for an invalid preprocessing shape or dtype.

    原题
  24. Accept either NumPy arrays or PyTorch tensors without unclear behavior.

    原题
  25. Compute the masked mean of [B, T, D] using a [B, T] mask.

    原题
  26. Compute pairwise cosine similarity for [N, D] and [M, D].

    原题
  27. Determine whether the true label is in the top-k predictions.

    原题
  28. Implement one-hot encoding without F.one_hot.

    原题
  29. Create label-smoothed targets.

    原题
  30. Compute a batched confusion matrix without per-example loops.

    原题
  31. Pad variable-length tensors and create a mask.

    原题
  32. Gather one class score per example from [B, C].

    原题
  33. Advanced indexing versus gather versus index_select?

    原题
  34. Diagnose CPU targets with GPU predictions.

    原题
  35. Explain contiguous tensors and .contiguous().

    原题
  36. Find the squeeze() batch-size-one bug.

    原题
  37. How do in-place operations affect autograd?

    原题
  38. Compare detach(), clone(), and torch.no_grad().

    原题
  39. Why can .item() slow a GPU loop?

    原题
  40. Implement fit, transform, and inverse_transform standardization.

    原题
  41. Normalize images with per-channel statistics.

    原题
  42. Implement a custom Dataset for numerical and categorical features.

    原题
  43. Write a collate_fn for variable-length sequences.

    原题
  44. Handle missing values without leakage.

    原题
  45. Handle an unseen category at inference.

    原题
  46. Where should preprocessing live?

    原题
  47. Make stochastic augmentation reproducible with DataLoader workers.

    原题
  48. Why might multiple DataLoader workers be slower?

    原题
  49. Pinned memory and non-blocking transfers?

    原题
  50. Implement binary accuracy from logits.

    原题
  51. Implement multiclass top-k accuracy.

    原题
  52. Micro, macro, and weighted F1?

    原题
  53. Masked mean squared error?

    原题
  54. MAPE and its failure cases?

    原题
  55. Confusion matrix without storing all predictions?

    原题
  56. Design a streaming metric.

    原题
  57. Why is averaging batch F1 wrong?

    原题
  58. Metrics for imbalanced fraud detection?

    原题
  59. How should a classification threshold be selected?

    原题
  60. Implement early stopping.

    原题
  61. Add gradient clipping.

    原题
  62. Add gradient accumulation.

    原题
  63. Add automatic mixed precision.

    原题
  64. Save and resume a checkpoint exactly.

    原题
  65. When should a learning-rate scheduler step?

    原题
  66. Freeze and later unfreeze a backbone.

    原题
  67. Why does validation differ between train() and eval()?

    原题
  68. Prevent gradients during validation.

    原题
  69. Calculate epoch loss with a smaller final batch.

    原题
  70. Handle a non-finite loss.

    原题
  71. Support classification and regression in one loop.

    原题
  72. Add callback hooks cleanly.

    原题
  73. Move nested batches to a device.

    原题
  74. Preserve input order and sample identifiers during prediction.

    原题
  75. Test a standardization utility, including constant features.

    原题
  76. Verify evaluation does not update model state.

    原题
  77. Compare CPU and GPU metric implementations.

    原题
  78. Test empty input, batch size one, and unexpected shapes.

    原题
  79. Use a tiny dataset to verify overfitting.

    原题
  80. Diagnose a loss that never changes.

    原题
  81. Diagnose validation changes across identical runs.

    原题
  82. Find a memory leak from retained graphs.

    原题
  83. Check gradients numerically.

    原题
  84. Verify identical predictions after checkpoint restoration.

    原题
  85. What is PyTorch, and how does it differ from frameworks such as TensorFlow?

    原题
  86. What are tensors in PyTorch?

    原题
  87. What is the difference between a Tensor and a Variable?

    原题
  88. How do you convert a NumPy array to a tensor?

    原题
  89. What is the purpose of .grad?

    原题
  90. What is CUDA, and how does it relate to PyTorch?

    原题
  91. How does autograd work?

    原题
  92. What are the main steps for creating a neural-network model?

    原题
  93. How does nn.Sequential differ from subclassing nn.Module?

    原题
  94. How do you implement a custom layer?

    原题
  95. What is the role of forward?

    原题
  96. What are optimizers, and how are they used?

    原题
  97. Why and when do you call zero_grad()?

    原题
  98. How do you implement learning-rate scheduling?

    原题
  99. Describe backpropagation in PyTorch.

    原题
  100. How does gradient clipping work, and why is it useful?

    原题
  101. How do you check whether a model is using the GPU?

    原题
  102. How do you monitor and reduce overfitting?

    原题
  103. What is batch normalization, and how does it affect training?

    原题
  104. How does PyTorch initialize neural-network weights?

    原题
  105. What common training problems occur, and how do you debug them?

    原题
  106. How do you build a DataLoader for a custom dataset?

    原题
  107. What are torchvision transforms used for?

    原题
  108. How do you preprocess time-series data for RNNs?

    原题
  109. What is data augmentation, and how is it implemented?

    原题
  110. How do you use GPUs for distributed PyTorch training?

    原题
  111. How do you implement transfer learning?

    原题
  112. Compare RNNs, LSTMs, and GRUs.

    原题
  113. What is TorchScript, and how does it help deployment?

    原题
  114. Implement a DataLoader for a CSV dataset.

    原题
  115. Demonstrate slicing, indexing, concatenation, and transposition.

    原题
  116. Create a feedforward MNIST model.

    原题
  117. Manually compute linear-regression gradients.

    原题
  118. Implement a CNN for image classification.

    原题
  119. Save and load a trained model.

    原题
  120. How do you handle imbalanced classes?

    原题
  121. How can PyTorch support real-time inference?

    原题
  122. When would you convert a model to ONNX?

    原题
  123. How would you deploy a model as a REST API?

    原题
  124. How do you fine-tune a pretrained model?

    原题
  125. What are GNNs, and how are they implemented in PyTorch?

    原题
  126. What are important NAS directions, and how can PyTorch support them?

    原题
  127. How are GANs implemented, and what makes them difficult?

    原题
  128. What is model quantization, and when is it useful?

    原题
  129. What role does PyTorch play in reinforcement learning?

    原题
  130. How do you create a custom C++ or CUDA operation?

    原题
  131. How should you discuss open-source contributions or community tools?

    原题
  132. How should you discuss a project where PyTorch was central?

    原题
  133. How do you improve experiment reproducibility?

    原题
  134. How can PyTorch Lightning simplify a PyTorch workflow?

    原题
  135. How would you normalize each row of a tensor without using a Python loop?

    原题
  136. What is the difference between view, reshape, and squeeze?

    原题
  137. How would you design a reusable preprocessing component?

    原题
  138. What is data leakage, and how do you prevent it during preprocessing?

    原题
  139. Explain precision, recall, and F1. When would you use each?

    原题
  140. Why is averaging F1 across batches usually incorrect?

    原题
  141. What are the essential steps in a PyTorch training loop?

    原题
  142. What is the difference between model.eval() and torch.no_grad() or torch.inference_mode()?

    原题
  143. What happens if you forget optimizer.zero_grad()?

    原题
  144. How would you refactor a monolithic ML script into clean modules?

    原题
  145. How would you write a utility that works on both CPU and GPU?

    原题
  146. What tests would you write for a tensor preprocessing or metric utility?

    原题
  147. What makes an ML utility reusable without excessive abstraction?

    原题
  148. Which validation belongs at module boundaries?

    原题
  149. When should a utility return tensors versus Python numbers?

    原题
  150. How do you keep preprocessing consistent across training, evaluation, and inference?

    原题
  151. How should an ML codebase be structured for independent testing?

    原题
  152. What can PyTorch control about reproducibility?

    原题
  153. How do you balance readable tensor code and vectorization?

    原题
  154. What should a training loop log?

    原题
  155. How do you review correctness across devices, dtypes, and shapes?

    原题
  156. What changes before moving notebook code into production?

    原题