Certainly! Below is a comprehensive implementation of an infinite-horizon Markov Decision Process (MDP) using PyTorch. The code adheres to PEP-8 standards, incorporates type hints, ensures efficiency, and includes robust error handling.
Overview
The implementation includes the following components:
- MDP Class: Represents the Markov Decision Process with states, actions, transition probabilities, cost function, and discount factor.
- Policy Class: Defines a stationary policy parameterized using PyTorch tensors, allowing for gradient-based optimization.
- Value Functions: Computes the state-value (
V) and action-value (Q) functions under a given policy.
- Policy Gradient Computation: Calculates the gradient of the expected discounted cost with respect to the policy parameters using the policy gradient theorem.
- Utility Functions: Includes methods for validating inputs and ensuring the probability distributions are correctly normalized.
Implementation
import torch
import torch.nn as nn
import torch.optim as optim
from typing import Dict, List, Tuple
import logging
# Configure logging for debugging and error messages
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class MDP:
"""
Represents an Infinite-Horizon Markov Decision Process (MDP).
"""
def __init__(
self,
states: List[str],
actions: List[str],
transition_prob: Dict[Tuple[str, str], Dict[str, float]],
cost: Dict[Tuple[str, str], float],
discount_factor: float,
):
"""
Initializes the MDP.
Args:
states (List[str]): List of states.
actions (List[str]): List of actions.
transition_prob (Dict[Tuple[str, str], Dict[str, float]]):
Transition probabilities P(s'|s,a).
cost (Dict[Tuple[str, str], float]):
Cost function c(s,a).
discount_factor (float):
Discount factor gamma, 0 < gamma < 1.
"""
self.states = states
self.num_states = len(states)
self.actions = actions
self.num_actions = len(actions)
self.state_to_idx = {state: idx for idx, state in enumerate(states)}
self.action_to_idx = {action: idx for idx, action in enumerate(actions)}
self.discount_factor = discount_factor
self.transition_prob = self._validate_transition_prob(transition_prob)
self.cost = self._validate_cost(cost)
def _validate_transition_prob(
self, transition_prob: Dict[Tuple[str, str], Dict[str, float]]
) -> torch.Tensor:
"""
Validates and converts transition probabilities to a tensor.
Args:
transition_prob: Transition probabilities P(s'|s,a).
Returns:
A tensor of shape (|S|, |A|, |S|).
"""
tensor = torch.zeros(
self.num_states, self.num_actions, self.num_states, dtype=torch.float32
)
for (state, action), probs in transition_prob.items():
if state not in self.state_to_idx:
logger.error(f"State '{state}' is not defined in states.")
raise ValueError(f"Invalid state: {state}")
if action not in self.action_to_idx:
logger.error(f"Action '{action}' is not defined in actions.")
raise ValueError(f"Invalid action: {action}")
s_idx = self.state_to_idx[state]
a_idx = self.action_to_idx[action]
total_prob = 0.0
for next_state, prob in probs.items():
if next_state not in self.state_to_idx:
logger.error(f"Next state '{next_state}' is not defined in states.")
raise ValueError(f"Invalid next state: {next_state}")
if prob < 0 or prob > 1:
logger.error(
f"Invalid probability value {prob} for transition."
)
raise ValueError("Transition probabilities must be in [0, 1].")
tensor[s_idx, a_idx, self.state_to_idx[next_state]] = prob
total_prob += prob
if not torch.isclose(torch.tensor(total_prob), torch.tensor(1.0)):
logger.error(
f"Transition probabilities for state '{state}' and action '{action}' do not sum to 1."
)
raise ValueError(
f"Transition probabilities for state '{state}' and action '{action}' must sum to 1."
)
return tensor
def _validate_cost(self, cost: Dict[Tuple[str, str], float]) -> torch.Tensor:
"""
Validates and converts cost function to a tensor.
Args:
cost: Cost function c(s,a).
Returns:
A tensor of shape (|S|, |A|).
"""
tensor = torch.zeros(self.num_states, self.num_actions, dtype=torch.float32)
for (state, action), c in cost.items():
if state not in self.state_to_idx:
logger.error(f"State '{state}' is not defined in states.")
raise ValueError(f"Invalid state: {state}")
if action not in self.action_to_idx:
logger.error(f"Action '{action}' is not defined in actions.")
raise ValueError(f"Invalid action: {action}")
if not (0.0 <= c <= 1.0):
logger.error(f"Cost {c} for state '{state}' and action '{action}' is out of [0,1].")
raise ValueError("Cost must be in [0, 1].")
s_idx = self.state_to_idx[state]
a_idx = self.action_to_idx[action]
tensor[s_idx, a_idx] = c
return tensor
def get_transition_prob(self, state: str, action: str) -> torch.Tensor:
"""
Retrieves the transition probabilities for a given state and action.
Args:
state (str): Current state.
action (str): Action taken.
Returns:
A tensor representing P(s'|s,a).
"""
if state not in self.state_to_idx:
logger.error(f"State '{state}' not recognized.")
raise ValueError(f"Invalid state: {state}")
if action not in self.action_to_idx:
logger.error(f"Action '{action}' not recognized.")
raise ValueError(f"Invalid action: {action}")
s_idx = self.state_to_idx[state]
a_idx = self.action_to_idx[action]
return self.transition_prob[s_idx, a_idx]
def get_cost(self, state: str, action: str) -> float:
"""
Retrieves the cost for a given state and action.
Args:
state (str): Current state.
action (str): Action taken.
Returns:
The cost associated with the state-action pair.
"""
if state not in self.state_to_idx:
logger.error(f"State '{state}' not recognized.")
raise ValueError(f"Invalid state: {state}")
if action not in self.action_to_idx:
logger.error(f"Action '{action}' not recognized.")
raise ValueError(f"Invalid action: {action}")
s_idx = self.state_to_idx[state]
a_idx = self.action_to_idx[action]
return self.cost[s_idx, a_idx].item()
class Policy(nn.Module):
"""
Represents a stationary policy π: S → Δ(A).
"""
def __init__(self, num_states: int, num_actions: int):
"""
Initializes the Policy.
Args:
num_states (int): Number of states |S|.
num_actions (int): Number of actions |A|.
"""
super(Policy, self).__init__()
# Initialize logits for each state-action pair
self.logits = nn.Parameter(torch.zeros(num_states, num_actions))
def forward(self) -> torch.Tensor:
"""
Computes the action probabilities using softmax.
Returns:
A tensor of shape (|S|, |A|) representing π(a|s).
"""
return torch.softmax(self.logits, dim=1)
def get_action_probabilities(self) -> torch.Tensor:
"""
Retrieves the action probability distribution π(a|s).
Returns:
A tensor of shape (|S|, |A|).
"""
return self.forward()
def get_action_distribution(self, state_idx: int) -> torch.distributions.Categorical:
"""
Retrieves the action distribution for a specific state.
Args:
state_idx (int): Index of the state.
Returns:
A Categorical distribution over actions.
"""
probs = self.forward()[state_idx]
return torch.distributions.Categorical(probs=probs)
def compute_q_values(
mdp: MDP, policy: Policy, tolerance: float = 1e-5, max_iterations: int = 1000
) -> torch.Tensor:
"""
Computes the Q-value function Q^π(s,a) for all state-action pairs using iterative policy evaluation.
Args:
mdp (MDP): The Markov Decision Process.
policy (Policy): The policy π.
tolerance (float): Convergence tolerance.
max_iterations (int): Maximum number of iterations.
Returns:
A tensor of shape (|S|, |A|) representing Q^π(s,a).
"""
V = torch.zeros(mdp.num_states, dtype=torch.float32)
Q = torch.zeros(mdp.num_states, mdp.num_actions, dtype=torch.float32)
pi = policy.get_action_probabilities()
for iteration in range(max_iterations):
V_prev = V.clone()
Q = mdp.cost + mdp.discount_factor * torch.matmul(mdp.transition_prob, V)
V = torch.sum(pi * Q, dim=1)
delta = torch.max(torch.abs(V - V_prev))
if delta.item() < tolerance:
logger.info(f"Q-value convergence achieved at iteration {iteration}.")
break
else:
logger.warning("Q-value did not converge within the maximum number of iterations.")
return Q
def compute_policy_gradient(
mdp: MDP,
policy: Policy,
initial_state_dist: torch.Tensor,
tolerance: float = 1e-5,
max_iterations: int = 1000,
) -> torch.Tensor:
"""
Computes the policy gradient ∇V^π_ρ using the policy gradient theorem.
Args:
mdp (MDP): The Markov Decision Process.
policy (Policy): The policy π.
initial_state_dist (torch.Tensor): Initial state distribution ρ of shape (|S|,).
tolerance (float): Convergence tolerance for value iteration.
max_iterations (int): Maximum number of iterations for value evaluation.
Returns:
A tensor of shape (|S|, |A|) representing ∇V^π_ρ.
"""
if initial_state_dist.shape[0] != mdp.num_states:
logger.error("Initial state distribution size does not match number of states.")
raise ValueError("Initial state distribution size mismatch.")
pi = policy.get_action_probabilities()
Q = compute_q_values(mdp, policy, tolerance, max_iterations)
# Compute discounted state-visitation distribution d^π_ρ
# Using d = (1 - γ) * (I - γ P_π)^-1 * ρ
P_pi = torch.zeros(mdp.num_states, mdp.num_states)
for s in range(mdp.num_states):
for a in range(mdp.num_actions):
P_pi[s] += pi[s, a] * mdp.transition_prob[s, a]
I = torch.eye(mdp.num_states)
try:
inv = torch.inverse(I - mdp.discount_factor * P_pi)
except RuntimeError as e:
logger.error("Matrix inversion failed. Check if (I - γ P_π) is invertible.")
raise ValueError("Matrix inversion failed.") from e
d = (1 - mdp.discount_factor) * torch.matmul(inv, initial_state_dist)
# Compute the gradient as (1 / (1 - γ)) * d * Q
gradient = (d.unsqueeze(1) / (1 - mdp.discount_factor)) * Q
return gradient
def example_usage():
"""
Demonstrates how to use the MDP and Policy classes to compute policy gradients.
"""
# Define states and actions
states = ["s0", "s1", "s2"]
actions = ["a0", "a1"]
# Define transition probabilities P(s'|s,a)
transition_prob = {
("s0", "a0"): {"s0": 0.5, "s1": 0.5},
("s0", "a1"): {"s1": 1.0},
("s1", "a0"): {"s0": 0.7, "s2": 0.3},
("s1", "a1"): {"s2": 1.0},
("s2", "a0"): {"s2": 1.0},
("s2", "a1"): {"s0": 0.4, "s1": 0.6},
}
# Define cost function c(s,a)
cost = {
("s0", "a0"): 0.2,
("s0", "a1"): 0.5,
("s1", "a0"): 0.3,
("s1", "a1"): 0.4,
("s2", "a0"): 0.1,
("s2", "a1"): 0.3,
}
# Define discount factor
gamma = 0.9
# Initialize MDP
mdp = MDP(states, actions, transition_prob, cost, gamma)
# Initialize Policy
policy = Policy(num_states=mdp.num_states, num_actions=mdp.num_actions)
# Define initial state distribution ρ
initial_state_dist = torch.tensor([1.0, 0.0, 0.0], dtype=torch.float32) # Starting at s0
# Compute policy gradient
gradient = compute_policy_gradient(mdp, policy, initial_state_dist)
logger.info(f"Policy Gradient:\n{gradient}")
# Example of updating the policy using the gradient
optimizer = optim.Adam(policy.parameters(), lr=0.01)
# Perform an optimization step
optimizer.zero_grad()
# Since we want to minimize the cost, we take the negative of the gradient
loss = torch.sum(gradient * policy.logits) # Example loss function
loss.backward()
optimizer.step()
logger.info("Policy updated using gradient.")
if __name__ == "__main__":
example_usage()
Explanation
-
MDP Class:
- Initialization (
__init__): Takes in the list of states, actions, transition probabilities, cost function, and discount factor. It validates the transition probabilities and the cost function to ensure they are well-defined and normalized.
- Validation Methods:
_validate_transition_prob and _validate_cost ensure that probabilities sum to 1 and that costs are within the range [0, 1].
- Accessor Methods:
get_transition_prob and get_cost provide easy access to transition probabilities and costs for specific state-action pairs.
-
Policy Class:
- Initialization (
__init__): Initializes the policy with learnable parameters (logits) for each state-action pair.
- Forward Method (
forward): Computes the action probabilities using the softmax function, ensuring that the probabilities form a valid distribution.
- Helper Methods:
get_action_probabilities and get_action_distribution provide access to the policy’s action probabilities and distributions.
-
Q-Value Computation (compute_q_values):
- Implements iterative policy evaluation to compute the Q-value function
Q^π(s,a) for all state-action pairs.
- Iteratively updates the value function
V until convergence based on the tolerance level.
-
Policy Gradient Computation (compute_policy_gradient):
- Utilizes the policy gradient theorem to compute the gradient of the expected discounted cost with respect to the policy parameters.
- Computes the discounted state-visitation distribution
d^π_ρ by solving the linear system (I - γ P_π) d = (1 - γ) ρ.
- Calculates the gradient as
(1 / (1 - γ)) * d * Q.
-
Example Usage (example_usage):
- Demonstrates how to initialize the MDP and Policy classes.
- Computes the policy gradient and performs a single optimization step to update the policy parameters using Adam optimizer.
- Logs relevant information for debugging and verification.
Error Handling
- Invalid Inputs: The code checks for invalid states, actions, transition probabilities that do not sum to 1, and costs outside the [0, 1] range.
- Matrix Inversion: Ensures that the matrix
(I - γ P_π) is invertible. If not, it raises a ValueError.
- Dimension Mismatch: Validates that the initial state distribution matches the number of states in the MDP.
Performance Considerations
- Tensor Operations: Utilizes efficient PyTorch tensor operations for matrix computations.
- Convergence Criteria: Uses a tolerance level to determine when iterative methods have sufficiently converged, preventing unnecessary computations.
- Vectorization: Avoids explicit Python loops where possible, leveraging PyTorch’s optimized backend for numerical operations.
Scalability
- The implementation is designed to handle large state and action spaces efficiently by leveraging PyTorch’s optimized tensor operations. However, for extremely large MDPs, further optimizations or approximations (such as function approximators for policies and value functions) might be necessary.
Conclusion
This implementation provides a robust and efficient framework for modeling and solving infinite-horizon MDPs using policy gradient methods in PyTorch. It ensures code maintainability, readability, and adherence to best practices, making it suitable for further extensions and integrations into larger projects.