TensorFlow と PyTorch の実装知識

eager と graph、train/eval、DataLoader、混合精度など、枠組みを実際に回すときの API と順序。理論の定義問題ではない。

同梱問題集の公開抜粋です。最初は問題と選択肢だけ出します。正解と解説は各問の「正解と解説を見る」を開くまで見えません。作者の既定表示は Ultra Practicebook、ライセンスは MIT です。試験団体の過去問や市販問題集の転載ではありません。

この問題集の位置づけ

損失関数が何か、という話は深層学習セットにあります。こちらは tf.function、GradientTape、model.eval()、clip_grad_norm_ のように、コードに名前が出る知識です。train() と no_grad() を同じだと思っていると、推論時の BatchNorm がバッチ統計のままになります。

言語設定は日本語 UI 向けですが、問題文は API 名が英語です。訳さずに識別子として読んでください。バージョンは TensorFlow 2 系と現行 PyTorch の一般的な用法に寄せています。古い TF 1.x の Session は出していません。間違えた API は、自分の訓練ループの該当行と突き合わせると残りやすいです。

学習目標

ゼログラッド → backward → step の順、eval と no_grad の役割の違い、Keras compile の三引数、DDP と DataParallel の差を、ドキュメントを開かなくても説明できるようにする。

対象者

チュートリアルどおりにモデルは動いたが、推論で Dropout が残る、勾配が溜まる、AMP で NaN が出る、といった事故を減らしたい人。E資格の数式セットでは触れない実装者向け。

学習方法

間違えた API は、自分のリポジトリの該当行と突き合わせる。解説の順序(zero_grad が先)をコメントとして残す。TensorFlow 問と PyTorch 問が交互に出るので、枠組み名を問題文で確認してから選ぶ。

問題

先に自分で選んでから、折りたたみを開いてください。解説は正解の言い換えだけでなく、隣の選択肢が文に入らない理由や、一緒に覚える連語を書いています。番号だけ暗記せず、解説の文を一度声に出してから次へ進んでください。

問 1

What is the default execution mode in TensorFlow 2.x?

  1. Graph Execution
  2. Eager Execution
  3. Lazy Execution
  4. XLA Execution
正解と解説を見る

正解: Eager Execution

TensorFlow 2.x defaults to Eager Execution, which runs operations immediately as Python statements are called. This improves debuggability and makes TF behave more like standard Python. 題は「What is the default execution mode in TensorFlow 2.x?」。

正解は 2。

選択肢は Graph Execution, Eager Execution, Lazy Execution, XLA Execution。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 2

In PyTorch, what is the correct order of steps in a standard training loop?

  1. loss.backward() -> optimizer.step() -> optimizer.zero_grad()
  2. optimizer.zero_grad() -> loss.backward() -> optimizer.step()
  3. optimizer.step() -> loss.backward() -> optimizer.zero_grad()
  4. optimizer.zero_grad() -> optimizer.step() -> loss.backward()
正解と解説を見る

正解: optimizer.zero_grad() -> loss.backward() -> optimizer.step()

Gradients must be zeroed before computing new ones to prevent accumulation from previous steps. Then loss.backward() computes gradients and optimizer.step() updates the weights. 題は「In PyTorch, what is the correct order of steps in a standard training loop?」。

正解は 2。

選択肢は loss.backward() -> optimizer.step() -> optimizer.zero_grad(), optimizer.zero_grad() -> loss.backward() -> optimizer.step(), optimizer.step() -> loss.backward() -> optimizer.zero_grad(), optimizer.zero_grad() -> optimizer.step() -> loss.backward()。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 3

Which PyTorch method sets a model into evaluation mode?

  1. model.freeze()
  2. model.predict()
  3. model.eval()
  4. model.inference()
正解と解説を見る

正解: model.eval()

model.eval() disables Dropout and switches BatchNorm to use running statistics instead of batch statistics. It should be paired with torch.no_grad() to also disable gradient tracking during inference. 題は「Which PyTorch method sets a model into evaluation mode?」。

正解は 3。

選択肢は model.freeze(), model.predict(), model.eval(), model.inference()。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 4

What does tf.function() do in TensorFlow?

  1. Converts a Python function into a TensorFlow static computation graph for faster execution
  2. Enables GPU memory allocation for a function
  3. Freezes the weights of a model
  4. Automatically tunes the learning rate
正解と解説を見る

正解: Converts a Python function into a TensorFlow static computation graph for faster execution

tf.function() traces the Python function and compiles it into a TensorFlow graph. This reduces Python overhead on repeated calls and enables XLA compilation for speed improvements. 題は「What does tf.function() do in TensorFlow?」。

正解は 1。

選択肢は Converts a Python function into a TensorFlow static computation graph for faster execution, Enables GPU memory allocation for a function, Freezes the weights of a model, Automatically tunes the learning rate。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 5

Which context manager in PyTorch disables gradient computation during inference?

  1. torch.no_grad()
  2. torch.disable_grad()
  3. torch.grad_off()
  4. torch.inference()
正解と解説を見る

正解: torch.no_grad()

torch.no_grad() prevents PyTorch from tracking operations for autograd, reducing memory usage and computation cost. It is typically used together with model.eval() during inference. 題は「Which context manager in PyTorch disables gradient computation during inference?」。

正解は 1。

選択肢は torch.no_grad(), torch.disable_grad(), torch.grad_off(), torch.inference()。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 6

What is the purpose of tf.GradientTape in TensorFlow?

  1. To record operations for automatic differentiation and manually compute gradients
  2. To visualize the model architecture
  3. To schedule the learning rate automatically
  4. To save model checkpoints during training
正解と解説を見る

正解: To record operations for automatic differentiation and manually compute gradients

tf.GradientTape records operations executed inside its context. Calling tape.gradient(loss, variables) computes the gradients of loss with respect to those variables. It is essential for custom training loops. 題は「What is the purpose of tf.GradientTape in TensorFlow?」。

正解は 1。

選択肢は To record operations for automatic differentiation and manually compute gradients, To visualize the model architecture, To schedule the learning rate automatically, To save model checkpoints during training。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 7

Which Keras method saves only the weights of a model?

  1. model.save('path')
  2. model.export('path')
  3. model.save_weights('path')
  4. tf.saved_model.save(model, 'path')
正解と解説を見る

正解: model.save_weights('path')

model.save_weights() stores only the weight values. model.save() stores the full model including architecture and optimizer state. Saving weights alone is useful when the architecture is defined separately. 題は「Which Keras method saves only the weights of a model?」。

正解は 3。

選択肢は model.save('path'), model.export('path'), model.save_weights('path'), tf.saved_model.save(model, 'path')。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 8

In PyTorch, what is the primary purpose of increasing num_workers in DataLoader?

  1. To increase the model parameter count
  2. To parallelize data loading across CPU processes and reduce GPU idle time
  3. To automatically increase the batch size
  4. To enable multi-GPU training
正解と解説を見る

正解: To parallelize data loading across CPU processes and reduce GPU idle time

num_workers specifies how many subprocesses are used for data loading. A higher value allows data to be prepared in parallel while the GPU is busy with the previous batch, reducing the data bottleneck. 題は「In PyTorch, what is the primary purpose of increasing num_workers in DataLoader?」。

正解は 2。

選択肢は To increase the model parameter count, To parallelize data loading across CPU processes and reduce GPU idle time, To automatically increase the batch size, To enable multi-GPU training。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 9

What is the main advantage of PyTorch's dynamic computation graph compared to TensorFlow 1.x's static graph?

  1. It always uses less memory
  2. It allows the graph to be modified at runtime enabling flexible debugging
  3. It runs faster on CPU without any configuration
  4. It automatically optimizes the model architecture
正解と解説を見る

正解: It allows the graph to be modified at runtime enabling flexible debugging

PyTorch builds the computation graph dynamically as operations execute (Define-by-Run). This allows standard Python control flow and makes debugging with tools like pdb straightforward. 題は「What is the main advantage of PyTorch's dynamic computation graph compared to Te」。

正解は 2。

選択肢は It always uses less memory, It allows the graph to be modified at runtime enabling flexible debugging, It runs faster on CPU without any configuration, It automatically optimizes the model architecture。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 10

In Keras, which three arguments are required when calling model.compile()?

  1. optimizer / loss / metrics
  2. layers / activations / dropout
  3. batch_size / epochs / shuffle
  4. input_shape / output_shape / units
正解と解説を見る

正解: optimizer / loss / metrics

model.compile() configures the model for training. optimizer specifies the update rule, loss defines the objective function, and metrics lists the evaluation criteria tracked during training and validation. 題は「In Keras, which three arguments are required when calling model.compile()?」。

正解は 1。

選択肢は optimizer / loss / metrics, layers / activations / dropout, batch_size / epochs / shuffle, input_shape / output_shape / units。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 11

Which method must be implemented when subclassing torch.nn.Module in PyTorch?

  1. run()
  2. call()
  3. forward()
  4. compute()
正解と解説を見る

正解: forward()

The forward() method defines the computation performed at every call. PyTorch's autograd engine automatically derives the backward pass from the operations recorded in forward(). 題は「Which method must be implemented when subclassing torch.nn.Module in PyTorch?」。

正解は 3。

選択肢は run(), call(), forward(), compute()。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 12

model.train() in PyTorch enables training-specific behavior in layers such as Dropout and BatchNorm.

正解と解説を見る

正解: true

model.train() sets the model to training mode, enabling stochastic Dropout and batch-level statistics in BatchNorm. This is the counterpart to model.eval() used during inference. 題は「model.train() in PyTorch enables training-specific behavior in layers such as Dr」。

正解は true。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 13

The Keras Functional API supports only sequential (linear) model architectures.

正解と解説を見る

正解: false

The Keras Functional API supports arbitrary DAG (Directed Acyclic Graph) architectures including multi-input, multi-output, and shared-layer models. Only the Sequential API is limited to linear stacks. 題は「The Keras Functional API supports only sequential (linear) model architectures.」。

正解は false。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 14

torch.no_grad() and model.eval() have identical effects on a PyTorch model.

正解と解説を見る

正解: false

model.eval() changes the behavior of layers such as Dropout and BatchNorm. torch.no_grad() disables gradient tracking to save memory and compute. Both are needed together for correct inference. 題は「torch.no_grad() and model.eval() have identical effects on a PyTorch model.」。

正解は false。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 15

What Python class must be subclassed to define a custom model in PyTorch?

正解と解説を見る

正解: torch.nn.Module

All custom models and layers in PyTorch are defined by subclassing torch.nn.Module and implementing the __init__() and forward() methods. 題は「What Python class must be subclassed to define a custom model in PyTorch?」。

正解は torch.nn.Module。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 16

What is the name of the TensorFlow Keras API used to build models by stacking layers linearly?

正解と解説を見る

正解: Sequential

tf.keras.Sequential allows building models by passing a list of layers or calling model.add(). It is limited to single-input single-output linear stacks of layers. 題は「What is the name of the TensorFlow Keras API used to build models by stacking la」。

正解は Sequential。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 17

Which PyTorch class implements the Adam optimization algorithm?

正解と解説を見る

正解: torch.optim.Adam

torch.optim.Adam implements the Adam optimizer, combining momentum and RMSProp-style per-parameter adaptive learning rates for efficient gradient-based optimization. 題は「Which PyTorch class implements the Adam optimization algorithm?」。

正解は torch.optim.Adam。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 18

Which PyTorch loss function is correct for binary classification with sigmoid output?

  1. torch.nn.CrossEntropyLoss()
  2. torch.nn.BCELoss()
  3. torch.nn.NLLLoss()
  4. torch.nn.MSELoss()
正解と解説を見る

正解: torch.nn.BCELoss()

BCELoss computes binary cross-entropy between the target and a predicted probability in [0, 1]. The model output must first pass through a sigmoid. BCEWithLogitsLoss combines sigmoid and BCE in one numerically stable operation.

問 19

What does tf.keras.callbacks.EarlyStopping do during training?

  1. Stops training when the monitored metric stops improving
  2. Reduces the learning rate after every epoch
  3. Saves the model weights after each epoch
  4. Terminates training after a fixed number of steps
正解と解説を見る

正解: Stops training when the monitored metric stops improving

EarlyStopping monitors a metric such as val_loss and halts training when it fails to improve for a specified number of epochs (patience). This prevents overfitting and unnecessary computation. 題は「What does tf.keras.callbacks.EarlyStopping do during training?」。

正解は 1。

選択肢は Stops training when the monitored metric stops improving, Reduces the learning rate after every epoch, Saves the model weights after each epoch, Terminates training after a fixed number of steps。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。

問 20

What interface must be implemented when subclassing torch.utils.data.Dataset?

  1. __init__ and __call__
  2. __len__ and __getitem__
  3. __iter__ and __next__
  4. __size__ and __fetch__
正解と解説を見る

正解: __len__ and __getitem__

__len__ returns the total number of samples and __getitem__ returns the sample at a given index. The resulting Dataset object is passed to DataLoader for batching, shuffling, and parallel loading. 題は「What interface must be implemented when subclassing torch.utils.data.Dataset?」。

正解は 2。

選択肢は __init__ and __call__, __len__ and __getitem__, __iter__ and __next__, __size__ and __fetch__。

カテゴリ DL の用語と、隣の分野の用語を取り違えない。

誤答は「近いが役割が違うサービス/手法/品詞」になっていることが多い。