Can you check for errors in my code? I need to know especially if i'm handling correctly the multiple environments in the ppo memory

import numpy as np
import torch, os, time, telegram, asyncio
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from lion_pytorch import Lion
from torch.distributions.categorical import Categorical
from torch.optim.lr_scheduler import StepLR
os.environ.setdefault('PATH', '')
from collections import deque
import gymnasium as gym
from gymnasium import spaces
import cv2
cv2.ocl.setUseOpenCL(False)
from gymnasium.vector import SyncVectorEnv

channel_id = "-1002031363666"
bot = telegram.Bot(token="<TRUFFLEHOG_REDACTED_TELEGRAMBOTTOKEN>")

async def send_message_to_channel(message_text):
    await bot.send_message(channel_id, message_text)

class TimeLimit(gym.Wrapper):
    def __init__(self, env, max_episode_steps=None):
        super(TimeLimit, self).__init__(env)
        self._max_episode_steps = max_episode_steps
        self._elapsed_steps = 0

    def step(self, ac):
        observation, reward, terminated, truncated, info = self.env.step(ac)
        done = terminated or truncated
        self._elapsed_steps += 1
        if self._elapsed_steps >= self._max_episode_steps:
            truncated = True
            info['TimeLimit.truncated'] = True
        return observation, reward, terminated, truncated, info

    def reset(self, **kwargs):
        self._elapsed_steps = 0
        return self.env.reset(**kwargs)


class NoopResetEnv(gym.Wrapper):
    def __init__(self, env, noop_max=30):
        """Sample initial states by taking random number of no-ops on reset.
        No-op is assumed to be action 0.
        """
        gym.Wrapper.__init__(self, env)
        self.noop_max = noop_max
        self.override_num_noops = None
        self.noop_action = 0
        assert env.unwrapped.get_action_meanings()[0] == 'NOOP'

    def reset(self, **kwargs):
        """ Do no-op action for a number of steps in [1, noop_max]."""
        self.env.reset(**kwargs)
        if self.override_num_noops is not None:
            noops = self.override_num_noops
        else:
            noops = self.unwrapped.np_random.integers(1, self.noop_max + 1)

            #noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) #pylint: disable=E1101
        assert noops > 0
        obs, info = None, None
        for _ in range(noops):
            obs, _, terminated, truncated, info = self.env.step(self.noop_action)
            done = terminated or truncated
            if done:
                obs, info = self.env.reset(**kwargs)
        return obs, info

    def step(self, ac):
        return self.env.step(ac)

class FireResetEnv(gym.Wrapper):
    def __init__(self, env):
        """Take action on reset for environments that are fixed until firing."""
        gym.Wrapper.__init__(self, env)
        assert env.unwrapped.get_action_meanings()[1] == 'FIRE'
        assert len(env.unwrapped.get_action_meanings()) >= 3

    def reset(self, **kwargs):
        self.env.reset(**kwargs)
        obs, _, terminated, truncated, info = self.env.step(1)
        done = terminated or truncated
        if done:
            self.env.reset(**kwargs)
        obs, _, terminated, truncated, info = self.env.step(2)
        done = terminated or truncated
        if done:
            self.env.reset(**kwargs)
        return obs, info

    def step(self, ac):
        return self.env.step(ac)

class EpisodicLifeEnv(gym.Wrapper):
    def __init__(self, env):
        """Make end-of-life == end-of-episode, but only reset on true game over.
        Done by DeepMind for the DQN and co. since it helps value estimation.
        """
        gym.Wrapper.__init__(self, env)
        self.lives = 0
        self.was_real_done  = True

    def step(self, action):
        obs, reward, terminated, truncated, info = self.env.step(action)
        done = terminated or truncated
        self.was_real_done = done
        # check current lives, make loss of life terminal,
        # then update lives to handle bonus lives
        lives = self.env.unwrapped.ale.lives()
        if lives < self.lives and lives > 0:
            # for Qbert sometimes we stay in lives == 0 condition for a few frames
            # so it's important to keep lives > 0, so that we only reset once
            # the environment advertises done.
            done = True
        self.lives = lives
        return obs, reward, terminated, truncated, info

    def reset(self, **kwargs):
        """Reset only when lives are exhausted.
        This way all states are still reachable even though lives are episodic,
        and the learner need not know about any of this behind-the-scenes.
        """
        if self.was_real_done:
            obs, info = self.env.reset(**kwargs)
        else:
            # no-op step to advance from terminal/lost life state
            obs, _, _, _, info = self.env.step(0)
        self.lives = self.env.unwrapped.ale.lives()
        return obs, info

class MaxAndSkipEnv(gym.Wrapper):
    def __init__(self, env, skip=4):
        """Return only every `skip`-th frame"""
        gym.Wrapper.__init__(self, env)
        # most recent raw observations (for max pooling across time steps)
        self._obs_buffer = np.zeros((2,)+env.observation_space.shape, dtype=np.uint8)
        self._skip       = skip

    def step(self, action):
        """Repeat action, sum reward, and max over last observations."""
        total_reward = 0.0
        done = None
        for i in range(self._skip):
            obs, reward, terminated, truncated, info = self.env.step(action)
            done = terminated or truncated
            if i == self._skip - 2: self._obs_buffer[0] = obs
            if i == self._skip - 1: self._obs_buffer[1] = obs
            total_reward += reward
            if done:
                break
        # Note that the observation on the done=True frame
        # doesn't matter
        max_frame = self._obs_buffer.max(axis=0)

        return max_frame, total_reward, terminated, truncated, info

    def reset(self, **kwargs):
        return self.env.reset(**kwargs)

class ClipRewardEnv(gym.RewardWrapper):
    def __init__(self, env):
        gym.RewardWrapper.__init__(self, env)

    def reward(self, reward):
        """Bin reward to {+1, 0, -1} by its sign."""
        return np.sign(reward)


class WarpFrame(gym.ObservationWrapper):
    def __init__(self, env, width=84, height=84, grayscale=True, dict_space_key=None):
        """
        Warp frames to 84x84 as done in the Nature paper and later work.

        If the environment uses dictionary observations, `dict_space_key` can be specified which indicates which
        observation should be warped.
        """
        super().__init__(env)
        self._width = width
        self._height = height
        self._grayscale = grayscale
        self._key = dict_space_key
        if self._grayscale:
            num_colors = 1
        else:
            num_colors = 3

        new_space = gym.spaces.Box(
            low=0,
            high=255,
            shape=(self._height, self._width, num_colors),
            dtype=np.uint8,
        )
        if self._key is None:
            original_space = self.observation_space
            self.observation_space = new_space
        else:
            original_space = self.observation_space.spaces[self._key]
            self.observation_space.spaces[self._key] = new_space
        assert original_space.dtype == np.uint8 and len(original_space.shape) == 3

    def observation(self, obs):
        if self._key is None:
            frame = obs
        else:
            frame = obs[self._key]

        if self._grayscale:
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        frame = cv2.resize(
            frame, (self._width, self._height), interpolation=cv2.INTER_AREA
        )
        if self._grayscale:
            frame = np.expand_dims(frame, -1)

        if self._key is None:
            obs = frame
        else:
            obs = obs.copy()
            obs[self._key] = frame
        return obs


class FrameStack(gym.Wrapper):
    def __init__(self, env, k):
        """Stack k last frames.

        Returns lazy array, which is much more memory efficient.

        See Also
        --------
        baselines.common.atari_wrappers.LazyFrames
        """
        gym.Wrapper.__init__(self, env)
        self.k = k
        self.frames = deque([], maxlen=k)
        shp = env.observation_space.shape
        self.observation_space = spaces.Box(low=0, high=255, shape=(shp[:-1] + (shp[-1] * k,)), dtype=env.observation_space.dtype)

    def reset(self):
        ob, info = self.env.reset()
        for _ in range(self.k):
            self.frames.append(ob)
        return self._get_ob(), info

    def step(self, action):
        ob, reward, terminated, truncated, info = self.env.step(action)
        done = terminated or truncated
        self.frames.append(ob)
        return self._get_ob(), reward, terminated, truncated, info

    def _get_ob(self):
        assert len(self.frames) == self.k
        return LazyFrames(list(self.frames))

class ScaledFloatFrame(gym.ObservationWrapper):
    def __init__(self, env):
        gym.ObservationWrapper.__init__(self, env)
        self.observation_space = gym.spaces.Box(low=0, high=1, shape=env.observation_space.shape, dtype=np.float32)

    def observation(self, observation):
        # careful! This undoes the memory optimization, use
        # with smaller replay buffers only.
        return np.array(observation).astype(np.float32) / 255.0

class LazyFrames(object):
    def __init__(self, frames):
        """This object ensures that common frames between the observations are only stored once.
        It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay
        buffers.

        This object should only be converted to numpy array before being passed to the model.

        You'd not believe how complex the previous solution was."""
        self._frames = frames
        self._out = None

    def _force(self):
        if self._out is None:
            self._out = np.concatenate(self._frames, axis=-1)
            self._frames = None
        return self._out

    def __array__(self, dtype=None):
        out = self._force()
        if dtype is not None:
            out = out.astype(dtype)
        return out

    def __len__(self):
        return len(self._force())

    def __getitem__(self, i):
        return self._force()[i]

    def count(self):
        frames = self._force()
        return frames.shape[frames.ndim - 1]

    def frame(self, i):
        return self._force()[..., i]

def make_atari(env_id, max_episode_steps=None, render=None):
    env = gym.make(env_id, render_mode=render)
    assert 'NoFrameskip' in env.spec.id
    env = NoopResetEnv(env, noop_max=30)
    env = MaxAndSkipEnv(env, skip=4)
    if max_episode_steps is not None:
        env = TimeLimit(env, max_episode_steps=max_episode_steps)
    return env

def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):
    """Configure environment for DeepMind-style Atari.
    """
    if episode_life:
        env = EpisodicLifeEnv(env)
    if 'FIRE' in env.unwrapped.get_action_meanings():
        env = FireResetEnv(env)
    env = WarpFrame(env)
    if scale:
        env = ScaledFloatFrame(env)
    if clip_rewards:
        env = ClipRewardEnv(env)
    if frame_stack:
        env = FrameStack(env, 4)
    return env


class PPOMemory:
    def __init__(self, batch_size):
        self.states = []
        self.probs = []
        self.vals = []
        self.actions = []
        self.rewards = []
        self.dones = []

        self.batch_size = batch_size

    def generate_batches(self):
        n_states = len(self.states)
        batch_start = np.arange(0, n_states, self.batch_size)
        indices = np.arange(n_states, dtype=np.int64)
        np.random.shuffle(indices)
        batches = [indices[i:i+self.batch_size] for i in batch_start]

        return np.array(self.states),\
                np.array(self.actions),\
                np.array(self.probs),\
                np.array(self.vals),\
                np.array(self.rewards),\
                np.array(self.dones),\
                batches

    def store_memory(self, states, actions, probs, vals, rewards, dones):
        self.states.extend(states)
        self.actions.extend(actions)
        self.probs.extend(probs)
        self.vals.extend(vals)
        self.rewards.extend(rewards)
        self.dones.extend(dones)

    def clear_memory(self):
        self.states = []
        self.probs = []
        self.actions = []
        self.rewards = []
        self.dones = []
        self.vals = []


class ActorConvNetwork_v2(nn.Module):

    def __init__(self, n_actions, input_dims, alpha,
                 fc1_dims=256, fc2_dims=256, chkpt_dir='tmp/ppo'):
        super(ActorConvNetwork_v2, self).__init__()

        def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
            nn.init.orthogonal_(layer.weight, std)
            nn.init.constant_(layer.bias, bias_const)
            return layer

        self.checkpoint_file = os.path.join(chkpt_dir, 'actor_torch_ppo')

        self.actor = nn.Sequential(
            layer_init(nn.Conv2d(4, 32, kernel_size=8, stride=4)),
            nn.ReLU(),
            layer_init(nn.Conv2d(32, 64, kernel_size=4, stride=2)),
            nn.ReLU(),
            layer_init(nn.Conv2d(64, 64, kernel_size=3, stride=1)),
            nn.ReLU(),
            nn.Flatten(),
            layer_init(nn.Linear(7 * 7 * 64, 512)),
            nn.ReLU(),
            layer_init(nn.Linear(512, n_actions), std=0.01),
            nn.Softmax(dim=-1)
        )

        self.optimizer = Lion(self.parameters(), lr=alpha)
        self.scheduler = StepLR(self.optimizer, step_size=1000, gamma=0.95)
        self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
        self.to(self.device)

    def forward(self, state):
        dist = self.actor(state).squeeze()
        dist = Categorical(dist)

        return dist

    def save_checkpoint(self):
        torch.save(self.state_dict(), self.checkpoint_file)

    def load_checkpoint(self):
        self.load_state_dict(torch.load(self.checkpoint_file))


class CriticConvNetwork_v2(nn.Module):
    def __init__(self, input_dims, alpha, fc1_dims=256, fc2_dims=256,
                 chkpt_dir='tmp/ppo'):
        super(CriticConvNetwork_v2, self).__init__()

        def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
            nn.init.orthogonal_(layer.weight, std)
            nn.init.constant_(layer.bias, bias_const)
            return layer

        self.checkpoint_file = os.path.join(chkpt_dir, 'critic_torch_ppo')
        self.critic = nn.Sequential(
            layer_init(nn.Conv2d(4, 32, kernel_size=8, stride=4)),
            nn.ReLU(),
            layer_init(nn.Conv2d(32, 64, kernel_size=4, stride=2)),
            nn.ReLU(),
            layer_init(nn.Conv2d(64, 64, kernel_size=3, stride=1)),
            nn.ReLU(),
            nn.Flatten(),
            layer_init(nn.Linear(7 * 7 * 64, 512)),
            nn.ReLU(),
            layer_init(nn.Linear(512, 1), std=1)
        )

        self.optimizer = Lion(self.parameters(), lr=alpha)
        self.scheduler = StepLR(self.optimizer, step_size=1000, gamma=0.95)
        self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
        self.to(self.device)

    def forward(self, state):
        value = self.critic(state)

        return value

class Agent:
    def __init__(self, n_actions, input_dims, gamma=0.99, alpha=0.0003, gae_lambda=0.95, policy_clip=0.2,
                 batch_size=64, n_epochs=10, ent_coeff=0.01, vf_coeff=0.5, max_norm_grad=0.5, import_models=False):
        self.gamma = gamma
        self.policy_clip = policy_clip
        self.n_epochs = n_epochs
        self.gae_lambda = gae_lambda
        self.vf_coeff = vf_coeff
        self.ent_coeff = ent_coeff
        self.max_norm_grad = max_norm_grad

        self.actor = ActorConvNetwork_v2(n_actions, input_dims, alpha)
        self.critic = CriticConvNetwork_v2(input_dims, alpha)

        if import_models:
            self.actor.load_checkpoint()
            self.critic.load_checkpoint()

        self.memory = PPOMemory(batch_size)
        self.batch_size = batch_size

    def remember(self, state, action, probs, vals, reward, done):
        self.memory.store_memory(state, action, probs, vals, reward, done)

    def save_models(self):
        print('... saving models ...')
        self.actor.save_checkpoint()
        self.critic.save_checkpoint()

    def load_models(self):
        print('... loading models ...')
        self.actor.load_checkpoint()
        self.critic.load_checkpoint()

    @torch.no_grad()
    def choose_action(self, observations):
        # observations shape: [num_envs, channels, height, width]
        states = torch.tensor(observations, dtype=torch.float).to(self.actor.device)

        dist = self.actor(states)
        values = self.critic(states)
        actions = dist.sample()

        probs = dist.log_prob(actions)
        # No need to squeeze or convert to items; keep tensors as-is
        # actions shape: [num_envs]
        # probs shape: [num_envs]
        # values shape: [num_envs]

        return actions.cpu().numpy(), probs.cpu().detach().numpy(), values.squeeze().cpu().detach().numpy()

    def compute_advantages(self, rewards, dones, values, batch_size, gamma=0.99, lambda_=0.95):
        advantages = np.zeros_like(rewards)
        last_adv = 0
        for t in reversed(range(len(rewards))):
            if dones[t]:
                next_non_terminal = 0
                next_value = 0
            else:
                next_non_terminal = 1
                if t + 1 < len(values):
                    next_value = values[t + 1]
                else:
                    next_value = 0  # Or use a bootstrap value if available
            delta = rewards[t] + gamma * next_value * next_non_terminal - values[t]
            advantages[t] = delta + gamma * lambda_ * next_non_terminal * last_adv
            last_adv = advantages[t]
        return advantages

    def learn(self):
        for _ in range(self.n_epochs):
            state_arr, action_arr, old_prob_arr, vals_arr, reward_arr, dones_arr, batches = self.memory.generate_batches()


            vals = torch.tensor(vals_arr, dtype=torch.float32).squeeze().to(self.actor.device)

            for batch in batches:
                self.actor.optimizer.zero_grad()
                self.critic.optimizer.zero_grad()

                states = torch.tensor(state_arr[batch], dtype=torch.float).to(self.actor.device)
                old_probs = torch.tensor(old_prob_arr[batch]).to(self.actor.device)
                actions = torch.tensor(action_arr[batch]).to(self.actor.device)


                advantages = self.compute_advantages(reward_arr[batch], dones_arr[batch], vals_arr[batch], self.batch_size)
                advantages_norm = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
                advantages_norm = torch.tensor(advantages_norm, dtype=torch.float32).to(self.actor.device)
                advantages = torch.tensor(advantages, dtype=torch.float32).to(self.actor.device)

                batch_vals = vals[batch]

                dist = self.actor(states)
                entropy = dist.entropy().mean()

                critic_value = self.critic(states).squeeze()

                new_probs = dist.log_prob(actions)
                prob_ratio = (new_probs - old_probs).exp()
                weighted_probs = advantages_norm * prob_ratio
                weighted_clipped_probs = torch.clamp(prob_ratio, 1 - self.policy_clip,
                                                 1 + self.policy_clip) * advantages_norm
                actor_loss = -torch.min(weighted_probs, weighted_clipped_probs).mean()

                returns = advantages + batch_vals
                critic_loss = (returns - critic_value) ** 2
                critic_loss = critic_loss.mean()

                total_loss = actor_loss + (self.vf_coeff * critic_loss) - (self.ent_coeff * entropy)
                total_loss.backward()

                torch.nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_norm_grad)
                self.actor.optimizer.step()
                self.critic.optimizer.step()
            self.actor.scheduler.step()
            self.critic.scheduler.step()

        self.memory.clear_memory()


total_number_steps = 1e7
learning_iteration = 0
num_envs = 8
num_step_per_iteration = num_envs * 2048
import_models = False
render = None

if __name__ == '__main__':
    def create_env(seed):
        def _init():
            env = make_atari("PongNoFrameskip-v4", 10000, render=render)
            env = wrap_deepmind(env, True, True, True, True)
            env.seed(seed)
            return env
        return _init

    envs = SyncVectorEnv([create_env(i) for i in range(num_envs)])
    agent = Agent(envs.single_action_space.n, [4, 84, 84], batch_size=64, ent_coeff=0.0, import_models=import_models)

    print(f"Training for {total_number_steps} steps.\n"
          f"---------------------\n"
          f"Parameter Recap\n"
          f"Number of step for iteration: {num_step_per_iteration}\n"
          f"Number of concurrent environments: {num_envs}\n"
          f"Step per environment before learning iteration: {num_step_per_iteration/num_envs}\n"
          f"---------------------\n"
          f"GLHF\n"
          )

    current_rewards = np.zeros(num_envs)  # Storing Environment Rewards for logging purposes.
    cumulative_rewards = np.zeros(num_envs)  # Tracking Reward for each environment.
    done_flags = np.zeros(num_envs, dtype=bool)

    start_training_time = time.time()  # Tracking time for logging purposes.

    observations, infos = envs.reset()  # First observation, start of training for ALL environments.
    observations = np.transpose(observations, [0, 3, 1, 2])  # [num_envs, channels, height, width]
    # TODO: Write wrapper to obtain transposed observation [num_envs, num_stack, h, w]

    for step in range(0, int(total_number_steps), num_envs):

        actions, probs, vals = agent.choose_action(observations)  # Sampling Action
        observations_, rewards, terminated, truncated, infos = envs.step(actions)  # Stepping the environment

        observations_ = np.transpose(observations_, [0, 3, 1, 2])  # As Above.
        dones = np.logical_or(terminated, truncated)  # done = truncated OR terminated, gym 0.26+
        cumulative_rewards += rewards  # [num_envs] Tracking scores.

        agent.remember(observations, actions, probs, vals, rewards, dones)
        # State, action, log_probs, values, rewards, dones. [num_envs] each.

        if np.any(dones):
            indices = np.where(dones)[0]
            current_rewards[indices] = cumulative_rewards[indices]
            cumulative_rewards[indices] = 0.0
            for idx in indices:
                if terminated[idx]:
                    final_obs = infos['final_observation'][idx]
                    final_obs = np.transpose(final_obs, [2, 0, 1])
                    final_obs_tensor = torch.tensor(final_obs, dtype=torch.float32).unsqueeze(0).to(agent.actor.device)
                    bootstrap_value = agent.critic(final_obs_tensor).detach().cpu().numpy()[0]
                    rewards[idx] += agent.gamma * bootstrap_value[0]
                else:
                    rewards[idx] += 0  # No bootstrap for truncated episodes
        if step % num_step_per_iteration == 0 and step != 0:

            print(f"Experience Collected. Learning.")
            agent.learn()
            learning_iteration += 1
            agent.save_models()
            mean_reward = np.mean(current_rewards)

            status = f"PongNoFrameskip-v4 - MultiEnv\n"\
                f"Learning Iteration: {learning_iteration}\n"\
                f"Reward: {mean_reward}\n"\
                f"Elapsed Time: {(time.time() - start_training_time)/60:.2f}\n"\
                f"Step: {step}\n"

            print(status)
            try:
                asyncio.get_event_loop().run_until_complete(
                    send_message_to_channel(
                        status
                    )
                )
            except:
                pass

        # Update the observations for environments that are not done
        observations = observations_