Skip to main content
The key new idea is:
DQN code = trains the model
PyTorch Profiler = measures what takes time during training

1. Import Gymnasium

Gymnasium provides the CartPole environment.
creates the game. The agent sees a state containing 4 values:
It can choose 2 actions:

2. Import PyTorch

PyTorch is used for:
  • Tensors
  • Neural networks
  • Calculating loss
  • Backpropagation
  • Updating model parameters
  • Profiling

3. Import neural network tools

nn provides neural-network layers. For example:

4. Import optimizer

The optimizer updates the model’s weights. You’re using:

5. Create CartPole

This creates the environment. Think of it as:
The goal is to keep the pole balanced for as long as possible.

6. Create the DQN model

This is the neural network. Its structure is:
For example:
Meaning:
The agent would choose right.

7. Create optimizer

model.parameters()

Gets all trainable weights from the network.

lr=0.001

Learning rate. It controls how much the weights change after each training step.

8. Start the profiler

This is the major new part.
This tells PyTorch:
“While the following code is running, monitor and record what the program is doing.”

What is a profiler?

A profiler helps answer questions like:
Think of it like a performance monitoring tool for your ML code.

9. CPU profiling

This tells the profiler to monitor CPU operations. You’re currently not profiling GPU/CUDA operations. So:

10. record_shapes=True

This tells the profiler to record the shapes of tensors involved in operations. For example, it can help you see something like:
This is useful when debugging performance.

11. Start training

Everything inside:
gets profiled. Your training starts here:
You’re running only 5 episodes. This is intentionally small because profiling adds overhead.

12. Reset environment

Starts a new CartPole episode. You get the initial state. Example:

13. Maximum 100 steps

The agent can take up to 100 actions in each episode. So potentially:
up to around 500 environment steps, although an episode can terminate earlier.

14. Convert state to tensor

Gymnasium gives you numerical values. PyTorch’s neural network expects tensors. So:

15. Forward pass

This is called the forward pass. The state goes through the neural network:
Example:

16. Select action

argmax() finds the largest Q-value. If:
then:
So:
means:

17. Take the action

The agent sends the action to CartPole. The environment returns:
For example:

18. Calculate target

Here you’re using the immediate reward as the target. If:
then:

Important

This is not a complete DQN target calculation. A proper DQN would normally use something like: target=r+γmaxQ(s,a)target = r + \gamma \max Q(s',a') when the episode hasn’t ended. Your earlier code actually included the future Q-value. This simplified version does not.

19. Calculate loss

Suppose:
Then:
The model is trying to make:

20. Clear old gradients

PyTorch accumulates gradients by default. So before calculating new gradients, we clear the previous ones.

21. Backward pass

This performs backpropagation. It calculates gradients showing how the model’s parameters contributed to the loss. Conceptually:

22. Update model

Adam uses the calculated gradients to update the neural network’s parameters. So:
That’s the actual learning process.

23. Update state

The next state becomes the current state.
Then the process repeats.

24. Stop if episode ends

If the pole falls or the environment reaches its limit, stop that episode. Then the next episode starts.

25. Print profiler results

After training finishes:
This is where you see the profiling information.

prof.key_averages()

Groups similar operations together. Instead of showing every single call separately, it summarizes operations. For example:

.table()

Formats the results as a table.

sort_by="cpu_time_total"

Sorts operations according to their total CPU execution time. So the most expensive operations appear near the top.

row_limit=10

Only show the top 10 operations. You may see output conceptually similar to:
The exact numbers depend on your computer and run.

26. Close environment

This releases resources used by the CartPole environment.

The Important Difference From Your Previous Code

Your previous code was mainly about:
This code adds:
So you now have two concepts:

DQN

Profiler