Bird
Raised Fist0
PyTorchml~20 mins

Dynamic computation graph advantage in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Dynamic computation graph advantage
Problem:You want to understand how dynamic computation graphs in PyTorch help when working with inputs of varying sizes or structures.
Current Metrics:N/A - This is a conceptual experiment focusing on model flexibility rather than accuracy metrics.
Issue:Static computation graphs (like in some other frameworks) require fixed input sizes and structures, making it hard to handle variable input lengths or conditional operations.
Your Task
Demonstrate how PyTorch's dynamic computation graph allows building a model that can handle inputs of different lengths and apply conditional operations during forward pass.
Use PyTorch only.
Do not use static graph frameworks.
Show model behavior with inputs of different sizes.
Hint 1
Hint 2
Hint 3
Solution
PyTorch
import torch
import torch.nn as nn

class DynamicModel(nn.Module):
    def __init__(self, input_size, hidden_size):
        super().__init__()
        self.rnn_cell = nn.RNNCell(input_size, hidden_size)
        self.fc = nn.Linear(hidden_size, 1)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)
        batch_size, seq_len, _ = x.size()
        hidden = torch.zeros(batch_size, self.rnn_cell.hidden_size)
        outputs = []
        for t in range(seq_len):
            input_t = x[:, t, :]
            hidden = self.rnn_cell(input_t, hidden)
            # Conditional operation: if mean of hidden > 0, apply ReLU else apply tanh
            if hidden.mean() > 0:
                activated = torch.relu(hidden)
            else:
                activated = torch.tanh(hidden)
            outputs.append(activated)
        # Stack outputs: (seq_len, batch_size, hidden_size) -> (batch_size, seq_len, hidden_size)
        outputs = torch.stack(outputs, dim=1)
        # Take last output for prediction
        last_output = outputs[:, -1, :]
        out = self.fc(last_output)
        return out

# Create model
model = DynamicModel(input_size=3, hidden_size=5)

# Example inputs with different sequence lengths
input1 = torch.randn(2, 4, 3)  # batch=2, seq_len=4, input_size=3
input2 = torch.randn(2, 6, 3)  # batch=2, seq_len=6, input_size=3

# Forward pass with input1
output1 = model(input1)
print(f"Output with seq_len=4: {output1}")

# Forward pass with input2
output2 = model(input2)
print(f"Output with seq_len=6: {output2}")
Implemented a custom RNNCell loop to process variable-length sequences dynamically.
Added a conditional inside the forward pass to apply different activations based on hidden state mean.
Demonstrated model can handle inputs of different sequence lengths without graph rebuilding.
Results Interpretation

Before: Static graph frameworks require fixed input sizes and fixed operations, making it hard to handle variable input lengths or conditional logic.

After: PyTorch's dynamic graph allows the model to run loops and conditionals during the forward pass, adapting to input size and data dynamically.

Dynamic computation graphs let you write models that can change their structure on the fly, making it easier to work with variable input sizes and conditional operations.
Bonus Experiment
Modify the model to handle batches where each sequence has a different length by padding and masking.
💡 Hint
Use PyTorch's pack_padded_sequence and pad_packed_sequence utilities to handle variable-length sequences efficiently.

Practice

(1/5)
1. What is the main advantage of a dynamic computation graph in PyTorch?
easy
A. It allows the model to change its structure during runtime based on input data.
B. It requires pre-defining the entire model graph before training.
C. It makes the model run faster by using static graphs.
D. It prevents any changes to the model once training starts.

Solution

  1. Step 1: Understand dynamic graph behavior

    Dynamic graphs build the model step-by-step as data flows, allowing changes during runtime.
  2. Step 2: Compare with static graphs

    Static graphs require the entire model to be fixed before running, unlike dynamic graphs.
  3. Final Answer:

    It allows the model to change its structure during runtime based on input data. -> Option A
  4. Quick Check:

    Dynamic graph = flexible model structure [OK]
Hint: Dynamic graphs let models adapt during runtime [OK]
Common Mistakes:
  • Confusing dynamic graphs with static graphs
  • Thinking model structure is fixed before training
  • Assuming dynamic graphs always run faster
2. Which PyTorch code snippet correctly creates a dynamic computation graph with gradient tracking for a simple addition?
easy
A. x = torch.tensor(2); y = torch.tensor(3); z = x + y
B. x = torch.tensor(2, graph_static=True); y = torch.tensor(3, graph_static=True); z = x + y
C. x = torch.tensor(2); y = torch.tensor(3); z = x * y
D. x = torch.tensor(2, requires_grad=True); y = torch.tensor(3, requires_grad=True); z = x + y

Solution

  1. Step 1: Identify dynamic graph creation

    In PyTorch, setting requires_grad=True enables tracking operations for dynamic graph.
  2. Step 2: Check code correctness

    x = torch.tensor(2, requires_grad=True); y = torch.tensor(3, requires_grad=True); z = x + y correctly sets requires_grad=True for tensors and adds them, building dynamic graph.
  3. Final Answer:

    x = torch.tensor(2, requires_grad=True); y = torch.tensor(3, requires_grad=True); z = x + y -> Option D
  4. Quick Check:

    requires_grad=True enables dynamic graph [OK]
Hint: Use requires_grad=True to track operations [OK]
Common Mistakes:
  • Missing requires_grad=True disables graph tracking
  • Using graph_static=True which is invalid
  • Confusing multiplication with addition
3. What will be the output of this PyTorch code snippet?
import torch
x = torch.tensor(1.0, requires_grad=True)
y = x * 2
if y.item() > 1.5:
    z = y * 3
else:
    z = y * 4
z.backward()
print(x.grad.item())
medium
A. 3.0
B. 6.0
C. 4.0
D. 2.0

Solution

  1. Step 1: Trace the computation graph

    x=1.0 with grad tracking; y = x*2 = 2.0; since y>1.5, z = y*3 = 6.0
  2. Step 2: Compute gradient with backward()

    dz/dx = dz/dy * dy/dx = 3 * 2 = 6; but PyTorch accumulates gradients, so x.grad = 6
  3. Final Answer:

    6.0 -> Option B
  4. Quick Check:

    Gradient = 6.0 [OK]
Hint: Follow operations and chain rule for gradients [OK]
Common Mistakes:
  • Ignoring the if condition effect
  • Confusing gradient with output value
  • Forgetting to call backward()
4. Identify the error in this PyTorch code that tries to use dynamic computation graph:
import torch
x = torch.tensor(2.0)
y = x * 3
z = y ** 2
z.backward()
print(x.grad)
medium
A. x tensor is missing requires_grad=True, so gradient is None.
B. Backward() is called on a non-scalar tensor causing error.
C. The power operator ** is not supported in PyTorch tensors.
D. The print statement syntax is incorrect.

Solution

  1. Step 1: Check requires_grad flag

    x is created without requires_grad=True, so no graph tracks operations on x.
  2. Step 2: Effect on backward()

    Calling backward() on z raises RuntimeError because no computation graph is tracked without requires_grad=True on x.
  3. Final Answer:

    x tensor is missing requires_grad=True, so gradient is None. -> Option A
  4. Quick Check:

    requires_grad=True needed for gradients [OK]
Hint: Always set requires_grad=True to track gradients [OK]
Common Mistakes:
  • Assuming backward() works without requires_grad
  • Thinking ** operator is invalid
  • Confusing print syntax errors
5. You want to build a PyTorch model that changes its forward pass based on input size dynamically. Which feature of dynamic computation graphs helps achieve this?
hard
A. Fixing the model architecture to a single shape for all inputs.
B. Pre-compiling the entire model graph before training starts.
C. Ability to define the computation graph on-the-fly during each forward pass.
D. Using static graph optimizations for faster inference.

Solution

  1. Step 1: Understand dynamic graph flexibility

    Dynamic graphs let you build the computation graph during each forward pass, adapting to input size.
  2. Step 2: Contrast with static graphs

    Static graphs require fixed architecture, so they can't adapt dynamically to input changes.
  3. Final Answer:

    Ability to define the computation graph on-the-fly during each forward pass. -> Option C
  4. Quick Check:

    Dynamic graph = on-the-fly graph building [OK]
Hint: Dynamic graphs build model each forward pass [OK]
Common Mistakes:
  • Confusing dynamic with static graph behavior
  • Thinking model must be fixed before training
  • Assuming static graphs allow input size changes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard