id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
158,616
import aiohttp from udemy_enroller.logger import get_logger logger = get_logger() The provided code snippet includes necessary dependencies for implementing the `http_get` function. Write a Python function `async def http_get(url, headers=None)` to solve the following problem: Send REST get request to the url passed in. :param url: The Url to get call get request on :param headers: The headers to pass with the get request :return: data if any exists Here is the function: async def http_get(url, headers=None): """ Send REST get request to the url passed in. :param url: The Url to get call get request on :param headers: The headers to pass with the get request :return: data if any exists """ if headers is None: headers = {} try: async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers) as response: text = await response.read() return text except Exception as e: logger.error(f"Error in get request: {e}")
Send REST get request to the url passed in. :param url: The Url to get call get request on :param headers: The headers to pass with the get request :return: data if any exists
158,617
import logging import logging.config import os from udemy_enroller.utils import get_app_dir class CustomFileHandler(logging.FileHandler): """Allows us to log to the app directory.""" def __init__(self, file_name="app.log", mode="a"): """Initialize.""" log_file_path = os.path.join(get_app_dir(), file_name) super(CustomFileHandler, self).__init__(log_file_path, mode) The provided code snippet includes necessary dependencies for implementing the `load_logging_config` function. Write a Python function `def load_logging_config() -> None` to solve the following problem: Load logging configuration. :return: None Here is the function: def load_logging_config() -> None: """ Load logging configuration. :return: None """ my_logger = logging.getLogger("udemy_enroller") my_logger.setLevel(logging.INFO) # File handler file_handler = CustomFileHandler() log_format = "%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(message)s" formatter = logging.Formatter(fmt=log_format) file_handler.setFormatter(formatter) my_logger.addHandler(file_handler) # Basic format for streamhandler stream_handler = logging.StreamHandler() simple_format = logging.Formatter(fmt="%(message)s") stream_handler.setFormatter(simple_format) my_logger.addHandler(stream_handler)
Load logging configuration. :return: None
158,618
import logging import logging.config import os from udemy_enroller.utils import get_app_dir The provided code snippet includes necessary dependencies for implementing the `get_logger` function. Write a Python function `def get_logger() -> logging.Logger` to solve the following problem: Get the app logger. :return: An instance of the app logger Here is the function: def get_logger() -> logging.Logger: """ Get the app logger. :return: An instance of the app logger """ return logging.getLogger("udemy_enroller")
Get the app logger. :return: An instance of the app logger
158,619
import json import os import re import time from dataclasses import dataclass, field from enum import Enum from functools import wraps from typing import Dict, List import requests from bs4 import BeautifulSoup from cloudscraper import create_scraper from udemy_enroller.logger import get_logger from udemy_enroller.settings import Settings from udemy_enroller.utils import get_app_dir The provided code snippet includes necessary dependencies for implementing the `format_requests` function. Write a Python function `def format_requests(func)` to solve the following problem: Handle requests response. Here is the function: def format_requests(func): """Handle requests response.""" @wraps(func) def formatting(*args, **kwargs): result = func(*args, **kwargs) result.raise_for_status() return result.json() return formatting
Handle requests response.
158,620
import os from pathlib import Path import shutil import sys from sphinx.application import Sphinx from sphinx.ext.autosummary import Autosummary from sphinx.pycode import ModuleAnalyzer sys.path.insert(0, str(PROJECT_PATH)) import pytorch_forecasting The provided code snippet includes necessary dependencies for implementing the `get_by_name` function. Write a Python function `def get_by_name(string: str)` to solve the following problem: Import by name and return imported module/function/class Args: string (str): module/function/class to import, e.g. 'pandas.read_csv' will return read_csv function as defined by pandas Returns: imported object Here is the function: def get_by_name(string: str): """ Import by name and return imported module/function/class Args: string (str): module/function/class to import, e.g. 'pandas.read_csv' will return read_csv function as defined by pandas Returns: imported object """ class_name = string.split(".")[-1] module_name = ".".join(string.split(".")[:-1]) if module_name == "": return getattr(sys.modules[__name__], class_name) mod = __import__(module_name, fromlist=[class_name]) return getattr(mod, class_name)
Import by name and return imported module/function/class Args: string (str): module/function/class to import, e.g. 'pandas.read_csv' will return read_csv function as defined by pandas Returns: imported object
158,621
import os from pathlib import Path import shutil import sys from sphinx.application import Sphinx from sphinx.ext.autosummary import Autosummary from sphinx.pycode import ModuleAnalyzer import pytorch_forecasting def skip(app, what, name, obj, skip, options): """ Document __init__ methods """ if name == "__init__": return True return skip class ModuleAutoSummary(Autosummary): def get_items(self, names): new_names = [] for name in names: mod = sys.modules[name] mod_items = getattr(mod, "__all__", mod.__dict__) for t in mod_items: if "." not in t and not t.startswith("_"): obj = get_by_name(f"{name}.{t}") if hasattr(obj, "__module__"): mod_name = obj.__module__ t = f"{mod_name}.{t}" if t.startswith("pytorch_forecasting"): new_names.append(t) new_items = super().get_items(sorted(new_names)) return new_items def setup(app: Sphinx): app.add_css_file("custom.css") app.connect("autodoc-skip-member", skip) app.add_directive("moduleautosummary", ModuleAutoSummary) app.add_js_file("https://buttons.github.io/buttons.js", **{"async": "async"})
null
158,622
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `integer_histogram` function. Write a Python function `def integer_histogram( data: torch.LongTensor, min: Union[None, int] = None, max: Union[None, int] = None ) -> torch.Tensor` to solve the following problem: Create histogram of integers in predefined range Args: data: data for which to create histogram min: minimum of histogram, is inferred from data by default max: maximum of histogram, is inferred from data by default Returns: histogram Here is the function: def integer_histogram( data: torch.LongTensor, min: Union[None, int] = None, max: Union[None, int] = None ) -> torch.Tensor: """ Create histogram of integers in predefined range Args: data: data for which to create histogram min: minimum of histogram, is inferred from data by default max: maximum of histogram, is inferred from data by default Returns: histogram """ uniques, counts = torch.unique(data, return_counts=True) if min is None: min = uniques.min() if max is None: max = uniques.max() hist = torch.zeros(max - min + 1, dtype=torch.long, device=data.device).scatter( dim=0, index=uniques - min, src=counts ) return hist
Create histogram of integers in predefined range Args: data: data for which to create histogram min: minimum of histogram, is inferred from data by default max: maximum of histogram, is inferred from data by default Returns: histogram
158,623
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `groupby_apply` function. Write a Python function `def groupby_apply( keys: torch.Tensor, values: torch.Tensor, bins: int = 95, reduction: str = "mean", return_histogram: bool = False ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]` to solve the following problem: Groupby apply for torch tensors Args: keys: tensor of groups (``0`` to ``bins``) values: values to aggregate - same size as keys bins: total number of groups reduction: either "mean" or "sum" return_histogram: if to return histogram on top Returns: tensor of size ``bins`` with aggregated values and optionally with counts of values Here is the function: def groupby_apply( keys: torch.Tensor, values: torch.Tensor, bins: int = 95, reduction: str = "mean", return_histogram: bool = False ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Groupby apply for torch tensors Args: keys: tensor of groups (``0`` to ``bins``) values: values to aggregate - same size as keys bins: total number of groups reduction: either "mean" or "sum" return_histogram: if to return histogram on top Returns: tensor of size ``bins`` with aggregated values and optionally with counts of values """ if reduction == "mean": reduce = torch.mean elif reduction == "sum": reduce = torch.sum else: raise ValueError(f"Unknown reduction '{reduction}'") uniques, counts = keys.unique(return_counts=True) groups = torch.stack([reduce(item) for item in torch.split_with_sizes(values, tuple(counts))]) reduced = torch.zeros(bins, dtype=values.dtype, device=values.device).scatter(dim=0, index=uniques, src=groups) if return_histogram: hist = torch.zeros(bins, dtype=torch.long, device=values.device).scatter(dim=0, index=uniques, src=counts) return reduced, hist else: return reduced
Groupby apply for torch tensors Args: keys: tensor of groups (``0`` to ``bins``) values: values to aggregate - same size as keys bins: total number of groups reduction: either "mean" or "sum" return_histogram: if to return histogram on top Returns: tensor of size ``bins`` with aggregated values and optionally with counts of values
158,624
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `profile` function. Write a Python function `def profile(function: Callable, profile_fname: str, filter: str = "", period=0.0001, **kwargs)` to solve the following problem: Profile a given function with ``vmprof``. Args: function (Callable): function to profile profile_fname (str): path where to save profile (`.txt` file will be saved with line profile) filter (str, optional): filter name (e.g. module name) to filter profile. Defaults to "". period (float, optional): frequency of calling profiler in seconds. Defaults to 0.0001. Here is the function: def profile(function: Callable, profile_fname: str, filter: str = "", period=0.0001, **kwargs): """ Profile a given function with ``vmprof``. Args: function (Callable): function to profile profile_fname (str): path where to save profile (`.txt` file will be saved with line profile) filter (str, optional): filter name (e.g. module name) to filter profile. Defaults to "". period (float, optional): frequency of calling profiler in seconds. Defaults to 0.0001. """ import vmprof from vmprof.show import LinesPrinter # profiler config with open(profile_fname, "wb+") as fd: # start profiler vmprof.enable(fd.fileno(), lines=True, period=period) # run function function(**kwargs) # stop profiler vmprof.disable() # write report to disk if kwargs.get("lines", True): with open(f"{os.path.splitext(profile_fname)[0]}.txt", "w") as f: with redirect_stdout(f): LinesPrinter(filter=filter).show(profile_fname)
Profile a given function with ``vmprof``. Args: function (Callable): function to profile profile_fname (str): path where to save profile (`.txt` file will be saved with line profile) filter (str, optional): filter name (e.g. module name) to filter profile. Defaults to "". period (float, optional): frequency of calling profiler in seconds. Defaults to 0.0001.
158,625
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `get_embedding_size` function. Write a Python function `def get_embedding_size(n: int, max_size: int = 100) -> int` to solve the following problem: Determine empirically good embedding sizes (formula taken from fastai). Args: n (int): number of classes max_size (int, optional): maximum embedding size. Defaults to 100. Returns: int: embedding size Here is the function: def get_embedding_size(n: int, max_size: int = 100) -> int: """ Determine empirically good embedding sizes (formula taken from fastai). Args: n (int): number of classes max_size (int, optional): maximum embedding size. Defaults to 100. Returns: int: embedding size """ if n > 2: return min(round(1.6 * n**0.56), max_size) else: return 1
Determine empirically good embedding sizes (formula taken from fastai). Args: n (int): number of classes max_size (int, optional): maximum embedding size. Defaults to 100. Returns: int: embedding size
158,626
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `create_mask` function. Write a Python function `def create_mask(size: int, lengths: torch.LongTensor, inverse: bool = False) -> torch.BoolTensor` to solve the following problem: Create boolean masks of shape len(lenghts) x size. An entry at (i, j) is True if lengths[i] > j. Args: size (int): size of second dimension lengths (torch.LongTensor): tensor of lengths inverse (bool, optional): If true, boolean mask is inverted. Defaults to False. Returns: torch.BoolTensor: mask Here is the function: def create_mask(size: int, lengths: torch.LongTensor, inverse: bool = False) -> torch.BoolTensor: """ Create boolean masks of shape len(lenghts) x size. An entry at (i, j) is True if lengths[i] > j. Args: size (int): size of second dimension lengths (torch.LongTensor): tensor of lengths inverse (bool, optional): If true, boolean mask is inverted. Defaults to False. Returns: torch.BoolTensor: mask """ if inverse: # return where values are return torch.arange(size, device=lengths.device).unsqueeze(0) < lengths.unsqueeze(-1) else: # return where no values are return torch.arange(size, device=lengths.device).unsqueeze(0) >= lengths.unsqueeze(-1)
Create boolean masks of shape len(lenghts) x size. An entry at (i, j) is True if lengths[i] > j. Args: size (int): size of second dimension lengths (torch.LongTensor): tensor of lengths inverse (bool, optional): If true, boolean mask is inverted. Defaults to False. Returns: torch.BoolTensor: mask
158,627
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn def next_fast_len(size): """ Returns the next largest number ``n >= size`` whose prime factors are all 2, 3, or 5. These sizes are efficient for fast fourier transforms. Equivalent to :func:`scipy.fftpack.next_fast_len`. Implementation from pyro :param int size: A positive number. :returns: A possibly larger number. :rtype int: """ try: return _NEXT_FAST_LEN[size] except KeyError: pass assert isinstance(size, int) and size > 0 next_size = size while True: remaining = next_size for n in (2, 3, 5): while remaining % n == 0: remaining //= n if remaining == 1: _NEXT_FAST_LEN[size] = next_size return next_size next_size += 1 The provided code snippet includes necessary dependencies for implementing the `autocorrelation` function. Write a Python function `def autocorrelation(input, dim=0)` to solve the following problem: Computes the autocorrelation of samples at dimension ``dim``. Reference: https://en.wikipedia.org/wiki/Autocorrelation#Efficient_computation Implementation copied form `pyro <https://github.com/pyro-ppl/pyro/blob/dev/pyro/ops/stats.py>`_. :param torch.Tensor input: the input tensor. :param int dim: the dimension to calculate autocorrelation. :returns torch.Tensor: autocorrelation of ``input``. Here is the function: def autocorrelation(input, dim=0): """ Computes the autocorrelation of samples at dimension ``dim``. Reference: https://en.wikipedia.org/wiki/Autocorrelation#Efficient_computation Implementation copied form `pyro <https://github.com/pyro-ppl/pyro/blob/dev/pyro/ops/stats.py>`_. :param torch.Tensor input: the input tensor. :param int dim: the dimension to calculate autocorrelation. :returns torch.Tensor: autocorrelation of ``input``. """ # Adapted from Stan implementation # https://github.com/stan-dev/math/blob/develop/stan/math/prim/mat/fun/autocorrelation.hpp N = input.size(dim) M = next_fast_len(N) M2 = 2 * M # transpose dim with -1 for Fourier transform input = input.transpose(dim, -1) # centering and padding x centered_signal = input - input.mean(dim=-1, keepdim=True) # Fourier transform freqvec = torch.view_as_real(rfft(centered_signal, n=M2)) # take square of magnitude of freqvec (or freqvec x freqvec*) freqvec_gram = freqvec.pow(2).sum(-1) # inverse Fourier transform autocorr = irfft(freqvec_gram, n=M2) # truncate and normalize the result, then transpose back to original shape autocorr = autocorr[..., :N] autocorr = autocorr / torch.tensor(range(N, 0, -1), dtype=input.dtype, device=input.device) autocorr = autocorr / autocorr[..., :1] return autocorr.transpose(dim, -1)
Computes the autocorrelation of samples at dimension ``dim``. Reference: https://en.wikipedia.org/wiki/Autocorrelation#Efficient_computation Implementation copied form `pyro <https://github.com/pyro-ppl/pyro/blob/dev/pyro/ops/stats.py>`_. :param torch.Tensor input: the input tensor. :param int dim: the dimension to calculate autocorrelation. :returns torch.Tensor: autocorrelation of ``input``.
158,628
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `unpack_sequence` function. Write a Python function `def unpack_sequence(sequence: Union[torch.Tensor, rnn.PackedSequence]) -> Tuple[torch.Tensor, torch.Tensor]` to solve the following problem: Unpack RNN sequence. Args: sequence (Union[torch.Tensor, rnn.PackedSequence]): RNN packed sequence or tensor of which first index are samples and second are timesteps Returns: Tuple[torch.Tensor, torch.Tensor]: tuple of unpacked sequence and length of samples Here is the function: def unpack_sequence(sequence: Union[torch.Tensor, rnn.PackedSequence]) -> Tuple[torch.Tensor, torch.Tensor]: """ Unpack RNN sequence. Args: sequence (Union[torch.Tensor, rnn.PackedSequence]): RNN packed sequence or tensor of which first index are samples and second are timesteps Returns: Tuple[torch.Tensor, torch.Tensor]: tuple of unpacked sequence and length of samples """ if isinstance(sequence, rnn.PackedSequence): sequence, lengths = rnn.pad_packed_sequence(sequence, batch_first=True) # batch sizes reside on the CPU by default -> we need to bring them to GPU lengths = lengths.to(sequence.device) else: lengths = torch.ones(sequence.size(0), device=sequence.device, dtype=torch.long) * sequence.size(1) return sequence, lengths
Unpack RNN sequence. Args: sequence (Union[torch.Tensor, rnn.PackedSequence]): RNN packed sequence or tensor of which first index are samples and second are timesteps Returns: Tuple[torch.Tensor, torch.Tensor]: tuple of unpacked sequence and length of samples
158,629
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `concat_sequences` function. Write a Python function `def concat_sequences( sequences: Union[List[torch.Tensor], List[rnn.PackedSequence]] ) -> Union[torch.Tensor, rnn.PackedSequence]` to solve the following problem: Concatenate RNN sequences. Args: sequences (Union[List[torch.Tensor], List[rnn.PackedSequence]): list of RNN packed sequences or tensors of which first index are samples and second are timesteps Returns: Union[torch.Tensor, rnn.PackedSequence]: concatenated sequence Here is the function: def concat_sequences( sequences: Union[List[torch.Tensor], List[rnn.PackedSequence]] ) -> Union[torch.Tensor, rnn.PackedSequence]: """ Concatenate RNN sequences. Args: sequences (Union[List[torch.Tensor], List[rnn.PackedSequence]): list of RNN packed sequences or tensors of which first index are samples and second are timesteps Returns: Union[torch.Tensor, rnn.PackedSequence]: concatenated sequence """ if isinstance(sequences[0], rnn.PackedSequence): return rnn.pack_sequence(sequences, enforce_sorted=False) elif isinstance(sequences[0], torch.Tensor): return torch.cat(sequences, dim=1) elif isinstance(sequences[0], (tuple, list)): return tuple( concat_sequences([sequences[ii][i] for ii in range(len(sequences))]) for i in range(len(sequences[0])) ) else: raise ValueError("Unsupported sequence type")
Concatenate RNN sequences. Args: sequences (Union[List[torch.Tensor], List[rnn.PackedSequence]): list of RNN packed sequences or tensors of which first index are samples and second are timesteps Returns: Union[torch.Tensor, rnn.PackedSequence]: concatenated sequence
158,630
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `padded_stack` function. Write a Python function `def padded_stack( tensors: List[torch.Tensor], side: str = "right", mode: str = "constant", value: Union[int, float] = 0 ) -> torch.Tensor` to solve the following problem: Stack tensors along first dimension and pad them along last dimension to ensure their size is equal. Args: tensors (List[torch.Tensor]): list of tensors to stack side (str): side on which to pad - "left" or "right". Defaults to "right". mode (str): 'constant', 'reflect', 'replicate' or 'circular'. Default: 'constant' value (Union[int, float]): value to use for constant padding Returns: torch.Tensor: stacked tensor Here is the function: def padded_stack( tensors: List[torch.Tensor], side: str = "right", mode: str = "constant", value: Union[int, float] = 0 ) -> torch.Tensor: """ Stack tensors along first dimension and pad them along last dimension to ensure their size is equal. Args: tensors (List[torch.Tensor]): list of tensors to stack side (str): side on which to pad - "left" or "right". Defaults to "right". mode (str): 'constant', 'reflect', 'replicate' or 'circular'. Default: 'constant' value (Union[int, float]): value to use for constant padding Returns: torch.Tensor: stacked tensor """ full_size = max([x.size(-1) for x in tensors]) def make_padding(pad): if side == "left": return (pad, 0) elif side == "right": return (0, pad) else: raise ValueError(f"side for padding '{side}' is unknown") out = torch.stack( [ F.pad(x, make_padding(full_size - x.size(-1)), mode=mode, value=value) if full_size - x.size(-1) > 0 else x for x in tensors ], dim=0, ) return out
Stack tensors along first dimension and pad them along last dimension to ensure their size is equal. Args: tensors (List[torch.Tensor]): list of tensors to stack side (str): side on which to pad - "left" or "right". Defaults to "right". mode (str): 'constant', 'reflect', 'replicate' or 'circular'. Default: 'constant' value (Union[int, float]): value to use for constant padding Returns: torch.Tensor: stacked tensor
158,631
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `to_list` function. Write a Python function `def to_list(value: Any) -> List[Any]` to solve the following problem: Convert value or list to list of values. If already list, return object directly Args: value (Any): value to convert Returns: List[Any]: list of values Here is the function: def to_list(value: Any) -> List[Any]: """ Convert value or list to list of values. If already list, return object directly Args: value (Any): value to convert Returns: List[Any]: list of values """ if isinstance(value, (tuple, list)) and not isinstance(value, rnn.PackedSequence): return value else: return [value]
Convert value or list to list of values. If already list, return object directly Args: value (Any): value to convert Returns: List[Any]: list of values
158,632
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `unsqueeze_like` function. Write a Python function `def unsqueeze_like(tensor: torch.Tensor, like: torch.Tensor)` to solve the following problem: Unsqueeze last dimensions of tensor to match another tensor's number of dimensions. Args: tensor (torch.Tensor): tensor to unsqueeze like (torch.Tensor): tensor whose dimensions to match Here is the function: def unsqueeze_like(tensor: torch.Tensor, like: torch.Tensor): """ Unsqueeze last dimensions of tensor to match another tensor's number of dimensions. Args: tensor (torch.Tensor): tensor to unsqueeze like (torch.Tensor): tensor whose dimensions to match """ n_unsqueezes = like.ndim - tensor.ndim if n_unsqueezes < 0: raise ValueError(f"tensor.ndim={tensor.ndim} > like.ndim={like.ndim}") elif n_unsqueezes == 0: return tensor else: return tensor[(...,) + (None,) * n_unsqueezes]
Unsqueeze last dimensions of tensor to match another tensor's number of dimensions. Args: tensor (torch.Tensor): tensor to unsqueeze like (torch.Tensor): tensor whose dimensions to match
158,633
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `apply_to_list` function. Write a Python function `def apply_to_list(obj: Union[List[Any], Any], func: Callable) -> Union[List[Any], Any]` to solve the following problem: Apply function to a list of objects or directly if passed value is not a list. This is useful if the passed object could be either a list to whose elements a function needs to be applied or just an object to whicht to apply the function. Args: obj (Union[List[Any], Any]): list/tuple on whose elements to apply function, otherwise object to whom to apply function func (Callable): function to apply Returns: Union[List[Any], Any]: list of objects or object depending on function output and if input ``obj`` is of type list/tuple Here is the function: def apply_to_list(obj: Union[List[Any], Any], func: Callable) -> Union[List[Any], Any]: """ Apply function to a list of objects or directly if passed value is not a list. This is useful if the passed object could be either a list to whose elements a function needs to be applied or just an object to whicht to apply the function. Args: obj (Union[List[Any], Any]): list/tuple on whose elements to apply function, otherwise object to whom to apply function func (Callable): function to apply Returns: Union[List[Any], Any]: list of objects or object depending on function output and if input ``obj`` is of type list/tuple """ if isinstance(obj, (list, tuple)) and not isinstance(obj, rnn.PackedSequence): return [func(o) for o in obj] else: return func(obj)
Apply function to a list of objects or directly if passed value is not a list. This is useful if the passed object could be either a list to whose elements a function needs to be applied or just an object to whicht to apply the function. Args: obj (Union[List[Any], Any]): list/tuple on whose elements to apply function, otherwise object to whom to apply function func (Callable): function to apply Returns: Union[List[Any], Any]: list of objects or object depending on function output and if input ``obj`` is of type list/tuple
158,634
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn class OutputMixIn: """ MixIn to give namedtuple some access capabilities of a dictionary """ def __getitem__(self, k): if isinstance(k, str): return getattr(self, k) else: return super().__getitem__(k) def get(self, k, default=None): return getattr(self, k, default) def items(self): return zip(self._fields, self) def keys(self): return self._fields def iget(self, idx: Union[int, slice]): """Select item(s) row-wise. Args: idx ([int, slice]): item to select Returns: Output of single item. """ return self.__class__(*(x[idx] for x in self)) The provided code snippet includes necessary dependencies for implementing the `move_to_device` function. Write a Python function `def move_to_device( x: Union[ Dict[str, Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]], torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor], ], device: Union[str, torch.DeviceObjType], ) -> Union[ Dict[str, Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]], torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor], ]` to solve the following problem: Move object to device. Args: x (dictionary of list of tensors): object (e.g. dictionary) of tensors to move to device device (Union[str, torch.DeviceObjType]): device, e.g. "cpu" Returns: x on targeted device Here is the function: def move_to_device( x: Union[ Dict[str, Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]], torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor], ], device: Union[str, torch.DeviceObjType], ) -> Union[ Dict[str, Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]], torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor], ]: """ Move object to device. Args: x (dictionary of list of tensors): object (e.g. dictionary) of tensors to move to device device (Union[str, torch.DeviceObjType]): device, e.g. "cpu" Returns: x on targeted device """ if isinstance(device, str): device = torch.device(device) if isinstance(x, dict): for name in x.keys(): x[name] = move_to_device(x[name], device=device) elif isinstance(x, OutputMixIn): for xi in x: move_to_device(xi, device=device) return x elif isinstance(x, torch.Tensor) and x.device != device: x = x.to(device) elif isinstance(x, (list, tuple)) and x[0].device != device: x = [move_to_device(xi, device=device) for xi in x] return x
Move object to device. Args: x (dictionary of list of tensors): object (e.g. dictionary) of tensors to move to device device (Union[str, torch.DeviceObjType]): device, e.g. "cpu" Returns: x on targeted device
158,635
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn class OutputMixIn: """ MixIn to give namedtuple some access capabilities of a dictionary """ def __getitem__(self, k): if isinstance(k, str): return getattr(self, k) else: return super().__getitem__(k) def get(self, k, default=None): return getattr(self, k, default) def items(self): return zip(self._fields, self) def keys(self): return self._fields def iget(self, idx: Union[int, slice]): """Select item(s) row-wise. Args: idx ([int, slice]): item to select Returns: Output of single item. """ return self.__class__(*(x[idx] for x in self)) The provided code snippet includes necessary dependencies for implementing the `detach` function. Write a Python function `def detach( x: Union[ Dict[str, Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]], torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor], ], ) -> Union[ Dict[str, Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]], torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor], ]` to solve the following problem: Detach object Args: x: object to detach Returns: detached object Here is the function: def detach( x: Union[ Dict[str, Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]], torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor], ], ) -> Union[ Dict[str, Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]], torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor], ]: """ Detach object Args: x: object to detach Returns: detached object """ if isinstance(x, torch.Tensor): return x.detach() elif isinstance(x, dict): return {name: detach(xi) for name, xi in x.items()} elif isinstance(x, OutputMixIn): return x.__class__(**{name: detach(xi) for name, xi in x.items()}) elif isinstance(x, (list, tuple)): return [detach(xi) for xi in x] else: return x
Detach object Args: x: object to detach Returns: detached object
158,636
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `masked_op` function. Write a Python function `def masked_op(tensor: torch.Tensor, op: str = "mean", dim: int = 0, mask: torch.Tensor = None) -> torch.Tensor` to solve the following problem: Calculate operation on masked tensor. Args: tensor (torch.Tensor): tensor to conduct operation over op (str): operation to apply. One of ["mean", "sum"]. Defaults to "mean". dim (int, optional): dimension to average over. Defaults to 0. mask (torch.Tensor, optional): boolean mask to apply (True=will take mean, False=ignore). Masks nan values by default. Returns: torch.Tensor: tensor with averaged out dimension Here is the function: def masked_op(tensor: torch.Tensor, op: str = "mean", dim: int = 0, mask: torch.Tensor = None) -> torch.Tensor: """Calculate operation on masked tensor. Args: tensor (torch.Tensor): tensor to conduct operation over op (str): operation to apply. One of ["mean", "sum"]. Defaults to "mean". dim (int, optional): dimension to average over. Defaults to 0. mask (torch.Tensor, optional): boolean mask to apply (True=will take mean, False=ignore). Masks nan values by default. Returns: torch.Tensor: tensor with averaged out dimension """ if mask is None: mask = ~torch.isnan(tensor) masked = tensor.masked_fill(~mask, 0.0) summed = masked.sum(dim=dim) if op == "mean": return summed / mask.sum(dim=dim) # Find the average elif op == "sum": return summed else: raise ValueError(f"unkown operation {op}")
Calculate operation on masked tensor. Args: tensor (torch.Tensor): tensor to conduct operation over op (str): operation to apply. One of ["mean", "sum"]. Defaults to "mean". dim (int, optional): dimension to average over. Defaults to 0. mask (torch.Tensor, optional): boolean mask to apply (True=will take mean, False=ignore). Masks nan values by default. Returns: torch.Tensor: tensor with averaged out dimension
158,637
from collections import namedtuple from contextlib import redirect_stdout import inspect import os from typing import Any, Callable, Dict, List, Tuple, Union import lightning.pytorch as pl import torch from torch import nn from torch.fft import irfft, rfft import torch.nn.functional as F from torch.nn.utils import rnn The provided code snippet includes necessary dependencies for implementing the `repr_class` function. Write a Python function `def repr_class( obj, attributes: Union[List[str], Dict[str, Any]], max_characters_before_break: int = 100, extra_attributes: Dict[str, Any] = {}, ) -> str` to solve the following problem: Print class name and parameters. Args: obj: class to format attributes (Union[List[str], Dict[str]]): list of attributes to show or dictionary of attributes and values to show max_characters_before_break (int): number of characters before breaking the into multiple lines extra_attributes (Dict[str, Any]): extra attributes to show in angled brackets Returns: str Here is the function: def repr_class( obj, attributes: Union[List[str], Dict[str, Any]], max_characters_before_break: int = 100, extra_attributes: Dict[str, Any] = {}, ) -> str: """Print class name and parameters. Args: obj: class to format attributes (Union[List[str], Dict[str]]): list of attributes to show or dictionary of attributes and values to show max_characters_before_break (int): number of characters before breaking the into multiple lines extra_attributes (Dict[str, Any]): extra attributes to show in angled brackets Returns: str """ # get attributes if isinstance(attributes, (tuple, list)): attributes = {name: getattr(obj, name) for name in attributes if hasattr(obj, name)} attributes_strings = [f"{name}={repr(value)}" for name, value in attributes.items()] # get header header_name = obj.__class__.__name__ # add extra attributes if len(extra_attributes) > 0: extra_attributes_strings = [f"{name}={repr(value)}" for name, value in extra_attributes.items()] if len(header_name) + 2 + len(", ".join(extra_attributes_strings)) > max_characters_before_break: header = f"{header_name}[\n\t" + ",\n\t".join(attributes_strings) + "\n](" else: header = f"{header_name}[{', '.join(extra_attributes_strings)}](" else: header = f"{header_name}(" # create final representation attributes_string = ", ".join(attributes_strings) if len(attributes_string) + len(header.split("\n")[-1]) + 1 > max_characters_before_break: attributes_string = "\n\t" + ",\n\t".join(attributes_strings) + "\n" return f"{header}{attributes_string})"
Print class name and parameters. Args: obj: class to format attributes (Union[List[str], Dict[str]]): list of attributes to show or dictionary of attributes and values to show max_characters_before_break (int): number of characters before breaking the into multiple lines extra_attributes (Dict[str, Any]): extra attributes to show in angled brackets Returns: str
158,638
import inspect from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import warnings from sklearn.base import BaseEstimator import torch from torch import distributions from torch.nn.utils import rnn from torchmetrics import Metric as LightningMetric from pytorch_forecasting.utils import create_mask, unpack_sequence, unsqueeze_like class Metric(LightningMetric): """ Base metric class that has basic functions that can handle predicting quantiles and operate in log space. See the `Lightning documentation <https://pytorch-lightning.readthedocs.io/en/latest/metrics.html>`_ for details of how to implement a new metric Other metrics should inherit from this base class """ full_state_update = False higher_is_better = False is_differentiable = True def __init__(self, name: str = None, quantiles: List[float] = None, reduction="mean", **kwargs): """ Initialize metric Args: name (str): metric name. Defaults to class name. quantiles (List[float], optional): quantiles for probability range. Defaults to None. reduction (str, optional): Reduction, "none", "mean" or "sqrt-mean". Defaults to "mean". """ self.quantiles = quantiles self.reduction = reduction if name is None: name = self.__class__.__name__ self.name = name super().__init__(**kwargs) def update(self, y_pred: torch.Tensor, y_actual: torch.Tensor): raise NotImplementedError() def compute(self) -> torch.Tensor: """ Abstract method that calcualtes metric Should be overriden in derived classes Args: y_pred: network output y_actual: actual values Returns: torch.Tensor: metric value on which backpropagation can be applied """ raise NotImplementedError() def rescale_parameters( self, parameters: torch.Tensor, target_scale: torch.Tensor, encoder: BaseEstimator ) -> torch.Tensor: """ Rescale normalized parameters into the scale required for the output. Args: parameters (torch.Tensor): normalized parameters (indexed by last dimension) target_scale (torch.Tensor): scale of parameters (n_batch_samples x (center, scale)) encoder (BaseEstimator): original encoder that normalized the target in the first place Returns: torch.Tensor: parameters in real/not normalized space """ return encoder(dict(prediction=parameters, target_scale=target_scale)) def to_prediction(self, y_pred: torch.Tensor) -> torch.Tensor: """ Convert network prediction into a point prediction. Args: y_pred: prediction output of network Returns: torch.Tensor: point prediction """ if y_pred.ndim == 3: if self.quantiles is None: assert y_pred.size(-1) == 1, "Prediction should only have one extra dimension" y_pred = y_pred[..., 0] else: y_pred = y_pred.mean(-1) return y_pred def to_quantiles(self, y_pred: torch.Tensor, quantiles: List[float] = None) -> torch.Tensor: """ Convert network prediction into a quantile prediction. Args: y_pred: prediction output of network quantiles (List[float], optional): quantiles for probability range. Defaults to quantiles as as defined in the class initialization. Returns: torch.Tensor: prediction quantiles """ if quantiles is None: quantiles = self.quantiles if y_pred.ndim == 2: return y_pred.unsqueeze(-1) elif y_pred.ndim == 3: if y_pred.size(2) > 1: # single dimension means all quantiles are the same assert quantiles is not None, "quantiles are not defined" y_pred = torch.quantile(y_pred, torch.tensor(quantiles, device=y_pred.device), dim=2).permute(1, 2, 0) return y_pred else: raise ValueError(f"prediction has 1 or more than 3 dimensions: {y_pred.ndim}") def __add__(self, metric: LightningMetric): composite_metric = CompositeMetric(metrics=[self]) new_metric = composite_metric + metric return new_metric def __mul__(self, multiplier: float): new_metric = CompositeMetric(metrics=[self], weights=[multiplier]) return new_metric def extra_repr(self) -> str: forbidden_attributes = ["name", "reduction"] attributes = list(inspect.signature(self.__class__).parameters.keys()) return ", ".join( [ f"{name}={repr(getattr(self, name))}" for name in attributes if hasattr(self, name) and name not in forbidden_attributes ] ) __rmul__ = __mul__ class TorchMetricWrapper(Metric): """ Wrap a torchmetric to work with PyTorch Forecasting. Does not support weighting of errors and only supports metrics for point predictions. """ def __init__(self, torchmetric: LightningMetric, reduction: str = None, **kwargs): """ Args: torchmetric (LightningMetric): Torchmetric to wrap. reduction (str, optional): use reduction with torchmetric directly. Defaults to None. """ super().__init__(**kwargs) if reduction is not None: raise ValueError("use reduction with torchmetric directly") self.torchmetric = torchmetric def _sync_dist(self, dist_sync_fn=None, process_group=None) -> None: # No syncing required here. syncing will be done in metric_a and metric_b pass def _wrap_compute(self, compute: Callable) -> Callable: return compute def reset(self) -> None: self.torchmetric.reset() def persistent(self, mode: bool = False) -> None: self.torchmetric.persistent(mode=mode) def _convert(self, y_pred: torch.Tensor, target: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # unpack target into target and weights if isinstance(target, (list, tuple)) and not isinstance(target, rnn.PackedSequence): target, weight = target if weight is not None: raise NotImplementedError( "Weighting is not supported for pure torchmetrics - " "implement a custom version or use pytorch-forecasting metrics" ) # convert to point prediction - limits applications of class y_pred = self.to_prediction(y_pred) # unpack target if it is PackedSequence if isinstance(target, rnn.PackedSequence): target, lengths = unpack_sequence(target) # create mask for different lengths length_mask = create_mask(target.size(1), lengths, inverse=True) target = target.masked_select(length_mask) y_pred = y_pred.masked_select(length_mask) y_pred = y_pred.flatten() target = target.flatten() return y_pred, target def update(self, y_pred: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor: # flatten target and prediction y_pred_flattened, target_flattened = self._convert(y_pred, target) # update metric self.torchmetric.update(y_pred_flattened, target_flattened, **kwargs) def forward(self, y_pred, target, **kwargs): # need this explicitly to avoid backpropagation errors because of sketchy caching y_pred_flattened, target_flattened = self._convert(y_pred, target) return self.torchmetric.forward(y_pred_flattened, target_flattened, **kwargs) def compute(self): res = self.torchmetric.compute() return res def __repr__(self): return f"WrappedTorchmetric({repr(self.torchmetric)})" class MultiLoss(LightningMetric): """ Metric that can be used with muliple metrics. """ full_state_update = False higher_is_better = False is_differentiable = True def __init__(self, metrics: List[LightningMetric], weights: List[float] = None): """ Args: metrics (List[LightningMetric], optional): list of metrics to combine. weights (List[float], optional): list of weights / multipliers for weights. Defaults to 1.0 for all metrics. """ assert len(metrics) > 0, "at least one metric has to be specified" if weights is None: weights = [1.0 for _ in metrics] assert len(weights) == len(metrics), "Number of weights has to match number of metrics" self.metrics = [convert_torchmetric_to_pytorch_forecasting_metric(m) for m in metrics] self.weights = weights super().__init__() def __repr__(self): name = ( f"{self.__class__.__name__}(" + ", ".join([f"{w:.3g} * {repr(m)}" if w != 1.0 else repr(m) for w, m in zip(self.weights, self.metrics)]) + ")" ) return name def __iter__(self): """ Iterate over metrics. """ return iter(self.metrics) def __len__(self) -> int: """ Number of metrics. Returns: int: number of metrics """ return len(self.metrics) def update(self, y_pred: torch.Tensor, y_actual: torch.Tensor, **kwargs) -> None: """ Update composite metric Args: y_pred: network output y_actual: actual values **kwargs: arguments to update function """ for idx, metric in enumerate(self.metrics): try: metric.update( y_pred[idx], (y_actual[0][idx], y_actual[1]), **{ name: value[idx] if isinstance(value, (list, tuple)) else value for name, value in kwargs.items() }, ) except TypeError: # silently update without kwargs if not supported metric.update(y_pred[idx], (y_actual[0][idx], y_actual[1])) def compute(self) -> torch.Tensor: """ Get metric Returns: torch.Tensor: metric """ results = [] for weight, metric in zip(self.weights, self.metrics): results.append(metric.compute() * weight) if len(results) == 1: results = results[0] else: results = torch.stack(results, dim=0).sum(0) return results def forward(self, y_pred: torch.Tensor, y_actual: torch.Tensor, **kwargs): """ Calculate composite metric Args: y_pred: network output y_actual: actual values **kwargs: arguments to update function Returns: torch.Tensor: metric value on which backpropagation can be applied """ results = [] for idx, metric in enumerate(self.metrics): try: res = metric( y_pred[idx], (y_actual[0][idx], y_actual[1]), **{ name: value[idx] if isinstance(value, (list, tuple)) else value for name, value in kwargs.items() }, ) except TypeError: # silently update without kwargs if not supported res = metric(y_pred[idx], (y_actual[0][idx], y_actual[1])) results.append(res * self.weights[idx]) if len(results) == 1: results = results[0] else: results = torch.stack(results, dim=0).sum(0) return results def _wrap_compute(self, compute: Callable) -> Callable: return compute def _sync_dist(self, dist_sync_fn: Optional[Callable] = None, process_group: Optional[Any] = None) -> None: # No syncing required here. syncing will be done in metrics pass def reset(self) -> None: for metric in self.metrics: metric.reset() def persistent(self, mode: bool = False) -> None: for metric in self.metrics: metric.persistent(mode=mode) def to_prediction(self, y_pred: torch.Tensor, **kwargs) -> torch.Tensor: """ Convert network prediction into a point prediction. Will use first metric in ``metrics`` attribute to calculate result. Args: y_pred: prediction output of network **kwargs: arguments for metrics Returns: torch.Tensor: point prediction """ result = [] for idx, metric in enumerate(self.metrics): try: result.append(metric.to_prediction(y_pred[idx], **kwargs)) except TypeError: result.append(metric.to_prediction(y_pred[idx])) return result def to_quantiles(self, y_pred: torch.Tensor, **kwargs) -> torch.Tensor: """ Convert network prediction into a quantile prediction. Will use first metric in ``metrics`` attribute to calculate result. Args: y_pred: prediction output of network **kwargs: parameters to each metric's ``to_quantiles()`` method Returns: torch.Tensor: prediction quantiles """ result = [] for idx, metric in enumerate(self.metrics): try: result.append(metric.to_quantiles(y_pred[idx], **kwargs)) except TypeError: result.append(metric.to_quantiles(y_pred[idx])) return result def __getitem__(self, idx: int): """ Return metric. Args: idx (int): metric index """ return self.metrics[idx] def __getattr__(self, name: str): """ Return dynamically attributes. Return attributes if defined in this class. If not, create dynamically attributes based on attributes of underlying metrics that are lists. Create functions if necessary. Arguments to functions are distributed to the functions if they are lists and their length matches the number of metrics. Otherwise, they are directly passed to each callable of the metrics Args: name (str): name of attribute Returns: attributes of this class or list of attributes of underlying class """ try: return super().__getattr__(name) except AttributeError as e: attribute_exists = all([hasattr(metric, name) for metric in self.metrics]) if attribute_exists: # check if to return callable or not and return function if yes if callable(getattr(self.metrics[0], name)): n = len(self.metrics) def func(*args, **kwargs): # if arg/kwarg is list and of length metric, then apply each part to a metric. otherwise # pass it directly to all metrics results = [] for idx, m in enumerate(self.metrics): new_args = [ arg[idx] if isinstance(arg, (list, tuple)) and not isinstance(arg, rnn.PackedSequence) and len(arg) == n else arg for arg in args ] new_kwargs = { key: val[idx] if isinstance(val, list) and not isinstance(val, rnn.PackedSequence) and len(val) == n else val for key, val in kwargs.items() } results.append(getattr(m, name)(*new_args, **new_kwargs)) return results return func else: # else return list of attributes return [getattr(metric, name) for metric in self.metrics] else: # attribute does not exist for all metrics raise e class CompositeMetric(LightningMetric): """ Metric that combines multiple metrics. Metric does not have to be called explicitly but is automatically created when adding and multiplying metrics with each other. Example: .. code-block:: python composite_metric = SMAPE() + 0.4 * MAE() """ full_state_update = False higher_is_better = False is_differentiable = True def __init__(self, metrics: List[LightningMetric] = [], weights: List[float] = None): """ Args: metrics (List[LightningMetric], optional): list of metrics to combine. Defaults to []. weights (List[float], optional): list of weights / multipliers for weights. Defaults to 1.0 for all metrics. """ if weights is None: weights = [1.0 for _ in metrics] assert len(weights) == len(metrics), "Number of weights has to match number of metrics" self.metrics = metrics self.weights = weights super().__init__() def __repr__(self): name = " + ".join([f"{w:.3g} * {repr(m)}" if w != 1.0 else repr(m) for w, m in zip(self.weights, self.metrics)]) return name def update(self, y_pred: torch.Tensor, y_actual: torch.Tensor, **kwargs): """ Update composite metric Args: y_pred: network output y_actual: actual values Returns: torch.Tensor: metric value on which backpropagation can be applied """ for metric in self.metrics: try: metric.update(y_pred, y_actual, **kwargs) except TypeError: metric.update(y_pred, y_actual) def compute(self) -> torch.Tensor: """ Get metric Returns: torch.Tensor: metric """ results = [] for weight, metric in zip(self.weights, self.metrics): results.append(metric.compute() * weight) if len(results) == 1: results = results[0] else: results = torch.stack(results, dim=0).sum(0) return results def forward(self, y_pred: torch.Tensor, y_actual: torch.Tensor, **kwargs): """ Calculate composite metric Args: y_pred: network output y_actual: actual values **kwargs: arguments to update function Returns: torch.Tensor: metric value on which backpropagation can be applied """ results = [] for weight, metric in zip(self.weights, self.metrics): try: results.append(metric(y_pred, y_actual, **kwargs) * weight) except TypeError: results.append(metric(y_pred, y_actual) * weight) if len(results) == 1: results = results[0] else: results = torch.stack(results, dim=0).sum(0) return results def _wrap_compute(self, compute: Callable) -> Callable: return compute def _sync_dist(self, dist_sync_fn: Optional[Callable] = None, process_group: Optional[Any] = None) -> None: # No syncing required here. syncing will be done in metrics pass def reset(self) -> None: for metric in self.metrics: metric.reset() def persistent(self, mode: bool = False) -> None: for metric in self.metrics: metric.persistent(mode=mode) def to_prediction(self, y_pred: torch.Tensor, **kwargs) -> torch.Tensor: """ Convert network prediction into a point prediction. Will use first metric in ``metrics`` attribute to calculate result. Args: y_pred: prediction output of network **kwargs: parameters to first metric `to_prediction` method Returns: torch.Tensor: point prediction """ return self.metrics[0].to_prediction(y_pred, **kwargs) def to_quantiles(self, y_pred: torch.Tensor, **kwargs) -> torch.Tensor: """ Convert network prediction into a quantile prediction. Will use first metric in ``metrics`` attribute to calculate result. Args: y_pred: prediction output of network **kwargs: parameters to first metric's ``to_quantiles()`` method Returns: torch.Tensor: prediction quantiles """ return self.metrics[0].to_quantiles(y_pred, **kwargs) def __add__(self, metric: LightningMetric): if isinstance(metric, self.__class__): self.metrics.extend(metric.metrics) self.weights.extend(metric.weights) else: self.metrics.append(metric) self.weights.append(1.0) return self def __mul__(self, multiplier: float): self.weights = [w * multiplier for w in self.weights] return self __rmul__ = __mul__ The provided code snippet includes necessary dependencies for implementing the `convert_torchmetric_to_pytorch_forecasting_metric` function. Write a Python function `def convert_torchmetric_to_pytorch_forecasting_metric(metric: LightningMetric) -> Metric` to solve the following problem: If necessary, convert a torchmetric to a PyTorch Forecasting metric that works with PyTorch Forecasting models. Args: metric (LightningMetric): metric to (potentially) convert Returns: Metric: PyTorch Forecasting metric Here is the function: def convert_torchmetric_to_pytorch_forecasting_metric(metric: LightningMetric) -> Metric: """ If necessary, convert a torchmetric to a PyTorch Forecasting metric that works with PyTorch Forecasting models. Args: metric (LightningMetric): metric to (potentially) convert Returns: Metric: PyTorch Forecasting metric """ if not isinstance(metric, (Metric, MultiLoss, CompositeMetric)): return TorchMetricWrapper(metric) else: return metric
If necessary, convert a torchmetric to a PyTorch Forecasting metric that works with PyTorch Forecasting models. Args: metric (LightningMetric): metric to (potentially) convert Returns: Metric: PyTorch Forecasting metric
158,639
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union import warnings import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin import torch from torch.distributions import constraints from torch.distributions.transforms import ( ExpTransform, PowerTransform, SigmoidTransform, Transform, _clipped_sigmoid, identity_transform, ) import torch.nn.functional as F from torch.nn.utils import rnn from pytorch_forecasting.utils import InitialParameterRepresenterMixIn def _plus_one(x): return x + 1
null
158,640
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union import warnings import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin import torch from torch.distributions import constraints from torch.distributions.transforms import ( ExpTransform, PowerTransform, SigmoidTransform, Transform, _clipped_sigmoid, identity_transform, ) import torch.nn.functional as F from torch.nn.utils import rnn from pytorch_forecasting.utils import InitialParameterRepresenterMixIn def _minus_one(x): return x - 1
null
158,641
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union import warnings import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin import torch from torch.distributions import constraints from torch.distributions.transforms import ( ExpTransform, PowerTransform, SigmoidTransform, Transform, _clipped_sigmoid, identity_transform, ) import torch.nn.functional as F from torch.nn.utils import rnn from pytorch_forecasting.utils import InitialParameterRepresenterMixIn def _identity(x): return x
null
158,642
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union import warnings import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin import torch from torch.distributions import constraints from torch.distributions.transforms import ( ExpTransform, PowerTransform, SigmoidTransform, Transform, _clipped_sigmoid, identity_transform, ) import torch.nn.functional as F from torch.nn.utils import rnn from pytorch_forecasting.utils import InitialParameterRepresenterMixIn def _clipped_logit(x): finfo = torch.finfo(x.dtype) x = x.clamp(min=finfo.eps, max=1.0 - finfo.eps) return x.log() - (-x).log1p()
null
158,643
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union import warnings import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin import torch from torch.distributions import constraints from torch.distributions.transforms import ( ExpTransform, PowerTransform, SigmoidTransform, Transform, _clipped_sigmoid, identity_transform, ) import torch.nn.functional as F from torch.nn.utils import rnn from pytorch_forecasting.utils import InitialParameterRepresenterMixIn def softplus_inv(y): finfo = torch.finfo(y.dtype) return y.where(y > 20.0, y + (y + finfo.eps).neg().expm1().neg().log())
null
158,644
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union import warnings import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin import torch from torch.distributions import constraints from torch.distributions.transforms import ( ExpTransform, PowerTransform, SigmoidTransform, Transform, _clipped_sigmoid, identity_transform, ) import torch.nn.functional as F from torch.nn.utils import rnn from pytorch_forecasting.utils import InitialParameterRepresenterMixIn def _square(y): return torch.pow(y, 2.0)
null
158,645
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union import warnings import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin import torch from torch.distributions import constraints from torch.distributions.transforms import ( ExpTransform, PowerTransform, SigmoidTransform, Transform, _clipped_sigmoid, identity_transform, ) import torch.nn.functional as F from torch.nn.utils import rnn from pytorch_forecasting.utils import InitialParameterRepresenterMixIn def _clipped_log(y): finfo = torch.finfo(y.dtype) return y.log().clamp(min=-1 / finfo.eps)
null
158,646
from pathlib import Path import numpy as np import pandas as pd import requests def _get_data_by_filename(fname: str) -> Path: """ Download file or used cached version. Args: fname (str): name of file to download Returns: Path: path at which file lives """ full_fname = DATA_PATH.joinpath(fname) # check if file exists - download if necessary if not full_fname.exists(): url = BASE_URL + fname download = requests.get(url, allow_redirects=True) with open(full_fname, "wb") as file: file.write(download.content) return full_fname The provided code snippet includes necessary dependencies for implementing the `get_stallion_data` function. Write a Python function `def get_stallion_data() -> pd.DataFrame` to solve the following problem: Demand data with covariates. ~20k samples of 350 timeseries. Important columns * Timeseries can be identified by ``agency`` and ``sku``. * ``volume`` is the demand * ``date`` is the month of the demand. Returns: pd.DataFrame: data Here is the function: def get_stallion_data() -> pd.DataFrame: """ Demand data with covariates. ~20k samples of 350 timeseries. Important columns * Timeseries can be identified by ``agency`` and ``sku``. * ``volume`` is the demand * ``date`` is the month of the demand. Returns: pd.DataFrame: data """ fname = _get_data_by_filename("stallion.parquet") return pd.read_parquet(fname)
Demand data with covariates. ~20k samples of 350 timeseries. Important columns * Timeseries can be identified by ``agency`` and ``sku``. * ``volume`` is the demand * ``date`` is the month of the demand. Returns: pd.DataFrame: data
158,647
from pathlib import Path import numpy as np import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `generate_ar_data` function. Write a Python function `def generate_ar_data( n_series: int = 10, timesteps: int = 400, seasonality: float = 3.0, trend: float = 3.0, noise: float = 0.1, level: float = 1.0, exp: bool = False, seed: int = 213, ) -> pd.DataFrame` to solve the following problem: Generate multivariate data without covariates. Eeach timeseries is generated from seasonality and trend. Important columns: * ``series``: series ID * ``time_idx``: time index * ``value``: target value Args: n_series (int, optional): Number of series. Defaults to 10. timesteps (int, optional): Number of timesteps. Defaults to 400. seasonality (float, optional): Normalized frequency, i.e. frequency is ``seasonality / timesteps``. Defaults to 3.0. trend (float, optional): Trend multiplier (seasonality is multiplied with 1.0). Defaults to 3.0. noise (float, optional): Level of gaussian noise. Defaults to 0.1. level (float, optional): Level multiplier (level is a constant to be aded to timeseries). Defaults to 1.0. exp (bool, optional): If to return exponential of timeseries values. Defaults to False. seed (int, optional): Random seed. Defaults to 213. Returns: pd.DataFrame: data Here is the function: def generate_ar_data( n_series: int = 10, timesteps: int = 400, seasonality: float = 3.0, trend: float = 3.0, noise: float = 0.1, level: float = 1.0, exp: bool = False, seed: int = 213, ) -> pd.DataFrame: """ Generate multivariate data without covariates. Eeach timeseries is generated from seasonality and trend. Important columns: * ``series``: series ID * ``time_idx``: time index * ``value``: target value Args: n_series (int, optional): Number of series. Defaults to 10. timesteps (int, optional): Number of timesteps. Defaults to 400. seasonality (float, optional): Normalized frequency, i.e. frequency is ``seasonality / timesteps``. Defaults to 3.0. trend (float, optional): Trend multiplier (seasonality is multiplied with 1.0). Defaults to 3.0. noise (float, optional): Level of gaussian noise. Defaults to 0.1. level (float, optional): Level multiplier (level is a constant to be aded to timeseries). Defaults to 1.0. exp (bool, optional): If to return exponential of timeseries values. Defaults to False. seed (int, optional): Random seed. Defaults to 213. Returns: pd.DataFrame: data """ # sample parameters np.random.seed(seed) linear_trends = np.random.normal(size=n_series)[:, None] / timesteps quadratic_trends = np.random.normal(size=n_series)[:, None] / timesteps**2 seasonalities = np.random.normal(size=n_series)[:, None] levels = level * np.random.normal(size=n_series)[:, None] # generate series x = np.arange(timesteps)[None, :] series = (x * linear_trends + x**2 * quadratic_trends) * trend + seasonalities * np.sin( 2 * np.pi * seasonality * x / timesteps ) # add noise series = levels * series * (1 + noise * np.random.normal(size=series.shape)) if exp: series = np.exp(series) # insert into dataframe data = ( pd.DataFrame(series) .stack() .reset_index() .rename(columns={"level_0": "series", "level_1": "time_idx", 0: "value"}) ) return data
Generate multivariate data without covariates. Eeach timeseries is generated from seasonality and trend. Important columns: * ``series``: series ID * ``time_idx``: time index * ``value``: target value Args: n_series (int, optional): Number of series. Defaults to 10. timesteps (int, optional): Number of timesteps. Defaults to 400. seasonality (float, optional): Normalized frequency, i.e. frequency is ``seasonality / timesteps``. Defaults to 3.0. trend (float, optional): Trend multiplier (seasonality is multiplied with 1.0). Defaults to 3.0. noise (float, optional): Level of gaussian noise. Defaults to 0.1. level (float, optional): Level multiplier (level is a constant to be aded to timeseries). Defaults to 1.0. exp (bool, optional): If to return exponential of timeseries values. Defaults to False. seed (int, optional): Random seed. Defaults to 213. Returns: pd.DataFrame: data
158,648
from copy import copy as _copy, deepcopy from functools import lru_cache import inspect from typing import Any, Callable, Dict, List, Tuple, Union import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.exceptions import NotFittedError from sklearn.preprocessing import RobustScaler, StandardScaler from sklearn.utils.validation import check_is_fitted import torch from torch.distributions import Beta from torch.nn.utils import rnn from torch.utils.data import DataLoader, Dataset from torch.utils.data.sampler import Sampler, SequentialSampler from pytorch_forecasting.data.encoders import ( EncoderNormalizer, GroupNormalizer, MultiNormalizer, NaNLabelEncoder, TorchNormalizer, ) from pytorch_forecasting.data.samplers import TimeSynchronizedBatchSampler from pytorch_forecasting.utils import repr_class The provided code snippet includes necessary dependencies for implementing the `_find_end_indices` function. Write a Python function `def _find_end_indices(diffs: np.ndarray, max_lengths: np.ndarray, min_length: int) -> Tuple[np.ndarray, np.ndarray]` to solve the following problem: Identify end indices in series even if some values are missing. Args: diffs (np.ndarray): array of differences to next time step. nans should be filled up with ones max_lengths (np.ndarray): maximum length of sequence by position. min_length (int): minimum length of sequence. Returns: Tuple[np.ndarray, np.ndarray]: tuple of arrays where first is end indices and second is list of start and end indices that are currently missing. Here is the function: def _find_end_indices(diffs: np.ndarray, max_lengths: np.ndarray, min_length: int) -> Tuple[np.ndarray, np.ndarray]: """ Identify end indices in series even if some values are missing. Args: diffs (np.ndarray): array of differences to next time step. nans should be filled up with ones max_lengths (np.ndarray): maximum length of sequence by position. min_length (int): minimum length of sequence. Returns: Tuple[np.ndarray, np.ndarray]: tuple of arrays where first is end indices and second is list of start and end indices that are currently missing. """ missing_start_ends = [] end_indices = [] length = 1 start_idx = 0 max_idx = len(diffs) - 1 max_length = max_lengths[start_idx] for idx, diff in enumerate(diffs): if length >= max_length: while length >= max_length: if length == max_length: end_indices.append(idx) else: end_indices.append(idx - 1) length -= diffs[start_idx] if start_idx < max_idx: start_idx += 1 max_length = max_lengths[start_idx] elif length >= min_length: missing_start_ends.append([start_idx, idx]) length += diff if len(missing_start_ends) > 0: # required for numba compliance return np.asarray(end_indices), np.asarray(missing_start_ends) else: return np.asarray(end_indices), np.empty((0, 2), dtype=np.int64)
Identify end indices in series even if some values are missing. Args: diffs (np.ndarray): array of differences to next time step. nans should be filled up with ones max_lengths (np.ndarray): maximum length of sequence by position. min_length (int): minimum length of sequence. Returns: Tuple[np.ndarray, np.ndarray]: tuple of arrays where first is end indices and second is list of start and end indices that are currently missing.
158,649
from copy import copy as _copy, deepcopy from functools import lru_cache import inspect from typing import Any, Callable, Dict, List, Tuple, Union import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.exceptions import NotFittedError from sklearn.preprocessing import RobustScaler, StandardScaler from sklearn.utils.validation import check_is_fitted import torch from torch.distributions import Beta from torch.nn.utils import rnn from torch.utils.data import DataLoader, Dataset from torch.utils.data.sampler import Sampler, SequentialSampler from pytorch_forecasting.data.encoders import ( EncoderNormalizer, GroupNormalizer, MultiNormalizer, NaNLabelEncoder, TorchNormalizer, ) from pytorch_forecasting.data.samplers import TimeSynchronizedBatchSampler from pytorch_forecasting.utils import repr_class The provided code snippet includes necessary dependencies for implementing the `check_for_nonfinite` function. Write a Python function `def check_for_nonfinite(tensor: torch.Tensor, names: Union[str, List[str]]) -> torch.Tensor` to solve the following problem: Check if 2D tensor contains NAs or inifinite values. Args: names (Union[str, List[str]]): name(s) of column(s) (used for error messages) tensor (torch.Tensor): tensor to check Returns: torch.Tensor: returns tensor if checks yield no issues Here is the function: def check_for_nonfinite(tensor: torch.Tensor, names: Union[str, List[str]]) -> torch.Tensor: """ Check if 2D tensor contains NAs or inifinite values. Args: names (Union[str, List[str]]): name(s) of column(s) (used for error messages) tensor (torch.Tensor): tensor to check Returns: torch.Tensor: returns tensor if checks yield no issues """ if isinstance(names, str): names = [names] assert tensor.ndim == 1 nans = (~torch.isfinite(tensor).unsqueeze(-1)).sum(0) else: assert tensor.ndim == 2 nans = (~torch.isfinite(tensor)).sum(0) for name, na in zip(names, nans): if na > 0: raise ValueError( f"{na} ({na/tensor.size(0):.2%}) of {name} " "values were found to be NA or infinite (even after encoding). NA values are not allowed " "`allow_missing_timesteps` refers to missing rows, not to missing values. Possible strategies to " f"fix the issue are (a) dropping the variable {name}, " "(b) using `NaNLabelEncoder(add_nan=True)` for categorical variables, " "(c) filling missing values and/or (d) optionally adding a variable indicating filled values" ) return tensor
Check if 2D tensor contains NAs or inifinite values. Args: names (Union[str, List[str]]): name(s) of column(s) (used for error messages) tensor (torch.Tensor): tensor to check Returns: torch.Tensor: returns tensor if checks yield no issues
158,650
from abc import ABC, abstractmethod from typing import Tuple, Type, Union import torch from torch import nn from torch.nn.utils import rnn class RNN(ABC, nn.RNNBase): """ Base class flexible RNNs. Forward function can handle sequences of length 0. """ def handle_no_encoding( self, hidden_state: HiddenState, no_encoding: torch.BoolTensor, initial_hidden_state: HiddenState ) -> HiddenState: """ Mask the hidden_state where there is no encoding. Args: hidden_state (HiddenState): hidden state where some entries need replacement no_encoding (torch.BoolTensor): positions that need replacement initial_hidden_state (HiddenState): hidden state to use for replacement Returns: HiddenState: hidden state with propagated initial hidden state where appropriate """ pass def init_hidden_state(self, x: torch.Tensor) -> HiddenState: """ Initialise a hidden_state. Args: x (torch.Tensor): network input Returns: HiddenState: default (zero-like) hidden state """ pass def repeat_interleave(self, hidden_state: HiddenState, n_samples: int) -> HiddenState: """ Duplicate the hidden_state n_samples times. Args: hidden_state (HiddenState): hidden state to repeat n_samples (int): number of repetitions Returns: HiddenState: repeated hidden state """ pass def forward( self, x: Union[rnn.PackedSequence, torch.Tensor], hx: HiddenState = None, lengths: torch.LongTensor = None, enforce_sorted: bool = True, ) -> Tuple[Union[rnn.PackedSequence, torch.Tensor], HiddenState]: """ Forward function of rnn that allows zero-length sequences. Functions as normal for RNN. Only changes output if lengths are defined. Args: x (Union[rnn.PackedSequence, torch.Tensor]): input to RNN. either packed sequence or tensor of padded sequences hx (HiddenState, optional): hidden state. Defaults to None. lengths (torch.LongTensor, optional): lengths of sequences. If not None, used to determine correct returned hidden state. Can contain zeros. Defaults to None. enforce_sorted (bool, optional): if lengths are passed, determines if RNN expects them to be sorted. Defaults to True. Returns: Tuple[Union[rnn.PackedSequence, torch.Tensor], HiddenState]: output and hidden state. Output is packed sequence if input has been a packed sequence. """ if isinstance(x, rnn.PackedSequence) or lengths is None: assert lengths is None, "cannot combine x of type PackedSequence with lengths argument" return super().forward(x, hx=hx) else: min_length = lengths.min() max_length = lengths.max() assert min_length >= 0, "sequence lengths must be great equals 0" if max_length == 0: hidden_state = self.init_hidden_state(x) if self.batch_first: out = torch.zeros(lengths.size(0), x.size(1), self.hidden_size, dtype=x.dtype, device=x.device) else: out = torch.zeros(x.size(0), lengths.size(0), self.hidden_size, dtype=x.dtype, device=x.device) return out, hidden_state else: pack_lengths = lengths.where(lengths > 0, torch.ones_like(lengths)) packed_out, hidden_state = super().forward( rnn.pack_padded_sequence( x, pack_lengths.cpu(), enforce_sorted=enforce_sorted, batch_first=self.batch_first ), hx=hx, ) # replace hidden cell with initial input if encoder_length is zero to determine correct initial state if min_length == 0: no_encoding = (lengths == 0)[ None, :, None ] # shape: n_layers * n_directions x batch_size x hidden_size if hx is None: initial_hidden_state = self.init_hidden_state(x) else: initial_hidden_state = hx # propagate initial hidden state when sequence length was 0 hidden_state = self.handle_no_encoding(hidden_state, no_encoding, initial_hidden_state) # return unpacked sequence out, _ = rnn.pad_packed_sequence(packed_out, batch_first=self.batch_first) return out, hidden_state class LSTM(RNN, nn.LSTM): """LSTM that can handle zero-length sequences""" def handle_no_encoding( self, hidden_state: HiddenState, no_encoding: torch.BoolTensor, initial_hidden_state: HiddenState ) -> HiddenState: hidden, cell = hidden_state hidden = hidden.masked_scatter(no_encoding, initial_hidden_state[0]) cell = cell.masked_scatter(no_encoding, initial_hidden_state[0]) return hidden, cell def init_hidden_state(self, x: torch.Tensor) -> HiddenState: num_directions = 2 if self.bidirectional else 1 if self.batch_first: batch_size = x.size(0) else: batch_size = x.size(1) hidden = torch.zeros( (self.num_layers * num_directions, batch_size, self.hidden_size), device=x.device, dtype=x.dtype, ) cell = torch.zeros( (self.num_layers * num_directions, batch_size, self.hidden_size), device=x.device, dtype=x.dtype, ) return hidden, cell def repeat_interleave(self, hidden_state: HiddenState, n_samples: int) -> HiddenState: hidden, cell = hidden_state hidden = hidden.repeat_interleave(n_samples, 1) cell = cell.repeat_interleave(n_samples, 1) return hidden, cell class GRU(RNN, nn.GRU): """GRU that can handle zero-length sequences""" def handle_no_encoding( self, hidden_state: HiddenState, no_encoding: torch.BoolTensor, initial_hidden_state: HiddenState ) -> HiddenState: return hidden_state.masked_scatter(no_encoding, initial_hidden_state) def init_hidden_state(self, x: torch.Tensor) -> HiddenState: if self.batch_first: batch_size = x.size(0) else: batch_size = x.size(1) num_directions = 2 if self.bidirectional else 1 hidden = torch.zeros( (self.num_layers * num_directions, batch_size, self.hidden_size), device=x.device, dtype=x.dtype, ) return hidden def repeat_interleave(self, hidden_state: HiddenState, n_samples: int) -> HiddenState: return hidden_state.repeat_interleave(n_samples, 1) The provided code snippet includes necessary dependencies for implementing the `get_rnn` function. Write a Python function `def get_rnn(cell_type: Union[Type[RNN], str]) -> Type[RNN]` to solve the following problem: Get LSTM or GRU. Args: cell_type (Union[RNN, str]): "LSTM" or "GRU" Returns: Type[RNN]: returns GRU or LSTM RNN module Here is the function: def get_rnn(cell_type: Union[Type[RNN], str]) -> Type[RNN]: """ Get LSTM or GRU. Args: cell_type (Union[RNN, str]): "LSTM" or "GRU" Returns: Type[RNN]: returns GRU or LSTM RNN module """ if isinstance(cell_type, RNN): rnn = cell_type elif cell_type == "LSTM": rnn = LSTM elif cell_type == "GRU": rnn = GRU else: raise ValueError(f"RNN type {cell_type} is not supported. supported: [LSTM, GRU]") return rnn
Get LSTM or GRU. Args: cell_type (Union[RNN, str]): "LSTM" or "GRU" Returns: Type[RNN]: returns GRU or LSTM RNN module
158,651
import copy import logging import os from typing import Any, Dict, Tuple, Union import lightning.pytorch as pl from lightning.pytorch.callbacks import LearningRateMonitor, ModelCheckpoint from lightning.pytorch.loggers import TensorBoardLogger from lightning.pytorch.tuner import Tuner import numpy as np import optuna from optuna.integration import PyTorchLightningPruningCallback import optuna.logging import statsmodels.api as sm import torch from torch.utils.data import DataLoader from pytorch_forecasting import TemporalFusionTransformer from pytorch_forecasting.data import TimeSeriesDataSet from pytorch_forecasting.metrics import QuantileLoss optuna_logger = logging.getLogger("optuna") class PyTorchLightningPruningCallbackAdjusted(PyTorchLightningPruningCallback, pl.Callback): pass The provided code snippet includes necessary dependencies for implementing the `optimize_hyperparameters` function. Write a Python function `def optimize_hyperparameters( train_dataloaders: DataLoader, val_dataloaders: DataLoader, model_path: str, max_epochs: int = 20, n_trials: int = 100, timeout: float = 3600 * 8.0, # 8 hours gradient_clip_val_range: Tuple[float, float] = (0.01, 100.0), hidden_size_range: Tuple[int, int] = (16, 265), hidden_continuous_size_range: Tuple[int, int] = (8, 64), attention_head_size_range: Tuple[int, int] = (1, 4), dropout_range: Tuple[float, float] = (0.1, 0.3), learning_rate_range: Tuple[float, float] = (1e-5, 1.0), use_learning_rate_finder: bool = True, trainer_kwargs: Dict[str, Any] = {}, log_dir: str = "lightning_logs", study: optuna.Study = None, verbose: Union[int, bool] = None, pruner: optuna.pruners.BasePruner = optuna.pruners.SuccessiveHalvingPruner(), **kwargs, ) -> optuna.Study` to solve the following problem: Optimize Temporal Fusion Transformer hyperparameters. Run hyperparameter optimization. Learning rate for is determined with the PyTorch Lightning learning rate finder. Args: train_dataloaders (DataLoader): dataloader for training model val_dataloaders (DataLoader): dataloader for validating model model_path (str): folder to which model checkpoints are saved max_epochs (int, optional): Maximum number of epochs to run training. Defaults to 20. n_trials (int, optional): Number of hyperparameter trials to run. Defaults to 100. timeout (float, optional): Time in seconds after which training is stopped regardless of number of epochs or validation metric. Defaults to 3600*8.0. hidden_size_range (Tuple[int, int], optional): Minimum and maximum of ``hidden_size`` hyperparameter. Defaults to (16, 265). hidden_continuous_size_range (Tuple[int, int], optional): Minimum and maximum of ``hidden_continuous_size`` hyperparameter. Defaults to (8, 64). attention_head_size_range (Tuple[int, int], optional): Minimum and maximum of ``attention_head_size`` hyperparameter. Defaults to (1, 4). dropout_range (Tuple[float, float], optional): Minimum and maximum of ``dropout`` hyperparameter. Defaults to (0.1, 0.3). learning_rate_range (Tuple[float, float], optional): Learning rate range. Defaults to (1e-5, 1.0). use_learning_rate_finder (bool): If to use learning rate finder or optimize as part of hyperparameters. Defaults to True. trainer_kwargs (Dict[str, Any], optional): Additional arguments to the `PyTorch Lightning trainer <https://pytorch-lightning.readthedocs.io/en/latest/trainer.html>`_ such as ``limit_train_batches``. Defaults to {}. log_dir (str, optional): Folder into which to log results for tensorboard. Defaults to "lightning_logs". study (optuna.Study, optional): study to resume. Will create new study by default. verbose (Union[int, bool]): level of verbosity. * None: no change in verbosity level (equivalent to verbose=1 by optuna-set default). * 0 or False: log only warnings. * 1 or True: log pruning events. * 2: optuna logging level at debug level. Defaults to None. pruner (optuna.pruners.BasePruner, optional): The optuna pruner to use. Defaults to optuna.pruners.SuccessiveHalvingPruner(). **kwargs: Additional arguments for the :py:class:`~TemporalFusionTransformer`. Returns: optuna.Study: optuna study results Here is the function: def optimize_hyperparameters( train_dataloaders: DataLoader, val_dataloaders: DataLoader, model_path: str, max_epochs: int = 20, n_trials: int = 100, timeout: float = 3600 * 8.0, # 8 hours gradient_clip_val_range: Tuple[float, float] = (0.01, 100.0), hidden_size_range: Tuple[int, int] = (16, 265), hidden_continuous_size_range: Tuple[int, int] = (8, 64), attention_head_size_range: Tuple[int, int] = (1, 4), dropout_range: Tuple[float, float] = (0.1, 0.3), learning_rate_range: Tuple[float, float] = (1e-5, 1.0), use_learning_rate_finder: bool = True, trainer_kwargs: Dict[str, Any] = {}, log_dir: str = "lightning_logs", study: optuna.Study = None, verbose: Union[int, bool] = None, pruner: optuna.pruners.BasePruner = optuna.pruners.SuccessiveHalvingPruner(), **kwargs, ) -> optuna.Study: """ Optimize Temporal Fusion Transformer hyperparameters. Run hyperparameter optimization. Learning rate for is determined with the PyTorch Lightning learning rate finder. Args: train_dataloaders (DataLoader): dataloader for training model val_dataloaders (DataLoader): dataloader for validating model model_path (str): folder to which model checkpoints are saved max_epochs (int, optional): Maximum number of epochs to run training. Defaults to 20. n_trials (int, optional): Number of hyperparameter trials to run. Defaults to 100. timeout (float, optional): Time in seconds after which training is stopped regardless of number of epochs or validation metric. Defaults to 3600*8.0. hidden_size_range (Tuple[int, int], optional): Minimum and maximum of ``hidden_size`` hyperparameter. Defaults to (16, 265). hidden_continuous_size_range (Tuple[int, int], optional): Minimum and maximum of ``hidden_continuous_size`` hyperparameter. Defaults to (8, 64). attention_head_size_range (Tuple[int, int], optional): Minimum and maximum of ``attention_head_size`` hyperparameter. Defaults to (1, 4). dropout_range (Tuple[float, float], optional): Minimum and maximum of ``dropout`` hyperparameter. Defaults to (0.1, 0.3). learning_rate_range (Tuple[float, float], optional): Learning rate range. Defaults to (1e-5, 1.0). use_learning_rate_finder (bool): If to use learning rate finder or optimize as part of hyperparameters. Defaults to True. trainer_kwargs (Dict[str, Any], optional): Additional arguments to the `PyTorch Lightning trainer <https://pytorch-lightning.readthedocs.io/en/latest/trainer.html>`_ such as ``limit_train_batches``. Defaults to {}. log_dir (str, optional): Folder into which to log results for tensorboard. Defaults to "lightning_logs". study (optuna.Study, optional): study to resume. Will create new study by default. verbose (Union[int, bool]): level of verbosity. * None: no change in verbosity level (equivalent to verbose=1 by optuna-set default). * 0 or False: log only warnings. * 1 or True: log pruning events. * 2: optuna logging level at debug level. Defaults to None. pruner (optuna.pruners.BasePruner, optional): The optuna pruner to use. Defaults to optuna.pruners.SuccessiveHalvingPruner(). **kwargs: Additional arguments for the :py:class:`~TemporalFusionTransformer`. Returns: optuna.Study: optuna study results """ assert isinstance(train_dataloaders.dataset, TimeSeriesDataSet) and isinstance( val_dataloaders.dataset, TimeSeriesDataSet ), "dataloaders must be built from timeseriesdataset" logging_level = { None: optuna.logging.get_verbosity(), 0: optuna.logging.WARNING, 1: optuna.logging.INFO, 2: optuna.logging.DEBUG, } optuna_verbose = logging_level[verbose] optuna.logging.set_verbosity(optuna_verbose) loss = kwargs.get( "loss", QuantileLoss() ) # need a deepcopy of loss as it will otherwise propagate from one trial to the next # create objective function def objective(trial: optuna.Trial) -> float: # Filenames for each trial must be made unique in order to access each checkpoint. checkpoint_callback = ModelCheckpoint( dirpath=os.path.join(model_path, "trial_{}".format(trial.number)), filename="{epoch}", monitor="val_loss" ) learning_rate_callback = LearningRateMonitor() logger = TensorBoardLogger(log_dir, name="optuna", version=trial.number) gradient_clip_val = trial.suggest_loguniform("gradient_clip_val", *gradient_clip_val_range) default_trainer_kwargs = dict( accelerator="auto", max_epochs=max_epochs, gradient_clip_val=gradient_clip_val, callbacks=[ learning_rate_callback, checkpoint_callback, PyTorchLightningPruningCallbackAdjusted(trial, monitor="val_loss"), ], logger=logger, enable_progress_bar=optuna_verbose < optuna.logging.INFO, enable_model_summary=[False, True][optuna_verbose < optuna.logging.INFO], ) default_trainer_kwargs.update(trainer_kwargs) trainer = pl.Trainer( **default_trainer_kwargs, ) # create model hidden_size = trial.suggest_int("hidden_size", *hidden_size_range, log=True) kwargs["loss"] = copy.deepcopy(loss) model = TemporalFusionTransformer.from_dataset( train_dataloaders.dataset, dropout=trial.suggest_uniform("dropout", *dropout_range), hidden_size=hidden_size, hidden_continuous_size=trial.suggest_int( "hidden_continuous_size", hidden_continuous_size_range[0], min(hidden_continuous_size_range[1], hidden_size), log=True, ), attention_head_size=trial.suggest_int("attention_head_size", *attention_head_size_range), log_interval=-1, **kwargs, ) # find good learning rate if use_learning_rate_finder: lr_trainer = pl.Trainer( gradient_clip_val=gradient_clip_val, accelerator="auto", logger=False, enable_progress_bar=False, enable_model_summary=False, ) tuner = Tuner(lr_trainer) res = tuner.lr_find( model, train_dataloaders=train_dataloaders, val_dataloaders=val_dataloaders, early_stop_threshold=10000, min_lr=learning_rate_range[0], num_training=100, max_lr=learning_rate_range[1], ) loss_finite = np.isfinite(res.results["loss"]) if loss_finite.sum() > 3: # at least 3 valid values required for learning rate finder lr_smoothed, loss_smoothed = sm.nonparametric.lowess( np.asarray(res.results["loss"])[loss_finite], np.asarray(res.results["lr"])[loss_finite], frac=1.0 / 10.0, )[min(loss_finite.sum() - 3, 10) : -1].T optimal_idx = np.gradient(loss_smoothed).argmin() optimal_lr = lr_smoothed[optimal_idx] else: optimal_idx = np.asarray(res.results["loss"]).argmin() optimal_lr = res.results["lr"][optimal_idx] optuna_logger.info(f"Using learning rate of {optimal_lr:.3g}") # add learning rate artificially model.hparams.learning_rate = trial.suggest_uniform("learning_rate", optimal_lr, optimal_lr) else: model.hparams.learning_rate = trial.suggest_loguniform("learning_rate", *learning_rate_range) # fit trainer.fit(model, train_dataloaders=train_dataloaders, val_dataloaders=val_dataloaders) # report result return trainer.callback_metrics["val_loss"].item() # setup optuna and run if study is None: study = optuna.create_study(direction="minimize", pruner=pruner) study.optimize(objective, n_trials=n_trials, timeout=timeout) return study
Optimize Temporal Fusion Transformer hyperparameters. Run hyperparameter optimization. Learning rate for is determined with the PyTorch Lightning learning rate finder. Args: train_dataloaders (DataLoader): dataloader for training model val_dataloaders (DataLoader): dataloader for validating model model_path (str): folder to which model checkpoints are saved max_epochs (int, optional): Maximum number of epochs to run training. Defaults to 20. n_trials (int, optional): Number of hyperparameter trials to run. Defaults to 100. timeout (float, optional): Time in seconds after which training is stopped regardless of number of epochs or validation metric. Defaults to 3600*8.0. hidden_size_range (Tuple[int, int], optional): Minimum and maximum of ``hidden_size`` hyperparameter. Defaults to (16, 265). hidden_continuous_size_range (Tuple[int, int], optional): Minimum and maximum of ``hidden_continuous_size`` hyperparameter. Defaults to (8, 64). attention_head_size_range (Tuple[int, int], optional): Minimum and maximum of ``attention_head_size`` hyperparameter. Defaults to (1, 4). dropout_range (Tuple[float, float], optional): Minimum and maximum of ``dropout`` hyperparameter. Defaults to (0.1, 0.3). learning_rate_range (Tuple[float, float], optional): Learning rate range. Defaults to (1e-5, 1.0). use_learning_rate_finder (bool): If to use learning rate finder or optimize as part of hyperparameters. Defaults to True. trainer_kwargs (Dict[str, Any], optional): Additional arguments to the `PyTorch Lightning trainer <https://pytorch-lightning.readthedocs.io/en/latest/trainer.html>`_ such as ``limit_train_batches``. Defaults to {}. log_dir (str, optional): Folder into which to log results for tensorboard. Defaults to "lightning_logs". study (optuna.Study, optional): study to resume. Will create new study by default. verbose (Union[int, bool]): level of verbosity. * None: no change in verbosity level (equivalent to verbose=1 by optuna-set default). * 0 or False: log only warnings. * 1 or True: log pruning events. * 2: optuna logging level at debug level. Defaults to None. pruner (optuna.pruners.BasePruner, optional): The optuna pruner to use. Defaults to optuna.pruners.SuccessiveHalvingPruner(). **kwargs: Additional arguments for the :py:class:`~TemporalFusionTransformer`. Returns: optuna.Study: optuna study results
158,652
from typing import Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def linear(input_size, output_size, bias=True, dropout: int = None): lin = nn.Linear(input_size, output_size, bias=bias) if dropout is not None: return nn.Sequential(nn.Dropout(dropout), lin) else: return lin
null
158,653
from typing import Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def linspace(backcast_length: int, forecast_length: int, centered: bool = False) -> Tuple[np.ndarray, np.ndarray]: if centered: norm = max(backcast_length, forecast_length) start = -backcast_length stop = forecast_length - 1 else: norm = backcast_length + forecast_length start = 0 stop = backcast_length + forecast_length - 1 lin_space = np.linspace(start / norm, stop / norm, backcast_length + forecast_length, dtype=np.float32) b_ls = lin_space[:backcast_length] f_ls = lin_space[backcast_length:] return b_ls, f_ls
null
158,654
from collections import namedtuple import copy from copy import deepcopy import inspect import logging import os from typing import Any, Callable, Dict, Iterable, List, Literal, Optional, Tuple, Union import warnings import lightning.pytorch as pl from lightning.pytorch import LightningModule, Trainer from lightning.pytorch.callbacks import BasePredictionWriter, LearningRateFinder from lightning.pytorch.trainer.states import RunningStage from lightning.pytorch.utilities.parsing import AttributeDict, get_init_args import matplotlib.pyplot as plt import numpy as np from numpy.lib.function_base import iterable import pandas as pd import pytorch_optimizer from pytorch_optimizer import Ranger21 import scipy.stats import torch import torch.nn as nn from torch.nn.utils import rnn from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau from torch.utils.data import DataLoader from tqdm.autonotebook import tqdm import yaml from pytorch_forecasting.data import TimeSeriesDataSet from pytorch_forecasting.data.encoders import EncoderNormalizer, GroupNormalizer, MultiNormalizer, NaNLabelEncoder from pytorch_forecasting.metrics import ( MAE, MASE, SMAPE, DistributionLoss, MultiHorizonMetric, MultiLoss, QuantileLoss, convert_torchmetric_to_pytorch_forecasting_metric, ) from pytorch_forecasting.metrics.base_metrics import Metric from pytorch_forecasting.models.nn.embeddings import MultiEmbedding from pytorch_forecasting.utils import ( InitialParameterRepresenterMixIn, OutputMixIn, TupleOutputMixIn, apply_to_list, concat_sequences, create_mask, get_embedding_size, groupby_apply, to_list, ) def _torch_cat_na(x: List[torch.Tensor]) -> torch.Tensor: """ Concatenate tensor along ``dim=0`` and add nans along ``dim=1`` if necessary. Allows concatenation of tensors where ``dim=1`` are not equal. Missing values are filled up with ``nan``. Args: x (List[torch.Tensor]): list of tensors to concatenate along dimension 0 Returns: torch.Tensor: concatenated tensor """ if x[0].ndim > 1: first_lens = [xi.shape[1] for xi in x] max_first_len = max(first_lens) if max_first_len > min(first_lens): x = [ xi if xi.shape[1] == max_first_len else torch.cat( [ xi, torch.full( (xi.shape[0], max_first_len - xi.shape[1], *xi.shape[2:]), float("nan"), device=xi.device ), ], dim=1, ) for xi in x ] # check if remaining dimensions are all equal if x[0].ndim > 2: remaining_dimensions_equal = all([all([xi.size(i) == x[0].size(i) for xi in x]) for i in range(2, x[0].ndim)]) else: remaining_dimensions_equal = True # deaggregate if remaining_dimensions_equal: return torch.cat(x, dim=0) else: # make list instead but warn warnings.warn( f"Not all dimensions are equal for tensors shapes. Example tensor {x[0].shape}. " "Returning list instead of torch.Tensor.", UserWarning, ) return [xii for xi in x for xii in xi] class OutputMixIn: """ MixIn to give namedtuple some access capabilities of a dictionary """ def __getitem__(self, k): if isinstance(k, str): return getattr(self, k) else: return super().__getitem__(k) def get(self, k, default=None): return getattr(self, k, default) def items(self): return zip(self._fields, self) def keys(self): return self._fields def iget(self, idx: Union[int, slice]): """Select item(s) row-wise. Args: idx ([int, slice]): item to select Returns: Output of single item. """ return self.__class__(*(x[idx] for x in self)) The provided code snippet includes necessary dependencies for implementing the `_concatenate_output` function. Write a Python function `def _concatenate_output( output: List[Dict[str, List[Union[List[torch.Tensor], torch.Tensor, bool, int, str, np.ndarray]]]] ) -> Dict[str, Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, int, bool, str]]]]` to solve the following problem: Concatenate multiple batches of output dictionary. Args: output (List[Dict[str, List[Union[List[torch.Tensor], torch.Tensor, bool, int, str, np.ndarray]]]]): list of outputs to concatenate. Each entry corresponds to a batch. Returns: Dict[str, Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, int, bool, str]]]]: concatenated output Here is the function: def _concatenate_output( output: List[Dict[str, List[Union[List[torch.Tensor], torch.Tensor, bool, int, str, np.ndarray]]]] ) -> Dict[str, Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, int, bool, str]]]]: """ Concatenate multiple batches of output dictionary. Args: output (List[Dict[str, List[Union[List[torch.Tensor], torch.Tensor, bool, int, str, np.ndarray]]]]): list of outputs to concatenate. Each entry corresponds to a batch. Returns: Dict[str, Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, int, bool, str]]]]: concatenated output """ output_cat = {} for name in output[0].keys(): v0 = output[0][name] # concatenate simple tensors if isinstance(v0, torch.Tensor): output_cat[name] = _torch_cat_na([out[name] for out in output]) # concatenate list of tensors elif isinstance(v0, (tuple, list)) and len(v0) > 0: output_cat[name] = [] for target_id in range(len(v0)): if isinstance(v0[target_id], torch.Tensor): output_cat[name].append(_torch_cat_na([out[name][target_id] for out in output])) else: try: output_cat[name].append(np.concatenate([out[name][target_id] for out in output], axis=0)) except ValueError: output_cat[name] = [item for out in output for item in out[name][target_id]] # flatten list for everything else else: try: output_cat[name] = np.concatenate([out[name] for out in output], axis=0) except ValueError: if iterable(output[0][name]): output_cat[name] = [item for out in output for item in out[name]] else: output_cat[name] = [out[name] for out in output] if isinstance(output[0], OutputMixIn): output_cat = output[0].__class__(**output_cat) return output_cat
Concatenate multiple batches of output dictionary. Args: output (List[Dict[str, List[Union[List[torch.Tensor], torch.Tensor, bool, int, str, np.ndarray]]]]): list of outputs to concatenate. Each entry corresponds to a batch. Returns: Dict[str, Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, int, bool, str]]]]: concatenated output
158,655
from functools import partial from typing import List, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def init_weights(module, initialization): if type(module) is torch.nn.Linear: if initialization == "orthogonal": torch.nn.init.orthogonal_(module.weight) elif initialization == "he_uniform": torch.nn.init.kaiming_uniform_(module.weight) elif initialization == "he_normal": torch.nn.init.kaiming_normal_(module.weight) elif initialization == "glorot_uniform": torch.nn.init.xavier_uniform_(module.weight) elif initialization == "glorot_normal": torch.nn.init.xavier_normal_(module.weight) elif initialization == "lecun_normal": pass # torch.nn.init.normal_(module.weight, 0.0, std=1/np.sqrt(module.weight.numel())) else: assert 1 < 0, f"Initialization {initialization} not found"
null
158,656
import torch import torch.nn.functional as F def stride_from_shape(shape): stride = [1] for x in reversed(shape[1:]): stride.append(stride[-1] * x) return list(reversed(stride)) def scatter_add_nd(input, indices, values): # input: [..., C], D dimension + C channel # indices: [N, D], long # values: [N, C] D = indices.shape[-1] C = input.shape[-1] size = input.shape[:-1] stride = stride_from_shape(size) assert len(size) == D input = input.view(-1, C) # [HW, C] flatten_indices = (indices * torch.tensor(stride, dtype=torch.long, device=indices.device)).sum(-1) # [N] input.scatter_add_(0, flatten_indices.unsqueeze(1).repeat(1, C), values) return input.view(*size, C)
null
158,657
import torch import torch.nn.functional as F def nearest_grid_put_2d(H, W, coords, values, return_count=False): # coords: [N, 2], float in [-1, 1] # values: [N, C] C = values.shape[-1] indices = (coords * 0.5 + 0.5) * torch.tensor( [H - 1, W - 1], dtype=torch.float32, device=coords.device ) indices = indices.round().long() # [N, 2] result = torch.zeros(H, W, C, device=values.device, dtype=values.dtype) # [H, W, C] count = torch.zeros(H, W, 1, device=values.device, dtype=values.dtype) # [H, W, 1] weights = torch.ones_like(values[..., :1]) # [N, 1] result, count = scatter_add_nd_with_count(result, count, indices, values, weights) if return_count: return result, count mask = (count.squeeze(-1) > 0) result[mask] = result[mask] / count[mask].repeat(1, C) return result def linear_grid_put_2d(H, W, coords, values, return_count=False): # coords: [N, 2], float in [-1, 1] # values: [N, C] C = values.shape[-1] indices = (coords * 0.5 + 0.5) * torch.tensor( [H - 1, W - 1], dtype=torch.float32, device=coords.device ) indices_00 = indices.floor().long() # [N, 2] indices_00[:, 0].clamp_(0, H - 2) indices_00[:, 1].clamp_(0, W - 2) indices_01 = indices_00 + torch.tensor( [0, 1], dtype=torch.long, device=indices.device ) indices_10 = indices_00 + torch.tensor( [1, 0], dtype=torch.long, device=indices.device ) indices_11 = indices_00 + torch.tensor( [1, 1], dtype=torch.long, device=indices.device ) h = indices[..., 0] - indices_00[..., 0].float() w = indices[..., 1] - indices_00[..., 1].float() w_00 = (1 - h) * (1 - w) w_01 = (1 - h) * w w_10 = h * (1 - w) w_11 = h * w result = torch.zeros(H, W, C, device=values.device, dtype=values.dtype) # [H, W, C] count = torch.zeros(H, W, 1, device=values.device, dtype=values.dtype) # [H, W, 1] weights = torch.ones_like(values[..., :1]) # [N, 1] result, count = scatter_add_nd_with_count(result, count, indices_00, values * w_00.unsqueeze(1), weights* w_00.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_01, values * w_01.unsqueeze(1), weights* w_01.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_10, values * w_10.unsqueeze(1), weights* w_10.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_11, values * w_11.unsqueeze(1), weights* w_11.unsqueeze(1)) if return_count: return result, count mask = (count.squeeze(-1) > 0) result[mask] = result[mask] / count[mask].repeat(1, C) return result def mipmap_linear_grid_put_2d(H, W, coords, values, min_resolution=32, return_count=False): # coords: [N, 2], float in [-1, 1] # values: [N, C] C = values.shape[-1] result = torch.zeros(H, W, C, device=values.device, dtype=values.dtype) # [H, W, C] count = torch.zeros(H, W, 1, device=values.device, dtype=values.dtype) # [H, W, 1] cur_H, cur_W = H, W while min(cur_H, cur_W) > min_resolution: # try to fill the holes mask = (count.squeeze(-1) == 0) if not mask.any(): break cur_result, cur_count = linear_grid_put_2d(cur_H, cur_W, coords, values, return_count=True) result[mask] = result[mask] + F.interpolate(cur_result.permute(2,0,1).unsqueeze(0).contiguous(), (H, W), mode='bilinear', align_corners=False).squeeze(0).permute(1,2,0).contiguous()[mask] count[mask] = count[mask] + F.interpolate(cur_count.view(1, 1, cur_H, cur_W), (H, W), mode='bilinear', align_corners=False).view(H, W, 1)[mask] cur_H //= 2 cur_W //= 2 if return_count: return result, count mask = (count.squeeze(-1) > 0) result[mask] = result[mask] / count[mask].repeat(1, C) return result def nearest_grid_put_3d(H, W, D, coords, values, return_count=False): # coords: [N, 3], float in [-1, 1] # values: [N, C] C = values.shape[-1] indices = (coords * 0.5 + 0.5) * torch.tensor( [H - 1, W - 1, D - 1], dtype=torch.float32, device=coords.device ) indices = indices.round().long() # [N, 2] result = torch.zeros(H, W, D, C, device=values.device, dtype=values.dtype) # [H, W, C] count = torch.zeros(H, W, D, 1, device=values.device, dtype=values.dtype) # [H, W, 1] weights = torch.ones_like(values[..., :1]) # [N, 1] result, count = scatter_add_nd_with_count(result, count, indices, values, weights) if return_count: return result, count mask = (count.squeeze(-1) > 0) result[mask] = result[mask] / count[mask].repeat(1, C) return result def linear_grid_put_3d(H, W, D, coords, values, return_count=False): # coords: [N, 3], float in [-1, 1] # values: [N, C] C = values.shape[-1] indices = (coords * 0.5 + 0.5) * torch.tensor( [H - 1, W - 1, D - 1], dtype=torch.float32, device=coords.device ) indices_000 = indices.floor().long() # [N, 3] indices_000[:, 0].clamp_(0, H - 2) indices_000[:, 1].clamp_(0, W - 2) indices_000[:, 2].clamp_(0, D - 2) indices_001 = indices_000 + torch.tensor([0, 0, 1], dtype=torch.long, device=indices.device) indices_010 = indices_000 + torch.tensor([0, 1, 0], dtype=torch.long, device=indices.device) indices_011 = indices_000 + torch.tensor([0, 1, 1], dtype=torch.long, device=indices.device) indices_100 = indices_000 + torch.tensor([1, 0, 0], dtype=torch.long, device=indices.device) indices_101 = indices_000 + torch.tensor([1, 0, 1], dtype=torch.long, device=indices.device) indices_110 = indices_000 + torch.tensor([1, 1, 0], dtype=torch.long, device=indices.device) indices_111 = indices_000 + torch.tensor([1, 1, 1], dtype=torch.long, device=indices.device) h = indices[..., 0] - indices_000[..., 0].float() w = indices[..., 1] - indices_000[..., 1].float() d = indices[..., 2] - indices_000[..., 2].float() w_000 = (1 - h) * (1 - w) * (1 - d) w_001 = (1 - h) * w * (1 - d) w_010 = h * (1 - w) * (1 - d) w_011 = h * w * (1 - d) w_100 = (1 - h) * (1 - w) * d w_101 = (1 - h) * w * d w_110 = h * (1 - w) * d w_111 = h * w * d result = torch.zeros(H, W, D, C, device=values.device, dtype=values.dtype) # [H, W, D, C] count = torch.zeros(H, W, D, 1, device=values.device, dtype=values.dtype) # [H, W, D, 1] weights = torch.ones_like(values[..., :1]) # [N, 1] result, count = scatter_add_nd_with_count(result, count, indices_000, values * w_000.unsqueeze(1), weights * w_000.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_001, values * w_001.unsqueeze(1), weights * w_001.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_010, values * w_010.unsqueeze(1), weights * w_010.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_011, values * w_011.unsqueeze(1), weights * w_011.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_100, values * w_100.unsqueeze(1), weights * w_100.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_101, values * w_101.unsqueeze(1), weights * w_101.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_110, values * w_110.unsqueeze(1), weights * w_110.unsqueeze(1)) result, count = scatter_add_nd_with_count(result, count, indices_111, values * w_111.unsqueeze(1), weights * w_111.unsqueeze(1)) if return_count: return result, count mask = (count.squeeze(-1) > 0) result[mask] = result[mask] / count[mask].repeat(1, C) return result def mipmap_linear_grid_put_3d(H, W, D, coords, values, min_resolution=32, return_count=False): # coords: [N, 3], float in [-1, 1] # values: [N, C] C = values.shape[-1] result = torch.zeros(H, W, D, C, device=values.device, dtype=values.dtype) # [H, W, D, C] count = torch.zeros(H, W, D, 1, device=values.device, dtype=values.dtype) # [H, W, D, 1] cur_H, cur_W, cur_D = H, W, D while min(min(cur_H, cur_W), cur_D) > min_resolution: # try to fill the holes mask = (count.squeeze(-1) == 0) if not mask.any(): break cur_result, cur_count = linear_grid_put_3d(cur_H, cur_W, cur_D, coords, values, return_count=True) result[mask] = result[mask] + F.interpolate(cur_result.permute(3,0,1,2).unsqueeze(0).contiguous(), (H, W, D), mode='trilinear', align_corners=False).squeeze(0).permute(1,2,3,0).contiguous()[mask] count[mask] = count[mask] + F.interpolate(cur_count.view(1, 1, cur_H, cur_W, cur_D), (H, W, D), mode='trilinear', align_corners=False).view(H, W, D, 1)[mask] cur_H //= 2 cur_W //= 2 cur_D //= 2 if return_count: return result, count mask = (count.squeeze(-1) > 0) result[mask] = result[mask] / count[mask].repeat(1, C) return result def grid_put(shape, coords, values, mode='linear-mipmap', min_resolution=32, return_raw=False): # shape: [D], list/tuple # coords: [N, D], float in [-1, 1] # values: [N, C] D = len(shape) assert D in [2, 3], f'only support D == 2 or 3, but got D == {D}' if mode == 'nearest': if D == 2: return nearest_grid_put_2d(*shape, coords, values, return_raw) else: return nearest_grid_put_3d(*shape, coords, values, return_raw) elif mode == 'linear': if D == 2: return linear_grid_put_2d(*shape, coords, values, return_raw) else: return linear_grid_put_3d(*shape, coords, values, return_raw) elif mode == 'linear-mipmap': if D == 2: return mipmap_linear_grid_put_2d(*shape, coords, values, min_resolution, return_raw) else: return mipmap_linear_grid_put_3d(*shape, coords, values, min_resolution, return_raw) else: raise NotImplementedError(f"got mode {mode}")
null
158,658
import numpy as np import pymeshlab as pml def poisson_mesh_reconstruction(points, normals=None): # points/normals: [N, 3] np.ndarray import open3d as o3d pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(points) # outlier removal pcd, ind = pcd.remove_statistical_outlier(nb_neighbors=20, std_ratio=10) # normals if normals is None: pcd.estimate_normals() else: pcd.normals = o3d.utility.Vector3dVector(normals[ind]) # visualize o3d.visualization.draw_geometries([pcd], point_show_normal=False) mesh, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson( pcd, depth=9 ) vertices_to_remove = densities < np.quantile(densities, 0.1) mesh.remove_vertices_by_mask(vertices_to_remove) # visualize o3d.visualization.draw_geometries([mesh]) vertices = np.asarray(mesh.vertices) triangles = np.asarray(mesh.triangles) print( f"[INFO] poisson mesh reconstruction: {points.shape} --> {vertices.shape} / {triangles.shape}" ) return vertices, triangles
null
158,659
import numpy as np import pymeshlab as pml def decimate_mesh( verts, faces, target, backend="pymeshlab", remesh=False, optimalplacement=True ): # optimalplacement: default is True, but for flat mesh must turn False to prevent spike artifect. _ori_vert_shape = verts.shape _ori_face_shape = faces.shape if backend == "pyfqmr": import pyfqmr solver = pyfqmr.Simplify() solver.setMesh(verts, faces) solver.simplify_mesh(target_count=target, preserve_border=False, verbose=False) verts, faces, normals = solver.getMesh() else: m = pml.Mesh(verts, faces) ms = pml.MeshSet() ms.add_mesh(m, "mesh") # will copy! # filters # ms.meshing_decimation_clustering(threshold=pml.PercentageValue(1)) ms.meshing_decimation_quadric_edge_collapse( targetfacenum=int(target), optimalplacement=optimalplacement ) if remesh: # ms.apply_coord_taubin_smoothing() ms.meshing_isotropic_explicit_remeshing( iterations=3, targetlen=pml.PercentageValue(1) ) # extract mesh m = ms.current_mesh() verts = m.vertex_matrix() faces = m.face_matrix() print( f"[INFO] mesh decimation: {_ori_vert_shape} --> {verts.shape}, {_ori_face_shape} --> {faces.shape}" ) return verts, faces
null
158,660
import numpy as np import pymeshlab as pml def clean_mesh( verts, faces, v_pct=1, min_f=64, min_d=20, repair=True, remesh=True, remesh_size=0.01, ): # verts: [N, 3] # faces: [N, 3] _ori_vert_shape = verts.shape _ori_face_shape = faces.shape m = pml.Mesh(verts, faces) ms = pml.MeshSet() ms.add_mesh(m, "mesh") # will copy! # filters ms.meshing_remove_unreferenced_vertices() # verts not refed by any faces if v_pct > 0: ms.meshing_merge_close_vertices( threshold=pml.PercentageValue(v_pct) ) # 1/10000 of bounding box diagonal ms.meshing_remove_duplicate_faces() # faces defined by the same verts ms.meshing_remove_null_faces() # faces with area == 0 if min_d > 0: ms.meshing_remove_connected_component_by_diameter( mincomponentdiag=pml.PercentageValue(min_d) ) if min_f > 0: ms.meshing_remove_connected_component_by_face_number(mincomponentsize=min_f) if repair: # ms.meshing_remove_t_vertices(method=0, threshold=40, repeat=True) ms.meshing_repair_non_manifold_edges(method=0) ms.meshing_repair_non_manifold_vertices(vertdispratio=0) if remesh: # ms.apply_coord_taubin_smoothing() ms.meshing_isotropic_explicit_remeshing( iterations=3, targetlen=pml.PureValue(remesh_size) ) # extract mesh m = ms.current_mesh() verts = m.vertex_matrix() faces = m.face_matrix() print( f"[INFO] mesh cleaning: {_ori_vert_shape} --> {verts.shape}, {_ori_face_shape} --> {faces.shape}" ) return verts, faces
null
158,661
import os import math import cv2 import trimesh import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import nvdiffrast.torch as dr from mesh import Mesh, safe_normalize def scale_img_nhwc(x, size, mag='bilinear', min='bilinear'): assert (x.shape[1] >= size[0] and x.shape[2] >= size[1]) or (x.shape[1] < size[0] and x.shape[2] < size[1]), "Trying to magnify image in one dimension and minify in the other" y = x.permute(0, 3, 1, 2) # NHWC -> NCHW if x.shape[1] > size[0] and x.shape[2] > size[1]: # Minification, previous size was bigger y = torch.nn.functional.interpolate(y, size, mode=min) else: # Magnification if mag == 'bilinear' or mag == 'bicubic': y = torch.nn.functional.interpolate(y, size, mode=mag, align_corners=True) else: y = torch.nn.functional.interpolate(y, size, mode=mag) return y.permute(0, 2, 3, 1).contiguous() # NCHW -> NHWC def scale_img_hwc(x, size, mag='bilinear', min='bilinear'): return scale_img_nhwc(x[None, ...], size, mag, min)[0]
null
158,662
import os import math import cv2 import trimesh import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import nvdiffrast.torch as dr from mesh import Mesh, safe_normalize def scale_img_nhwc(x, size, mag='bilinear', min='bilinear'): # NCHW -> NHWC def scale_img_nhw(x, size, mag='bilinear', min='bilinear'): return scale_img_nhwc(x[..., None], size, mag, min)[..., 0]
null
158,663
import os import math import cv2 import trimesh import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import nvdiffrast.torch as dr from mesh import Mesh, safe_normalize def scale_img_nhwc(x, size, mag='bilinear', min='bilinear'): assert (x.shape[1] >= size[0] and x.shape[2] >= size[1]) or (x.shape[1] < size[0] and x.shape[2] < size[1]), "Trying to magnify image in one dimension and minify in the other" y = x.permute(0, 3, 1, 2) # NHWC -> NCHW if x.shape[1] > size[0] and x.shape[2] > size[1]: # Minification, previous size was bigger y = torch.nn.functional.interpolate(y, size, mode=min) else: # Magnification if mag == 'bilinear' or mag == 'bicubic': y = torch.nn.functional.interpolate(y, size, mode=mag, align_corners=True) else: y = torch.nn.functional.interpolate(y, size, mode=mag) return y.permute(0, 2, 3, 1).contiguous() # NCHW -> NHWC def scale_img_hw(x, size, mag='bilinear', min='bilinear'): return scale_img_nhwc(x[None, ..., None], size, mag, min)[0, ..., 0]
null
158,664
import os import math import cv2 import trimesh import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import nvdiffrast.torch as dr from mesh import Mesh, safe_normalize def trunc_rev_sigmoid(x, eps=1e-6): x = x.clamp(eps, 1 - eps) return torch.log(x / (1 - x))
null
158,665
import os import math import cv2 import trimesh import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import nvdiffrast.torch as dr from mesh import Mesh, safe_normalize def make_divisible(x, m=8): return int(math.ceil(x / m) * m)
null
158,668
import torch C0 = 0.28209479177387814 def SH2RGB(sh): return sh * C0 + 0.5
null
158,669
import os import cv2 import torch import trimesh import numpy as np def length(x, eps=1e-20): return torch.sqrt(torch.clamp(dot(x, x), min=eps)) def safe_normalize(x, eps=1e-20): return x / length(x, eps)
null
158,670
import os import math import numpy as np from typing import NamedTuple from plyfile import PlyData, PlyElement import torch from torch import nn from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from sh_utils import eval_sh, SH2RGB, RGB2SH from mesh import Mesh from mesh_utils import decimate_mesh, clean_mesh import kiui def inverse_sigmoid(x): return torch.log(x/(1-x))
null
158,671
import os import math import numpy as np from typing import NamedTuple from plyfile import PlyData, PlyElement import torch from torch import nn from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from sh_utils import eval_sh, SH2RGB, RGB2SH from mesh import Mesh from mesh_utils import decimate_mesh, clean_mesh import kiui def get_expon_lr_func( lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000 ): def helper(step): if lr_init == lr_final: # constant lr, ignore other params return lr_init if step < 0 or (lr_init == 0.0 and lr_final == 0.0): # Disable this parameter return 0.0 if lr_delay_steps > 0: # A kind of reverse cosine decay. delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin( 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1) ) else: delay_rate = 1.0 t = np.clip(step / max_steps, 0, 1) log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t) return delay_rate * log_lerp return helper
null
158,672
import os import math import numpy as np from typing import NamedTuple from plyfile import PlyData, PlyElement import torch from torch import nn from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from sh_utils import eval_sh, SH2RGB, RGB2SH from mesh import Mesh from mesh_utils import decimate_mesh, clean_mesh import kiui def strip_lowerdiag(L): uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device="cuda") uncertainty[:, 0] = L[:, 0, 0] uncertainty[:, 1] = L[:, 0, 1] uncertainty[:, 2] = L[:, 0, 2] uncertainty[:, 3] = L[:, 1, 1] uncertainty[:, 4] = L[:, 1, 2] uncertainty[:, 5] = L[:, 2, 2] return uncertainty def strip_symmetric(sym): return strip_lowerdiag(sym)
null
158,673
import os import math import numpy as np from typing import NamedTuple from plyfile import PlyData, PlyElement import torch from torch import nn from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from sh_utils import eval_sh, SH2RGB, RGB2SH from mesh import Mesh from mesh_utils import decimate_mesh, clean_mesh import kiui def gaussian_3d_coeff(xyzs, covs): # xyzs: [N, 3] # covs: [N, 6] x, y, z = xyzs[:, 0], xyzs[:, 1], xyzs[:, 2] a, b, c, d, e, f = covs[:, 0], covs[:, 1], covs[:, 2], covs[:, 3], covs[:, 4], covs[:, 5] # eps must be small enough !!! inv_det = 1 / (a * d * f + 2 * e * c * b - e**2 * a - c**2 * d - b**2 * f + 1e-24) inv_a = (d * f - e**2) * inv_det inv_b = (e * c - b * f) * inv_det inv_c = (e * b - c * d) * inv_det inv_d = (a * f - c**2) * inv_det inv_e = (b * c - e * a) * inv_det inv_f = (a * d - b**2) * inv_det power = -0.5 * (x**2 * inv_a + y**2 * inv_d + z**2 * inv_f) - x * y * inv_b - x * z * inv_c - y * z * inv_e power[power > 0] = -1e10 # abnormal values... make weights 0 return torch.exp(power)
null
158,674
import os import math import numpy as np from typing import NamedTuple from plyfile import PlyData, PlyElement import torch from torch import nn from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from sh_utils import eval_sh, SH2RGB, RGB2SH from mesh import Mesh from mesh_utils import decimate_mesh, clean_mesh import kiui def build_rotation(r): norm = torch.sqrt(r[:,0]*r[:,0] + r[:,1]*r[:,1] + r[:,2]*r[:,2] + r[:,3]*r[:,3]) q = r / norm[:, None] R = torch.zeros((q.size(0), 3, 3), device='cuda') r = q[:, 0] x = q[:, 1] y = q[:, 2] z = q[:, 3] R[:, 0, 0] = 1 - 2 * (y*y + z*z) R[:, 0, 1] = 2 * (x*y - r*z) R[:, 0, 2] = 2 * (x*z + r*y) R[:, 1, 0] = 2 * (x*y + r*z) R[:, 1, 1] = 1 - 2 * (x*x + z*z) R[:, 1, 2] = 2 * (y*z - r*x) R[:, 2, 0] = 2 * (x*z - r*y) R[:, 2, 1] = 2 * (y*z + r*x) R[:, 2, 2] = 1 - 2 * (x*x + y*y) return R def build_scaling_rotation(s, r): L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device="cuda") R = build_rotation(r) L[:,0,0] = s[:,0] L[:,1,1] = s[:,1] L[:,2,2] = s[:,2] L = R @ L return L
null
158,675
import os import math import numpy as np from typing import NamedTuple from plyfile import PlyData, PlyElement import torch from torch import nn from diff_gaussian_rasterization import ( GaussianRasterizationSettings, GaussianRasterizer, ) from simple_knn._C import distCUDA2 from sh_utils import eval_sh, SH2RGB, RGB2SH from mesh import Mesh from mesh_utils import decimate_mesh, clean_mesh import kiui def getProjectionMatrix(znear, zfar, fovX, fovY): tanHalfFovY = math.tan((fovY / 2)) tanHalfFovX = math.tan((fovX / 2)) P = torch.zeros(4, 4) z_sign = 1.0 P[0, 0] = 1 / tanHalfFovX P[1, 1] = 1 / tanHalfFovY P[3, 2] = z_sign P[2, 2] = z_sign * zfar / (zfar - znear) P[2, 3] = -(zfar * znear) / (zfar - znear) return P
null
158,676
import gradio as gr import os from PIL import Image import subprocess def check_img_input(control_image): if control_image is None: raise gr.Error("Please select or upload an input image")
null
158,677
import gradio as gr import os from PIL import Image import subprocess def optimize_stage_1(image_block: Image.Image, preprocess_chk: bool, elevation_slider: float): if not os.path.exists('tmp_data'): os.makedirs('tmp_data') if preprocess_chk: # save image to a designated path image_block.save(os.path.join('tmp_data', 'tmp.png')) # preprocess image print(f'python process.py {os.path.join("tmp_data", "tmp.png")}') subprocess.run(f'python process.py {os.path.join("tmp_data", "tmp.png")}', shell=True) else: image_block.save(os.path.join('tmp_data', 'tmp_rgba.png')) # stage 1 subprocess.run(f'python main.py --config {os.path.join("configs", "image.yaml")} input={os.path.join("tmp_data", "tmp_rgba.png")} save_path=tmp mesh_format=glb elevation={elevation_slider} force_cuda_rast=True', shell=True) return os.path.join('logs', 'tmp_mesh.glb')
null
158,678
import gradio as gr import os from PIL import Image import subprocess def optimize_stage_2(elevation_slider: float): # stage 2 subprocess.run(f'python main2.py --config {os.path.join("configs", "image.yaml")} input={os.path.join("tmp_data", "tmp_rgba.png")} save_path=tmp mesh_format=glb elevation={elevation_slider} force_cuda_rast=True', shell=True) return os.path.join('logs', 'tmp.glb')
null
158,679
import numpy as np from scipy.spatial.transform import Rotation as R import torch def look_at(campos, target, opengl=True): # campos: [N, 3], camera/eye position # target: [N, 3], object to look at # return: [N, 3, 3], rotation matrix if not opengl: # camera forward aligns with -z forward_vector = safe_normalize(target - campos) up_vector = np.array([0, 1, 0], dtype=np.float32) right_vector = safe_normalize(np.cross(forward_vector, up_vector)) up_vector = safe_normalize(np.cross(right_vector, forward_vector)) else: # camera forward aligns with +z forward_vector = safe_normalize(campos - target) up_vector = np.array([0, 1, 0], dtype=np.float32) right_vector = safe_normalize(np.cross(up_vector, forward_vector)) up_vector = safe_normalize(np.cross(forward_vector, right_vector)) R = np.stack([right_vector, up_vector, forward_vector], axis=1) return R def orbit_camera(elevation, azimuth, radius=1, is_degree=True, target=None, opengl=True): # radius: scalar # elevation: scalar, in (-90, 90), from +y to -y is (-90, 90) # azimuth: scalar, in (-180, 180), from +z to +x is (0, 90) # return: [4, 4], camera pose matrix if is_degree: elevation = np.deg2rad(elevation) azimuth = np.deg2rad(azimuth) x = radius * np.cos(elevation) * np.sin(azimuth) y = - radius * np.sin(elevation) z = radius * np.cos(elevation) * np.cos(azimuth) if target is None: target = np.zeros([3], dtype=np.float32) campos = np.array([x, y, z]) + target # [3] T = np.eye(4, dtype=np.float32) T[:3, :3] = look_at(campos, target, opengl) T[:3, 3] = campos return T
null
158,680
from diffusers import ( DDIMScheduler, StableDiffusionPipeline, ) from diffusers.utils.import_utils import is_xformers_available import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def seed_everything(seed): torch.manual_seed(seed) torch.cuda.manual_seed(seed) # torch.backends.cudnn.deterministic = True # torch.backends.cudnn.benchmark = True
null
158,681
from typing import List import torch import torch.nn as nn class DiscretePolicyNetwork(nn.Module): def __init__(self, obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of discrete action policy network used in PPO, which is mainly composed of two parts: encoder and head. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(DiscretePolicyNetwork, self).__init__() # Define encoder module, which maps raw state into embedding vector. # It could be different for various state, such as Convolution Neural Network (CNN) for image state and Multilayer perceptron (MLP) for vector state, respectively. # Here we use one-layer MLP for vector state, i.e. # $$y = max(Wx+b, 0)$$ self.encoder = nn.Sequential( nn.Linear(obs_shape, 32), nn.ReLU(), ) # Define discrete action logit output network, just one-layer FC, i.e. # $$y=Wx+b$$ self.head = nn.Linear(32, action_shape) # delimiter def forward(self, x: torch.Tensor) -> torch.Tensor: """ **Overview**: The computation graph of discrete action policy network used in PPO. ``x -> encoder -> head -> logit`` . """ # Transform original state into embedding vector, i.e. $$(B, *) -> (B, N)$$ x = self.encoder(x) # Calculate logit for each possible discrete action choices, i.e. $$(B, N) -> (B, A)$$ logit = self.head(x) return logit def sample_action(logit: torch.Tensor) -> torch.Tensor: """ **Overview**: The function of sampling discrete action, input shape = (B, action_shape), output shape = (B, ). In this example, the distributions shapes are: batch_shape = (B, ), event_shape = (), sample_shape = (). """ # Transform logit (raw output of policy network, e.g. last fully connected layer) into probability. # $$\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}$$ prob = torch.softmax(logit, dim=-1) # Construct categorical distribution. The probability mass function is: $$f(x=i|\boldsymbol{p})=p_i$$ # <link https://en.wikipedia.org/wiki/Categorical_distribution link> dist = torch.distributions.Categorical(probs=prob) # Sample one discrete action per sample (state input) and return it. return dist.sample() The provided code snippet includes necessary dependencies for implementing the `test_sample_discrete_action` function. Write a Python function `def test_sample_discrete_action()` to solve the following problem: **Overview**: The function of testing sampling discrete action. Construct a naive policy and sample a group of action. Here is the function: def test_sample_discrete_action(): """ **Overview**: The function of testing sampling discrete action. Construct a naive policy and sample a group of action. """ # Set batch_size = 4, obs_shape = 10, action_shape = 6. B, obs_shape, action_shape = 4, 10, 6 # Generate state data from uniform distribution in [0, 1]. state = torch.rand(B, obs_shape) # Define policy network with encoder and head. policy_network = DiscretePolicyNetwork(obs_shape, action_shape) # Policy network forward procedure, input state and output logit. # $$ logit = \pi(a|s)$$ logit = policy_network(state) assert logit.shape == (B, action_shape) # Sample action accoding to corresponding logit. action = sample_action(logit) assert action.shape == (B, )
**Overview**: The function of testing sampling discrete action. Construct a naive policy and sample a group of action.
158,682
from typing import List import torch import torch.nn as nn class MultiDiscretePolicyNetwork(nn.Module): def __init__(self, obs_shape: int, action_shape: List[int]) -> None: """ **Overview**: The definition of multi discrete action policy network used in PPO, which uses multiple discrete head. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(MultiDiscretePolicyNetwork, self).__init__() # Define encoder module, which maps raw state into embedding vector. # It could be different for various state, such as Convolution Neural Network (CNN) for image state and Multilayer perceptron (MLP) for vector state, respectively. # Here we use one-layer MLP for vector state, i.e. # $$y = max(Wx+b, 0)$$ self.encoder = nn.Sequential( nn.Linear(obs_shape, 32), nn.ReLU(), ) # Define multiple discrete head according to the concrete sub action size. self.head = nn.ModuleList() for size in action_shape: self.head.append(nn.Linear(32, size)) # delimiter def forward(self, x: torch.Tensor) -> List[torch.Tensor]: """ **Overview**: The computation graph of discrete action policy network used in PPO. ``x -> encoder -> multiple head -> multiple logit`` . """ # Transform original state into embedding vector, i.e. $$(B, *) -> (B, N)$$ x = self.encoder(x) # Calculate multiple logit for each possible discrete action, i.e. $$(B, N) -> [(B, A_1), ..., (B, A_N)]$$ logit = [h(x) for h in self.head] return logit def sample_action(logit: torch.Tensor) -> torch.Tensor: """ **Overview**: The function of sampling discrete action, input shape = (B, action_shape), output shape = (B, ). In this example, the distributions shapes are: batch_shape = (B, ), event_shape = (), sample_shape = (). """ # Transform logit (raw output of policy network, e.g. last fully connected layer) into probability. # $$\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}$$ prob = torch.softmax(logit, dim=-1) # Construct categorical distribution. The probability mass function is: $$f(x=i|\boldsymbol{p})=p_i$$ # <link https://en.wikipedia.org/wiki/Categorical_distribution link> dist = torch.distributions.Categorical(probs=prob) # Sample one discrete action per sample (state input) and return it. return dist.sample() The provided code snippet includes necessary dependencies for implementing the `test_sample_multi_discrete_action` function. Write a Python function `def test_sample_multi_discrete_action()` to solve the following problem: **Overview**: The function of testing sampling multi-discrete action. Construct a naive policy and sample a group of multi-discrete action. Here is the function: def test_sample_multi_discrete_action(): """ **Overview**: The function of testing sampling multi-discrete action. Construct a naive policy and sample a group of multi-discrete action. """ # Set batch_size = 4, obs_shape = 10, action_shape = [4, 5, 6]. B, obs_shape, action_shape = 4, 10, [4, 5, 6] # Generate state data from uniform distribution in [0, 1]. state = torch.rand(B, obs_shape) # Define policy network with encoder and head. policy_network = MultiDiscretePolicyNetwork(obs_shape, action_shape) # Policy network forward procedure, input state and output multiple logit. # $$ logit = \pi(a|s)$$ logit = policy_network(state) for i in range(len(logit)): assert logit[i].shape == (B, action_shape[i]) # Sample action accoding to corresponding logit one by one. for i in range(len(logit)): action_i = sample_action(logit[i]) assert action_i.shape == (B, )
**Overview**: The function of testing sampling multi-discrete action. Construct a naive policy and sample a group of multi-discrete action.
158,683
from typing import List import torch import torch.nn as nn class DiscretePolicyNetwork(nn.Module): def __init__(self, obs_shape: int, action_shape: int) -> None: """ **DiscretePolicyNetwork 定义概述**: 定义 PPO 中所使用的离散动作策略网络,其主要包含两部分:编码器(encoder)和决策输出头(head) """ # 继承 PyTorch 神经网络类所必需的操作,自定义的神经网络必须是 ``nn.Module`` 的子类 super(DiscretePolicyNetwork, self).__init__() # 定义编码器模块,将原始的状态映射为特征向量。对于不同的环境,可能状态信息的模态不同,需要根据情况选择适当的编码器神经网络,例如对于图片状态信息就常常使用卷积神经网络 # 这里我们用一个简单的单层 MLP 作为例子,即: # $$y = max(Wx+b, 0)$$ self.encoder = nn.Sequential( nn.Linear(obs_shape, 32), nn.ReLU(), ) # 定义离散动作的决策输出头,一般仅仅一层全连接层即可,即: # $$y=Wx+b$$ self.head = nn.Linear(32, action_shape) # delimiter def forward(self, x: torch.Tensor) -> torch.Tensor: """ **forward 函数功能概述**: 描述 PPO 中所使用的离散动作策略网络的前向计算图 ``x -> encoder -> head -> logit`` . """ # 将原始的状态信息转换为特征向量,维度变化为: $$(B, *) -> (B, N)$$ x = self.encoder(x) # 为每个可能的离散动作选项,计算相应的 logit,维度变化为: $$(B, N) -> (B, A)$$ logit = self.head(x) return logit def sample_action(logit: torch.Tensor) -> torch.Tensor: """ **sample_action 函数功能概述**: 输入 logit 采样获得离散动作,输入维度为 (B, action_shape) 输出维度为 output shape = (B, ) 在这个示例中,课程中提到的 distributions 工具库的三个维度分别为 batch_shape = (B, ), event_shape = (), sample_shape = () """ # 将 logit 转化为概率(logit 一般指神经网络的原始输出,不经过激活函数,例如最后一层全连接层的输出) # $$\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}$$ prob = torch.softmax(logit, dim=-1) # 构建广义伯努利分布。它的概率质量函数为: $$f(x=i|\boldsymbol{p})=p_i$$ # <link https://en.wikipedia.org/wiki/Categorical_distribution link> dist = torch.distributions.Categorical(probs=prob) # 为一个 batch 里的每个样本采样一个离散动作,并返回它 return dist.sample() The provided code snippet includes necessary dependencies for implementing the `test_sample_discrete_action` function. Write a Python function `def test_sample_discrete_action()` to solve the following problem: **test_sample_discrete_action 函数功能概述**: 离散动作空间的主函数,构建一个简单的策略网络,执行前向计算过程,并采样得到一组离散动作 Here is the function: def test_sample_discrete_action(): """ **test_sample_discrete_action 函数功能概述**: 离散动作空间的主函数,构建一个简单的策略网络,执行前向计算过程,并采样得到一组离散动作 """ # 设置相关参数 batch_size = 4, obs_shape = 10, action_shape = 6. B, obs_shape, action_shape = 4, 10, 6 # 从0-1 的均匀分布中生成状态数据 state = torch.rand(B, obs_shape) # 定义策略网络 policy_network = DiscretePolicyNetwork(obs_shape, action_shape) # 策略网络执行前向计算,即输入状态输出 logit # $$ logit = \pi(a|s)$$ logit = policy_network(state) assert logit.shape == (B, action_shape) # 根据 logit 采样得到最终的离散动作 action = sample_action(logit) assert action.shape == (B, )
**test_sample_discrete_action 函数功能概述**: 离散动作空间的主函数,构建一个简单的策略网络,执行前向计算过程,并采样得到一组离散动作
158,684
from typing import List import torch import torch.nn as nn class MultiDiscretePolicyNetwork(nn.Module): def __init__(self, obs_shape: int, action_shape: List[int]) -> None: """ **MultiDiscretePolicyNetwork 定义概述**: 定义 PPO 中所使用的多维离散动作策略网络,其主要包含两部分:编码器(encoder)和多维决策输出头(head) """ # 继承 PyTorch 神经网络类所必需的操作,自定义的神经网络必须是 ``nn.Module`` 的子类 super(MultiDiscretePolicyNetwork, self).__init__() # 定义编码器模块,将原始的状态映射为特征向量。对于不同的环境,可能状态信息的模态不同,需要根据情况选择适当的编码器神经网络,例如对于图片状态信息就常常使用卷积神经网络 # 这里我们用一个简单的单层 MLP 作为例子,即: # $$y = max(Wx+b, 0)$$ self.encoder = nn.Sequential( nn.Linear(obs_shape, 32), nn.ReLU(), ) # 定义多维离散动作的决策输出头,即创建多个离散动作的预测器,整体用 ``nn.ModuleList`` 进行管理 self.head = nn.ModuleList() for size in action_shape: self.head.append(nn.Linear(32, size)) # delimiter def forward(self, x: torch.Tensor) -> List[torch.Tensor]: """ **Overview**: The computation graph of discrete action policy network used in PPO. ``x -> encoder -> multiple head -> multiple logit`` . """ # 将原始的状态信息转换为特征向量,维度变化为: $$(B, *) -> (B, N)$$ x = self.encoder(x) # 为每个可能的离散动作选项,计算相应的 logit,维度变化为: $$(B, N) -> [(B, A_1), ..., (B, A_N)]$$ logit = [h(x) for h in self.head] return logit def sample_action(logit: torch.Tensor) -> torch.Tensor: """ **sample_action 函数功能概述**: 输入 logit 采样获得离散动作,输入维度为 (B, action_shape) 输出维度为 output shape = (B, ) 在这个示例中,课程中提到的 distributions 工具库的三个维度分别为 batch_shape = (B, ), event_shape = (), sample_shape = () """ # 将 logit 转化为概率(logit 一般指神经网络的原始输出,不经过激活函数,例如最后一层全连接层的输出) # $$\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}$$ prob = torch.softmax(logit, dim=-1) # 构建广义伯努利分布。它的概率质量函数为: $$f(x=i|\boldsymbol{p})=p_i$$ # <link https://en.wikipedia.org/wiki/Categorical_distribution link> dist = torch.distributions.Categorical(probs=prob) # 为一个 batch 里的每个样本采样一个离散动作,并返回它 return dist.sample() The provided code snippet includes necessary dependencies for implementing the `test_sample_multi_discrete_action` function. Write a Python function `def test_sample_multi_discrete_action()` to solve the following problem: **test_sample_multi_discrete_action 函数功能概述**: 多维离散动作空间的主函数,构建一个简单的策略网络,执行前向计算过程,并采样得到一组多维离散动作 Here is the function: def test_sample_multi_discrete_action(): """ **test_sample_multi_discrete_action 函数功能概述**: 多维离散动作空间的主函数,构建一个简单的策略网络,执行前向计算过程,并采样得到一组多维离散动作 """ # Set batch_size = 4, obs_shape = 10, action_shape = [4, 5, 6]. B, obs_shape, action_shape = 4, 10, [4, 5, 6] # 从0-1 的均匀分布中生成状态数据 state = torch.rand(B, obs_shape) # 定义策略网络 policy_network = MultiDiscretePolicyNetwork(obs_shape, action_shape) # 策略网络执行前向计算,即输入状态输出多个 logit # $$ logit = \pi(a|s)$$ logit = policy_network(state) for i in range(len(logit)): assert logit[i].shape == (B, action_shape[i]) # 对于多个 logit,依次调用采样函数,根据相应的 logit 采样得到最终的离散动作 for i in range(len(logit)): action_i = sample_action(logit[i]) assert action_i.shape == (B, )
**test_sample_multi_discrete_action 函数功能概述**: 多维离散动作空间的主函数,构建一个简单的策略网络,执行前向计算过程,并采样得到一组多维离散动作
158,685
from typing import Dict import torch import torch.nn as nn from torch.distributions import Normal, Independent class ContinuousPolicyNetwork(nn.Module): def __init__(self, obs_shape: int, action_shape: int) -> None: """ **ContinuousPolicyNetwork 定义概述**: 定义 PPO 中所使用的连续动作策略网络,其主要包含三部分:编码器(encoder),均值(mu)和对数空间标准差(log_sigma) """ # 继承 PyTorch 神经网络类所必需的操作,自定义的神经网络必须是 ``nn.Module`` 的子类 super(ContinuousPolicyNetwork, self).__init__() # 定义编码器模块,将原始的状态映射为特征向量。对于不同的环境,可能状态信息的模态不同,需要根据情况选择适当的编码器神经网络,例如对于图片状态信息就常常使用卷积神经网络 # 这里我们用一个简单的两层 MLP 作为例子,即: # $$ y = max(W_2 max(W_1x+b_1, 0) + b_2, 0)$$ self.encoder = nn.Sequential( nn.Linear(obs_shape, 16), nn.ReLU(), nn.Linear(16, 32), nn.ReLU(), ) # 定义输出均值 mu 的模块,一般使用一层全连接层即可,输出的 mu 将用于构建高斯分布 # $$ \mu = Wx + b $$ self.mu = nn.Linear(32, action_shape) # 定义对数空间标准差 log_sigma 模块,它是一个与输入状态无关的可学习参数。 # 这里定义成对数空间,取值和使用比较方便。你也可以根据自己的需要,调整它的初始化值 # $$\sigma = e^w$$ self.log_sigma = nn.Parameter(torch.zeros(1, action_shape)) # delimiter def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: """ **forward 函数功能概述**: 描述 PPO 中所使用的连续动作策略网络的前向计算图 ``x -> encoder -> mu -> \mu`` . ``log_sigma -> exp -> sigma`` . """ # 将原始的状态信息转换为特征向量,维度变化为: $$(B, *) -> (B, N)$$ x = self.encoder(x) # 根据特征向量输出动作均值 mu,维度变化为: $$(B, N) -> (B, A)$$ mu = self.mu(x) # 借助”广播“机制让对数空间标准差的维度和均值一致(在 batch 维度上复制) # ``zeros_like`` 操作并不会传递梯度 # <link https://pytorch.org/tutorials/beginner/introyt/tensors_deeper_tutorial.html#in-brief-tensor-broadcasting link> log_sigma = self.log_sigma + torch.zeros_like(mu) # 通过取指数操作得到最终的标准差 sigma # $$\sigma = e^w$$ sigma = torch.exp(log_sigma) return {'mu': mu, 'sigma': sigma} def sample_continuous_action(logit: Dict[str, torch.Tensor]) -> torch.Tensor: """ **sample_continuous_action 函数功能概述**: 输入 logit(包含 mu 和 sigma)采样得到离散动作,输入是一个包含 mu 和 sigma 的字典,它们的维度都是 (B, action_shape),输出的维度是 (B, action_shape)。 在这个示例中,课程中提到的 distributions 工具库的三个维度分别为 batch_shape = (B, ), event_shape = (action_shape, ), sample_shape = () """ # 根据 mu 和 sigma 构建高斯分布 # $$X \sim \mathcal{N}(\mu,\,\sigma^{2})$$ # 它的概率密度函数为: $$f(x) = \frac{1}{\sigma\sqrt{2\pi}} \exp\left( -\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^{\!2}\,\right)$$ # <link https://en.wikipedia.org/wiki/Normal_distribution link> dist = Normal(logit['mu'], logit['sigma']) # 将 ``action_shape`` 个高斯分布转义为一个有着对角协方差矩阵的多维高斯分布。 # 并保证高斯分布中,每一维之间都是互相独立的(因为协方差矩阵是对角矩阵) # <link https://pytorch.org/docs/stable/distributions.html#independent link> dist = Independent(dist, 1) # 为一个 batch 里的每个样本采样一个维度为 ``action_shape`` 的连续动作,并返回它 return dist.sample() The provided code snippet includes necessary dependencies for implementing the `test_sample_continuous_action` function. Write a Python function `def test_sample_continuous_action()` to solve the following problem: **test_sample_continuous_action 函数功能概述**: 连续动作空间的主函数,构建一个简单的连续动作策略网络,执行前向计算过程,并采样得到一组连续动作 Here is the function: def test_sample_continuous_action(): """ **test_sample_continuous_action 函数功能概述**: 连续动作空间的主函数,构建一个简单的连续动作策略网络,执行前向计算过程,并采样得到一组连续动作 """ # 设置相关参数 batch_size = 4, obs_shape = 10, action_shape = 6. # ``action_shape`` 在离散和连续动作空间中的语义不太一样,前者是表示可选择的离散选项的个数,但只从中选出某一离散动作,而后者是连续动作的数量(维度) B, obs_shape, action_shape = 4, 10, 6 # 从0-1 的均匀分布中生成状态数据 state = torch.rand(B, obs_shape) # 定义策略网络(类似重参数化方法) policy_network = ContinuousPolicyNetwork(obs_shape, action_shape) # 策略网络执行前向计算,即输入状态输出字典类型的 logit # $$ \mu, \sigma = \pi(a|s)$$ logit = policy_network(state) assert isinstance(logit, dict) assert logit['mu'].shape == (B, action_shape) assert logit['sigma'].shape == (B, action_shape) # 根据 logit (mu, sigma) 采样得到最终的连续动作 action = sample_continuous_action(logit) assert action.shape == (B, action_shape)
**test_sample_continuous_action 函数功能概述**: 连续动作空间的主函数,构建一个简单的连续动作策略网络,执行前向计算过程,并采样得到一组连续动作
158,686
from ding.bonus import PPOF def lunarlander_discrete(): # Please install lunarlander env first, `pip3 install box2d` agent = PPOF(env='lunarlander_discrete', exp_name='./lunarlander_discrete_demo') agent.train(step=int(1e5)) # Classic RL interaction loop and save replay video agent.deploy(enable_save_replay=True)
null
158,687
from ding.bonus import PPOF def lunarlander_continuous(): # Please install lunarlander env first, `pip3 install box2d` agent = PPOF(env='lunarlander_continuous', exp_name='./lunarlander_continuous_demo', seed=314) agent.train(step=int(1e5)) # Batch (Vectorized) evaluation agent.batch_evaluate(env_num=4, n_evaluator_episode=8)
null
158,688
from ding.bonus import PPOF def rocket_landing(): # Please install rocket env first, `pip3 install git+https://github.com/nighood/rocket-recycling@master#egg=rocket_recycling` agent = PPOF(env='rocket_landing', exp_name='./rocket_landing_demo') agent.train(step=int(5e6), context='spawn')
null
158,689
from ding.bonus import PPOF def drone_fly(): # Please install gym_pybullet_drones env first, `pip3 install git+https://github.com/zjowowen/gym-pybullet-drones@master` agent = PPOF(env='drone_fly', exp_name='./drone_fly_demo') agent.train(step=int(5e6))
null
158,690
from ding.bonus import PPOF def hybrid_moving(): # Please install gym_hybrid env first, refer to the doc `https://di-engine-docs.readthedocs.io/zh_CN/latest/13_envs/gym_hybrid_zh.html` agent = PPOF(env='hybrid_moving', exp_name='./hybrid_moving_demo') agent.train(step=int(5e6))
null
158,691
from typing import Dict import torch import torch.nn as nn import treetensor.torch as ttorch from torch.distributions import Normal, Independent class HybridPolicyNetwork(nn.Module): def __init__(self, obs_shape: int, action_shape: Dict[str, int]) -> None: """ **HybridPolicyNetwork 概述**: 定义 PPO 中所使用的混合动作空间(这里特指参数化动作空间)策略网络,其主要包含三部分:编码器(encoder),动作类型预测器(离散)和动作参数预测器(continuous) """ # 继承 PyTorch 神经网络类所必需的操作,自定义的神经网络必须是 ``nn.Module`` 的子类 super(HybridPolicyNetwork, self).__init__() # 定义编码器模块,将原始的状态映射为特征向量。对于不同的环境,可能状态信息的模态不同,需要根据情况选择适当的编码器神经网络,例如对于图片状态信息就常常使用卷积神经网络 # 这里我们用一个简单的两层 MLP 作为例子,即: # $$ y = max(W_2 max(W_1x+b_1, 0) + b_2, 0)$$ self.encoder = nn.Sequential( nn.Linear(obs_shape, 16), nn.ReLU(), nn.Linear(16, 32), nn.ReLU(), ) # 定义离散动作类型预测器,输出离散动作的 logit # $$ y = Wx + b $$ self.action_type_shape = action_shape['action_type_shape'] self.action_type_head = nn.Linear(32, self.action_type_shape) # 定义连续动作参数预测器,类似 PPO 在连续动作上的设计,输出相应的 mu 和 sigma # $$ \mu = Wx + b $$ # $$\sigma = e^w$$ self.action_args_shape = action_shape['action_args_shape'] self.action_args_mu = nn.Linear(32, self.action_args_shape) self.action_args_log_sigma = nn.Parameter(torch.zeros(1, self.action_args_shape)) # delimiter def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: """ **forward 函数功能概述**: 描述 PPO 中所使用的混合动作策略网络的前向计算图 ``x -> encoder -> action_type_head -> action_type_logit`` . ``x -> encoder -> action_args_mu -> \mu`` . ``action_args_log_sigma -> exp -> sigma`` . """ # 将原始的状态信息转换为特征向量,维度变化为: $$(B, *) -> (B, N)$$ x = self.encoder(x) # 输出离散动作类型的 logit logit = self.action_type_head(x) # 根据特征向量输出动作均值 mu mu = self.action_args_mu(x) # 借助”广播“机制让对数空间标准差的维度和均值一致(在 batch 维度上复制 # ``zeros_like`` 操作并不会传递梯度 # <link https://pytorch.org/tutorials/beginner/introyt/tensors_deeper_tutorial.html#in-brief-tensor-broadcasting link> log_sigma = self.action_args_log_sigma + torch.zeros_like(mu) # 通过取指数操作得到最终的标准差 sigma # $$\sigma = e^w$$ sigma = torch.exp(log_sigma) # 返回 treetensor 类型的输出 return ttorch.as_tensor({'action_type': logit, 'action_args': {'mu': mu, 'sigma': sigma}}) def sample_hybrid_action(logit: ttorch.Tensor) -> torch.Tensor: """ **sample_hybrid_action 函数功能概述**: 输入 logit 采样得到混合动作,输入是一个 treetensor 包含 ``action_type`` 和 ``action_args`` 两部分 """ # 将 logit 转化为概率(logit 一般指神经网络的原始输出,不经过激活函数,例如最后一层全连接层的输出) # $$\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}$$ prob = torch.softmax(logit.action_type, dim=-1) # 构建广义伯努利分布。它的概率质量函数为: $$f(x=i|\boldsymbol{p})=p_i$$ # <link https://en.wikipedia.org/wiki/Categorical_distribution link> discrete_dist = torch.distributions.Categorical(probs=prob) # 为一个 batch 里的每个样本采样一个离散动作,并返回它 action_type = discrete_dist.sample() # 根据 mu 和 sigma 构建高斯分布 # $$X \sim \mathcal{N}(\mu,\,\sigma^{2})$$ # 它的概率密度函数为: $$f(x) = \frac{1}{\sigma\sqrt{2\pi}} \exp\left( -\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^{\!2}\,\right)$$ # <link https://en.wikipedia.org/wiki/Normal_distribution link> continuous_dist = Normal(logit.action_args.mu, logit.action_args.sigma) # 将 ``action_shape`` 个高斯分布转义为一个有着对角协方差矩阵的多维高斯分布。 # 并保证高斯分布中,每一维之间都是互相独立的(因为协方差矩阵是对角矩阵) # <link https://pytorch.org/docs/stable/distributions.html#independent link> continuous_dist = Independent(continuous_dist, 1) # 为一个 batch 里的每个样本采样一个维度为 ``action_shape`` 的连续参数 action_args = continuous_dist.sample() # 返回最终的混合动作(参数化动作) return ttorch.as_tensor({ 'action_type': action_type, 'action_args': action_args, }) The provided code snippet includes necessary dependencies for implementing the `test_sample_hybrid_action` function. Write a Python function `def test_sample_hybrid_action()` to solve the following problem: **test_sample_hybrid_action 函数功能概述**: 混合动作空间的主函数,构建一个混合动作空间的策略网络,执行前向计算过程,并采样得到一组混合动作 Here is the function: def test_sample_hybrid_action(): """ **test_sample_hybrid_action 函数功能概述**: 混合动作空间的主函数,构建一个混合动作空间的策略网络,执行前向计算过程,并采样得到一组混合动作 """ # 设置相关参数 batch_size = 4, obs_shape = 10, action_shape 是一个字典,包含 3 种可选择的离散动作类型选项和 3 种对应的连续参数。动作类型和参数之间的关系将用下方的 mask 变量来表示 B, obs_shape, action_shape = 4, 10, {'action_type_shape': 3, 'action_args_shape': 3} mask = [[0, 1, 0], [1, 0, 0], [0, 0, 1]] # 从0-1 的均匀分布中生成状态数据 state = torch.rand(B, obs_shape) # 定义策略网络,包含编码器,离散动作类型预测器和连续动作参数预测器 policy_network = HybridPolicyNetwork(obs_shape, action_shape) # 策略网络执行前向计算,即输入状态输出 treetensor 类型的 logit logit = policy_network(state) assert isinstance(logit, ttorch.Tensor) assert logit.action_type.shape == (B, action_shape['action_type_shape']) assert logit.action_args.mu.shape == (B, action_shape['action_args_shape']) assert logit.action_args.sigma.shape == (B, action_shape['action_args_shape']) # 根据 logit 中的相关部分采样相应的动作部分 action = sample_hybrid_action(logit) assert action.action_type.shape == (B, ) assert action.action_args.shape == (B, action_shape['action_args_shape']) # 通过动作类型查找获得每个数据样本具体所对应的 mask data_mask = torch.as_tensor([mask[i] for i in action.action_type]).bool() # 用 mask 选择(过滤)出动作类型相对应的动作参数,并重新赋值 filtered_action_args = ttorch.masked_select(action.action_args, data_mask) action.action_args = filtered_action_args assert action.action_args.shape == (B, ) # (treetensor 使用举例)通过切片操作选择部分训练样本 selected_action = action[1:3] assert selected_action.action_type.shape == (2, )
**test_sample_hybrid_action 函数功能概述**: 混合动作空间的主函数,构建一个混合动作空间的策略网络,执行前向计算过程,并采样得到一组混合动作
158,692
from typing import Dict import torch import torch.nn as nn from torch.distributions import Normal, Independent class ContinuousPolicyNetwork(nn.Module): def __init__(self, obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of continuous action policy network used in PPO, which is mainly composed of three parts: encoder, mu and log_sigma. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(ContinuousPolicyNetwork, self).__init__() # Define encoder module, which maps raw state into embedding vector. # It could be different for various state, such as Convolution Neural Network (CNN) for image state and Multilayer perceptron (MLP) for vector state, respectively. # Here we use two-layer MLP for vector state. # $$ y = max(W_2 max(W_1x+b_1, 0) + b_2, 0)$$ self.encoder = nn.Sequential( nn.Linear(obs_shape, 16), nn.ReLU(), nn.Linear(16, 32), nn.ReLU(), ) # Define mu module, which is a FC and outputs the argument mu for gaussian distribution. # $$ \mu = Wx + b $$ self.mu = nn.Linear(32, action_shape) # Define log_sigma module, which is a learnable parameter but independent to state. # Here we set it as log_sigma for the convenience of optimization and usage. You can also adjust its initial value for your demands. # $$\sigma = e^w$$ self.log_sigma = nn.Parameter(torch.zeros(1, action_shape)) # delimiter def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: """ **Overview**: The computation graph of continuous action policy network used in PPO. ``x -> encoder -> mu -> \mu`` . ``log_sigma -> exp -> sigma`` . """ # Transform original state into embedding vector, i.e. $$(B, *) -> (B, N)$$ x = self.encoder(x) # Output the argument mu depending on the embedding vector, i.e. $$(B, N) -> (B, A)$$ mu = self.mu(x) # Utilize broadcast mechanism to make the same shape between log_sigma and mu. # ``zeros_like`` operation doesn't pass gradient. # <link https://pytorch.org/tutorials/beginner/introyt/tensors_deeper_tutorial.html#in-brief-tensor-broadcasting link> log_sigma = self.log_sigma + torch.zeros_like(mu) # Utilize exponential operation to produce the actual sigma. # $$\sigma = e^w$$ sigma = torch.exp(log_sigma) return {'mu': mu, 'sigma': sigma} def sample_continuous_action(logit: Dict[str, torch.Tensor]) -> torch.Tensor: """ **Overview**: The function of sampling continuous action, input is a dict with two keys ``mu`` and ``sigma`` , both of them has shape = (B, action_shape), output shape = (B, action_shape). In this example, the distributions shapes are: batch_shape = (B, ), event_shape = (action_shape, ), sample_shape = (). """ # Construct gaussian distribution, i.e. # $$X \sim \mathcal{N}(\mu,\,\sigma^{2})$$ # Its probability density function is: $$f(x) = \frac{1}{\sigma\sqrt{2\pi}} \exp\left( -\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^{\!2}\,\right)$$ # <link https://en.wikipedia.org/wiki/Normal_distribution link> dist = Normal(logit['mu'], logit['sigma']) # Reinterpret ``action_shape`` gaussian distribution into a multivariate gaussian distribution with diagonal convariance matrix. # Ensure each event is independent with each other. # <link https://pytorch.org/docs/stable/distributions.html#independent link> dist = Independent(dist, 1) # Sample one action of the shape ``action_shape`` per sample (state input) and return it. return dist.sample() The provided code snippet includes necessary dependencies for implementing the `test_sample_continuous_action` function. Write a Python function `def test_sample_continuous_action()` to solve the following problem: **Overview**: The function of testing sampling continuous action. Construct a standard continuous action policy and sample a group of action. Here is the function: def test_sample_continuous_action(): """ **Overview**: The function of testing sampling continuous action. Construct a standard continuous action policy and sample a group of action. """ # Set batch_size = 4, obs_shape = 10, action_shape = 6. # ``action_shape`` is different from discrete and continuous action. The former is the possible # choice of a discrete action while the latter is the dimension of continuous action. B, obs_shape, action_shape = 4, 10, 6 # Generate state data from uniform distribution in [0, 1]. state = torch.rand(B, obs_shape) # Define continuous action network (which is similar to reparameterization) with encoder, mu and log_sigma. policy_network = ContinuousPolicyNetwork(obs_shape, action_shape) # Policy network forward procedure, input state and output dict-type logit. # $$ \mu, \sigma = \pi(a|s)$$ logit = policy_network(state) assert isinstance(logit, dict) assert logit['mu'].shape == (B, action_shape) assert logit['sigma'].shape == (B, action_shape) # Sample action accoding to corresponding logit (i.e., mu and sigma). action = sample_continuous_action(logit) assert action.shape == (B, action_shape)
**Overview**: The function of testing sampling continuous action. Construct a standard continuous action policy and sample a group of action.
158,693
from typing import Dict import torch import torch.nn as nn import treetensor.torch as ttorch from torch.distributions import Normal, Independent class HybridPolicyNetwork(nn.Module): def __init__(self, obs_shape: int, action_shape: Dict[str, int]) -> None: """ **Overview**: The definition of hybrid action policy network used in PPO, which is mainly composed of three parts: encoder, action_type head (discrete) and action_args head (continuous). """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(HybridPolicyNetwork, self).__init__() # Define encoder module, which maps raw state into embedding vector. # It could be different for various state, such as Convolution Neural Network (CNN) for image state and Multilayer perceptron (MLP) for vector state, respectively. # $$ y = max(W_2 max(W_1x+b_1, 0) + b_2, 0)$$ self.encoder = nn.Sequential( nn.Linear(obs_shape, 16), nn.ReLU(), nn.Linear(16, 32), nn.ReLU(), ) # Define action_type head module, which outputs discrete logit. # $$ y = Wx + b $$ self.action_type_shape = action_shape['action_type_shape'] self.action_type_head = nn.Linear(32, self.action_type_shape) # Define action_args head module, which outputs corresponding continuous action arguments. # $$ \mu = Wx + b $$ # $$\sigma = e^w$$ self.action_args_shape = action_shape['action_args_shape'] self.action_args_mu = nn.Linear(32, self.action_args_shape) self.action_args_log_sigma = nn.Parameter(torch.zeros(1, self.action_args_shape)) # delimiter def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: """ **Overview**: The computation graph of hybrid action policy network used in PPO. ``x -> encoder -> action_type_head -> action_type_logit`` . ``x -> encoder -> action_args_mu -> \mu`` . ``action_args_log_sigma -> exp -> sigma`` . """ # Transform original state into embedding vector, i.e. $$(B, *) -> (B, N)$$ x = self.encoder(x) # Output discrete action logit. logit = self.action_type_head(x) # Output the argument mu depending on the embedding vector. mu = self.action_args_mu(x) # Utilize broadcast mechanism to make the same shape between log_sigma and mu. # ``zeros_like`` operation doesn't pass gradient. # <link https://pytorch.org/tutorials/beginner/introyt/tensors_deeper_tutorial.html#in-brief-tensor-broadcasting link> log_sigma = self.action_args_log_sigma + torch.zeros_like(mu) # Utilize exponential operation to produce the actual sigma. # $$\sigma = e^w$$ sigma = torch.exp(log_sigma) # Return treetensor-type output. return ttorch.as_tensor({'action_type': logit, 'action_args': {'mu': mu, 'sigma': sigma}}) def sample_hybrid_action(logit: ttorch.Tensor) -> torch.Tensor: """ **Overview**: The function of sampling hybrid action, input is a treetensor with two keys ``action_type`` and ``action_args`` . """ # Transform logit (raw output of discrete policy head, e.g. last fully connected layer) into probability. # $$\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}$$ prob = torch.softmax(logit.action_type, dim=-1) # Construct categorical distribution. The probability mass function is: $$f(x=i|\boldsymbol{p})=p_i$$ # <link https://en.wikipedia.org/wiki/Categorical_distribution link> discrete_dist = torch.distributions.Categorical(probs=prob) # Sample one discrete action type per sample (state input). action_type = discrete_dist.sample() # Construct gaussian distribution # $$X \sim \mathcal{N}(\mu,\,\sigma^{2})$$ # Its probability density function is: $$f(x) = \frac{1}{\sigma\sqrt{2\pi}} \exp\left( -\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^{\!2}\,\right)$$ # <link https://en.wikipedia.org/wiki/Normal_distribution link> continuous_dist = Normal(logit.action_args.mu, logit.action_args.sigma) # Reinterpret ``action_shape`` gaussian distribution into a multivariate gaussian distribution with # diagonal convariance matrix. # Ensure each event is independent with each other. # <link https://pytorch.org/docs/stable/distributions.html#independent link> continuous_dist = Independent(continuous_dist, 1) # Sample one action args of the shape ``action_shape`` per sample (state input). action_args = continuous_dist.sample() # Return the final parameterized action. return ttorch.as_tensor({ 'action_type': action_type, 'action_args': action_args, }) The provided code snippet includes necessary dependencies for implementing the `test_sample_hybrid_action` function. Write a Python function `def test_sample_hybrid_action()` to solve the following problem: **Overview**: The function of testing sampling hybrid action. Construct a hybrid action (parameterized action) policy and sample a group of action. Here is the function: def test_sample_hybrid_action(): """ **Overview**: The function of testing sampling hybrid action. Construct a hybrid action (parameterized action) policy and sample a group of action. """ # Set batch_size = 4, obs_shape = 10, action_shape is a dict, including 3 possible discrete action types and 3 corresponding continuous arguments. The relationship between action_type and action_args are represented by the below ``mask`` . B, obs_shape, action_shape = 4, 10, {'action_type_shape': 3, 'action_args_shape': 3} mask = [[0, 1, 0], [1, 0, 0], [0, 0, 1]] # Generate state data from uniform distribution in [0, 1]. state = torch.rand(B, obs_shape) # Define hybrid action network with encoder, discrete head and continuous head. policy_network = HybridPolicyNetwork(obs_shape, action_shape) # Policy network forward procedure, input state and output treetensor-type logit. logit = policy_network(state) assert isinstance(logit, ttorch.Tensor) assert logit.action_type.shape == (B, action_shape['action_type_shape']) assert logit.action_args.mu.shape == (B, action_shape['action_args_shape']) assert logit.action_args.sigma.shape == (B, action_shape['action_args_shape']) # Sample action accoding to corresponding logit part. action = sample_hybrid_action(logit) assert action.action_type.shape == (B, ) assert action.action_args.shape == (B, action_shape['action_args_shape']) # Acquire each sample's mask by looking up in ``mask`` with action type。 data_mask = torch.as_tensor([mask[i] for i in action.action_type]).bool() # Filter corresponding action_args according to mask and re-assign it. filtered_action_args = ttorch.masked_select(action.action_args, data_mask) action.action_args = filtered_action_args assert action.action_args.shape == (B, ) # Select some samples with slicing (for example). selected_action = action[1:3] assert selected_action.action_type.shape == (2, )
**Overview**: The function of testing sampling hybrid action. Construct a hybrid action (parameterized action) policy and sample a group of action.
158,694
from typing import Optional, Dict import warnings import numpy as np import torch import torch.nn as nn import treetensor from ding.torch_utils import GRUGatingUnit, build_normalization from ding.torch_utils.network.nn_module import fc_block from ding.torch_utils.network.gtrxl import PositionalEmbedding, Memory, AttentionXL class GTrXL(nn.Module): """ **Overview**: PyTorch implementation for GTrXL, which is used to model the long-term time dependency in reinforcement learning. """ def __init__( self, input_dim: int, head_dim: int = 128, embedding_dim: int = 256, head_num: int = 2, mlp_num: int = 2, layer_num: int = 3, memory_len: int = 64, dropout_ratio: float = 0., activation: nn.Module = nn.ReLU(), gru_gating: bool = True, gru_bias: float = 2., use_embedding_layer: bool = True, ) -> None: super(GTrXL, self).__init__() assert embedding_dim % 2 == 0, 'embedding_dim={} should be even'.format(input_dim) self.head_num = head_num self.head_dim = head_dim self.layer_num = layer_num self.embedding_dim = embedding_dim if isinstance(input_dim, list): input_dim = np.prod(input_dim) # Initialize embedding layer. self.use_embedding_layer = use_embedding_layer if self.use_embedding_layer: self.embedding = fc_block(input_dim, embedding_dim, activation=activation) # Initialize activate function. self.activation = activation # Initialize position embedding. self.pos_embedding = PositionalEmbedding(embedding_dim) # Memory to save hidden states of past segments. It will be initialized in the forward method to get its size dynamically. self.memory = None self.memory_len = memory_len # Initialize GTrXL layers. layers = [] # Put all the embedding_dims into a list. # For the i-th layer, the input embedding is dims[i], while the output embedding is dims[i+1] dims = [embedding_dim] + [embedding_dim] * layer_num self.dropout = nn.Dropout(dropout_ratio) if dropout_ratio > 0 else nn.Identity() for i in range(layer_num): layers.append( GatedTransformerXLLayer( dims[i], head_dim, dims[i+1], head_num, mlp_num, self.dropout, self.activation, gru_gating, gru_bias ) ) self.layers = nn.Sequential(*layers) # u and v are the parameters to compute global content bias and global positional bias. self.u, self.v = ( torch.nn.Parameter(torch.zeros(self.head_num, self.head_dim)), torch.nn.Parameter(torch.zeros(self.head_num, self.head_dim)), ) # Create an attention mask for each different seq_len. In this way we don't need to create a new one each time we call the forward method. self.att_mask = {} # Create a pos embedding for each different seq_len. In this way we don't need to create a new one each time we call the forward method. self.pos_embedding_dict = {} # delimiter def reset_memory(self, batch_size: Optional[int] = None, state: Optional[torch.Tensor] = None): """ **Overview**: Reset the memory of GTrXL, which is called at the beginning of each episode. Memory is used to save hidden states of past segments. """ # Reset the memory of GTrXL. self.memory = Memory(memory_len=self.memory_len, layer_num=self.layer_num, embedding_dim=self.embedding_dim) # If batch_size is not None, specify the batch_size when initializing the memory. if batch_size is not None: self.memory = Memory(self.memory_len, batch_size, self.embedding_dim, self.layer_num) # If state is not None, add state into the memory. elif state is not None: self.memory.init(state) # delimiter def get_memory(self): """ **Overview**: Access the memory of GTrXL. """ # Get the memory of GTrXL. if self.memory is None: return None else: return self.memory.get() # delimiter def forward(self, x: torch.Tensor, batch_first: bool = False, return_mem: bool = True) -> Dict[str, torch.Tensor]: """ **Overview**: The forward computation graph of GTrXL. """ # If the first dimension of input x is batch_size, # then reshape x from [batch_size ,sequence_length ,input_dim] to [sequence_length, batch_size, input_dim] if batch_first: x = torch.transpose(x, 1, 0) cur_seq, bs = x.shape[:2] # Get back memory. memory = None if self.memory is None else self.memory.get() # Abnormal case: no memory or memory shape mismatch. if memory is None: self.reset_memory(bs) elif memory.shape[-2] != bs or memory.shape[-1] != self.embedding_dim: warnings.warn( "Memory {} and Input {} dimensions don't match," " this will cause the memory to be initialized to fit your input!".format( list(memory.shape[-2:]), [x.shape[-2]] + [self.embedding_dim] ) ) self.reset_memory(bs) self.memory.to(x.device) memory = self.memory.get() # Pass through embedding layer. if self.use_embedding_layer: x = self.dropout(self.embedding(x)) # Get full sequence length: memory length + current length prev_seq = self.memory_len full_seq = cur_seq + prev_seq # If the attention mask for current sequence length is already created, reuse the mask stored in ``self.att_mask`` . if cur_seq in self.att_mask.keys(): attn_mask = self.att_mask[cur_seq] # Otherwise, create a new attention mask and store it into ``self.att_mask`` . else: # For example, if cur_seq = 3, full_seq = 7, then the mask is: # $$ \begin{matrix} 0 & 0 & 0 & 0 & 0 & 1 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 \end{matrix}$$ # This forces that the hidden state of current token is only associated with previous tokens. attn_mask = ( torch.triu( torch.ones((cur_seq, full_seq)), diagonal=1 + prev_seq, ).bool().unsqueeze(-1).to(x.device) ) self.att_mask[cur_seq] = attn_mask # If the position encoding for current sequence length is already created, reuse it stored in ``self.pos_embedding_dict`` . if cur_seq in self.pos_embedding_dict.keys(): pos_embedding = self.pos_embedding_dict[cur_seq] # Otherwise, create a new position encoding and store it into ``self.pos_embedding_dict`` . else: pos_ips = torch.arange(full_seq - 1, -1, -1.0, dtype=torch.float) # full_seq pos_embedding = self.pos_embedding(pos_ips.to(x.device)) self.pos_embedding_dict[cur_seq] = pos_embedding pos_embedding = self.dropout(pos_embedding) # full_seq x 1 x embedding_dim hidden_state = [x] out = x # Calculate results for each GTrXL layer. for i in range(self.layer_num): layer = self.layers[i] out = layer( out, pos_embedding, self.u, self.v, mask=attn_mask, memory=memory[i], ) hidden_state.append(out.clone()) out = self.dropout(out) # Update the GTrXL memory. self.memory.update(hidden_state) # If the first dimension of output is required to be batch_size, then reshape x from [sequence_length, batch_size, input_dim] to [batch_size ,sequence_length ,input_dim]. if batch_first: out = torch.transpose(out, 1, 0) # Return memory is needed. if return_mem: output = treetensor.Object({"logit": out, "memory": memory}) else: output = treetensor.Object({"logit": out}) return output The provided code snippet includes necessary dependencies for implementing the `test_gtrxl` function. Write a Python function `def test_gtrxl() -> None` to solve the following problem: **Overview**: Test function of GTrXL. Here is the function: def test_gtrxl() -> None: """ **Overview**: Test function of GTrXL. """ # Generate data for testing. input_dim = 128 seq_len = 64 bs = 32 embedding_dim = 256 layer_num = 5 mem_len = 40 memory = [None, torch.rand(layer_num + 1, mem_len, bs, embedding_dim)] # Test GTrXL under different situations. for i in range(2): m = memory[i] model = GTrXL( input_dim=input_dim, head_dim=2, embedding_dim=embedding_dim, memory_len=mem_len, head_num=2, mlp_num=2, layer_num=layer_num, ) # Input shape: [sequence_length, batch_size, input_dim] input = torch.rand(seq_len, bs, input_dim, requires_grad=True) # Reset the model memory. if m is None: model.reset_memory(batch_size=bs) else: model.reset_memory(state=m) output = model(input) # Check the shape of output. assert output['logit'].shape == (seq_len, bs, embedding_dim) assert output['memory'].shape == (layer_num + 1, mem_len, bs, embedding_dim) torch.sum(output['logit']).backward() # Check the gradient. assert isinstance(input.grad, torch.Tensor) # Check memory. memory_out = output['memory'] if m is not None: assert torch.all(torch.eq(memory_out, m))
**Overview**: Test function of GTrXL.
158,695
from typing import Optional, Union, Tuple, List, Dict import torch import torch.nn as nn from ding.torch_utils.network.rnn import is_sequence from ding.torch_utils import build_normalization class LSTM(nn.Module): """ **Overview**: Implementation of LSTM cell with layer norm. Layer normalization is beneficial to the performance and stability of LSTM. """ def __init__( self, input_size: int, hidden_size: int, num_layers: int, norm_type: Optional[str] = 'LN', dropout: float = 0. ) -> None: # Initialize arguments. super(LSTM, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers # Initialize normalization functions. # Layer normalization normalizes the activations of a layer across the feature dimension. # In general, layer normalization is applied to the inputs to the LSTM gate activations. # Because layer normalization reduces the internal covariate shift of the LSTM gates, # making LSTM more consistent across time steps. norm_func = build_normalization(norm_type) self.norm = nn.ModuleList([norm_func(hidden_size * 4) for _ in range(2 * num_layers)]) # Initialize LSTM parameters with orthogonal initialization. # Orthogonal Initialization can significantly improve the performance of LSTM. self.wx = nn.ParameterList() self.wh = nn.ParameterList() dims = [input_size] + [hidden_size] * num_layers for l in range(num_layers): # wx is the weights for input, while hx is the weights for the hidden state. # Each LSTM cell has 4 gates (input, forget, output, and candidate gates), # and the weights transform the input and hidden state into concatenated vectors, # of which the shape is [num_layers, hidden_size * 4]. self.wx.append(nn.init.orthogonal_(nn.Parameter(torch.zeros(dims[l], dims[l + 1] * 4)))) self.wh.append(nn.init.orthogonal_(nn.Parameter(torch.zeros(hidden_size, hidden_size * 4)))) # Similarly, the bias is the bias of concatenated vectors, so the shape is: [num_layers, hidden_size * 4] self.bias = nn.init.orthogonal_(nn.Parameter(torch.zeros(num_layers, hidden_size * 4))) # Initialize the Dropout Layer. self.use_dropout = dropout > 0. if self.use_dropout: self.dropout = nn.Dropout(dropout) def forward(self, inputs: torch.Tensor, prev_state: torch.Tensor, ) -> Tuple[torch.Tensor, Union[torch.Tensor, list]]: """ **Overview**: Forward computation of LSTM with layer norm. """ # The shape of input is: [sequence length, batch size, input size] seq_len, batch_size = inputs.shape[:2] # Dealing with different types of input and return preprocessed prev_state. # If prev_state is None, it indicates that this is the beginning of a sequence. # In this case, prev_state will be initialized as zero. if prev_state is None: prev_state = ( torch.zeros( self.num_layers, batch_size, self.hidden_size, dtype=inputs.dtype, device=inputs.device) , torch.zeros( self.num_layers, batch_size, self.hidden_size, dtype=inputs.dtype, device=inputs.device) ) # If prev_state is not None, then preprocess it into one batch. else: assert len(prev_state) == batch_size state = [[v for v in prev.values()] for prev in prev_state] state = list(zip(*state)) prev_state = [torch.cat(t, dim=1) for t in state] H, C = prev_state x = inputs next_state = [] for l in range(self.num_layers): h, c = H[l], C[l] new_x = [] for s in range(seq_len): # Calculate $$z, z^i, z^f, z^o$$ simultaneously. gate = self.norm[l * 2](torch.matmul(x[s], self.wx[l]) ) + self.norm[l * 2 + 1](torch.matmul(h, self.wh[l])) if self.bias is not None: gate += self.bias[l] gate = list(torch.chunk(gate, 4, dim=1)) i, f, o, z = gate # $$z^i = \sigma (Wx^ix^t + Wh^ih^{t-1})$$ i = torch.sigmoid(i) # $$z^f = \sigma (Wx^fx^t + Wh^fh^{t-1})$$ f = torch.sigmoid(f) # $$z^o = \sigma (Wx^ox^t + Wh^oh^{t-1})$$ o = torch.sigmoid(o) # $$z = tanh(Wxx^t + Whh^{t-1})$$ z = torch.tanh(z) # $$c^t = z^f \odot c^{t-1}+z^i \odot z$$ c = f * c + i * z # $$h^t = z^o \odot tanh(c^t)$$ h = o * torch.tanh(c) new_x.append(h) next_state.append((h, c)) x = torch.stack(new_x, dim=0) # Dropout layer. if self.use_dropout and l != self.num_layers - 1: x = self.dropout(x) next_state = [torch.stack(t, dim=0) for t in zip(*next_state)] # Return list type, split the next_state . h, c = next_state batch_size = h.shape[1] # Split h with shape [num_layers, batch_size, hidden_size] to a list with length batch_size # and each element is a tensor with shape [num_layers, 1, hidden_size]. The same operation is performed on c. next_state = [torch.chunk(h, batch_size, dim=1), torch.chunk(c, batch_size, dim=1)] next_state = list(zip(*next_state)) next_state = [{k: v for k, v in zip(['h', 'c'], item)} for item in next_state] return x, next_state The provided code snippet includes necessary dependencies for implementing the `test_lstm` function. Write a Python function `def test_lstm()` to solve the following problem: **Overview**: Test function of LSTM. Here is the function: def test_lstm(): """ **Overview**: Test function of LSTM. """ # Randomly generate test data. seq_len = 2 num_layers = 3 input_size = 4 hidden_size = 5 batch_size = 6 norm_type = 'LN' dropout = 0.1 input = torch.rand(seq_len, batch_size, input_size).requires_grad_(True) lstm = LSTM(input_size, hidden_size, num_layers, norm_type, dropout) # Test the LSTM recurrently, using the hidden states of last input as new prev_state. prev_state = None for s in range(seq_len): input_step = input[s:s + 1] # The prev_state is None if the input_step is the first step of the sequence. Otherwise, # the prev_state contains a list of dictions with key ``h`` , ``c`` , # and the corresponding values are tensors with shape [num_layers, 1, hidden_size]. # The length of the list equals to the batch_size. output, prev_state = lstm(input_step, prev_state) # Check the shape of output and prev_state. assert output.shape == (1, batch_size, hidden_size) assert len(prev_state) == batch_size assert prev_state[0]['h'].shape == (num_layers, 1, hidden_size) assert prev_state[0]['c'].shape == (num_layers, 1, hidden_size) torch.mean(output).backward() # Check the grad of input. assert isinstance(input.grad, torch.Tensor)
**Overview**: Test function of LSTM.
158,696
import torch from marl_network import CTDEActorCriticNetworky_data, ppo_policy_error class CTDEActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, local_obs_shape: int, global_obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of centralized training decentralized execution (CTDE) actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent shares the same parameters in the network so that they can be processed as a batch in parallel. The input of value network is ``global_obs`` while the input of policy network is ``local_obs`` . Global information used in value network can provide more guidance for the training of policy network. Local information used in policy network can make the policy network more robust to the decentralized execution. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(CTDEActorCriticNetwork, self).__init__() # Define local and global encoder respectively. self.agent_num = agent_num self.local_encoder = nn.Sequential( nn.Linear(local_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) self.global_encoder = nn.Sequential( nn.Linear(global_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) # Define discrete action logit output network, just one-layer FC. self.policy_head = nn.Linear(64, action_shape) # Define scalar value output network. self.value_head = nn.Linear(64, 1) # delimiter def forward(self, local_obs: torch.Tensor, global_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of CTDE actor-critic network, processing all agents' ``local_obs`` and ``global_obs`` and output corresponding policy logit and value in parallel. There are two possible designs for ``global_obs`` : The former is a shared global state for all agents, i.e. $$(B, S)$$. Tha latter is a kind of agent-specific global state, i.e. $$(B, A, S')$$. For more details, you can refer to <link https://di-engine-docs.readthedocs.io/zh_CN/latest/04_best_practice/marl_zh.html#id10 link>. """ # Call policy network with local obs and critic network with global obs respectively. policy = self.policy_head(self.local_encoder(local_obs)) value = self.value_head(self.global_encoder(global_obs)) return ttorch.as_tensor({ 'logit': policy, 'value': value, }) ppo_policy_data = namedtuple('ppo_policy_data', ['logit_new', 'logit_old', 'action', 'adv', 'weight']) def ppo_policy_error(data: namedtuple, clip_ratio: float = 0.2, dual_clip: Optional[float] = None) -> Tuple[namedtuple, namedtuple]: """ **Overview**: Implementation of Proximal Policy Optimization (PPO) <link https://arxiv.org/pdf/1707.06347.pdf link> with entropy bonus, value_clip and dual_clip. """ # Unpack data: $$<\pi_{new}(a|s), \pi_{old}(a|s), a, A^{\pi_{old}}(s, a), w>$$ logit_new, logit_old, action, adv, weight = data # Prepare weight for default cases. if weight is None: weight = torch.ones_like(adv) # Prepare policy distribution from logit and get log propability. dist_new = torch.distributions.categorical.Categorical(logits=logit_new) dist_old = torch.distributions.categorical.Categorical(logits=logit_old) logp_new = dist_new.log_prob(action) logp_old = dist_old.log_prob(action) # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi_{new}(a^n|s^n) log(\pi_{new}(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . dist_new_entropy = dist_new.entropy() entropy_loss = (dist_new_entropy * weight).mean() # Importance sampling weight: $$r(\theta) = \frac{\pi_{new}(a|s)}{\pi_{old}(a|s)}$$ ratio = torch.exp(logp_new - logp_old) # Original surrogate objective: $$r(\theta) A^{\pi_{old}}(s, a)$$ surr1 = ratio * adv # <b>Clipped surrogate objective:</b> $$clip(r(\theta), 1-\epsilon, 1+\epsilon) A^{\pi_{old}}(s, a)$$ surr2 = ratio.clamp(1 - clip_ratio, 1 + clip_ratio) * adv # Dual clip proposed by <link https://arxiv.org/abs/1912.09729 link> . # Only use dual_clip when adv < 0. if dual_clip is not None: clip1 = torch.min(surr1, surr2) clip2 = torch.max(clip1, dual_clip * adv) policy_loss = -(torch.where(adv < 0, clip2, clip1) * weight).mean() # PPO-Clipped Loss: $$min(r(\theta) A^{\pi_{old}}(s, a), clip(r(\theta), 1-\epsilon, 1+\epsilon) A^{\pi_{old}}(s, a))$$ # Multiply sample-wise weight and reduce mean in batch dimension. else: policy_loss = (-torch.min(surr1, surr2) * weight).mean() # Add some visualization metrics to monitor optimization status. with torch.no_grad(): approx_kl = (logp_old - logp_new).mean().item() clipped = ratio.gt(1 + clip_ratio) | ratio.lt(1 - clip_ratio) clipfrac = torch.as_tensor(clipped).float().mean().item() # Return final loss items and information. return ppo_policy_loss(policy_loss, entropy_loss), ppo_info(approx_kl, clipfrac) def gae(data: tuple, gamma: float = 0.99, lambda_: float = 0.97) -> torch.FloatTensor: """ **Overview**: Implementation of the Generalized Advantage Estimator (GAE) as proposed in arXiv:1506.02438. This function calculates the advantages, which are used to update policy parameters in reinforcement learning. Arguments: - data (:obj:`namedtuple`): Tuple containing trajectory data including state values, next state values, rewards, done flags, and trajectory flags. Please note that the ``done`` flag signals the termination of an episode, whereas the ``traj_flag`` indicates the completion of a trajectory, which represents a segment within an episode. - gamma (:obj:`float`): Discount factor for future rewards, should be in the range [0, 1]. Default is 0.99. - lambda_ (:obj:`float`): The decay rate for the GAE, should be in the range [0, 1]. Default is 0.97. As lambda approaches 0, it introduces bias, and as lambda approaches 1, it increases variance due to the cumulative effect of terms. Returns: - adv (:obj:`torch.FloatTensor`): The calculated advantage estimates. Shapes: - value (:obj:`torch.FloatTensor`): Size of (T, B), where T is the length of the trajectory and B is the batch size. - next_value (:obj:`torch.FloatTensor`): Size of (T, B) - reward (:obj:`torch.FloatTensor`): Size of (T, B) - adv (:obj:`torch.FloatTensor`): Size of (T, B) """ # Unpack the input data. value, next_value, reward, done, traj_flag = data # Convert the done and trajectory flags to tensor format. done = torch.tensor(done).float() traj_flag = torch.tensor(traj_flag).float() # Expand ``done`` for possible broadcast operation in multi-agent cases if len(value.shape) == 2: done = done.unsqueeze(1) # If done equals 1, it indicates the end of an episode, thus the next state value should be 0. next_value *= (1 - done) # Calculate the temporal difference (TD) error for each time step. # $$\delta_t=-V_{\phi}(s_t)+r_t+V_{\phi}(s_{t+1})$$ delta = reward + gamma * next_value - value # Set the GAE decay factor. If traj_flag equals 1, the factor will be 0. Otherwise, the factor is gamma * lambda. factor = gamma * lambda_ * (1 - traj_flag) # Initialize the advantage tensor. adv = torch.zeros_like(value) # Calculate ``adv`` in a reversed sequence. # Consider the definition of GAE: $$A^{GAE}_t = \sum_{i=1}\gamma^{i-1}\lambda^{i-1}\delta_{t+i-1}$$ # Rewrite the equation above in a recurrent form, we finally have: $$A^{GAE}_t = \delta_t + \gamma\lambda A^{GAE}_{t+1}$$ gae_item = torch.zeros_like(value[0]) for t in reversed(range(reward.shape[0])): gae_item = delta[t] + factor[t] * gae_item adv[t] = gae_item # Return the calculated advantage estimates. return adv The provided code snippet includes necessary dependencies for implementing the `mappo_training_opeator` function. Write a Python function `def mappo_training_opeator() -> None` to solve the following problem: **概述** 这是关于 CTDE MAPPO 算法训练过程的核心函数。 首先,定义一些超参数,神经网络和优化器,然后生成构造的测试数据并计算演员-评论家损失 (Actor-Critic loss)。 最后,使用优化器更新网络参数。在实际应用中,训练数据应该是由环境进行在线交互得到的。 注意在本文件中,策略网络指的是演员 (Actor),价值网络指的是评论家 (Critic)。 Here is the function: def mappo_training_opeator() -> None: """ **概述** 这是关于 CTDE MAPPO 算法训练过程的核心函数。 首先,定义一些超参数,神经网络和优化器,然后生成构造的测试数据并计算演员-评论家损失 (Actor-Critic loss)。 最后,使用优化器更新网络参数。在实际应用中,训练数据应该是由环境进行在线交互得到的。 注意在本文件中,策略网络指的是演员 (Actor),价值网络指的是评论家 (Critic)。 """ # 设置必要的超参数。 batch_size, agent_num, local_state_shape, agent_specific_global_state_shape, action_shape = 4, 5, 10, 25, 6 # 熵加成权重,有利于探索。 entropy_weight = 0.001 # 价值损失权重,旨在平衡不同损失函数量级。 value_weight = 0.5 # 未来奖励的折扣系数。 discount_factor = 0.99 # 根据运行环境设置 tensor 设备为 cuda 或者 cpu。 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 定义多智能体神经网络和优化器。 model = CTDEActorCriticNetwork(agent_num, local_state_shape, agent_specific_global_state_shape, action_shape) model.to(device) # Adam 是深度强化学习中最常用的优化器。 如果你想添加权重衰减机制,应该使用 ``torch.optim.AdamW`` 。 optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 定义相应的测试数据,需要保持数据格式与环境交互生成的数据格式相同。 # 注意,数据应该与网络保持相同的计算设备 (device)。 # 为简单起见,这里我们将整个批次数据视为一个完整的 episode。 # 在实际应用中,训练批次是多个 episode 的组合。我们通常使用 ``done`` 变量来划分不同的 episode 。 local_state = torch.randn(batch_size, agent_num, local_state_shape).to(device) agent_specific_global_state = torch.randn(batch_size, agent_num, agent_specific_global_state_shape).to(device) logit_old = torch.randn(batch_size, agent_num, action_shape).to(device) value_old = torch.randn(batch_size, agent_num).to(device) done = torch.zeros(batch_size).to(device) done[-1] = 1 action = torch.randint(0, action_shape, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # 目标回报可以用不同的方法计算。这里我们使用奖励的折扣累计值。 # 还可以使用广义优势估计 (GAE) 法、n-step TD 方法等等。 return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-Critic 网络前向传播。 output = model(local_state, agent_specific_global_state) # ``squeeze`` 操作将 shape 从 $$(B, A, 1)$$ 转化为 $$(B, A)$$. value = output.value.squeeze(-1) # 使用广义优势估计(Generalized Advantage Estimation,简称GAE)方法来计算优势(Advantage)。 # 优势是策略损失的一种“权重”,因此它被包含在 ``torch.no_grad()`` 中,表示不进行梯度计算。 # ``done`` 是回合结束的标志。``traj_flag`` 是轨迹(trajectory)的标志。 # 在这里,我们将整个批次数据视为一个完整的回合,所以 ``done`` 和 ``traj_flag`` 是相同的。 with torch.no_grad(): traj_flag = done gae_data = (value, value_old, reward, done, traj_flag) adv = gae(gae_data, discount_factor, 0.95) # 为 PPO policy loss 计算准备数据. data = ppo_policy_data(output.logit, logit_old, action, adv, None) # 计算 PPO policy loss. loss, info = ppo_policy_error(data) # 计算 value loss. value_loss = torch.nn.functional.mse_loss(value, return_) # 策略损失 (PPO policy loss)、价值损失 (value loss) 和熵损失 (entropy_loss) 的加权和。 total_loss = loss.policy_loss + value_weight * value_loss - entropy_weight * loss.entropy_loss # PyTorch loss 反向传播和优化器更新。 optimizer.zero_grad() total_loss.backward() optimizer.step() # 打印训练信息。 print( 'total_loss: {:.4f}, policy_loss: {:.4f}, value_loss: {:.4f}, entropy_loss: {:.4f}'.format( total_loss, loss.policy_loss, value_loss, loss.entropy_loss ) ) print('approximate_kl_divergence: {:.4f}, clip_fraction: {:.4f}'.format(info.approx_kl, info.clipfrac)) print('mappo_training_opeator is ok')
**概述** 这是关于 CTDE MAPPO 算法训练过程的核心函数。 首先,定义一些超参数,神经网络和优化器,然后生成构造的测试数据并计算演员-评论家损失 (Actor-Critic loss)。 最后,使用优化器更新网络参数。在实际应用中,训练数据应该是由环境进行在线交互得到的。 注意在本文件中,策略网络指的是演员 (Actor),价值网络指的是评论家 (Critic)。
158,697
import torch from marl_network import CTDEActorCriticNetwork from ppo import ppo_policy_data, ppo_policy_error from gae import gae class CTDEActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, local_obs_shape: int, global_obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of centralized training decentralized execution (CTDE) actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent shares the same parameters in the network so that they can be processed as a batch in parallel. The input of value network is ``global_obs`` while the input of policy network is ``local_obs`` . Global information used in value network can provide more guidance for the training of policy network. Local information used in policy network can make the policy network more robust to the decentralized execution. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(CTDEActorCriticNetwork, self).__init__() # Define local and global encoder respectively. self.agent_num = agent_num self.local_encoder = nn.Sequential( nn.Linear(local_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) self.global_encoder = nn.Sequential( nn.Linear(global_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) # Define discrete action logit output network, just one-layer FC. self.policy_head = nn.Linear(64, action_shape) # Define scalar value output network. self.value_head = nn.Linear(64, 1) # delimiter def forward(self, local_obs: torch.Tensor, global_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of CTDE actor-critic network, processing all agents' ``local_obs`` and ``global_obs`` and output corresponding policy logit and value in parallel. There are two possible designs for ``global_obs`` : The former is a shared global state for all agents, i.e. $$(B, S)$$. Tha latter is a kind of agent-specific global state, i.e. $$(B, A, S')$$. For more details, you can refer to <link https://di-engine-docs.readthedocs.io/zh_CN/latest/04_best_practice/marl_zh.html#id10 link>. """ # Call policy network with local obs and critic network with global obs respectively. policy = self.policy_head(self.local_encoder(local_obs)) value = self.value_head(self.global_encoder(global_obs)) return ttorch.as_tensor({ 'logit': policy, 'value': value, }) ppo_policy_data = namedtuple('ppo_policy_data', ['logit_new', 'logit_old', 'action', 'adv', 'weight']) def ppo_policy_error(data: namedtuple, clip_ratio: float = 0.2, dual_clip: Optional[float] = None) -> Tuple[namedtuple, namedtuple]: """ **Overview**: Implementation of Proximal Policy Optimization (PPO) <link https://arxiv.org/pdf/1707.06347.pdf link> with entropy bonus, value_clip and dual_clip. """ # Unpack data: $$<\pi_{new}(a|s), \pi_{old}(a|s), a, A^{\pi_{old}}(s, a), w>$$ logit_new, logit_old, action, adv, weight = data # Prepare weight for default cases. if weight is None: weight = torch.ones_like(adv) # Prepare policy distribution from logit and get log propability. dist_new = torch.distributions.categorical.Categorical(logits=logit_new) dist_old = torch.distributions.categorical.Categorical(logits=logit_old) logp_new = dist_new.log_prob(action) logp_old = dist_old.log_prob(action) # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi_{new}(a^n|s^n) log(\pi_{new}(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . dist_new_entropy = dist_new.entropy() entropy_loss = (dist_new_entropy * weight).mean() # Importance sampling weight: $$r(\theta) = \frac{\pi_{new}(a|s)}{\pi_{old}(a|s)}$$ ratio = torch.exp(logp_new - logp_old) # Original surrogate objective: $$r(\theta) A^{\pi_{old}}(s, a)$$ surr1 = ratio * adv # <b>Clipped surrogate objective:</b> $$clip(r(\theta), 1-\epsilon, 1+\epsilon) A^{\pi_{old}}(s, a)$$ surr2 = ratio.clamp(1 - clip_ratio, 1 + clip_ratio) * adv # Dual clip proposed by <link https://arxiv.org/abs/1912.09729 link> . # Only use dual_clip when adv < 0. if dual_clip is not None: clip1 = torch.min(surr1, surr2) clip2 = torch.max(clip1, dual_clip * adv) policy_loss = -(torch.where(adv < 0, clip2, clip1) * weight).mean() # PPO-Clipped Loss: $$min(r(\theta) A^{\pi_{old}}(s, a), clip(r(\theta), 1-\epsilon, 1+\epsilon) A^{\pi_{old}}(s, a))$$ # Multiply sample-wise weight and reduce mean in batch dimension. else: policy_loss = (-torch.min(surr1, surr2) * weight).mean() # Add some visualization metrics to monitor optimization status. with torch.no_grad(): approx_kl = (logp_old - logp_new).mean().item() clipped = ratio.gt(1 + clip_ratio) | ratio.lt(1 - clip_ratio) clipfrac = torch.as_tensor(clipped).float().mean().item() # Return final loss items and information. return ppo_policy_loss(policy_loss, entropy_loss), ppo_info(approx_kl, clipfrac) def gae(data: tuple, gamma: float = 0.99, lambda_: float = 0.97) -> torch.FloatTensor: """ **Overview**: Implementation of the Generalized Advantage Estimator (GAE) as proposed in arXiv:1506.02438. This function calculates the advantages, which are used to update policy parameters in reinforcement learning. Arguments: - data (:obj:`namedtuple`): Tuple containing trajectory data including state values, next state values, rewards, done flags, and trajectory flags. Please note that the ``done`` flag signals the termination of an episode, whereas the ``traj_flag`` indicates the completion of a trajectory, which represents a segment within an episode. - gamma (:obj:`float`): Discount factor for future rewards, should be in the range [0, 1]. Default is 0.99. - lambda_ (:obj:`float`): The decay rate for the GAE, should be in the range [0, 1]. Default is 0.97. As lambda approaches 0, it introduces bias, and as lambda approaches 1, it increases variance due to the cumulative effect of terms. Returns: - adv (:obj:`torch.FloatTensor`): The calculated advantage estimates. Shapes: - value (:obj:`torch.FloatTensor`): Size of (T, B), where T is the length of the trajectory and B is the batch size. - next_value (:obj:`torch.FloatTensor`): Size of (T, B) - reward (:obj:`torch.FloatTensor`): Size of (T, B) - adv (:obj:`torch.FloatTensor`): Size of (T, B) """ # Unpack the input data. value, next_value, reward, done, traj_flag = data # Convert the done and trajectory flags to tensor format. done = torch.tensor(done).float() traj_flag = torch.tensor(traj_flag).float() # Expand ``done`` for possible broadcast operation in multi-agent cases if len(value.shape) == 2: done = done.unsqueeze(1) # If done equals 1, it indicates the end of an episode, thus the next state value should be 0. next_value *= (1 - done) # Calculate the temporal difference (TD) error for each time step. # $$\delta_t=-V_{\phi}(s_t)+r_t+V_{\phi}(s_{t+1})$$ delta = reward + gamma * next_value - value # Set the GAE decay factor. If traj_flag equals 1, the factor will be 0. Otherwise, the factor is gamma * lambda. factor = gamma * lambda_ * (1 - traj_flag) # Initialize the advantage tensor. adv = torch.zeros_like(value) # Calculate ``adv`` in a reversed sequence. # Consider the definition of GAE: $$A^{GAE}_t = \sum_{i=1}\gamma^{i-1}\lambda^{i-1}\delta_{t+i-1}$$ # Rewrite the equation above in a recurrent form, we finally have: $$A^{GAE}_t = \delta_t + \gamma\lambda A^{GAE}_{t+1}$$ gae_item = torch.zeros_like(value[0]) for t in reversed(range(reward.shape[0])): gae_item = delta[t] + factor[t] * gae_item adv[t] = gae_item # Return the calculated advantage estimates. return adv The provided code snippet includes necessary dependencies for implementing the `mappo_training_opeator` function. Write a Python function `def mappo_training_opeator() -> None` to solve the following problem: **Overview**: The main function about the training process of CTDE PPO algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file. Here is the function: def mappo_training_opeator() -> None: """ **Overview**: The main function about the training process of CTDE PPO algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file. """ # Set necessary hyper-parameters. batch_size, agent_num, local_state_shape, agent_specific_global_state_shape, action_shape = 4, 5, 10, 25, 6 # Entropy bonus weight, which is beneficial to exploration. entropy_weight = 0.001 # Value loss weight, which aims to balance the loss scale. value_weight = 0.5 # Discount factor for future reward. discount_factor = 0.99 # Set the tensor device to cuda or cpu according to the runtime environment. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Define the multi-agent neural network and optimizer. model = CTDEActorCriticNetwork(agent_num, local_state_shape, agent_specific_global_state_shape, action_shape) model.to(device) # Adam is the most commonly used optimizer in deep reinforcement learning. If you want to add # weight decay mechanism, you should use ``torch.optim.AdamW`` . optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # Define the corresponding fake data following the same data format of the interacting with the environment. # Note that the data should keep the same device with the network. # For simplicity, we regard the whole batch data as a entire episode. # In practice, the training batch is the combination of multiple episodes. We often use # ``done`` variable to distinguish the different episodes. local_state = torch.randn(batch_size, agent_num, local_state_shape).to(device) agent_specific_global_state = torch.randn(batch_size, agent_num, agent_specific_global_state_shape).to(device) logit_old = torch.randn(batch_size, agent_num, action_shape).to(device) value_old = torch.randn(batch_size, agent_num).to(device) done = torch.zeros(batch_size).to(device) done[-1] = 1 action = torch.randint(0, action_shape, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # Return_ can be computed with different methods. Here we use the discounted cumulative sum of the reward. # You can also use the generalized advantage estimation (GAE) method, n-step return method, etc. return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-critic network forward propagation. output = model(local_state, agent_specific_global_state) # ``squeeze`` operation transforms shape from $$(B, A, 1)$$ to $$(B, A)$$. value = output.value.squeeze(-1) # Use generalized advantage estimation (GAE) method to calculate the advantage. # Advantage is a kind of "weight" for policy loss, therefore it is wrapperd in ``torch.no_grad()`` . # ``done`` is the terminal flag of the episode. ``traj_flag`` is the flag of the trajectory. # Here we regard the whole batch data as a entire episode, so ``done`` and ``traj_flag`` are the same. with torch.no_grad(): traj_flag = done gae_data = (value, value_old, reward, done, traj_flag) adv = gae(gae_data, discount_factor, 0.95) # Prepare the data for PPO policy loss calculation. data = ppo_policy_data(output.logit, logit_old, action, adv, None) # Calculate the PPO policy loss. loss, info = ppo_policy_error(data) # Calculate the value loss. value_loss = torch.nn.functional.mse_loss(value, return_) # Weighted sum of policy loss, value loss and entropy loss. total_loss = loss.policy_loss + value_weight * value_loss - entropy_weight * loss.entropy_loss # PyTorch loss back propagation and optimizer update. optimizer.zero_grad() total_loss.backward() optimizer.step() # Logging the training information. print( 'total_loss: {:.4f}, policy_loss: {:.4f}, value_loss: {:.4f}, entropy_loss: {:.4f}'.format( total_loss, loss.policy_loss, value_loss, loss.entropy_loss ) ) print('approximate_kl_divergence: {:.4f}, clip_fraction: {:.4f}'.format(info.approx_kl, info.clipfrac)) print('mappo_training_opeator is ok')
**Overview**: The main function about the training process of CTDE PPO algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file.
158,698
import torch from marl_network import CTDEActorCriticNetwork from pg import pg_data, pg_error class CTDEActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, local_obs_shape: int, global_obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of centralized training decentralized execution (CTDE) actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent shares the same parameters in the network so that they can be processed as a batch in parallel. The input of value network is ``global_obs`` while the input of policy network is ``local_obs`` . Global information used in value network can provide more guidance for the training of policy network. Local information used in policy network can make the policy network more robust to the decentralized execution. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(CTDEActorCriticNetwork, self).__init__() # Define local and global encoder respectively. self.agent_num = agent_num self.local_encoder = nn.Sequential( nn.Linear(local_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) self.global_encoder = nn.Sequential( nn.Linear(global_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) # Define discrete action logit output network, just one-layer FC. self.policy_head = nn.Linear(64, action_shape) # Define scalar value output network. self.value_head = nn.Linear(64, 1) # delimiter def forward(self, local_obs: torch.Tensor, global_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of CTDE actor-critic network, processing all agents' ``local_obs`` and ``global_obs`` and output corresponding policy logit and value in parallel. There are two possible designs for ``global_obs`` : The former is a shared global state for all agents, i.e. $$(B, S)$$. Tha latter is a kind of agent-specific global state, i.e. $$(B, A, S')$$. For more details, you can refer to <link https://di-engine-docs.readthedocs.io/zh_CN/latest/04_best_practice/marl_zh.html#id10 link>. """ # Call policy network with local obs and critic network with global obs respectively. policy = self.policy_head(self.local_encoder(local_obs)) value = self.value_head(self.global_encoder(global_obs)) return ttorch.as_tensor({ 'logit': policy, 'value': value, }) pg_data = namedtuple('pg_data', ['logit', 'action', 'return_']) def pg_error(data: namedtuple) -> namedtuple: """ **Overview**: Implementation of PG (Policy Gradient) """ # Unpack data: $$<\pi(a|s), a, G_t>$$ logit, action, return_ = data # Prepare policy distribution from logit and get log propability. dist = torch.distributions.categorical.Categorical(logits=logit) log_prob = dist.log_prob(action) # Policy loss: $$- \frac 1 N \sum_{n=1}^{N} log(\pi(a^n|s^n)) G_t^n$$ policy_loss = -(log_prob * return_).mean() # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi(a^n|s^n) log(\pi(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . entropy_loss = dist.entropy().mean() # Return the concrete loss items. return pg_loss(policy_loss, entropy_loss) The provided code snippet includes necessary dependencies for implementing the `mapg_training_opeator` function. Write a Python function `def mapg_training_opeator() -> None` to solve the following problem: **Overview**: The main function about the training process of CTDE policy gradient algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the policy gradient loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. Here is the function: def mapg_training_opeator() -> None: """ **Overview**: The main function about the training process of CTDE policy gradient algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the policy gradient loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. """ # Set necessary hyper-parameters. batch_size, agent_num, local_state_shape, global_state_shape, action_shape = 4, 5, 10, 20, 6 # Entropy bonus weight, which is beneficial to exploration. entropy_weight = 0.001 # Discount factor for future reward. discount_factor = 0.99 # Set the tensor device to cuda or cpu according to the runtime environment. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Define the CTDE multi-agent neural network and optimizer. model = CTDEActorCriticNetwork(agent_num, local_state_shape, global_state_shape, action_shape) model.to(device) # Adam is the most commonly used optimizer in deep reinforcement learning. If you want to add # weight decay mechanism, you should use ``torch.optim.AdamW`` . optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # Define the corresponding fake data following the same data format of the interacting with the environment. # Note that the data should keep the same device with the network. # For simplicity, we regard the whole batch data as a entire episode. # In practice, the training batch is the combination of multiple episodes. We often use # ``done`` variable to distinguish the different episodes. local_state = torch.randn(batch_size, agent_num, local_state_shape).to(device) global_state = torch.randn(batch_size, global_state_shape).to(device) action = torch.randint(0, action_shape, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # For naive policy gradient algorithm, the return is computed by the discounted cumulative sum of the reward. return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-critic network forward propagation. output = model(local_state, global_state) # Prepare the data for policy gradient loss calculation. data = pg_data(output.logit, action, return_) # Calculate the policy gradient loss. loss = pg_error(data) # Weighted sum of policy loss and entropy loss. # Note here we only use the policy network part of the actor-critic network and compute policy loss. # If you want to use the value network part, you should define the value loss and add it to the total loss. total_loss = loss.policy_loss - entropy_weight * loss.entropy_loss # PyTorch loss back propagation and optimizer update. optimizer.zero_grad() total_loss.backward() optimizer.step() print('mapg_training_opeator is ok')
**Overview**: The main function about the training process of CTDE policy gradient algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the policy gradient loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment.
158,699
import torch from marl_network import CTDEActorCriticNetwork from pg import pg_data, pg_error class CTDEActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, local_obs_shape: int, global_obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of centralized training decentralized execution (CTDE) actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent shares the same parameters in the network so that they can be processed as a batch in parallel. The input of value network is ``global_obs`` while the input of policy network is ``local_obs`` . Global information used in value network can provide more guidance for the training of policy network. Local information used in policy network can make the policy network more robust to the decentralized execution. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(CTDEActorCriticNetwork, self).__init__() # Define local and global encoder respectively. self.agent_num = agent_num self.local_encoder = nn.Sequential( nn.Linear(local_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) self.global_encoder = nn.Sequential( nn.Linear(global_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) # Define discrete action logit output network, just one-layer FC. self.policy_head = nn.Linear(64, action_shape) # Define scalar value output network. self.value_head = nn.Linear(64, 1) # delimiter def forward(self, local_obs: torch.Tensor, global_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of CTDE actor-critic network, processing all agents' ``local_obs`` and ``global_obs`` and output corresponding policy logit and value in parallel. There are two possible designs for ``global_obs`` : The former is a shared global state for all agents, i.e. $$(B, S)$$. Tha latter is a kind of agent-specific global state, i.e. $$(B, A, S')$$. For more details, you can refer to <link https://di-engine-docs.readthedocs.io/zh_CN/latest/04_best_practice/marl_zh.html#id10 link>. """ # Call policy network with local obs and critic network with global obs respectively. policy = self.policy_head(self.local_encoder(local_obs)) value = self.value_head(self.global_encoder(global_obs)) return ttorch.as_tensor({ 'logit': policy, 'value': value, }) pg_data = namedtuple('pg_data', ['logit', 'action', 'return_']) def pg_error(data: namedtuple) -> namedtuple: """ **Overview**: Implementation of PG (Policy Gradient) """ # Unpack data: $$<\pi(a|s), a, G_t>$$ logit, action, return_ = data # Prepare policy distribution from logit and get log propability. dist = torch.distributions.categorical.Categorical(logits=logit) log_prob = dist.log_prob(action) # Policy loss: $$- \frac 1 N \sum_{n=1}^{N} log(\pi(a^n|s^n)) G_t^n$$ policy_loss = -(log_prob * return_).mean() # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi(a^n|s^n) log(\pi(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . entropy_loss = dist.entropy().mean() # Return the concrete loss items. return pg_loss(policy_loss, entropy_loss) The provided code snippet includes necessary dependencies for implementing the `maac_training_opeator` function. Write a Python function `def maac_training_opeator() -> None` to solve the following problem: **Overview**: The main function about the training process of CTDE actor-critic algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file. Here is the function: def maac_training_opeator() -> None: """ **Overview**: The main function about the training process of CTDE actor-critic algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file. """ # Set necessary hyper-parameters. batch_size, agent_num, local_state_shape, global_state_shape, action_shape = 4, 5, 10, 20, 6 # Entropy bonus weight, which is beneficial to exploration. entropy_weight = 0.001 # Value loss weight, which aims to balance the loss scale. value_weight = 0.5 # Discount factor for future reward. discount_factor = 0.99 # Set the tensor device to cuda or cpu according to the runtime environment. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Define the multi-agent neural network and optimizer. model = CTDEActorCriticNetwork(agent_num, local_state_shape, global_state_shape, action_shape) model.to(device) # Adam is the most commonly used optimizer in deep reinforcement learning. If you want to add # weight decay mechanism, you should use ``torch.optim.AdamW`` . optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # Define the corresponding fake data following the same data format of the interacting with the environment. # Note that the data should keep the same device with the network. # For simplicity, we regard the whole batch data as a entire episode. # In practice, the training batch is the combination of multiple episodes. We often use # ``done`` variable to distinguish the different episodes. local_state = torch.randn(batch_size, agent_num, local_state_shape).to(device) global_state = torch.randn(batch_size, global_state_shape).to(device) action = torch.randint(0, action_shape, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # Return_ can be computed with different methods. Here we use the discounted cumulative sum of the reward. # You can also use the generalized advantage estimation (GAE) method, n-step return method, etc. return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-critic network forward propagation. output = model(local_state, global_state) # Keep value with the shape of $$(B, 1)$$, which can automatically broadcast agent dimension. value = output.value # Prepare the data for policy gradient loss calculation. # ``detach`` operation means stop gradient for ``value`` in policy gradient loss calculation. data = pg_data(output.logit, action, value.detach()) # Calculate the policy gradient loss. loss = pg_error(data) # Calculate the value loss. # Note we use the same global state for all agents to calculate value, therefore the target is the # sum of returns of all the agents. value_loss = torch.nn.functional.mse_loss(value, return_.sum(dim=-1, keepdim=True)) # Weighted sum of policy loss, value loss and entropy loss. total_loss = loss.policy_loss + value_weight * value_loss - entropy_weight * loss.entropy_loss # PyTorch loss back propagation and optimizer update. optimizer.zero_grad() total_loss.backward() optimizer.step() print('maac_training_opeator is ok')
**Overview**: The main function about the training process of CTDE actor-critic algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file.
158,700
import torch import torch.nn as nn import treetensor.torch as ttorch class SharedActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, obs_shape: int, action_shape: int) -> None: """ **功能概述**: 在多智能体场景下,使用策略梯度算法,各个智能体独立决策但共享参数的 Actor-Critic 网络定义。 由于各个智能体共享一个网络,因此它们的输入状态可以在一个 batch 中并行计算。 """ # PyTorch 在继承 ``nn.Module`` 类的时候,必须执行这个初始化方法。 super(SharedActorCriticNetwork, self).__init__() # 输入的形状是: $$(B, A, O)$$. self.agent_num = agent_num # 定义一个所有智能体共享的 Actor-Critic 网络。 self.actor_critic_network = ActorCriticNetwork(obs_shape, action_shape) # delimiter def forward(self, local_obs: torch.Tensor) -> ttorch.Tensor: """ **功能概述**: 共享参数的 Actor-Critic 网络计算图。 处理所有智能体的 ``local_obs``,并输出对应的策略分布和状态价值。 """ # 并行处理所有智能体的 ``local_obs``。 return self.actor_critic_network(local_obs) The provided code snippet includes necessary dependencies for implementing the `test_shared_ac_network` function. Write a Python function `def test_shared_ac_network() -> None` to solve the following problem: **test_shared_ac_network 功能概述**: 用于测试共享参数的 Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。 Here is the function: def test_shared_ac_network() -> None: """ **test_shared_ac_network 功能概述**: 用于测试共享参数的 Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。 """ # 设置 batch size,智能体个数,状态的形状和动作空间的维度。 batch_size = 4 agent_num = 3 obs_shape = 10 action_shape = 5 # 定义一个共享参数的 Actor-Critic 网络。 network = SharedActorCriticNetwork(agent_num, obs_shape, action_shape) # 随机生成伪数据,为各个智能体生成随机的状态。 local_obs = torch.randn(batch_size, agent_num, obs_shape) # 前向计算过程,将局部状态输入网络,得到输出。 result = network(local_obs) # 验证输出的形状。 assert result['logit'].shape == (batch_size, agent_num, action_shape) assert result['value'].shape == (batch_size, agent_num, 1)
**test_shared_ac_network 功能概述**: 用于测试共享参数的 Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。
158,701
import torch import torch.nn as nn import treetensor.torch as ttorch class IndependentActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, obs_shape: int, action_shape: int) -> None: """ **功能概述**: 在多智能体场景下,使用策略梯度算法,各个智能体独立决策且具有独立参数的 Actor-Critic 网络定义。 各个智能体拥有自己独立的 Actor-Critic 网络,拥有独立的参数。 """ # PyTorch 在继承 ``nn.Module`` 类的时候,必须执行这个初始化方法。 super(IndependentActorCriticNetwork, self).__init__() # 定义数量为 ``agent_num`` 的各自独立的 Actor-Critic 网络。记每个智能体对应一个网络。 # 为了利用 ``nn.Module`` 的一些特殊属性,我们使用 ``nn.ModuleList`` 作为作为存储这些网络的容器,而非 Python 自带的列表。 self.agent_num = agent_num self.actor_critic_networks = nn.ModuleList( [ActorCriticNetwork(obs_shape, action_shape) for _ in range(agent_num)] ) # delimiter def forward(self, local_obs: torch.Tensor) -> ttorch.Tensor: """ **功能概述**: 独立 Actor-Critic 网络的计算图。 串行地处理各个智能体的 ``local_obs``,并输出对应的策略概率分布和状态价值。 """ # 切分数据,串行地调用网络逐一处理各个智能体的 ``local_obs``。 return ttorch.cat([net(local_obs[:, i:i + 1]) for i, net in enumerate(self.actor_critic_networks)], dim=1) The provided code snippet includes necessary dependencies for implementing the `test_independent_ac_network` function. Write a Python function `def test_independent_ac_network() -> None` to solve the following problem: **test_independent_ac_network 功能概述**: 用于测试独立参数 Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。 Here is the function: def test_independent_ac_network() -> None: """ **test_independent_ac_network 功能概述**: 用于测试独立参数 Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。 """ # 设置 batch size,智能体个数,状态的形状和动作空间的维度。 batch_size = 4 agent_num = 3 obs_shape = 10 action_shape = 5 # 定义一个独立参数的 Actor-Critic 网络。 network = IndependentActorCriticNetwork(agent_num, obs_shape, action_shape) # 随机生成伪数据,为各个智能体生成随机的状态。 local_obs = torch.randn(batch_size, agent_num, obs_shape) # 前向计算过程,将局部状态输入网络,得到输出。 result = network(local_obs) # 验证输出的形状。 assert result['logit'].shape == (batch_size, agent_num, action_shape) assert result['value'].shape == (batch_size, agent_num, 1)
**test_independent_ac_network 功能概述**: 用于测试独立参数 Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。
158,702
import torch import torch.nn as nn import treetensor.torch as ttorch class CTDEActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, local_obs_shape: int, global_obs_shape: int, action_shape: int) -> None: """ **Overview**: 在多智能体场景下,集中式训练分布式执行 (centralized training and decentralized execution, CTDE) 网络的定义。 各个智能体共享同样的网络参数,因此它们可以在一个 batch 中并行地进行计算。 价值网络的输入是全局信息 ``global_obs``,而策略网络的输入是单个智能体的局部信息 ``local_obs``。 价值网络提取的全局信息,可以为使用局部信息的策略提供更多的指导; 策略网络提取的局部信息,可以使得网络在分布式执行的时候,更具有高效性和鲁棒性。 """ # PyTorch 在继承 ``nn.Module`` 类的时候,必须执行这个初始化方法。 super(CTDEActorCriticNetwork, self).__init__() # 分别定义局部信息编码器和全局信息编码器。 self.agent_num = agent_num self.local_encoder = nn.Sequential( nn.Linear(local_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) self.global_encoder = nn.Sequential( nn.Linear(global_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) # 定义离散动作的输出网络,仅包含一个全连接层。 self.policy_head = nn.Linear(64, action_shape) # 定义一个仅输出单个值的价值网络。 self.value_head = nn.Linear(64, 1) # delimiter def forward(self, local_obs: torch.Tensor, global_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: CTDE Actor-Critic 网络的计算图。 并行地处理各个智能体的 ``local_obs`` 和 ``global_obs``,并输出对应的策略分布和状态价值。 针对 ``global_obs`` 的设计,存在两种不同的方式:1) 对各个智能体采用一个共享的全局状态,即 ``global_obs`` 的形状为 $$(B, S)$$ 2) 对各个智能体设计不同的全局状态,即 ``global_obs`` 的形状为 $$(B, A, S')$$. 关于这个问题的更多细节,可以参考链接 <link https://di-engine-docs.readthedocs.io/zh_CN/latest/04_best_practice/marl_zh.html#id10 link> """ # 用策略网络 (Actor) 处理局部的状态生成动作,用价值网络 (Critic) 处理全局状态生成价值。 policy = self.policy_head(self.local_encoder(local_obs)) value = self.value_head(self.global_encoder(global_obs)) return ttorch.as_tensor({ 'logit': policy, 'value': value, }) The provided code snippet includes necessary dependencies for implementing the `test_ctde_ac_network` function. Write a Python function `def test_ctde_ac_network() -> None` to solve the following problem: **test_ctde_ac_network 功能概述**: 用于测试 CTDE Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。 Here is the function: def test_ctde_ac_network() -> None: """ **test_ctde_ac_network 功能概述**: 用于测试 CTDE Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。 """ # 设置 batch size,智能体个数,状态的形状和动作空间的维度。 batch_size = 4 agent_num = 3 local_obs_shape = 10 global_obs_shape = 20 action_shape = 5 # 测试共享全局状态的情况。 network = CTDEActorCriticNetwork(agent_num, local_obs_shape, global_obs_shape, action_shape) local_obs = torch.randn(batch_size, agent_num, local_obs_shape) global_obs = torch.randn(batch_size, global_obs_shape) result = network(local_obs, global_obs) # 验证输出的形状。 assert result['logit'].shape == (batch_size, agent_num, action_shape) assert result['value'].shape == (batch_size, 1) # 测试不共享全局状态的情况。 agent_specific_global_obs_shape = 25 network = CTDEActorCriticNetwork(agent_num, local_obs_shape, agent_specific_global_obs_shape, action_shape) local_obs = torch.randn(batch_size, agent_num, local_obs_shape) agent_specific_global_obs = torch.randn(batch_size, agent_num, agent_specific_global_obs_shape) result = network(local_obs, agent_specific_global_obs) # 验证输出的形状。 assert result['logit'].shape == (batch_size, agent_num, action_shape) assert result['value'].shape == (batch_size, agent_num, 1)
**test_ctde_ac_network 功能概述**: 用于测试 CTDE Actor-Critic 网络。首先创建一个网络,并输入一个 batch 的数据。随后验证其输出各部分的形状。
158,703
import torch from marl_network import IndependentActorCriticNetwork from pg import pg_data, pg_error class IndependentActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of independent actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent owns an independent actor-critic network with its own parameters. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(IndependentActorCriticNetwork, self).__init__() # Define ``agent_num`` independent actor-critic networks for each agent. # To reuse some attributes of ``nn.Module`` , we use ``nn.ModuleList`` to store these networks instead of Python native list. self.agent_num = agent_num self.actor_critic_networks = nn.ModuleList( [ActorCriticNetwork(obs_shape, action_shape) for _ in range(agent_num)] ) # delimiter def forward(self, local_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of independent actor-critic network, serially processing each agent's ``local_obs`` and output the cooresponding policy logit and value respectively. """ # Slice data, call the actor_critic_network serially, then concatenate the output. return ttorch.cat([net(local_obs[:, i:i + 1]) for i, net in enumerate(self.actor_critic_networks)], dim=1) pg_data = namedtuple('pg_data', ['logit', 'action', 'return_']) def pg_error(data: namedtuple) -> namedtuple: """ **Overview**: Implementation of PG (Policy Gradient) """ # Unpack data: $$<\pi(a|s), a, G_t>$$ logit, action, return_ = data # Prepare policy distribution from logit and get log propability. dist = torch.distributions.categorical.Categorical(logits=logit) log_prob = dist.log_prob(action) # Policy loss: $$- \frac 1 N \sum_{n=1}^{N} log(\pi(a^n|s^n)) G_t^n$$ policy_loss = -(log_prob * return_).mean() # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi(a^n|s^n) log(\pi(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . entropy_loss = dist.entropy().mean() # Return the concrete loss items. return pg_loss(policy_loss, entropy_loss) The provided code snippet includes necessary dependencies for implementing the `independentpg_training_opeator` function. Write a Python function `def independentpg_training_opeator() -> None` to solve the following problem: **Overview**: The main function about the training process of independent policy gradient algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the policy gradient loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. Here is the function: def independentpg_training_opeator() -> None: """ **Overview**: The main function about the training process of independent policy gradient algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the policy gradient loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. """ # Set necessary hyper-parameters. batch_size, agent_num, local_state_dim, global_state_dim, action_dim = 4, 5, 10, 20, 6 # Entropy bonus weight, which is beneficial to exploration. entropy_weight = 0.001 # Discount factor for future reward. discount_factor = 0.99 # Set the tensor device to cuda or cpu according to the runtime environment. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Define the multi-agent neural network and optimizer. # Here we use the independent actor-critic network as the example, you can also use the shared-parameter network. model = IndependentActorCriticNetwork(agent_num, local_state_dim, action_dim) model.to(device) # Adam is the most commonly used optimizer in deep reinforcement learning. If you want to add # weight decay mechanism, you should use ``torch.optim.AdamW`` . optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # Define the corresponding fake data following the same data format of the interacting with the environment. # Note that the data should keep the same device with the network. # For simplicity, we regard the whole batch data as a entire episode. # In practice, the training batch is the combination of multiple episodes. We often use # ``done`` variable to distinguish the different episodes. local_state = torch.randn(batch_size, agent_num, local_state_dim).to(device) action = torch.randint(0, action_dim, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # For naive policy gradient algorithm, the return is computed by the discounted cumulative sum of the reward. return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-critic network forward propagation. output = model(local_state) # Prepare the data for policy gradient loss calculation. data = pg_data(output.logit, action, return_) # Calculate the policy gradient loss. loss = pg_error(data) # Weighted sum of policy loss and entropy loss. # Note here we only use the policy network part of the actor-critic network and compute policy loss. # If you want to use the value network part, you should define the value loss and add it to the total loss. total_loss = loss.policy_loss - entropy_weight * loss.entropy_loss # PyTorch loss back propagation and optimizer update. optimizer.zero_grad() total_loss.backward() optimizer.step() print('independentpg_training_opeator is ok')
**Overview**: The main function about the training process of independent policy gradient algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the policy gradient loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment.
158,704
import torch from marl_network import IndependentActorCriticNetwork from pg import pg_data, pg_error class IndependentActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of independent actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent owns an independent actor-critic network with its own parameters. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(IndependentActorCriticNetwork, self).__init__() # Define ``agent_num`` independent actor-critic networks for each agent. # To reuse some attributes of ``nn.Module`` , we use ``nn.ModuleList`` to store these networks instead of Python native list. self.agent_num = agent_num self.actor_critic_networks = nn.ModuleList( [ActorCriticNetwork(obs_shape, action_shape) for _ in range(agent_num)] ) # delimiter def forward(self, local_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of independent actor-critic network, serially processing each agent's ``local_obs`` and output the cooresponding policy logit and value respectively. """ # Slice data, call the actor_critic_network serially, then concatenate the output. return ttorch.cat([net(local_obs[:, i:i + 1]) for i, net in enumerate(self.actor_critic_networks)], dim=1) pg_data = namedtuple('pg_data', ['logit', 'action', 'return_']) def pg_error(data: namedtuple) -> namedtuple: """ **Overview**: Implementation of PG (Policy Gradient) """ # Unpack data: $$<\pi(a|s), a, G_t>$$ logit, action, return_ = data # Prepare policy distribution from logit and get log propability. dist = torch.distributions.categorical.Categorical(logits=logit) log_prob = dist.log_prob(action) # Policy loss: $$- \frac 1 N \sum_{n=1}^{N} log(\pi(a^n|s^n)) G_t^n$$ policy_loss = -(log_prob * return_).mean() # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi(a^n|s^n) log(\pi(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . entropy_loss = dist.entropy().mean() # Return the concrete loss items. return pg_loss(policy_loss, entropy_loss) The provided code snippet includes necessary dependencies for implementing the `independentac_training_opeator` function. Write a Python function `def independentac_training_opeator() -> None` to solve the following problem: **Overview**: The main function about the training process of independent actor-critic algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file. Here is the function: def independentac_training_opeator() -> None: """ **Overview**: The main function about the training process of independent actor-critic algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file. """ # Set necessary hyper-parameters. batch_size, agent_num, local_state_dim, global_state_dim, action_dim = 4, 5, 10, 20, 6 # Entropy bonus weight, which is beneficial to exploration. entropy_weight = 0.001 # Value loss weight, which aims to balance the loss scale. value_weight = 0.5 # Discount factor for future reward. discount_factor = 0.99 # Set the tensor device to cuda or cpu according to the runtime environment. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Define the multi-agent neural network and optimizer. # Here we use the independent actor-critic network as the example, you can also use the shared-parameter network. model = IndependentActorCriticNetwork(agent_num, local_state_dim, action_dim) model.to(device) # Adam is the most commonly used optimizer in deep reinforcement learning. If you want to add # weight decay mechanism, you should use ``torch.optim.AdamW`` . optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # Define the corresponding fake data following the same data format of the interacting with the environment. # Note that the data should keep the same device with the network. # For simplicity, we regard the whole batch data as a entire episode. # In practice, the training batch is the combination of multiple episodes. We often use # ``done`` variable to distinguish the different episodes. local_state = torch.randn(batch_size, agent_num, local_state_dim).to(device) action = torch.randint(0, action_dim, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # Return_ can be computed with different methods. Here we use the discounted cumulative sum of the reward. # You can also use the generalized advantage estimation (GAE) method, n-step return method, etc. return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-critic network forward propagation. output = model(local_state) # ``squeeze`` operation transforms shape from $$(B, A, 1)$$ to $$(B, A)$$. value = output.value.squeeze(-1) # Prepare the data for policy gradient loss calculation. # ``detach`` operation means stop gradient for ``value`` in policy gradient loss calculation. data = pg_data(output.logit, action, value.detach()) # Calculate the policy gradient loss. loss = pg_error(data) # Calculate the value loss. value_loss = torch.nn.functional.mse_loss(value, return_) # Weighted sum of policy loss, value loss and entropy loss. total_loss = loss.policy_loss + value_weight * value_loss - entropy_weight * loss.entropy_loss # PyTorch loss back propagation and optimizer update. optimizer.zero_grad() total_loss.backward() optimizer.step() print('independentac_training_opeator is ok')
**Overview**: The main function about the training process of independent actor-critic algorithm. Define some hyper-parameters, the neural network and optimizer, then generate fake data and calculate the actor-critic loss. Finally, update the network parameters with optimizer. In practice, the training data should be replaced by the results getting from the interacting with the environment. BTW, policy network means actor and value network indicates critic in this file.
158,705
import torch from marl_network import IndependentActorCriticNetworkg_error class IndependentActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of independent actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent owns an independent actor-critic network with its own parameters. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(IndependentActorCriticNetwork, self).__init__() # Define ``agent_num`` independent actor-critic networks for each agent. # To reuse some attributes of ``nn.Module`` , we use ``nn.ModuleList`` to store these networks instead of Python native list. self.agent_num = agent_num self.actor_critic_networks = nn.ModuleList( [ActorCriticNetwork(obs_shape, action_shape) for _ in range(agent_num)] ) # delimiter def forward(self, local_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of independent actor-critic network, serially processing each agent's ``local_obs`` and output the cooresponding policy logit and value respectively. """ # Slice data, call the actor_critic_network serially, then concatenate the output. return ttorch.cat([net(local_obs[:, i:i + 1]) for i, net in enumerate(self.actor_critic_networks)], dim=1) pg_data = namedtuple('pg_data', ['logit', 'action', 'return_']) def pg_error(data: namedtuple) -> namedtuple: """ **Overview**: Implementation of PG (Policy Gradient) """ # Unpack data: $$<\pi(a|s), a, G_t>$$ logit, action, return_ = data # Prepare policy distribution from logit and get log propability. dist = torch.distributions.categorical.Categorical(logits=logit) log_prob = dist.log_prob(action) # Policy loss: $$- \frac 1 N \sum_{n=1}^{N} log(\pi(a^n|s^n)) G_t^n$$ policy_loss = -(log_prob * return_).mean() # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi(a^n|s^n) log(\pi(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . entropy_loss = dist.entropy().mean() # Return the concrete loss items. return pg_loss(policy_loss, entropy_loss) The provided code snippet includes necessary dependencies for implementing the `independentpg_training_opeator` function. Write a Python function `def independentpg_training_opeator() -> None` to solve the following problem: **independentpg_training_opeator 功能概述**: 关于独立策略梯度算法训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成的伪数据并计算策略梯度损失。 最后,使用优化器更新网络参数。在实际应用中,这些伪数据应该被与环境交互得到的真实数据替换。 Here is the function: def independentpg_training_opeator() -> None: """ **independentpg_training_opeator 功能概述**: 关于独立策略梯度算法训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成的伪数据并计算策略梯度损失。 最后,使用优化器更新网络参数。在实际应用中,这些伪数据应该被与环境交互得到的真实数据替换。 """ # 设置必要的超参数。 batch_size, agent_num, local_state_dim, global_state_dim, action_dim = 4, 5, 10, 20, 6 # Entropy bonus 的权重,有助于智能体进行探索。 entropy_weight = 0.001 # 对未来奖励的折扣因子 discount_factor = 0.99 # 根据运行环境设定,决定 tensor 放置于 cpu 或是 cuda 。 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 定义多智能体神经网络和优化器。 # 在这里,我们使用 ``IndependentActorCriticNetwork`` 作为示例,你也可使用共享参数的网络。 model = IndependentActorCriticNetwork(agent_num, local_state_dim, action_dim) model.to(device) # Adam 是深度强化学习中最常用的优化器。如果你想使用 weight decay,你应当使用 ``torch.optim.AdamW`` 优化器 optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 定义对应随机生成的伪数据,其格式与真实和环境交互得到的数据相同。 # 要注意,数据和网络应当在相同的设备上 (cpu 或 cuda)。 # 简单起见,我们这里假定一个 batch 的数据构成了一个完整的 episode。 # 在真实实践中,一个训练 batch 可能是多个 episode 混在一起的结果。我们常常使用 ``done`` 这个变量来区分不同的 episodes。 local_state = torch.randn(batch_size, agent_num, local_state_dim).to(device) action = torch.randint(0, action_dim, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # 对于最基础的策略梯度算法,return 值由带折扣因子的累积奖励计算得来。 return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-Critic 网络前向计算. output = model(local_state) # 准备用于计算策略梯度损失函数的数据。 data = pg_data(output.logit, action, return_) # 计算策略梯度算法的损失函数。 loss = pg_error(data) # 策略损失函数部分和熵损失函数部分的加权和。 # 注意,这里我们只使用了网络的“策略部分”(即 Actor 部分)来计算策略损失函数。 # 如果你想要使用网络的“价值部分”(即 Critic 部分),你需要定义相应的价值损失函数并将其加入最终的总损失函数之中。 total_loss = loss.policy_loss - entropy_weight * loss.entropy_loss # PyTorch 的反向传播及参数更新。 optimizer.zero_grad() total_loss.backward() optimizer.step() print('independentpg_training_operator is ok')
**independentpg_training_opeator 功能概述**: 关于独立策略梯度算法训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成的伪数据并计算策略梯度损失。 最后,使用优化器更新网络参数。在实际应用中,这些伪数据应该被与环境交互得到的真实数据替换。
158,706
import torch from marl_network import IndependentActorCriticNetworkg_error class IndependentActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of independent actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent owns an independent actor-critic network with its own parameters. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(IndependentActorCriticNetwork, self).__init__() # Define ``agent_num`` independent actor-critic networks for each agent. # To reuse some attributes of ``nn.Module`` , we use ``nn.ModuleList`` to store these networks instead of Python native list. self.agent_num = agent_num self.actor_critic_networks = nn.ModuleList( [ActorCriticNetwork(obs_shape, action_shape) for _ in range(agent_num)] ) # delimiter def forward(self, local_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of independent actor-critic network, serially processing each agent's ``local_obs`` and output the cooresponding policy logit and value respectively. """ # Slice data, call the actor_critic_network serially, then concatenate the output. return ttorch.cat([net(local_obs[:, i:i + 1]) for i, net in enumerate(self.actor_critic_networks)], dim=1) pg_data = namedtuple('pg_data', ['logit', 'action', 'return_']) def pg_error(data: namedtuple) -> namedtuple: """ **Overview**: Implementation of PG (Policy Gradient) """ # Unpack data: $$<\pi(a|s), a, G_t>$$ logit, action, return_ = data # Prepare policy distribution from logit and get log propability. dist = torch.distributions.categorical.Categorical(logits=logit) log_prob = dist.log_prob(action) # Policy loss: $$- \frac 1 N \sum_{n=1}^{N} log(\pi(a^n|s^n)) G_t^n$$ policy_loss = -(log_prob * return_).mean() # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi(a^n|s^n) log(\pi(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . entropy_loss = dist.entropy().mean() # Return the concrete loss items. return pg_loss(policy_loss, entropy_loss) The provided code snippet includes necessary dependencies for implementing the `independentac_training_opeator` function. Write a Python function `def independentac_training_opeator() -> None` to solve the following problem: **independentac_training_opeator 功能概述**: 关于独立 Actor-Critic 算法的训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成随机伪数据并计算相关损失函数。在实践中,训练数据应被替换为与环境互动获得的结果。 最后,使用优化器更新网络参数。在本文中,网络的策略部分指的是 Actor,而价值部分网络则指的是 Critic。 Here is the function: def independentac_training_opeator() -> None: """ **independentac_training_opeator 功能概述**: 关于独立 Actor-Critic 算法的训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成随机伪数据并计算相关损失函数。在实践中,训练数据应被替换为与环境互动获得的结果。 最后,使用优化器更新网络参数。在本文中,网络的策略部分指的是 Actor,而价值部分网络则指的是 Critic。 """ # 设置必要的超参数。 batch_size, agent_num, local_state_dim, global_state_dim, action_dim = 4, 5, 10, 20, 6 # Entropy bonus 的权重,有助于智能体进行探索。 entropy_weight = 0.001 # 价值损失函数的权重,用于平衡损失函数值的大小。 value_weight = 0.5 # 对未来奖励的折扣因子 discount_factor = 0.99 # 根据运行环境设定,决定 tensor 放置于 cpu 或是 cuda 。 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 定义多智能体神经网络和优化器。 # 在这里,我们使用 ``IndependentActorCriticNetwork`` 作为示例,你也可使用共享参数的网络。 model = IndependentActorCriticNetwork(agent_num, local_state_dim, action_dim) model.to(device) # Adam 是深度强化学习中最常用的优化器。如果你想使用 weight decay,你应当使用 ``torch.optim.AdamW`` 优化器 optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 定义对应随机生成的伪数据,其格式与真实和环境交互得到的数据相同。 # 要注意,数据和网络应当在相同的设备上 (cpu 或 cuda)。 # 简单起见,我们这里假定一个 batch 的数据构成了一个完整的 episode。 # 在真实实践中,一个训练 batch 可能是多个 episode 混在一起的结果。我们常常使用 ``done`` 这个变量来区分不同的 episodes。 local_state = torch.randn(batch_size, agent_num, local_state_dim).to(device) action = torch.randint(0, action_dim, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # 累积回报值可以使用多种不同的方式进行计算,在这里我们使用由带折扣因子的累积奖励。 # 你也可以使用 generalized advantage estimation (GAE), n-step 等其他方式计算该值。 return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-Critic 网络前向计算。 output = model(local_state) # ``squeeze`` 操作将张量 从 $$(B, A, 1)$$ 变化为 $$(B, A)$$ value = output.value.squeeze(-1) # 准备用于计算策略梯度损失函数的数据。 # ``detach`` 操作可以使得在计算损失函数的梯度时, ``value`` 的梯度不进行反向传播。 data = pg_data(output.logit, action, value.detach()) # 计算策略梯度损失函数。 loss = pg_error(data) # 计算价值损失函数。 value_loss = torch.nn.functional.mse_loss(value, return_) # 策略损失函数、价值损失函数、熵损失函数的加权和。 total_loss = loss.policy_loss + value_weight * value_loss - entropy_weight * loss.entropy_loss # PyTorch 的反向传播及参数更新。 optimizer.zero_grad() total_loss.backward() optimizer.step() print('independentac_training_operator is ok')
**independentac_training_opeator 功能概述**: 关于独立 Actor-Critic 算法的训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成随机伪数据并计算相关损失函数。在实践中,训练数据应被替换为与环境互动获得的结果。 最后,使用优化器更新网络参数。在本文中,网络的策略部分指的是 Actor,而价值部分网络则指的是 Critic。
158,707
import torch from marl_network import CTDEActorCriticNetworkg_error class CTDEActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, local_obs_shape: int, global_obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of centralized training decentralized execution (CTDE) actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent shares the same parameters in the network so that they can be processed as a batch in parallel. The input of value network is ``global_obs`` while the input of policy network is ``local_obs`` . Global information used in value network can provide more guidance for the training of policy network. Local information used in policy network can make the policy network more robust to the decentralized execution. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(CTDEActorCriticNetwork, self).__init__() # Define local and global encoder respectively. self.agent_num = agent_num self.local_encoder = nn.Sequential( nn.Linear(local_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) self.global_encoder = nn.Sequential( nn.Linear(global_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) # Define discrete action logit output network, just one-layer FC. self.policy_head = nn.Linear(64, action_shape) # Define scalar value output network. self.value_head = nn.Linear(64, 1) # delimiter def forward(self, local_obs: torch.Tensor, global_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of CTDE actor-critic network, processing all agents' ``local_obs`` and ``global_obs`` and output corresponding policy logit and value in parallel. There are two possible designs for ``global_obs`` : The former is a shared global state for all agents, i.e. $$(B, S)$$. Tha latter is a kind of agent-specific global state, i.e. $$(B, A, S')$$. For more details, you can refer to <link https://di-engine-docs.readthedocs.io/zh_CN/latest/04_best_practice/marl_zh.html#id10 link>. """ # Call policy network with local obs and critic network with global obs respectively. policy = self.policy_head(self.local_encoder(local_obs)) value = self.value_head(self.global_encoder(global_obs)) return ttorch.as_tensor({ 'logit': policy, 'value': value, }) pg_data = namedtuple('pg_data', ['logit', 'action', 'return_']) def pg_error(data: namedtuple) -> namedtuple: """ **Overview**: Implementation of PG (Policy Gradient) """ # Unpack data: $$<\pi(a|s), a, G_t>$$ logit, action, return_ = data # Prepare policy distribution from logit and get log propability. dist = torch.distributions.categorical.Categorical(logits=logit) log_prob = dist.log_prob(action) # Policy loss: $$- \frac 1 N \sum_{n=1}^{N} log(\pi(a^n|s^n)) G_t^n$$ policy_loss = -(log_prob * return_).mean() # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi(a^n|s^n) log(\pi(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . entropy_loss = dist.entropy().mean() # Return the concrete loss items. return pg_loss(policy_loss, entropy_loss) The provided code snippet includes necessary dependencies for implementing the `mapg_training_opeator` function. Write a Python function `def mapg_training_opeator() -> None` to solve the following problem: **mapg_training_opeator 功能概述**: 关于 CTDE 策略梯度算法训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成假数据并计算策略梯度损失。 最后,使用优化器更新网络参数。在实际实践中,这些伪数据应该被与环境交互得到的真实数据替换。 Here is the function: def mapg_training_opeator() -> None: """ **mapg_training_opeator 功能概述**: 关于 CTDE 策略梯度算法训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成假数据并计算策略梯度损失。 最后,使用优化器更新网络参数。在实际实践中,这些伪数据应该被与环境交互得到的真实数据替换。 """ # 设置必要的超参数。 batch_size, agent_num, local_state_shape, global_state_shape, action_shape = 4, 5, 10, 20, 6 # Entropy bonus 的权重,有助于智能体进行探索。 entropy_weight = 0.001 # 对未来奖励的折扣因子 discount_factor = 0.99 # 根据运行环境设定,决定 tensor 放置于 cpu 或是 cuda 。 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 定义 CTDE 多智能体神经网络和优化器。 model = CTDEActorCriticNetwork(agent_num, local_state_shape, global_state_shape, action_shape) model.to(device) # Adam 是深度强化学习中最常用的优化器。如果你想使用 weight decay,你应当使用 ``torch.optim.AdamW`` 优化器 optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 定义对应随机生成的伪数据,其格式与真实和环境交互得到的数据相同。 # 要注意,数据和网络应当在相同的设备上 (cpu 或 cuda)。 # 简单起见,我们这里假定一个 batch 的数据构成了一个完整的 episode。 # 在真实实践中,一个训练 batch 可能是多个 episode 混在一起的结果。我们常常使用 ``done`` 这个变量来区分不同的 episodes。 local_state = torch.randn(batch_size, agent_num, local_state_shape).to(device) global_state = torch.randn(batch_size, global_state_shape).to(device) action = torch.randint(0, action_shape, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # 对于最基础的策略梯度算法,累积回报值由带折扣因子的累积奖励计算得来。 return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-Critic 网络前向计算. output = model(local_state, global_state) # 准备用于计算策略梯度损失函数的数据。 data = pg_data(output.logit, action, return_) # 计算策略梯度算法的损失函数。 loss = pg_error(data) # 策略损失函数部分和熵损失函数部分的加权和。 # 注意,这里我们只使用了网络的“策略部分”(即 Actor 部分)来计算策略损失函数。 # 如果你想要使用网络的“价值部分”(即 Critic 部分),你需要定义相应的价值损失函数并将其加入最终的总损失函数之中。 total_loss = loss.policy_loss - entropy_weight * loss.entropy_loss # PyTorch 的反向传播及参数更新。 optimizer.zero_grad() total_loss.backward() optimizer.step() print('mapg_training_operator is ok')
**mapg_training_opeator 功能概述**: 关于 CTDE 策略梯度算法训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成假数据并计算策略梯度损失。 最后,使用优化器更新网络参数。在实际实践中,这些伪数据应该被与环境交互得到的真实数据替换。
158,708
import torch from marl_network import CTDEActorCriticNetworkg_error class CTDEActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, local_obs_shape: int, global_obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of centralized training decentralized execution (CTDE) actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent shares the same parameters in the network so that they can be processed as a batch in parallel. The input of value network is ``global_obs`` while the input of policy network is ``local_obs`` . Global information used in value network can provide more guidance for the training of policy network. Local information used in policy network can make the policy network more robust to the decentralized execution. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(CTDEActorCriticNetwork, self).__init__() # Define local and global encoder respectively. self.agent_num = agent_num self.local_encoder = nn.Sequential( nn.Linear(local_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) self.global_encoder = nn.Sequential( nn.Linear(global_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) # Define discrete action logit output network, just one-layer FC. self.policy_head = nn.Linear(64, action_shape) # Define scalar value output network. self.value_head = nn.Linear(64, 1) # delimiter def forward(self, local_obs: torch.Tensor, global_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of CTDE actor-critic network, processing all agents' ``local_obs`` and ``global_obs`` and output corresponding policy logit and value in parallel. There are two possible designs for ``global_obs`` : The former is a shared global state for all agents, i.e. $$(B, S)$$. Tha latter is a kind of agent-specific global state, i.e. $$(B, A, S')$$. For more details, you can refer to <link https://di-engine-docs.readthedocs.io/zh_CN/latest/04_best_practice/marl_zh.html#id10 link>. """ # Call policy network with local obs and critic network with global obs respectively. policy = self.policy_head(self.local_encoder(local_obs)) value = self.value_head(self.global_encoder(global_obs)) return ttorch.as_tensor({ 'logit': policy, 'value': value, }) pg_data = namedtuple('pg_data', ['logit', 'action', 'return_']) def pg_error(data: namedtuple) -> namedtuple: """ **Overview**: Implementation of PG (Policy Gradient) """ # Unpack data: $$<\pi(a|s), a, G_t>$$ logit, action, return_ = data # Prepare policy distribution from logit and get log propability. dist = torch.distributions.categorical.Categorical(logits=logit) log_prob = dist.log_prob(action) # Policy loss: $$- \frac 1 N \sum_{n=1}^{N} log(\pi(a^n|s^n)) G_t^n$$ policy_loss = -(log_prob * return_).mean() # Entropy bonus: $$\frac 1 N \sum_{n=1}^{N} \sum_{a^n}\pi(a^n|s^n) log(\pi(a^n|s^n))$$ # P.S. the final loss is ``policy_loss - entropy_weight * entropy_loss`` . entropy_loss = dist.entropy().mean() # Return the concrete loss items. return pg_loss(policy_loss, entropy_loss) The provided code snippet includes necessary dependencies for implementing the `maac_training_opeator` function. Write a Python function `def maac_training_opeator() -> None` to solve the following problem: **maac_training_opeator 功能概述**: 关于 CTDE Actor-Critic 算法的训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成随机伪数据并计算相关损失函数。在实践中,训练数据应被替换为与环境互动获得的结果。 最后,使用优化器更新网络参数。在本文中,网络的策略部分指的是 Actor,而价值部分网络则指的是 Critic。 Here is the function: def maac_training_opeator() -> None: """ **maac_training_opeator 功能概述**: 关于 CTDE Actor-Critic 算法的训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成随机伪数据并计算相关损失函数。在实践中,训练数据应被替换为与环境互动获得的结果。 最后,使用优化器更新网络参数。在本文中,网络的策略部分指的是 Actor,而价值部分网络则指的是 Critic。 """ # 设置必要的超参数。 batch_size, agent_num, local_state_shape, global_state_shape, action_shape = 4, 5, 10, 20, 6 # Entropy bonus 的权重,有助于智能体进行探索。 entropy_weight = 0.001 # 价值损失函数的权重,用于平衡损失函数值的大小。 value_weight = 0.5 # 对未来奖励的折扣因子 discount_factor = 0.99 # 根据运行环境设定,决定 tensor 放置于 cpu 或是 cuda 。 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 定义多智能体神经网络和优化器。 model = CTDEActorCriticNetwork(agent_num, local_state_shape, global_state_shape, action_shape) model.to(device) # Adam 是深度强化学习中最常用的优化器。如果你想使用 weight decay,你应当使用 ``torch.optim.AdamW`` 优化器 optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 定义对应随机生成的伪数据,其格式与真实和环境交互得到的数据相同。 # 要注意,数据和网络应当在相同的设备上 (cpu 或 cuda)。 # 简单起见,我们这里假定一个 batch 的数据构成了一个完整的 episode。 # 在真实实践中,一个训练 batch 可能是多个 episode 混在一起的结果。我们常常使用 ``done`` 这个变量来区分不同的 episodes。 local_state = torch.randn(batch_size, agent_num, local_state_shape).to(device) global_state = torch.randn(batch_size, global_state_shape).to(device) action = torch.randint(0, action_shape, (batch_size, agent_num)).to(device) reward = torch.randn(batch_size, agent_num).to(device) # 累积回报值可以使用多种不同的方式进行计算,在这里我们使用由带折扣因子的累积奖励。 # 你也可以使用 generalized advantage estimation (GAE), n-step 等其他方式计算该值。 return_ = torch.zeros_like(reward) for i in reversed(range(batch_size)): return_[i] = reward[i] + (discount_factor * return_[i + 1] if i + 1 < batch_size else 0) # Actor-Critic 网络前向计算。 output = model(local_state, global_state) # 保证 value 的形状为 $$(B, 1)$$, 这样可以使得这个张量在后续计算中可以自动广播出不同智能体的维度。 value = output.value # 准备用于计算策略梯度损失函数的数据。 # ``detach`` 操作可以使得在计算损失函数的梯度时, ``value`` 的梯度不进行反向传播。 data = pg_data(output.logit, action, value.detach()) # 计算策略梯度损失函数。 loss = pg_error(data) # 计算价值损失函数。 # 需要注意的是,由于我们对于各个智能体都使用同一个全局的状态来计算价值函数,因此总的目标价值应当是各个智能体的回报之和。 value_loss = torch.nn.functional.mse_loss(value, return_.sum(dim=-1, keepdim=True)) # 策略损失函数、价值损失函数、熵损失函数的加权和。 total_loss = loss.policy_loss + value_weight * value_loss - entropy_weight * loss.entropy_loss # PyTorch 的反向传播及参数更新。 optimizer.zero_grad() total_loss.backward() optimizer.step() print('maac_training_operator is ok')
**maac_training_opeator 功能概述**: 关于 CTDE Actor-Critic 算法的训练过程的主函数。 定义一些超参数,神经网络和优化器,然后生成随机伪数据并计算相关损失函数。在实践中,训练数据应被替换为与环境互动获得的结果。 最后,使用优化器更新网络参数。在本文中,网络的策略部分指的是 Actor,而价值部分网络则指的是 Critic。
158,709
import torch import torch.nn as nn import treetensor.torch as ttorch class SharedActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of shared parameters actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent shares the same parameters in the network so that they can be processed as a batch in parallel. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(SharedActorCriticNetwork, self).__init__() # The shape of forward input is $$(B, A, O)$$. self.agent_num = agent_num # Define a shared actor-critic network used for all the agents. self.actor_critic_network = ActorCriticNetwork(obs_shape, action_shape) # delimiter def forward(self, local_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of shared parameters actor-critic network, processing all agents' ``local_obs`` and output corresponding policy logit and value respectively. """ # Call the actor_critic_network in parallel. return self.actor_critic_network(local_obs) The provided code snippet includes necessary dependencies for implementing the `test_shared_ac_network` function. Write a Python function `def test_shared_ac_network() -> None` to solve the following problem: **Overview**: The function of testing shared parameters actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output. Here is the function: def test_shared_ac_network() -> None: """ **Overview**: The function of testing shared parameters actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output. """ # Set batch size, agent number, observation shape and action shape. batch_size = 4 agent_num = 3 obs_shape = 10 action_shape = 5 # Define a shared actor-critic network. network = SharedActorCriticNetwork(agent_num, obs_shape, action_shape) # Generate a batch of local obs data for all agents from the standard normal distribution. local_obs = torch.randn(batch_size, agent_num, obs_shape) # Actor-critic network forward procedure, pass the local obs data to the network and get the output. result = network(local_obs) # Validate the shape of output. assert result['logit'].shape == (batch_size, agent_num, action_shape) assert result['value'].shape == (batch_size, agent_num, 1)
**Overview**: The function of testing shared parameters actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output.
158,710
import torch import torch.nn as nn import treetensor.torch as ttorch class IndependentActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of independent actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent owns an independent actor-critic network with its own parameters. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(IndependentActorCriticNetwork, self).__init__() # Define ``agent_num`` independent actor-critic networks for each agent. # To reuse some attributes of ``nn.Module`` , we use ``nn.ModuleList`` to store these networks instead of Python native list. self.agent_num = agent_num self.actor_critic_networks = nn.ModuleList( [ActorCriticNetwork(obs_shape, action_shape) for _ in range(agent_num)] ) # delimiter def forward(self, local_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of independent actor-critic network, serially processing each agent's ``local_obs`` and output the cooresponding policy logit and value respectively. """ # Slice data, call the actor_critic_network serially, then concatenate the output. return ttorch.cat([net(local_obs[:, i:i + 1]) for i, net in enumerate(self.actor_critic_networks)], dim=1) The provided code snippet includes necessary dependencies for implementing the `test_independent_ac_network` function. Write a Python function `def test_independent_ac_network() -> None` to solve the following problem: **Overview**: The function of testing independent actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output. Here is the function: def test_independent_ac_network() -> None: """ **Overview**: The function of testing independent actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output. """ # Set batch size, agent number, observation shape and action shape. batch_size = 4 agent_num = 3 obs_shape = 10 action_shape = 5 # Define a independent actor-critic network. network = IndependentActorCriticNetwork(agent_num, obs_shape, action_shape) # Generate a batch of local obs data for all agents from the standard normal distribution. local_obs = torch.randn(batch_size, agent_num, obs_shape) # Actor-critic network forward procedure, pass the local obs data to the network and get the output. result = network(local_obs) # Validate the shape of output. assert result['logit'].shape == (batch_size, agent_num, action_shape) assert result['value'].shape == (batch_size, agent_num, 1)
**Overview**: The function of testing independent actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output.
158,711
import torch import torch.nn as nn import treetensor.torch as ttorch class CTDEActorCriticNetwork(nn.Module): def __init__(self, agent_num: int, local_obs_shape: int, global_obs_shape: int, action_shape: int) -> None: """ **Overview**: The definition of centralized training decentralized execution (CTDE) actor-critic network in policy gradient algorithms for multi-agent scenarios. Each agent shares the same parameters in the network so that they can be processed as a batch in parallel. The input of value network is ``global_obs`` while the input of policy network is ``local_obs`` . Global information used in value network can provide more guidance for the training of policy network. Local information used in policy network can make the policy network more robust to the decentralized execution. """ # PyTorch necessary requirements for extending ``nn.Module`` . Our network should also subclass this class. super(CTDEActorCriticNetwork, self).__init__() # Define local and global encoder respectively. self.agent_num = agent_num self.local_encoder = nn.Sequential( nn.Linear(local_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) self.global_encoder = nn.Sequential( nn.Linear(global_obs_shape, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), ) # Define discrete action logit output network, just one-layer FC. self.policy_head = nn.Linear(64, action_shape) # Define scalar value output network. self.value_head = nn.Linear(64, 1) # delimiter def forward(self, local_obs: torch.Tensor, global_obs: torch.Tensor) -> ttorch.Tensor: """ **Overview**: The computation graph of CTDE actor-critic network, processing all agents' ``local_obs`` and ``global_obs`` and output corresponding policy logit and value in parallel. There are two possible designs for ``global_obs`` : The former is a shared global state for all agents, i.e. $$(B, S)$$. Tha latter is a kind of agent-specific global state, i.e. $$(B, A, S')$$. For more details, you can refer to <link https://di-engine-docs.readthedocs.io/zh_CN/latest/04_best_practice/marl_zh.html#id10 link>. """ # Call policy network with local obs and critic network with global obs respectively. policy = self.policy_head(self.local_encoder(local_obs)) value = self.value_head(self.global_encoder(global_obs)) return ttorch.as_tensor({ 'logit': policy, 'value': value, }) The provided code snippet includes necessary dependencies for implementing the `test_ctde_ac_network` function. Write a Python function `def test_ctde_ac_network() -> None` to solve the following problem: **Overview**: The function of testing CTDE actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output. Here is the function: def test_ctde_ac_network() -> None: """ **Overview**: The function of testing CTDE actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output. """ # Set batch size, agent number, observation shape and action shape. batch_size = 4 agent_num = 3 local_obs_shape = 10 global_obs_shape = 20 action_shape = 5 # Test case for the shared global obs. network = CTDEActorCriticNetwork(agent_num, local_obs_shape, global_obs_shape, action_shape) local_obs = torch.randn(batch_size, agent_num, local_obs_shape) global_obs = torch.randn(batch_size, global_obs_shape) result = network(local_obs, global_obs) assert result['logit'].shape == (batch_size, agent_num, action_shape) assert result['value'].shape == (batch_size, 1) # Test case for the agent-specific global obs. agent_specific_global_obs_shape = 25 network = CTDEActorCriticNetwork(agent_num, local_obs_shape, agent_specific_global_obs_shape, action_shape) local_obs = torch.randn(batch_size, agent_num, local_obs_shape) agent_specific_global_obs = torch.randn(batch_size, agent_num, agent_specific_global_obs_shape) result = network(local_obs, agent_specific_global_obs) assert result['logit'].shape == (batch_size, agent_num, action_shape) assert result['value'].shape == (batch_size, agent_num, 1)
**Overview**: The function of testing CTDE actor-critic network. Construct a network and pass a batch of data to it. Then validate the shape of different parts of output.
158,712
import numpy as np import torch.nn as nn import torch from torch.autograd import Function from copy import deepcopy class LinearFunction(Function): """ **LinearFunction 定义概述**: 这是一个线性的可导函数,等价于神经网络中的线性层(全连接层)。公式是: $$output = input \cdot weight^T + bias$$ """ def forward(ctx, input_, weight, bias): """ **forward 函数功能概述**: 线性函数的前向传播计算过程。 """ # 保存参数,用于后续反向传播。 ctx.save_for_backward(input_, weight) # 前向传播: $$output = input \cdot weight^T + bias$$ output = input_.mm(weight.t()) output += bias return output # delimiter def backward(ctx, grad_output): """ **backward 函数功能概述**: 线性函数的反向传播计算过程。 """ # 拿回在前向传播中保存的参数。 input_, weight = ctx.saved_tensors # 初始化梯度为 None。这是因为并不是所有的参数都需要被求导,如果某参数无需被求导,其梯度应当返回 None。 grad_input, grad_weight, grad_bias = None, None, None # 对输入 input 进行反向传播: $$ \nabla input = \nabla output \cdot weight $$ if ctx.needs_input_grad[0]: grad_input = grad_output.mm(weight) # 对权重 weight 进行反向传播: $$ \nabla weight = \nabla output^T \cdot input $$ if ctx.needs_input_grad[1]: grad_weight = grad_output.t().mm(input_) # 对权重 bias 进行反向传播: $$ \nabla bias = \sum \nabla output $$ if ctx.needs_input_grad[2]: grad_bias = grad_output.sum(0) return grad_input, grad_weight, grad_bias The provided code snippet includes necessary dependencies for implementing the `test_linear_function` function. Write a Python function `def test_linear_function()` to solve the following problem: **test_linear_function 函数功能概述**: 测试定义的线性函数,对前向传播结果,以及反向传播结果进行结果检查。 Here is the function: def test_linear_function(): """ **test_linear_function 函数功能概述**: 测试定义的线性函数,对前向传播结果,以及反向传播结果进行结果检查。 """ # 生成测试数据。 w = torch.randn(4, 3, requires_grad=True) x = torch.randn(1, 3, requires_grad=False) b = torch.randn(4, requires_grad=True) # 使用 PyTorch 内置方法完成线性计算。 o = torch.sum(x @ w.t() + b) # 使用 PyTorch 内置的自动求导完成反向传播。 o.backward() # 保留反向传播结果,用于后续结果检查。 w_grad, b_grad = deepcopy(w.grad), deepcopy(b.grad) w.grad, x.grad, b.grad = None, None, None # 使用自定义的线性函数进行前向传播。 linear_func = LinearFunction() o = torch.sum(linear_func.apply(x, w, b)) # 反向传播。 o.backward() # 对求导的结果进行正确性检查。 assert x.grad is None assert torch.sum(torch.abs(w_grad - w.grad)) < 1e-6 assert torch.sum(torch.abs(b_grad - b.grad)) < 1e-6
**test_linear_function 函数功能概述**: 测试定义的线性函数,对前向传播结果,以及反向传播结果进行结果检查。
158,713
import numpy as np import torch.nn as nn import torch from torch.autograd import Function from copy import deepcopy The provided code snippet includes necessary dependencies for implementing the `test_auto_grad` function. Write a Python function `def test_auto_grad()` to solve the following problem: **test_auto_grad 函数功能概述**: 测试自动求导的机制,对比用 Numpy 的手写求导与 PyTorch 的自动求导结果。 Here is the function: def test_auto_grad(): """ **test_auto_grad 函数功能概述**: 测试自动求导的机制,对比用 Numpy 的手写求导与 PyTorch 的自动求导结果。 """ # 规定测试数据的格式。 B, D = 3, 4 # 生成 Numpy 版本的测试数据。 x = np.random.randn(B, D) y = np.random.randn(B, D) z = np.random.randn(B, D) # Numpy 版本的前向传播。 a = x * y b = a + z c = np.sum(b) # Numpy 版本的反向传播。 grad_c = 1.0 grad_b = grad_c * np.ones((B, D)) grad_a = grad_b.copy() grad_z = grad_b.copy() grad_x = grad_a * y grad_y = grad_a * x # 将 Numpy 版本的测试数据转化为 PyTorch 版本。 x = nn.Parameter(torch.from_numpy(x)).requires_grad_(True) y = nn.Parameter(torch.from_numpy(y)).requires_grad_(True) z = nn.Parameter(torch.from_numpy(z)).requires_grad_(True) # PyTorch 版本的前向传播。 a = x * y b = a + z c = torch.sum(b) # PyTorch 版本的反向传播。 c.backward() # 检查求导的结果是否一致。 assert torch.sum(torch.abs(torch.from_numpy(grad_x) - x.grad)) < 1e-6 assert torch.sum(torch.abs(torch.from_numpy(grad_y) - y.grad)) < 1e-6 assert torch.sum(torch.abs(torch.from_numpy(grad_z) - z.grad)) < 1e-6
**test_auto_grad 函数功能概述**: 测试自动求导的机制,对比用 Numpy 的手写求导与 PyTorch 的自动求导结果。
158,714
import numpy as np import torch.nn as nn import torch from torch.autograd import Function from copy import deepcopy class LinearFunction(Function): """ **Overview**: Implementation of linear (Fully Connected) layer. """ def forward(ctx, input_, weight, bias): """ **Overview**: Forward implementation of linear layer. """ # Save parameters for backward. ctx.save_for_backward(input_, weight) # Forward calculation: $$output = input \cdot weight^T + bias$$ output = input_.mm(weight.t()) output += bias return output # delimiter def backward(ctx, grad_output): """ **Overview**: Backward implementation of linear layer. """ # Get saved parameters back. input_, weight = ctx.saved_tensors # Initialize gradients to be None. grad_input, grad_weight, grad_bias = None, None, None # Calculate gradient for input: $$ \nabla input = \nabla output \cdot weight $$ if ctx.needs_input_grad[0]: grad_input = grad_output.mm(weight) # Calculate gradient for weight: $$ \nabla weight = \nabla output^T \cdot input $$ if ctx.needs_input_grad[1]: grad_weight = grad_output.t().mm(input_) # Calculate gradient for bias: $$ \nabla bias = \sum \nabla output $$ if ctx.needs_input_grad[2]: grad_bias = grad_output.sum(0) return grad_input, grad_weight, grad_bias The provided code snippet includes necessary dependencies for implementing the `test_linear_function` function. Write a Python function `def test_linear_function()` to solve the following problem: **Overview**: Test linear function for both forward and backward operation. Here is the function: def test_linear_function(): """ **Overview**: Test linear function for both forward and backward operation. """ # Generate data. w = torch.randn(4, 3, requires_grad=True) x = torch.randn(1, 3, requires_grad=False) b = torch.randn(4, requires_grad=True) # Forward computation graph. o = torch.sum(x @ w.t() + b) # Backward using auto-grad mechanism. o.backward() # Save gradients for checking correctness. w_grad, b_grad = deepcopy(w.grad), deepcopy(b.grad) w.grad, x.grad, b.grad = None, None, None # Forward using our defined LinearFunction. linear_func = LinearFunction() o = torch.sum(linear_func.apply(x, w, b)) # Backward. o.backward() # Check whether the results are correct. assert x.grad is None assert torch.sum(torch.abs(w_grad - w.grad)) < 1e-6 assert torch.sum(torch.abs(b_grad - b.grad)) < 1e-6
**Overview**: Test linear function for both forward and backward operation.
158,715
import numpy as np import torch.nn as nn import torch from torch.autograd import Function from copy import deepcopy The provided code snippet includes necessary dependencies for implementing the `test_auto_grad` function. Write a Python function `def test_auto_grad()` to solve the following problem: **Overview**: Test auto-grad mechanism, compare numpy hand-crafed version and PyTorch auto-grad version. Here is the function: def test_auto_grad(): """ **Overview**: Test auto-grad mechanism, compare numpy hand-crafed version and PyTorch auto-grad version. """ # Generate data B, D = 3, 4 # Numpy version. x = np.random.randn(B, D) y = np.random.randn(B, D) z = np.random.randn(B, D) # Forward. a = x * y b = a + z c = np.sum(b) # Backward. grad_c = 1.0 grad_b = grad_c * np.ones((B, D)) grad_a = grad_b.copy() grad_z = grad_b.copy() grad_x = grad_a * y grad_y = grad_a * x # PyTorch version. x = nn.Parameter(torch.from_numpy(x)).requires_grad_(True) y = nn.Parameter(torch.from_numpy(y)).requires_grad_(True) z = nn.Parameter(torch.from_numpy(z)).requires_grad_(True) # Forward. a = x * y b = a + z c = torch.sum(b) # Backward. c.backward() # Check whether the results are correct. assert torch.sum(torch.abs(torch.from_numpy(grad_x) - x.grad)) < 1e-6 assert torch.sum(torch.abs(torch.from_numpy(grad_y) - y.grad)) < 1e-6 assert torch.sum(torch.abs(torch.from_numpy(grad_z) - z.grad)) < 1e-6
**Overview**: Test auto-grad mechanism, compare numpy hand-crafed version and PyTorch auto-grad version.
158,716
import cv2 import gym import numpy as np import gym_super_mario_bros from nes_py.wrappers import JoypadSpace from ding.envs import DingEnvWrapper from ding.envs.env_wrappers import MaxAndSkipWrapper, WarpFrameWrapper, ScaledFloatFrameWrapper, FrameStackWrapper, \ EvalEpisodeReturnEnv def wrapped_mario_env(): """ **Overview**: Wrap mario environment with various wrappers. """ # Original environment declaration. env = gym_super_mario_bros.make("SuperMarioBros-1-1-v0") return DingEnvWrapper( # Restrict action space to 2 discrete action: right and jump (A). JoypadSpace(env, [["right"], ["right", "A"]]), cfg={ 'env_wrapper': [ # Return the max value of states in adjacent 4 frames. This works like a max-pooling in temporal dimension. lambda env: MaxAndSkipWrapper(env, skip=4), # Resize (bilinear interpolation) the image size into 84 x 84 and convert RGB to GREY. lambda env: WarpFrameWrapper(env, size=84), # Normalize the state value into [0, 1]. $$scaled\_x = \frac {x - \min(x)} {\max(x) - \min (x)} $$ lambda env: ScaledFloatFrameWrapper(env), # Stack adjacent 4 frames together to be one state. lambda env: FrameStackWrapper(env, n_frames=4), # Calculate episode return for evaluation. lambda env: EvalEpisodeReturnEnv(env), ] } ) def wrapped_mario_env_optical(): """ **Overview**: Wrap mario environment with optical flow wrapper. """ # Original environment declaration. env = gym_super_mario_bros.make("SuperMarioBros-1-1-v0") return DingEnvWrapper( # Restrict action space to 2 discrete action: right and jump (A). JoypadSpace(env, [["right"], ["right", "A"]]), cfg={ 'env_wrapper': [ # Return the max value of states in adjacent 4 frames. This works like a max-pooling in temporal dimension. lambda env: MaxAndSkipWrapper(env, skip=4), # Resize (bilinear interpolation) the image size into 84 x 84 and convert RGB to GREY. lambda env: WarpFrameWrapper(env, size=84), # Add optical flow information. lambda env: OpticalFlowWrapper(env), # Normalize the state value into [0, 1]. $$scaled\_x = \frac {x - \min(x)} {\max(x) - \min (x)} $$ lambda env: ScaledFloatFrameWrapper(env), # Calculate episode return for evaluation. lambda env: EvalEpisodeReturnEnv(env), ] } ) The provided code snippet includes necessary dependencies for implementing the `test_wrapper` function. Write a Python function `def test_wrapper()` to solve the following problem: **Overview**: Test two types wrappers and check output obs shape. Here is the function: def test_wrapper(): """ **Overview**: Test two types wrappers and check output obs shape. """ # Test environment with stacked frames. env = wrapped_mario_env() obs = env.reset() assert obs.shape == (4, 84, 84) # Test environment with optical flow. env = wrapped_mario_env_optical() obs = env.reset() assert obs.shape == (3, 84, 84)
**Overview**: Test two types wrappers and check output obs shape.
158,717
import torch import torch.nn as nn def one_hot(val: torch.LongTensor, num: int) -> torch.FloatTensor: """ **Overview**: Convert a ``torch.LongTensor`` to one hot encoding with scatter API. This implementation can be slightly faster than ``torch.nn.functional.one_hot`` . """ # Remember original shape of ``val`` . old_shape = val.shape # Reshape ``val`` into 2D tensor. val_reshape = val.reshape(-1, 1) # Initialize return tensor with float32 dtype and the same device as val. ret = torch.zeros(val_reshape.shape[0], num, device=val.device) # Fill value 1 into tensor ``ret`` , according to the index stored in ``val_reshape`` . It is an inplace operation. ret.scatter_(1, val_reshape, 1) # Return the reshaped result with the same prefix shape as original shape of val. return ret.reshape(*old_shape, num) def get_one_hot_encoding(num: int): """ **Overview**: Implementation of one hot encoding with nn.Embedding API. """ # Use the identity matrix as weight tensor. # Use freezed embedding as fixed one-hot transformation. return nn.Embedding.from_pretrained(torch.eye(num), freeze=True, padding_idx=None) def get_binary_encoding(bit_num: int): """ **Overview**: Implementation of binary encoding with nn.Embedding API. """ # Generate a matrix with shape $$2^{B} \times B $$ where B is the bit_num. # Each row with index n contains the binary representation of n. location_embedding = [] for n in range(2 ** bit_num): s = '0' * (bit_num - len(bin(n)[2:])) + bin(n)[2:] location_embedding.append(list(int(i) for i in s)) mat = torch.FloatTensor(location_embedding) # Use the generated result as transformation.. return torch.nn.Embedding.from_pretrained(mat, freeze=True, padding_idx=None) The provided code snippet includes necessary dependencies for implementing the `test_encoding` function. Write a Python function `def test_encoding()` to solve the following problem: **Overview**: Test different encoding methods. Here is the function: def test_encoding(): """ **Overview**: Test different encoding methods. """ # Test one-hot encoding with nn.Embedding and scatter, compare two float32 dtype tensor. x = torch.LongTensor([9, 0, 1, 2, 1, 3, 5]) one_hot_enc = get_one_hot_encoding(10) y = one_hot_enc(x) y_ = one_hot(x, num=10) assert torch.sum(torch.abs(y - y_)) < 1e-6 # Test binary encoding, compare two int64 dtype tensor. bin_enc = get_binary_encoding(2) x = torch.arange(4) y = bin_enc(x) ground_truth = torch.LongTensor([[0, 0], [0, 1], [1, 0], [1, 1]]) assert torch.eq(y, ground_truth).all()
**Overview**: Test different encoding methods.