A dynamic computation graph lets the model change its steps while running. This helps when data or tasks are different each time.
Dynamic computation graph advantage in PyTorch
import torch # Define a simple dynamic graph example def dynamic_graph_example(x): if x.sum() > 0: y = x * 2 else: y = x - 2 return y input_tensor = torch.tensor([1.0, -1.0, 2.0], requires_grad=True) output = dynamic_graph_example(input_tensor) output.backward(torch.ones_like(output)) print(output) print(input_tensor.grad)
Dynamic graphs are created on the fly during the forward pass.
PyTorch builds the graph as you run operations, so you can use normal Python control flow.
import torch def dynamic_graph_example(x): if x.sum() > 0: y = x * 2 else: y = x - 2 return y input_tensor = torch.tensor([1.0, -1.0, 2.0], requires_grad=True) output = dynamic_graph_example(input_tensor) print(output)
import torch def dynamic_graph_example(x): if x.sum() > 10: y = x * 3 else: y = x / 2 return y input_tensor = torch.tensor([2.0, 3.0, 4.0], requires_grad=True) output = dynamic_graph_example(input_tensor) print(output)
This program shows how the dynamic graph changes for two inputs: one with positive sum and one with negative sum. It prints outputs and gradients to see the effect.
import torch def dynamic_graph_example(x): if x.sum() > 0: y = x * 2 else: y = x - 2 return y # Create input tensors input_positive = torch.tensor([1.0, -1.0, 2.0], requires_grad=True) input_negative = torch.tensor([-3.0, -2.0, -1.0], requires_grad=True) print('Before backward:') print('input_positive:', input_positive) print('input_negative:', input_negative) # Forward pass output_positive = dynamic_graph_example(input_positive) output_negative = dynamic_graph_example(input_negative) print('\nOutputs:') print('output_positive:', output_positive) print('output_negative:', output_negative) # Backward pass output_positive.sum().backward() output_negative.sum().backward() print('\nGradients after backward:') print('input_positive.grad:', input_positive.grad) print('input_negative.grad:', input_negative.grad)
Dynamic graphs let you use normal Python code like if-else and loops inside model definitions.
They make debugging easier because errors show up immediately during the forward pass.
Dynamic graphs may be slower than static graphs for some tasks but are more flexible.
Dynamic computation graphs build the model step-by-step as data flows through.
This allows models to change behavior based on input or conditions.
PyTorch uses dynamic graphs, making it easy to write flexible and debuggable models.
Practice
Solution
Step 1: Understand dynamic graph behavior
Dynamic graphs build the model step-by-step as data flows, allowing changes during runtime.Step 2: Compare with static graphs
Static graphs require the entire model to be fixed before running, unlike dynamic graphs.Final Answer:
It allows the model to change its structure during runtime based on input data. -> Option AQuick Check:
Dynamic graph = flexible model structure [OK]
- Confusing dynamic graphs with static graphs
- Thinking model structure is fixed before training
- Assuming dynamic graphs always run faster
Solution
Step 1: Identify dynamic graph creation
In PyTorch, setting requires_grad=True enables tracking operations for dynamic graph.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.Final Answer:
x = torch.tensor(2, requires_grad=True); y = torch.tensor(3, requires_grad=True); z = x + y -> Option DQuick Check:
requires_grad=True enables dynamic graph [OK]
- Missing requires_grad=True disables graph tracking
- Using graph_static=True which is invalid
- Confusing multiplication with addition
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())Solution
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.0Step 2: Compute gradient with backward()
dz/dx = dz/dy * dy/dx = 3 * 2 = 6; but PyTorch accumulates gradients, so x.grad = 6Final Answer:
6.0 -> Option BQuick Check:
Gradient = 6.0 [OK]
- Ignoring the if condition effect
- Confusing gradient with output value
- Forgetting to call backward()
import torch x = torch.tensor(2.0) y = x * 3 z = y ** 2 z.backward() print(x.grad)
Solution
Step 1: Check requires_grad flag
x is created without requires_grad=True, so no graph tracks operations on x.Step 2: Effect on backward()
Calling backward() on z raises RuntimeError because no computation graph is tracked without requires_grad=True on x.Final Answer:
x tensor is missing requires_grad=True, so gradient is None. -> Option AQuick Check:
requires_grad=True needed for gradients [OK]
- Assuming backward() works without requires_grad
- Thinking ** operator is invalid
- Confusing print syntax errors
Solution
Step 1: Understand dynamic graph flexibility
Dynamic graphs let you build the computation graph during each forward pass, adapting to input size.Step 2: Contrast with static graphs
Static graphs require fixed architecture, so they can't adapt dynamically to input changes.Final Answer:
Ability to define the computation graph on-the-fly during each forward pass. -> Option CQuick Check:
Dynamic graph = on-the-fly graph building [OK]
- Confusing dynamic with static graph behavior
- Thinking model must be fixed before training
- Assuming static graphs allow input size changes
Ready to prove it?
Pass the test and this pattern moves unknown
