Instruction

This homework covers Module 4: Reinforcement Learning.

Students may discuss homework exercises with one another. However, sharing, copying, or providing any part of a completed homework solution or code is an infraction of the University’s rules on Academic Integrity. Any violation will be punished as severely as possible. Final submissions must be uploaded to Gradescope using entry code XE3YJ6 (course ID 1370811). No email or hard copy will be accepted. For late submission policy and grading rubrics, please refer to the course website.

Question 1: Value Iteration in a Gridworld [20 pts]

Consider the following deterministic gridworld, inspired by Frozen Lake. The environment has 25 states arranged in a \(5 \times 5\) grid. Mario starts in the top-left cell, and Princess Toadstool is in the bottom-right cell. Our goal is to find a policy that maximizes the expected discounted return under the rules below.

The gridworld, with Mario at the start and Princess Toadstool at the goal.
The gridworld, with Mario at the start and Princess Toadstool at the goal.

The state is Mario’s current cell. You may represent it by a row and column pair or by an index from 1 to 25, numbering cells from left to right within each row. At every nonterminal state, the available actions are up, down, left, and right. Each action takes one time step and moves Mario one cell in the chosen direction, unless it would take him outside the grid.

The reward for each action is determined as follows:

Holes and turtles remain in place, and their penalties apply on every visit. Since the transition dynamics and rewards are known, you can use value iteration without simulating training data.

  1. Clearly define the state space, action space, transition dynamics, and reward function. Implement value iteration with discount factor \(\gamma=0.9\). Explain the main steps of your code, including the initialization and stopping criterion. Present the estimated optimal value function as a \(5 \times 5\) matrix arranged like the grid.

  2. Obtain a greedy policy by choosing, at each nonterminal state, an action that maximizes the immediate reward plus the discounted value of the next state. Display the policy on a \(5 \times 5\) grid using arrows or letters, and mark the goal separately. If several actions attain the same maximum, you may choose any one of them.

Question 2: Fitted Q-Iteration for Continuous Actions [30 pts]

In the lecture, we used fitted Q-iteration (FQI) to learn a CartPole policy with actions \(\{-1,+1\}\). In this question, extend the method to continuous actions \(A_t\in[-1,1]\), where the action specifies the direction and relative magnitude of the applied force.

Use the supplied CartPole simulator, with its initial-state distribution and termination rules. Use the binary safe-region reward (reward.method = "discrete") from the FQI lecture: the reward is 1 if both the next cart position and next pole angle are within 0.1 of zero, and 0 otherwise. Set \(\gamma=0.9\) and limit each rollout to 200 transitions. As in the notes, distinguish failure, which has zero continuation value, from the rollout cutoff, which only stops data collection.

  1. Implement a behavior policy that independently samples an action from \(\mathcal{N}(0,0.5^2)\) at each step and clips it to \([-1,1]\): values below \(-1\) are replaced by \(-1\), and values above \(1\) are replaced by \(1\). Generate 200 training episodes under this policy. Plot the distribution of the sampled actions and briefly explain the effect of clipping at the endpoints.

  2. Choose a regression method to approximate the Q-function and explain how you maximize the fitted Q-function over \([-1,1]\). One option is to evaluate it on a grid of action values that includes both endpoints. Another is to find the maximizer analytically when the model permits it. A model linear in the action generally selects an endpoint. To allow an interior optimum with a quadratic model, include a term quadratic in the action and compare any feasible stationary point with the endpoints. Squared state variables alone do not provide curvature in the action.

    Implement 20 FQI iterations starting from \(\widehat Q_0=0\), reusing the same training data throughout. Use your chosen maximization method both in the Bellman targets and to obtain the final greedy policy. Explain your model and tuning choices. Plot a diagnostic, such as changes in fitted Q-values on a fixed set of state-action pairs, and discuss whether the iterates stabilize or show signs of instability.

  3. Evaluate the learned policy and the behavior policy from part (a) using 50 new initial states sampled from the simulator’s initial-state distribution. Use the same initial states for both policies, the same reward, and the same 200-transition cutoff. Report the mean discounted return and mean episode length for each policy. Discuss whether the learned policy improves on the behavior policy and any limitations of your approach.

Question 3: REINFORCE [15 pts]

In the lecture, we introduced REINFORCE, which directly optimizes a parameterized policy using sampled trajectories. In this question, we will implement REINFORCE and examine the effect of adding a baseline.

Use the three-state MDP from the example One Logistic-Policy Update in the Policy Gradient Methods lecture, with the same transition matrices, rewards, and discount factor \(\gamma=0.7\). Each episode starts from state 1. For this exercise, use the expected discounted return over \(T=20\) steps as the objective, with \(R_t=r(S_t,A_t)\).

Consider the logistic policy

\[ \pi_\theta(1\mid s)=\frac{\exp(\theta_s)}{1+\exp(\theta_s)}, \qquad \pi_\theta(2\mid s)=1-\pi_\theta(1\mid s), \]

where \(\theta=(\theta_1,\theta_2,\theta_3)^T\). Initialize \(\theta=(0,0,0)^T\).

  1. [3 pts] Show that the derivative of the log-policy with respect to \(\theta_s\), when the current state is \(s\), is

    \[ \frac{\partial}{\partial\theta_s}\log\pi_\theta(A_t\mid s) = \mathbf{1}\{A_t=1\}-\pi_\theta(1\mid s). \]

    The derivatives with respect to parameters corresponding to other states are zero.

  2. [8 pts] Implement REINFORCE using simulated trajectories. Hold the policy parameters fixed while generating each episode. For each time point, calculate

    \[ G_t=\sum_{k=t}^{T-1}\gamma^{k-t}R_k, \]

    and, after the episode, update the policy parameters once using

    \[ \theta_{\mathrm{new}} = \theta+\eta\sum_{t=0}^{T-1} \gamma^tG_t\nabla_\theta\log\pi_\theta(A_t\mid S_t), \]

    where \(\eta>0\) is a learning rate of your choice. Evaluate all log-policy derivatives using the parameters that generated the episode.

    Train the policy using 500 episodes. Plot the average discounted episode return \(G_0\) over training, using averages over consecutive groups of 20 episodes. Report your learning rate and the final probability of choosing action 1 in each state.

  3. [4 pts] Repeat part (b), starting from the same initial parameters and using the same learning rate and episode budget, but with a constant baseline \(b=10\). That is, replace \(G_t\) by \(G_t-b\) in the REINFORCE update.

    Compare the training curves. Then hold each learned policy fixed and evaluate it using 100 new simulated episodes, each starting from state 1 and running for 20 steps. Report the mean discounted return for each policy. In your run, how did the baseline affect the training curve and final policy performance? Briefly discuss your findings; a constant baseline need not improve either.

Question 4: Policy Learning with MetaWorld [35 pts]

In this question, we will use MetaWorld, a robotic simulation benchmark containing 50 manipulation tasks, including opening doors, pulling drawers, pressing buttons, and moving objects (Yu et al., 2020). Our goal is to explore methods for learning a policy with a continuous, multidimensional action space in a chosen robotic task.

The following figure illustrates a sequence of frames from a successful door-opening trajectory in MetaWorld.

Example of a door-opening trajectory in MetaWorld.
Example of a door-opening trajectory in MetaWorld.

You are free to choose any one of the MetaWorld simulation environments.

Setup

You will need Python for this question. You may use VS Code, Jupyter Notebook, or any other Python development environment. We recommend a shared 64-bit Python 3.12 installation. The pinned MetaWorld version below supports Python 3.10 to 3.13.

On Windows, install Python 3.12 from python.org if needed. Then run the following in PowerShell:

py -3.12 -m pip install --user `
  "metaworld==3.1.1" "gymnasium==1.4.0" `
  "mujoco==3.3.0" matplotlib

On macOS or Linux, use the corresponding Python 3.12 installation:

python3.12 -m pip install --user \
  "metaworld==3.1.1" "gymnasium==1.4.0" \
  "mujoco==3.3.0" matplotlib

These commands install packages for your user account. Make sure your editor or notebook uses the same Python installation. The example below has been tested on Windows with Python 3.12; MetaWorld officially lists Linux and macOS as supported platforms. Windows users may also use WSL.

The following example generates one trajectory using a random policy in the door-open-v3 environment.

import gymnasium as gym
import metaworld

env = gym.make(
    "Meta-World/MT1",
    env_name="door-open-v3",
    seed=123,
    max_episode_steps=200,
    terminate_on_success=False,
)
env.action_space.seed(124)

state, info = env.reset()
total_reward = 0
success = False

for t in range(200):
    action = env.action_space.sample()
    next_state, reward, terminated, truncated, info = env.step(action)

    total_reward += reward
    success = success or bool(info.get("success", 0))
    state = next_state

    if terminated or truncated:
        break

print("Total reward:", total_reward)
print("Success:", success)

env.close()

The constructor seed controls the environment and task selection; the action space is seeded separately. In MetaWorld 3.1.1, passing a seed only to reset() does not reseed the underlying simulator. You may choose another task, such as drawer-open-v3, button-press-v3, or faucet-open-v3. Refer to the MetaWorld website for additional information.

  1. [5 pts] Choose one MetaWorld simulation environment and briefly describe its state space, action space, reward function, and objective. Generate trajectories using a random policy and summarize its performance.

  2. [10 pts] Choose a reinforcement learning algorithm to learn a policy for your selected environment. You may use any method discussed in class or another suitable method. The action space is continuous and multidimensional, so searching over many combinations of actions can require large amounts of data and computation. Try to find a more efficient way to represent or optimize over this action space. You may consider dimension reduction, a structured parameterization of the actions or policy, or another approach of your own. Explain how your method handles the action space, justify your choices, and discuss the implications for data requirements and computational cost. You are encouraged to explore your own ideas.

  3. [10 pts] Implement your algorithm and train a policy using the simulator. Clearly explain your approach, including the choices of function approximation, tuning parameters, and other relevant implementation details. Provide appropriate training diagnostics and discuss what they show.

  4. [10 pts] Evaluate your learned policy and a random policy in the simulator using at least 20 new episodes for each. Use the same episode cutoff and task distribution for both policies, and report the cutoff. Compare their mean cumulative rewards and success rates, counting an episode as successful if the simulator reports success at any step. Present your results using figures and tables. You can also visualize a representative trajectory, similar to the figure above. The main objective is to explore and evaluate ideas for learning a policy with a complex action space, rather than to achieve the best possible performance. Clear explanations and sound reasoning are sufficient to earn full credit. Explain what you tried, what the results suggest about your approach, and possible improvements, including reasons for limited performance when relevant.

This is an open-ended question. You are encouraged to use AI tools to help with this task, following the disclosure and responsibility requirements in the instructions. Include your Python code, figures, and tables.

Reference: Yu, T., Quillen, D., He, Z., Julian, R., Hausman, K., Finn, C., and Levine, S. (2020). Meta-World: A Benchmark and Evaluation for Multi-Task and Meta Reinforcement Learning. Proceedings of the Conference on Robot Learning, 1094-1100.