instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Generate consistent docstrings |
import math
import Box2D
import numpy as np
from gym.error import DependencyNotInstalled
try:
from Box2D.b2 import fixtureDef, polygonShape, revoluteJointDef
except ImportError:
raise DependencyNotInstalled("box2D is not installed, run `pip install gym[box2d]`")
SIZE = 0.02
ENGINE_POWER = 100000000 * SIZE... | --- +++ @@ -1,3 +1,11 @@+"""
+Top-down car dynamics simulation.
+
+Some ideas are taken from this great tutorial http://www.iforce2d.net/b2dtut/top-down-car by Chris Campbell.
+This simulation is a bit more detailed, with wheels rotation.
+
+Created by Oleg Klimov
+"""
import math
@@ -128,6 +136,11 @@ self... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/box2d/car_dynamics.py |
Add clean documentation to messy code | __credits__ = ["Andrea PIERRÉ"]
import math
import warnings
from typing import TYPE_CHECKING, Optional
import numpy as np
import gym
from gym import error, spaces
from gym.error import DependencyNotInstalled
from gym.utils import EzPickle, colorize
from gym.utils.step_api_compatibility import step_api_compatibility
... | --- +++ @@ -73,6 +73,115 @@
class LunarLander(gym.Env, EzPickle):
+ """
+ ### Description
+ This environment is a classic rocket trajectory optimization problem.
+ According to Pontryagin's maximum principle, it is optimal to fire the
+ engine at full throttle or turn it off. This is the reason why t... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/box2d/lunar_lander.py |
Provide clean and structured docstrings | from typing import Any, List, Optional, Tuple, Union
import numpy as np
import gym
from gym.vector.utils.spaces import batch_space
__all__ = ["VectorEnv"]
class VectorEnv(gym.Env):
def __init__(
self,
num_envs: int,
observation_space: gym.Space,
action_space: gym.Space,
):
... | --- +++ @@ -1,3 +1,4 @@+"""Base class for vectorized environments."""
from typing import Any, List, Optional, Tuple, Union
import numpy as np
@@ -9,6 +10,17 @@
class VectorEnv(gym.Env):
+ """Base class for vectorized environments. Runs multiple independent copies of the same environment in parallel.
+
+ T... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/vector/vector_env.py |
Help me document legacy Python code | import numpy as np
import gym
from gym.spaces import Box
try:
import cv2
except ImportError:
cv2 = None
class AtariPreprocessing(gym.Wrapper):
def __init__(
self,
env: gym.Env,
noop_max: int = 30,
frame_skip: int = 4,
screen_size: int = 84,
terminal_on_li... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of Atari 2600 Preprocessing following the guidelines of Machado et al., 2018."""
import numpy as np
import gym
@@ -10,6 +11,21 @@
class AtariPreprocessing(gym.Wrapper):
+ """Atari 2600 preprocessing wrapper.
+
+ This class follows the guidelines in Machado et al. ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/atari_preprocessing.py |
Add return value explanations in docstrings | from copy import deepcopy
from typing import Any, Callable, Iterator, List, Optional, Sequence, Union
import numpy as np
from gym import Env
from gym.spaces import Space
from gym.vector.utils import concatenate, create_empty_array, iterate
from gym.vector.vector_env import VectorEnv
__all__ = ["SyncVectorEnv"]
cla... | --- +++ @@ -1,3 +1,4 @@+"""A synchronous vector environment."""
from copy import deepcopy
from typing import Any, Callable, Iterator, List, Optional, Sequence, Union
@@ -12,6 +13,19 @@
class SyncVectorEnv(VectorEnv):
+ """Vectorized environment that serially runs multiple environments.
+
+ Example::
+
+ ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/vector/sync_vector_env.py |
Auto-generate documentation strings for this file | from collections import OrderedDict
from collections.abc import Mapping, Sequence
from typing import Any
from typing import Dict as TypingDict
from typing import List, Optional
from typing import Sequence as TypingSequence
from typing import Tuple, Union
import numpy as np
from gym.spaces.space import Space
class D... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of a space that represents the cartesian product of other spaces as a dictionary."""
from collections import OrderedDict
from collections.abc import Mapping, Sequence
from typing import Any
@@ -12,6 +13,43 @@
class Dict(Space[TypingDict[str, Space]], Mapping):
+ """A ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/dict.py |
Can you add docstrings to this Python file? | from collections import deque
from typing import Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import gym.error
from gym import Env, logger
from gym.core import ActType, ObsType
from gym.error import DependencyNotInstalled
from gym.logger import deprecation
try:
import pygame
from pygame im... | --- +++ @@ -1,3 +1,4 @@+"""Utilities of visualising an environment."""
from collections import deque
from typing import Callable, Dict, List, Optional, Tuple, Union
@@ -30,9 +31,11 @@
class MissingKeysToAction(Exception):
+ """Raised when the environment does not have a default ``keys_to_action`` mapping."""... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/utils/play.py |
Fill in missing docstrings in my code | from collections import deque
from typing import Union
import numpy as np
import gym
from gym.error import DependencyNotInstalled
from gym.spaces import Box
class LazyFrames:
__slots__ = ("frame_shape", "dtype", "shape", "lz4_compress", "_frames")
def __init__(self, frames: list, lz4_compress: bool = Fals... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper that stacks frames."""
from collections import deque
from typing import Union
@@ -9,10 +10,26 @@
class LazyFrames:
+ """Ensures common frames are only stored once to optimize memory use.
+
+ To further reduce the memory use, it is optionally to turn on lz4 to compress th... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/frame_stack.py |
Write reusable docstrings |
import math
from typing import Optional
import numpy as np
import gym
from gym import spaces
from gym.envs.classic_control import utils
from gym.error import DependencyNotInstalled
class Continuous_MountainCarEnv(gym.Env):
metadata = {
"render_modes": ["human", "rgb_array"],
"render_fps": 30,
... | --- +++ @@ -1,3 +1,17 @@+"""
+@author: Olivier Sigaud
+
+A merge between two sources:
+
+* Adaptation of the MountainCar Environment from the "FAReinforcement" library
+of Jose Antonio Martin H. (version 1.0), adapted by 'Tom Schaul, tom@idsia.ch'
+and then modified by Arnaud de Broissia
+
+* the gym MountainCar envir... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/classic_control/continuous_mountain_car.py |
Create Google-style docstrings for my code | from collections.abc import Sequence as CollectionSequence
from typing import Iterable, Optional
from typing import Sequence as TypingSequence
from typing import Tuple as TypingTuple
from typing import Union
import numpy as np
from gym.spaces.space import Space
class Tuple(Space[tuple], CollectionSequence):
de... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of a space that represents the cartesian product of other spaces."""
from collections.abc import Sequence as CollectionSequence
from typing import Iterable, Optional
from typing import Sequence as TypingSequence
@@ -10,12 +11,31 @@
class Tuple(Space[tuple], CollectionSeq... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/tuple.py |
Provide docstrings following PEP 257 | from typing import Any, Dict, FrozenSet, Optional, Set, Tuple, Union
import numpy as np
from gym.spaces.space import Space
alphanumeric: FrozenSet[str] = frozenset(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
class Text(Space[str]):
def __init__(
self,
max_length: in... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of a space that represents textual strings."""
from typing import Any, Dict, FrozenSet, Optional, Set, Tuple, Union
import numpy as np
@@ -10,6 +11,17 @@
class Text(Space[str]):
+ r"""A space representing a string comprised of characters from a given charset.
+
+ ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/text.py |
Add docstrings to existing functions | from contextlib import closing
from io import StringIO
from os import path
from typing import Optional
import numpy as np
from gym import Env, logger, spaces, utils
from gym.envs.toy_text.utils import categorical_sample
from gym.error import DependencyNotInstalled
MAP = [
"+---------+",
"|R: | : :G|",
"|... | --- +++ @@ -22,6 +22,103 @@
class TaxiEnv(Env):
+ """
+
+ The Taxi Problem
+ from "Hierarchical Reinforcement Learning with the MAXQ Value Function Decomposition"
+ by Tom Dietterich
+
+ ### Description
+ There are four designated locations in the grid world indicated by R(ed),
+ G(reen), Y(ell... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/toy_text/taxi.py |
Create documentation for each function signature | import math
from typing import Optional
import numpy as np
import gym
from gym import spaces
from gym.envs.classic_control import utils
from gym.error import DependencyNotInstalled
class MountainCarEnv(gym.Env):
metadata = {
"render_modes": ["human", "rgb_array"],
"render_fps": 30,
}
d... | --- +++ @@ -1,3 +1,7 @@+"""
+http://incompleteideas.net/MountainCar/MountainCar1.cp
+permalink: https://perma.cc/6Z2N-PFWC
+"""
import math
from typing import Optional
@@ -10,6 +14,86 @@
class MountainCarEnv(gym.Env):
+ """
+ ### Description
+
+ The Mountain Car MDP is a deterministic MDP that consists... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/classic_control/mountain_car.py |
Create docstrings for all classes and functions | import operator as op
from collections import OrderedDict
from functools import reduce, singledispatch
from typing import Dict as TypingDict
from typing import TypeVar, Union, cast
import numpy as np
from gym.spaces import (
Box,
Dict,
Discrete,
Graph,
GraphInstance,
MultiBinary,
MultiDisc... | --- +++ @@ -1,3 +1,8 @@+"""Implementation of utility functions that can be applied to spaces.
+
+These functions mostly take care of flattening and unflattening elements of spaces
+ to facilitate their usage in learning code.
+"""
import operator as op
from collections import OrderedDict
from functools import reduce... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/utils.py |
Generate helpful docstrings for debugging | import gym
from gym.core import ActType
from gym.utils.passive_env_checker import (
check_action_space,
check_observation_space,
env_render_passive_checker,
env_reset_passive_checker,
env_step_passive_checker,
)
class PassiveEnvChecker(gym.Wrapper):
def __init__(self, env):
super().__... | --- +++ @@ -1,3 +1,4 @@+"""A passive environment checker wrapper for an environment's observation and action space along with the reset, step and render functions."""
import gym
from gym.core import ActType
from gym.utils.passive_env_checker import (
@@ -10,8 +11,10 @@
class PassiveEnvChecker(gym.Wrapper):
+ ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/env_checker.py |
Please document this code using docstrings | import gym
class AutoResetWrapper(gym.Wrapper):
def __init__(self, env: gym.Env):
super().__init__(env)
def step(self, action):
obs, reward, terminated, truncated, info = self.env.step(action)
if terminated or truncated:
new_obs, new_info = self.env.reset()
a... | --- +++ @@ -1,12 +1,46 @@+"""Wrapper that autoreset environments when `terminated=True` or `truncated=True`."""
import gym
class AutoResetWrapper(gym.Wrapper):
+ """A class for providing an automatic reset functionality for gym environments when calling :meth:`self.step`.
+
+ When calling step causes :meth:... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/autoreset.py |
Add clean documentation to messy code | import sys
import warnings
from typing import Optional, Type
from gym.utils import colorize
DEBUG = 10
INFO = 20
WARN = 30
ERROR = 40
DISABLED = 50
min_level = 30
# Ensure DeprecationWarning to be displayed (#2685, #3059)
warnings.filterwarnings("once", "", DeprecationWarning, module=r"^gym\.")
def set_level(lev... | --- +++ @@ -1,3 +1,4 @@+"""Set of functions for logging messages."""
import sys
import warnings
from typing import Optional, Type
@@ -18,16 +19,19 @@
def set_level(level: int):
+ """Set logging threshold on current logger."""
global min_level
min_level = level
def debug(msg: str, *args: object)... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/logger.py |
Add detailed docstrings explaining each function | import gym
import gym.spaces as spaces
class FlattenObservation(gym.ObservationWrapper):
def __init__(self, env: gym.Env):
super().__init__(env)
self.observation_space = spaces.flatten_space(env.observation_space)
def observation(self, observation):
return spaces.flatten(self.env.obs... | --- +++ @@ -1,12 +1,40 @@+"""Wrapper for flattening observations of an environment."""
import gym
import gym.spaces as spaces
class FlattenObservation(gym.ObservationWrapper):
+ """Observation wrapper that flattens the observation.
+
+ Example:
+ >>> import gym
+ >>> env = gym.make('CarRacing... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/flatten_observation.py |
Create documentation strings for testing functions | from typing import Iterable, List, Optional, Union
import gym
from gym.vector.async_vector_env import AsyncVectorEnv
from gym.vector.sync_vector_env import SyncVectorEnv
from gym.vector.vector_env import VectorEnv, VectorEnvWrapper
__all__ = ["AsyncVectorEnv", "SyncVectorEnv", "VectorEnv", "VectorEnvWrapper", "make"]... | --- +++ @@ -1,3 +1,4 @@+"""Module for vector environments."""
from typing import Iterable, List, Optional, Union
import gym
@@ -16,8 +17,33 @@ disable_env_checker: Optional[bool] = None,
**kwargs,
) -> VectorEnv:
+ """Create a vectorized environment from multiple copies of an environment, from its id.
... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/vector/__init__.py |
Provide clean and structured docstrings | import inspect
from functools import partial
from typing import Callable
import numpy as np
from gym import Space, error, logger, spaces
def _check_box_observation_space(observation_space: spaces.Box):
# Check if the box is an image
if len(observation_space.shape) == 3:
if observation_space.dtype !=... | --- +++ @@ -1,3 +1,4 @@+"""A set of functions for passively checking environment implementations."""
import inspect
from functools import partial
from typing import Callable
@@ -8,6 +9,11 @@
def _check_box_observation_space(observation_space: spaces.Box):
+ """Checks that a :class:`Box` observation space is d... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/utils/passive_env_checker.py |
Add docstrings for internal functions | import warnings
class Error(Exception):
# Local errors
class Unregistered(Error):
class UnregisteredEnv(Unregistered):
class NamespaceNotFound(UnregisteredEnv):
class NameNotFound(UnregisteredEnv):
class VersionNotFound(UnregisteredEnv):
class UnregisteredBenchmark(Unregistered):
class DeprecatedEnv(E... | --- +++ @@ -1,58 +1,75 @@+"""Set of Error classes for gym."""
import warnings
class Error(Exception):
+ """Error superclass."""
# Local errors
class Unregistered(Error):
+ """Raised when the user requests an item from the registry that does not actually exist."""
class UnregisteredEnv(Unregis... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/error.py |
Add professional docstrings to my codebase |
from typing import Optional, SupportsFloat, Tuple
def verify_number_and_cast(x: SupportsFloat) -> float:
try:
x = float(x)
except (ValueError, TypeError):
raise ValueError(f"An option ({x}) could not be converted to a float.")
return x
def maybe_parse_reset_bounds(
options: Optional... | --- +++ @@ -1,8 +1,12 @@+"""
+Utility functions used for classic control environments.
+"""
from typing import Optional, SupportsFloat, Tuple
def verify_number_and_cast(x: SupportsFloat) -> float:
+ """Verify parameter is a single number and cast to a float."""
try:
x = float(x)
except (Va... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/classic_control/utils.py |
Create docstrings for each class method | from typing import Optional
import numpy as np
from numpy import cos, pi, sin
from gym import core, logger, spaces
from gym.error import DependencyNotInstalled
__copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy"
__credits__ = [
"Alborz Geramifard",
"Robert H. Klein",
"Christoph Dann",
"Wil... | --- +++ @@ -1,3 +1,4 @@+"""classic Acrobot task"""
from typing import Optional
import numpy as np
@@ -23,6 +24,116 @@
class AcrobotEnv(core.Env):
+ """
+ ### Description
+
+ The Acrobot environment is based on Sutton's work in
+ ["Generalization in Reinforcement Learning: Successful Examples Using S... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/classic_control/acrobot.py |
Expand my code with proper documentation strings | import numpy as np
import gym
from gym.spaces import Box
class GrayScaleObservation(gym.ObservationWrapper):
def __init__(self, env: gym.Env, keep_dim: bool = False):
super().__init__(env)
self.keep_dim = keep_dim
assert (
isinstance(self.observation_space, Box)
... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper that converts a color observation to grayscale."""
import numpy as np
import gym
@@ -5,8 +6,28 @@
class GrayScaleObservation(gym.ObservationWrapper):
+ """Convert the image observation from RGB to gray scale.
+
+ Example:
+ >>> env = gym.make('CarRacing-v1')
+ ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/gray_scale_observation.py |
Add docstrings for internal functions | from collections import OrderedDict
from copy import deepcopy
from functools import singledispatch
from typing import Iterator
import numpy as np
from gym.error import CustomSpaceError
from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple
BaseGymSpaces = (Box, Discrete, MultiDiscrete, ... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for gym spaces: batch space and iterator."""
from collections import OrderedDict
from copy import deepcopy
from functools import singledispatch
@@ -15,6 +16,28 @@
@singledispatch
def batch_space(space: Space, n: int = 1) -> Space:
+ """Create a (batched) space, cont... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/vector/utils/spaces.py |
Add docstrings to clarify complex logic | from collections.abc import Sequence as CollectionSequence
from typing import Any, List, Optional, Tuple, Union
import numpy as np
import gym
from gym.spaces.space import Space
class Sequence(Space[Tuple]):
def __init__(
self,
space: Space,
seed: Optional[Union[int, np.random.Generator]... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of a space that represents finite-length sequences."""
from collections.abc import Sequence as CollectionSequence
from typing import Any, List, Optional, Tuple, Union
@@ -8,12 +9,30 @@
class Sequence(Space[Tuple]):
+ r"""This space represent sets of finite-length seq... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/sequence.py |
Generate consistent documentation across files | from typing import Optional, Sequence, Tuple, Union
import numpy as np
from gym.spaces.space import Space
class MultiBinary(Space[np.ndarray]):
def __init__(
self,
n: Union[np.ndarray, Sequence[int], int],
seed: Optional[Union[int, np.random.Generator]] = None,
):
if isinsta... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of a space that consists of binary np.ndarrays of a fixed shape."""
from typing import Optional, Sequence, Tuple, Union
import numpy as np
@@ -6,12 +7,34 @@
class MultiBinary(Space[np.ndarray]):
+ """An n-shape binary space.
+
+ Elements of this space are binary a... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/multi_binary.py |
Add docstrings that explain logic | import contextlib
import copy
import difflib
import importlib
import importlib.util
import re
import sys
import warnings
from dataclasses import dataclass, field
from typing import (
Callable,
Dict,
List,
Optional,
Sequence,
SupportsFloat,
Tuple,
Union,
overload,
)
import numpy as n... | --- +++ @@ -49,6 +49,14 @@
def load(name: str) -> callable:
+ """Loads an environment with name and returns an environment creation function
+
+ Args:
+ name: The environment name
+
+ Returns:
+ Calls the environment constructor
+ """
mod_name, attr_name = name.split(":")
mod = i... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/registration.py |
Write docstrings for backend logic | import collections
import os
import time
from threading import Lock
import glfw
import imageio
import mujoco
import numpy as np
def _import_egl(width, height):
from mujoco.egl import GLContext
return GLContext(width, height)
def _import_glfw(width, height):
from mujoco.glfw import GLContext
retur... | --- +++ @@ -37,6 +37,7 @@
class RenderContext:
+ """Render context superclass for offscreen and window rendering."""
def __init__(self, model, data, offscreen=True):
@@ -156,6 +157,7 @@ self.cam.distance = self.model.stat.extent
def add_overlay(self, gridpos: int, text1: str, text2: str):... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/mujoco/mujoco_rendering.py |
Create simple docstrings for beginners | from typing import Iterable, List, Optional, Sequence, Tuple, Union
import numpy as np
from gym import logger
from gym.spaces.discrete import Discrete
from gym.spaces.space import Space
class MultiDiscrete(Space[np.ndarray]):
def __init__(
self,
nvec: Union[np.ndarray, list],
dtype=np.i... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of a space that represents the cartesian product of `Discrete` spaces."""
from typing import Iterable, List, Optional, Sequence, Tuple, Union
import numpy as np
@@ -8,6 +9,31 @@
class MultiDiscrete(Space[np.ndarray]):
+ """This represents the cartesian product of arb... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/multi_discrete.py |
Generate docstrings for each module | import os
from typing import Callable, Optional
import gym
from gym import logger
try:
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
except ImportError:
raise gym.error.DependencyNotInstalled(
"MoviePy is not installed, run `pip install moviepy`"
)
def capped_cubic_video_sched... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions to save rendering videos."""
import os
from typing import Callable, Optional
@@ -13,6 +14,16 @@
def capped_cubic_video_schedule(episode_id: int) -> bool:
+ """The default episode trigger.
+
+ This function will trigger recordings at the episode indices 0, 1, 4,... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/utils/save_video.py |
Generate docstrings for each module | import numpy as np
import gym
from gym import ActionWrapper
from gym.spaces import Box
class ClipAction(ActionWrapper):
def __init__(self, env: gym.Env):
assert isinstance(env.action_space, Box)
super().__init__(env)
def action(self, action):
return np.clip(action, self.action_space... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper for clipping actions within a valid bound."""
import numpy as np
import gym
@@ -6,10 +7,34 @@
class ClipAction(ActionWrapper):
+ """Clip the continuous action within the valid :class:`Box` observation space bound.
+
+ Example:
+ >>> import gym
+ >>> env = g... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/clip_action.py |
Please document this code using docstrings | from typing import Optional, Union
import numpy as np
from gym.spaces.space import Space
class Discrete(Space[int]):
def __init__(
self,
n: int,
seed: Optional[Union[int, np.random.Generator]] = None,
start: int = 0,
):
assert isinstance(n, (int, np.integer))
... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of a space consisting of finitely many elements."""
from typing import Optional, Union
import numpy as np
@@ -6,6 +7,15 @@
class Discrete(Space[int]):
+ r"""A space consisting of finitely many elements.
+
+ This class represents a finite subset of integers, more s... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/discrete.py |
Create docstrings for reusable components | import numpy as np
import gym
from gym.error import DependencyNotInstalled
class HumanRendering(gym.Wrapper):
def __init__(self, env):
super().__init__(env)
assert env.render_mode in [
"rgb_array",
"rgb_array_list",
], f"Expected env.render_mode to be one of 'rgb_... | --- +++ @@ -1,3 +1,4 @@+"""A wrapper that adds human-renering functionality to an environment."""
import numpy as np
import gym
@@ -5,8 +6,45 @@
class HumanRendering(gym.Wrapper):
+ """Performs human rendering for an environment that only supports "rgb_array"rendering.
+
+ This wrapper is particularly use... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/human_rendering.py |
Generate NumPy-style docstrings |
from typing import (
Any,
Generic,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
)
import numpy as np
from gym.utils import seeding
T_cov = TypeVar("T_cov", covariant=True)
class Space(Generic[T_cov]):
def __init__(
self,
... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of the `Space` metaclass."""
from typing import (
Any,
@@ -21,6 +22,30 @@
class Space(Generic[T_cov]):
+ """Superclass that is used to define observation and action spaces.
+
+ Spaces are crucially used in Gym to define the format of valid actions and observat... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/space.py |
Create structured documentation for my script | from typing import Any, Optional, Tuple
import numpy as np
from gym import error
def np_random(seed: Optional[int] = None) -> Tuple[np.random.Generator, Any]:
if seed is not None and not (isinstance(seed, int) and 0 <= seed):
raise error.Error(f"Seed must be a non-negative integer or omitted, not {seed}... | --- +++ @@ -1,3 +1,4 @@+"""Set of random number generator functions: seeding, generator, hashing seeds."""
from typing import Any, Optional, Tuple
import numpy as np
@@ -6,6 +7,17 @@
def np_random(seed: Optional[int] = None) -> Tuple[np.random.Generator, Any]:
+ """Generates a random number generator from th... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/utils/seeding.py |
Add docstrings to incomplete code | import multiprocessing as mp
from collections import OrderedDict
from ctypes import c_bool
from functools import singledispatch
from typing import Union
import numpy as np
from gym.error import CustomSpaceError
from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple
__all__ = ["create_sh... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for vector environments to share memory between processes."""
import multiprocessing as mp
from collections import OrderedDict
from ctypes import c_bool
@@ -16,6 +17,21 @@ def create_shared_memory(
space: Space, n: int = 1, ctx=mp
) -> Union[dict, tuple, mp.Array]:
... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/vector/utils/shared_memory.py |
Document helper functions with docstrings | from contextlib import closing
from io import StringIO
from os import path
from typing import List, Optional
import numpy as np
from gym import Env, logger, spaces, utils
from gym.envs.toy_text.utils import categorical_sample
from gym.error import DependencyNotInstalled
LEFT = 0
DOWN = 1
RIGHT = 2
UP = 3
MAPS = {
... | --- +++ @@ -51,6 +51,15 @@
def generate_random_map(size: int = 8, p: float = 0.8) -> List[str]:
+ """Generates a random valid map (one that has a path from start to goal)
+
+ Args:
+ size: size of each side of the grid
+ p: probability that a tile is frozen
+
+ Returns:
+ A random vali... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/toy_text/frozen_lake.py |
Provide clean and structured docstrings | import sys
from typing import Any, Dict, Optional, Tuple
import gym
from gym.core import ObsType
from gym.utils.step_api_compatibility import convert_to_terminated_truncated_step_api
if sys.version_info >= (3, 8):
from typing import Protocol, runtime_checkable
elif sys.version_info >= (3, 7):
from typing_exte... | --- +++ @@ -1,3 +1,4 @@+"""A compatibility wrapper converting an old-style environment into a valid environment."""
import sys
from typing import Any, Dict, Optional, Tuple
@@ -16,29 +17,52 @@
@runtime_checkable
class LegacyEnv(Protocol):
+ """A protocol for environments using the old step API."""
obse... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/compatibility.py |
Can you add docstrings to this Python file? | from typing import Tuple, Union
import numpy as np
from gym.core import ObsType
DoneStepType = Tuple[
Union[ObsType, np.ndarray],
Union[float, np.ndarray],
Union[bool, np.ndarray],
Union[dict, list],
]
TerminatedTruncatedStepType = Tuple[
Union[ObsType, np.ndarray],
Union[float, np.ndarray],... | --- +++ @@ -1,3 +1,4 @@+"""Contains methods for step compatibility, from old-to-new and new-to-old API."""
from typing import Tuple, Union
import numpy as np
@@ -23,6 +24,12 @@ def convert_to_terminated_truncated_step_api(
step_returns: Union[DoneStepType, TerminatedTruncatedStepType], is_vector_env=False
) -... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/utils/step_api_compatibility.py |
Generate docstrings with examples |
import inspect
from copy import deepcopy
import numpy as np
import gym
from gym import logger, spaces
from gym.utils.passive_env_checker import (
check_action_space,
check_observation_space,
env_render_passive_checker,
env_reset_passive_checker,
env_step_passive_checker,
)
def data_equivalence(... | --- +++ @@ -1,3 +1,18 @@+"""A set of functions for checking an environment details.
+
+This file is originally from the Stable Baselines3 repository hosted on GitHub
+(https://github.com/DLR-RM/stable-baselines3/)
+Original Author: Antonin Raffin
+
+It also uses some warnings/assertions from the PettingZoo repository h... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/utils/env_checker.py |
Add docstrings to clarify complex logic | import json
import os
import os.path
import tempfile
from typing import List, Optional
from gym import error, logger
class VideoRecorder:
def __init__(
self,
env,
path: Optional[str] = None,
metadata: Optional[dict] = None,
enabled: bool = True,
base_path: Optiona... | --- +++ @@ -1,3 +1,4 @@+"""A wrapper for video recording environments by rolling it out, frame by frame."""
import json
import os
import os.path
@@ -8,6 +9,13 @@
class VideoRecorder:
+ """VideoRecorder renders a nice movie of a rollout, frame by frame.
+
+ It comes with an ``enabled`` option, so you can st... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/monitoring/video_recorder.py |
Add docstrings for production code | from typing import Dict, List, Optional, Sequence, SupportsFloat, Tuple, Type, Union
import numpy as np
import gym.error
from gym import logger
from gym.spaces.space import Space
def _short_repr(arr: np.ndarray) -> str:
if arr.size != 0 and np.min(arr) == np.max(arr):
return str(np.min(arr))
return ... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of a space that represents closed boxes in euclidean space."""
from typing import Dict, List, Optional, Sequence, SupportsFloat, Tuple, Type, Union
import numpy as np
@@ -8,16 +9,46 @@
def _short_repr(arr: np.ndarray) -> str:
+ """Create a shortened string representa... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/spaces/box.py |
Generate NumPy-style docstrings | from collections import OrderedDict
from functools import singledispatch
from typing import Iterable, Union
import numpy as np
from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple
__all__ = ["concatenate", "create_empty_array"]
@singledispatch
def concatenate(
space: Space, item... | --- +++ @@ -1,3 +1,4 @@+"""Numpy utility functions: concatenate space samples and create empty array."""
from collections import OrderedDict
from functools import singledispatch
from typing import Iterable, Union
@@ -13,6 +14,29 @@ def concatenate(
space: Space, items: Iterable, out: Union[tuple, dict, np.ndarr... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/vector/utils/numpy_utils.py |
Create docstrings for reusable components | from os import path
from typing import Optional, Union
import numpy as np
import gym
from gym import error, logger, spaces
from gym.spaces import Space
try:
import mujoco_py
except ImportError as e:
MUJOCO_PY_IMPORT_ERROR = e
else:
MUJOCO_PY_IMPORT_ERROR = None
try:
import mujoco
except ImportError ... | --- +++ @@ -26,6 +26,7 @@
class BaseMujocoEnv(gym.Env):
+ """Superclass for all MuJoCo environments."""
def __init__(
self,
@@ -83,20 +84,40 @@ # ----------------------------
def reset_model(self):
+ """
+ Reset the robot degrees of freedom (qpos and qvel).
+ Imple... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/mujoco/mujoco_env.py |
Add return value explanations in docstrings | import multiprocessing as mp
import sys
import time
from copy import deepcopy
from enum import Enum
from typing import List, Optional, Sequence, Tuple, Union
import numpy as np
import gym
from gym import logger
from gym.core import ObsType
from gym.error import (
AlreadyPendingCallError,
ClosedEnvironmentErro... | --- +++ @@ -1,3 +1,4 @@+"""An async vector environment."""
import multiprocessing as mp
import sys
import time
@@ -39,6 +40,21 @@
class AsyncVectorEnv(VectorEnv):
+ """Vectorized environment that runs multiple environments in parallel.
+
+ It uses ``multiprocessing`` processes, and pipes for communication.... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/vector/async_vector_env.py |
Add docstrings to make code maintainable | from contextlib import closing
from io import StringIO
from os import path
from typing import Optional
import numpy as np
from gym import Env, logger, spaces
from gym.envs.toy_text.utils import categorical_sample
from gym.error import DependencyNotInstalled
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
class CliffWalkingEnv(... | --- +++ @@ -16,6 +16,51 @@
class CliffWalkingEnv(Env):
+ """
+ This is a simple implementation of the Gridworld Cliff
+ reinforcement learning task.
+
+ Adapted from Example 6.6 (page 106) from [Reinforcement Learning: An Introduction
+ by Sutton and Barto](http://incompleteideas.net/book/bookdraft20... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/envs/toy_text/cliffwalking.py |
Add docstrings including usage examples | import contextlib
import os
__all__ = ["CloudpickleWrapper", "clear_mpi_env_vars"]
class CloudpickleWrapper:
def __init__(self, fn: callable):
self.fn = fn
def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.fn)
def __setstate__(self, ob):
import p... | --- +++ @@ -1,3 +1,4 @@+"""Miscellaneous utilities."""
import contextlib
import os
@@ -5,26 +6,43 @@
class CloudpickleWrapper:
+ """Wrapper that uses cloudpickle to pickle and unpickle the result."""
def __init__(self, fn: callable):
+ """Cloudpickle wrapper for a function."""
self.fn ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/vector/utils/misc.py |
Generate NumPy-style docstrings | import gym
from gym.error import ResetNeeded
class OrderEnforcing(gym.Wrapper):
def __init__(self, env: gym.Env, disable_render_order_enforcing: bool = False):
super().__init__(env)
self._has_reset: bool = False
self._disable_render_order_enforcing: bool = disable_render_order_enforcing
... | --- +++ @@ -1,24 +1,48 @@+"""Wrapper to enforce the proper ordering of environment operations."""
import gym
from gym.error import ResetNeeded
class OrderEnforcing(gym.Wrapper):
+ """A wrapper that will produce an error if :meth:`step` is called before an initial :meth:`reset`.
+
+ Example:
+ >>> fr... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/order_enforcing.py |
Add minimal docstrings for each function | import numpy as np
import gym
# taken from https://github.com/openai/baselines/blob/master/baselines/common/vec_env/vec_normalize.py
class RunningMeanStd:
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, epsilon=1e-4, shape=()):
self.mean = np... | --- +++ @@ -1,3 +1,4 @@+"""Set of wrappers for normalizing actions and observations."""
import numpy as np
import gym
@@ -5,20 +6,24 @@
# taken from https://github.com/openai/baselines/blob/master/baselines/common/vec_env/vec_normalize.py
class RunningMeanStd:
+ """Tracks the mean, variance and count of value... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/normalize.py |
Improve documentation using docstrings | from typing import Union
import numpy as np
import gym
from gym import spaces
class RescaleAction(gym.ActionWrapper):
def __init__(
self,
env: gym.Env,
min_action: Union[float, int, np.ndarray],
max_action: Union[float, int, np.ndarray],
):
assert isinstance(
... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper for rescaling actions to within a max and min action."""
from typing import Union
import numpy as np
@@ -7,6 +8,24 @@
class RescaleAction(gym.ActionWrapper):
+ """Affinely rescales the continuous action space of the environment to the range [min_action, max_action].
+
+ ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/rescale_action.py |
Create docstrings for reusable components | import os
from typing import Callable, Optional
import gym
from gym import logger
from gym.wrappers.monitoring import video_recorder
def capped_cubic_video_schedule(episode_id: int) -> bool:
if episode_id < 1000:
return int(round(episode_id ** (1.0 / 3))) ** 3 == episode_id
else:
return episo... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper for recording videos."""
import os
from typing import Callable, Optional
@@ -7,6 +8,16 @@
def capped_cubic_video_schedule(episode_id: int) -> bool:
+ """The default episode trigger.
+
+ This function will trigger recordings at the episode indices 0, 1, 4, 8, 27, ..., :ma... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/record_video.py |
Add docstrings to meet PEP guidelines | import time
from collections import deque
from typing import Optional
import numpy as np
import gym
def add_vector_episode_statistics(
info: dict, episode_info: dict, num_envs: int, env_num: int
):
info["episode"] = info.get("episode", {})
info["_episode"] = info.get("_episode", np.zeros(num_envs, dtyp... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper that tracks the cumulative rewards and episode lengths."""
import time
from collections import deque
from typing import Optional
@@ -10,6 +11,19 @@ def add_vector_episode_statistics(
info: dict, episode_info: dict, num_envs: int, env_num: int
):
+ """Add episode statistics... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/record_episode_statistics.py |
Create documentation strings for testing functions | import collections
import copy
from collections.abc import MutableMapping
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import gym
from gym import spaces
STATE_KEY = "state"
class PixelObservationWrapper(gym.ObservationWrapper):
def __init__(
self,
env: gym.Env,
... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper for augmenting observations by pixel values."""
import collections
import copy
from collections.abc import MutableMapping
@@ -12,6 +13,38 @@
class PixelObservationWrapper(gym.ObservationWrapper):
+ """Augment observations by pixel values.
+
+ Observations of this wrapper ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/pixel_observation.py |
Replace inline comments with docstrings | import gym
from gym.logger import deprecation
from gym.utils.step_api_compatibility import (
convert_to_done_step_api,
convert_to_terminated_truncated_step_api,
)
class StepAPICompatibility(gym.Wrapper):
def __init__(self, env: gym.Env, output_truncation_bool: bool = True):
super().__init__(env)
... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of StepAPICompatibility wrapper class for transforming envs between new and old step API."""
import gym
from gym.logger import deprecation
from gym.utils.step_api_compatibility import (
@@ -7,8 +8,33 @@
class StepAPICompatibility(gym.Wrapper):
+ r"""A wrapper which ca... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/step_api_compatibility.py |
Add docstrings to improve readability | from typing import Optional
import gym
class TimeLimit(gym.Wrapper):
def __init__(
self,
env: gym.Env,
max_episode_steps: Optional[int] = None,
):
super().__init__(env)
if max_episode_steps is None and self.env.spec is not None:
max_episode_steps = env.spe... | --- +++ @@ -1,15 +1,33 @@+"""Wrapper for limiting the time steps of an environment."""
from typing import Optional
import gym
class TimeLimit(gym.Wrapper):
+ """This wrapper will issue a `truncated` signal if a maximum number of timesteps is exceeded.
+
+ If a truncation is not defined inside the environ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/time_limit.py |
Create documentation for each function signature | from typing import Union
import numpy as np
import gym
from gym.error import DependencyNotInstalled
from gym.spaces import Box
class ResizeObservation(gym.ObservationWrapper):
def __init__(self, env: gym.Env, shape: Union[tuple, int]):
super().__init__(env)
if isinstance(shape, int):
... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper for resizing observations."""
from typing import Union
import numpy as np
@@ -8,8 +9,29 @@
class ResizeObservation(gym.ObservationWrapper):
+ """Resize the image observation.
+
+ This wrapper works on environments with image observations (or more generally observations o... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/resize_observation.py |
Create docstrings for API functions | import gym
class RenderCollection(gym.Wrapper):
def __init__(self, env: gym.Env, pop_frames: bool = True, reset_clean: bool = True):
super().__init__(env)
assert env.render_mode is not None
assert not env.render_mode.endswith("_list")
self.frame_list = []
self.reset_clean ... | --- +++ @@ -1,9 +1,20 @@+"""A wrapper that adds render collection mode to an environment."""
import gym
class RenderCollection(gym.Wrapper):
+ """Save collection of render frames."""
def __init__(self, env: gym.Env, pop_frames: bool = True, reset_clean: bool = True):
+ """Initialize a :class:`Ren... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/render_collection.py |
Create docstrings for each class method | from typing import Any, Callable
import gym
class TransformObservation(gym.ObservationWrapper):
def __init__(self, env: gym.Env, f: Callable[[Any], Any]):
super().__init__(env)
assert callable(f)
self.f = f
def observation(self, observation):
return self.f(observation) | --- +++ @@ -1,14 +1,43 @@+"""Wrapper for transforming observations."""
from typing import Any, Callable
import gym
class TransformObservation(gym.ObservationWrapper):
+ """Transform the observation via an arbitrary function :attr:`f`.
+
+ The function :attr:`f` should be defined on the observation space ... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/transform_observation.py |
Expand my code with proper documentation strings |
from typing import List
import gym
class VectorListInfo(gym.Wrapper):
def __init__(self, env):
assert getattr(
env, "is_vector_env", False
), "This wrapper can only be used in vectorized environments."
super().__init__(env)
def step(self, action):
observation, r... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper that converts the info format for vec envs into the list format."""
from typing import List
@@ -5,25 +6,67 @@
class VectorListInfo(gym.Wrapper):
+ """Converts infos of vectorized environments from dict to List[dict].
+
+ This wrapper converts the info format of a
+ v... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/vector_list_info.py |
Add well-formatted docstrings | import numpy as np
import gym
from gym.spaces import Box
class TimeAwareObservation(gym.ObservationWrapper):
def __init__(self, env: gym.Env):
super().__init__(env)
assert isinstance(env.observation_space, Box)
assert env.observation_space.dtype == np.float32
low = np.append(self... | --- +++ @@ -1,3 +1,4 @@+"""Wrapper for adding time aware observations to environment observation."""
import numpy as np
import gym
@@ -5,8 +6,27 @@
class TimeAwareObservation(gym.ObservationWrapper):
+ """Augment the observation with the current time step in the episode.
+
+ The observation space of the w... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/time_aware_observation.py |
Generate consistent documentation across files | from typing import Callable
import gym
from gym import RewardWrapper
class TransformReward(RewardWrapper):
def __init__(self, env: gym.Env, f: Callable[[float], float]):
super().__init__(env)
assert callable(f)
self.f = f
def reward(self, reward):
return self.f(reward) | --- +++ @@ -1,3 +1,4 @@+"""Wrapper for transforming the reward."""
from typing import Callable
import gym
@@ -5,11 +6,39 @@
class TransformReward(RewardWrapper):
+ """Transform the reward via an arbitrary function.
+
+ Warning:
+ If the base environment specifies a reward range which is not invaria... | https://raw.githubusercontent.com/openai/gym/HEAD/gym/wrappers/transform_reward.py |
Add docstrings to clarify complex logic |
import json
import os
import pprint
fpath = os.path.join(os.path.dirname( __file__ ), '..', 'README.md')
examples = []
# The globals
current_example = 1
sequence_num = 1
current_section_name = ""
STATEMENT_PREFIXES = ["...", ">>> ", "$ "]
HOSTED_NOTEBOOK_INSTRUCTIONS = """
## Hosted notebook instructions
This i... | --- +++ @@ -1,3 +1,21 @@+"""
+An inefficient monolithic piece of code that'll generate jupyter notebook
+from the projects main README.
+
+PS: If you are a recruiter, please don't judge me by this piece of code. I wrote it
+in hurry. I know this is messy and can be simplified, but I don't want to change it
+much becaus... | https://raw.githubusercontent.com/satwikkansal/wtfpython/HEAD/irrelevant/notebook_generator.py |
Document functions with clear intent | import math
from typing import Optional, Tuple, Union
import torch
from torchvision import transforms
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, DEFAULT_CROP_PCT
from timm.data.auto_augment import rand_augment_transform, augment_and_mix_transform, auto_augment_transform
from timm.dat... | --- +++ @@ -1,3 +1,8 @@+""" Transforms Factory
+Factory methods for building image transforms for use with TIMM (PyTorch Image Models)
+
+Hacked together by / Copyright 2019, Ross Wightman
+"""
import math
from typing import Optional, Tuple, Union
@@ -20,6 +25,19 @@ use_prefetcher: bool = False,
no... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/transforms_factory.py |
Create documentation strings for testing functions | import os
from typing import Optional
from torchvision.datasets import CIFAR100, CIFAR10, MNIST, KMNIST, FashionMNIST, ImageFolder
try:
from torchvision.datasets import Places365
has_places365 = True
except ImportError:
has_places365 = False
try:
from torchvision.datasets import INaturalist
has_ina... | --- +++ @@ -1,3 +1,7 @@+""" Dataset Factory
+
+Hacked together by / Copyright 2021, Ross Wightman
+"""
import os
from typing import Optional
@@ -73,6 +77,38 @@ trust_remote_code: bool = False,
**kwargs,
):
+ """ Dataset factory method
+
+ In parentheses after each arg are the type of dataset... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/dataset_factory.py |
Please document this code using docstrings | import math
import numbers
import random
import warnings
from typing import List, Sequence, Tuple, Union
import torch
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
try:
from torchvision.transforms.functional import InterpolationMode
has_interpolation_mode = True
exce... | --- +++ @@ -33,6 +33,7 @@
class ToTensor:
+ """ ToTensor with no rescaling of values"""
def __init__(self, dtype=torch.float32):
self.dtype = dtype
@@ -41,11 +42,20 @@
class MaybeToTensor(transforms.ToTensor):
+ """Convert a PIL Image or ndarray to tensor if it's not already one.
+ """
... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/transforms.py |
Add minimal docstrings for each function | import io
import logging
from typing import Optional
import torch
import torch.utils.data as data
from PIL import Image
from .readers import create_reader
_logger = logging.getLogger(__name__)
_ERROR_RETRY = 20
class ImageDataset(data.Dataset):
def __init__(
self,
root,
r... | --- +++ @@ -1,3 +1,7 @@+""" Quick n Simple Image Folder, Tarfile based DataSet
+
+Hacked together by / Copyright 2019, Ross Wightman
+"""
import io
import logging
from typing import Optional
@@ -164,6 +168,7 @@
class AugMixDataset(torch.utils.data.Dataset):
+ """Dataset wrapper to perform AugMix or other clea... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/dataset.py |
Add docstrings to my Python code | import os
from typing import Dict, List, Optional, Set, Tuple, Union
from timm.utils.misc import natural_key
from .class_map import load_class_map
from .img_extensions import get_img_extensions
from .reader import Reader
def find_images_and_targets(
folder: str,
types: Optional[Union[List, Tuple, Se... | --- +++ @@ -1,3 +1,10 @@+""" A dataset reader that extracts images from folders
+
+Folders are scanned recursively to find image files. Labels are based
+on the folder hierarchy, just leaf folders by default.
+
+Hacked together by / Copyright 2020 Ross Wightman
+"""
import os
from typing import Dict, List, Optional, ... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/readers/reader_image_folder.py |
Write docstrings for backend logic | from typing import List, Optional, Tuple, Union
import torch
from torch import nn
import torch.nn.functional as F
from .helpers import make_divisible
from .weight_init import trunc_normal_
from .trace_utils import _assert
def rel_logits_1d(q, rel_k, permute_mask: List[int]):
B, H, W, dim = q.shape
rel_size ... | --- +++ @@ -1,3 +1,21 @@+""" Halo Self Attention
+
+Paper: `Scaling Local Self-Attention for Parameter Efficient Visual Backbones`
+ - https://arxiv.org/abs/2103.12731
+
+@misc{2103.12731,
+Author = {Ashish Vaswani and Prajit Ramachandran and Aravind Srinivas and Niki Parmar and Blake Hechtman and
+ Jonathon Shle... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/halo_attn.py |
Add docstrings that explain purpose and usage | from typing import List, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
def drop_block_2d(
x: torch.Tensor,
drop_prob: float = 0.1,
block_size: int = 7,
gamma_scale: float = 1.0,
with_noise: bool = False,
inplace: bool = False,
couple_... | --- +++ @@ -1,3 +1,19 @@+""" DropBlock, DropPath
+
+PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers.
+
+Papers:
+DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890)
+
+Deep Networks with Stochastic Depth (https://arxiv.org/abs/1603.... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/drop.py |
Write docstrings for data processing functions | from itertools import repeat
import collections.abc
# From PyTorch internals
def _ntuple(n):
def parse(x):
if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
return tuple(x)
return tuple(repeat(x, n))
return parse
to_1tuple = _ntuple(1)
to_2tuple = _ntuple(2)
... | --- +++ @@ -1,9 +1,24 @@+""" Layer/Module Helpers
+
+Hacked together by / Copyright 2020 Ross Wightman
+"""
from itertools import repeat
import collections.abc
# From PyTorch internals
def _ntuple(n):
+ """Return a function that converts input to an n-tuple.
+
+ Scalar values are repeated n times, while i... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/helpers.py |
Generate docstrings for exported functions | from typing import List, Optional, Type, Union
import torch
from torch import nn as nn
from torch.nn import functional as F
from .config import use_fused_attn
from .create_conv2d import create_conv2d
from .helpers import to_2tuple
from .pool2d_same import create_pool2d
class MultiQueryAttentionV2(nn.Module):
d... | --- +++ @@ -11,6 +11,18 @@
class MultiQueryAttentionV2(nn.Module):
+ """Multi Query Attention.
+
+ Fast Transformer Decoding: One Write-Head is All You Need
+ https://arxiv.org/pdf/1911.02150.pdf
+
+ This is an acceletor optimized version - removing multiple unnecessary
+ tensor transpose by re-arran... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/attention2d.py |
Add docstrings for internal functions | import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):
# NOTE I've seen CUDA illegal memory access errors being caused by the normal_()
# paths, flip the order so normal is run on CPU if this becomes a problem
# Issue has been fixed ... | --- +++ @@ -1,3 +1,10 @@+""" Random Erasing (Cutout)
+
+Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0
+Copyright Zhun Zhong & Liang Zheng
+
+Hacked together by / Copyright 2019, Ross Wightman
+"""
import random
import math
@@ -17,6 +24,24 @@
class RandomErasing:
+ "... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/random_erasing.py |
Add docstrings that explain purpose and usage | import math
import os
import sys
from typing import Optional
import torch
import torch.distributed as dist
from PIL import Image
try:
import tensorflow as tf
tf.config.set_visible_devices([], 'GPU') # Hands off my GPU! (or pip install tensorflow-cpu)
import tensorflow_datasets as tfds
try:
tf... | --- +++ @@ -1,3 +1,11 @@+""" Dataset reader that wraps TFDS datasets
+
+Wraps many (most?) TFDS image-classification datasets
+from https://github.com/tensorflow/datasets
+https://www.tensorflow.org/datasets/catalog/overview#image_classification
+
+Hacked together by / Copyright 2020 Ross Wightman
+"""
import math
im... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/readers/reader_tfds.py |
Add docstrings for utility scripts | import io
import json
import logging
import math
import os
import random
import sys
from dataclasses import dataclass
from functools import partial
from itertools import islice
from typing import Any, Callable, Dict, List, Optional, Tuple
import torch
import torch.distributed as dist
import yaml
from PIL import Image
... | --- +++ @@ -1,3 +1,7 @@+""" Dataset reader for webdataset
+
+Hacked together by / Copyright 2022 Ross Wightman
+"""
import io
import json
import logging
@@ -120,6 +124,7 @@
def log_and_continue(exn):
+ """Call in an exception handler to ignore exceptions, issue a warning, and continue."""
_logger.warning... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/readers/reader_wds.py |
Document this code for team use | from functools import partial
from typing import Optional, Type, Union, Tuple
from torch import nn as nn
from .grn import GlobalResponseNorm
from .helpers import to_2tuple
class Mlp(nn.Module):
def __init__(
self,
in_features: int,
hidden_features: Optional[int] = None,
... | --- +++ @@ -1,3 +1,7 @@+""" MLP module w/ dropout and configurable activation layer
+
+Hacked together by / Copyright 2020 Ross Wightman
+"""
from functools import partial
from typing import Optional, Type, Union, Tuple
@@ -8,6 +12,10 @@
class Mlp(nn.Module):
+ """ MLP as used in Vision Transformer, MLP-Mixe... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/mlp.py |
Document functions with detailed explanations | import logging
import math
from typing import Callable, Dict, List, Optional, Tuple, Union
import torch
from torch import nn as nn
import torch.nn.functional as F
from .format import Format, nchw_to
from .helpers import to_2tuple
from .trace_utils import _assert
_logger = logging.getLogger(__name__)
class PatchEmb... | --- +++ @@ -1,3 +1,13 @@+""" Image to Patch Embedding using Conv2d
+
+A convolution based approach to patchifying a 2D image w/ embedding projection.
+
+Based on code in:
+ * https://github.com/google-research/vision_transformer
+ * https://github.com/google-research/big_vision/tree/main/big_vision
+
+Hacked together... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/patch_embed.py |
Generate missing documentation strings | import logging
import random
from contextlib import suppress
from functools import partial
from itertools import repeat
from typing import Callable, Optional, Tuple, Union
import torch
import torch.utils.data
import numpy as np
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from .dataset import It... | --- +++ @@ -1,3 +1,10 @@+""" Loader Factory, Fast Collate, CUDA Prefetcher
+
+Prefetcher and Fast Collate inspired by NVIDIA APEX example at
+https://github.com/NVIDIA/apex/commit/d5e2bb4bdeedd27b1dfaf5bb2b24d6c000dee9be#diff-cf86c282ff7fba81fad27a559379d5bf
+
+Hacked together by / Copyright 2019, Ross Wightman
+"""
i... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/loader.py |
Add minimal docstrings for each function | from typing import Optional, Tuple
import torch
from torch import nn
import torch.nn.functional as F
from .grid import ndgrid
from .helpers import to_2tuple, make_divisible
from .weight_init import trunc_normal_
def rel_pos_indices(size, device=None):
size = to_2tuple(size)
pos = torch.stack(ndgrid(
... | --- +++ @@ -1,3 +1,25 @@+""" Lambda Layer
+
+Paper: `LambdaNetworks: Modeling Long-Range Interactions Without Attention`
+ - https://arxiv.org/abs/2102.08602
+
+@misc{2102.08602,
+Author = {Irwan Bello},
+Title = {LambdaNetworks: Modeling Long-Range Interactions Without Attention},
+Year = {2021},
+}
+
+Status:
+Thi... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/lambda_layer.py |
Add docstrings that explain logic | import logging
import os
import pickle
import tarfile
from glob import glob
from typing import List, Tuple, Dict, Set, Optional, Union
import numpy as np
from timm.utils.misc import natural_key
from .class_map import load_class_map
from .img_extensions import get_img_extensions
from .reader import Reader
_logger = ... | --- +++ @@ -1,3 +1,14 @@+""" A dataset reader that reads tarfile based datasets
+
+This reader can extract image samples from:
+* a single tar of image files
+* a folder of multiple tarfiles containing imagefiles
+* a tar of tars containing image files
+
+Labels are based on the combined folder and/or tar name structur... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/readers/reader_image_in_tar.py |
Please document this code using docstrings |
import torch
from torch import nn as nn
from torch.nn import functional as F
def swish_fwd(x):
return x.mul(torch.sigmoid(x))
def swish_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
return grad_output * (x_sigmoid * (1 + x * (1 - x_sigmoid)))
class SwishAutoFn(torch.autograd.Function):
@stati... | --- +++ @@ -1,3 +1,13 @@+""" Activations (memory-efficient w/ custom autograd)
+
+A collection of activations fn and modules with a common interface so that they can
+easily be swapped. All have an `inplace` arg even if not used.
+
+These activations are not compatible with jit scripting or ONNX export of the model, pl... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/activations_me.py |
Add docstrings to my Python code |
import math
import random
import warnings
from typing import Dict, List, Optional, Sequence, Tuple, Union
import torch
from PIL import Image
from torchvision import transforms
from torchvision.transforms import functional as F
from torchvision.transforms.functional import InterpolationMode
from .transforms import st... | --- +++ @@ -1,3 +1,13 @@+""" NaFlex (NaViT + FlexiViT) Transforms and Collation
+
+Implements PyTorch versions of the transforms described in the NaViT and FlexiViT papers:
+- NaViT: https://arxiv.org/abs/2307.14995
+- FlexiViT: https://arxiv.org/abs/2212.08013
+
+Enables variable resolution/aspect ratio image handling... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/naflex_transforms.py |
Write docstrings for this repository |
import torch
from torch import nn as nn
class GlobalResponseNorm(nn.Module):
def __init__(
self,
dim: int,
eps: float = 1e-6,
channels_last: bool = True,
device=None,
dtype=None,
):
dd = {'device': device, 'dtype': dtype}
... | --- +++ @@ -1,9 +1,23 @@+""" Global Response Normalization Module
+
+Based on the GRN layer presented in
+`ConvNeXt-V2 - Co-designing and Scaling ConvNets with Masked Autoencoders` - https://arxiv.org/abs/2301.00808
+
+This implementation
+* works for both NCHW and NHWC tensor layouts
+* uses affine param names matchin... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/grn.py |
Generate NumPy-style docstrings | from functools import partial
from math import comb # Python 3.8
from typing import Callable, Optional, Type, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from .padding import get_padding
from .typing import LayerType
class BlurPool2d(nn.Module):
def __init__(
self,
... | --- +++ @@ -1,3 +1,10 @@+"""
+BlurPool layer inspired by
+ - Kornia's Max_BlurPool2d
+ - Making Convolutional Networks Shift-Invariant Again :cite:`zhang2019shiftinvar`
+
+Hacked together by Chris Ha and Ross Wightman
+"""
from functools import partial
from math import comb # Python 3.8
from typing import Callable,... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/blur_pool.py |
Add professional docstrings to my codebase | from typing import Optional, Type, Union
import torch
from torch import nn
from .create_act import create_act_layer
from .helpers import make_divisible
from .norm import GroupNorm1
class CoordAttn(nn.Module):
def __init__(
self,
channels: int,
rd_ratio: float = 1. / 16,
... | --- +++ @@ -1,3 +1,15 @@+""" Coordinate Attention and Variants
+
+Coordinate Attention decomposes channel attention into two 1D feature encoding processes
+to capture long-range dependencies with precise positional information. This module includes
+the original implementation along with simplified and other variants.
... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/coord_attn.py |
Write documentation strings for class attributes | from collections import OrderedDict
from functools import partial
from typing import Optional, Union, Callable
import torch
import torch.nn as nn
from torch.nn import functional as F
from .adaptive_avgmax_pool import SelectAdaptivePool2d
from .create_act import get_act_layer
from .create_norm import get_norm_layer
... | --- +++ @@ -1,3 +1,7 @@+""" Classifier head and layer factory
+
+Hacked together by / Copyright 2020 Ross Wightman
+"""
from collections import OrderedDict
from functools import partial
from typing import Optional, Union, Callable
@@ -71,6 +75,7 @@
class ClassifierHead(nn.Module):
+ """Classifier head w/ conf... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/classifier.py |
Document all public functions with docstrings | from typing import Tuple
import torch
def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]:
try:
return torch.meshgrid(*tensors, indexing='ij')
except TypeError:
# old PyTorch < 1.10 will follow this path as it does not have indexing arg,
# the old behaviour of meshgrid was 'ij'
r... | --- +++ @@ -4,6 +4,21 @@
def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]:
+ """generate N-D grid in dimension order.
+
+ The ndgrid function is like meshgrid except that the order of the first two input arguments are switched.
+
+ That is, the statement
+ [X1,X2,X3] = ndgrid(x1,x2,x3)
+
+ produces t... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/grid.py |
Generate docstrings for exported functions | from typing import Optional, Type
import torch
from torch import nn
from torch.nn import functional as F
from ._fx import register_notrace_module
from .conv_bn_act import ConvNormAct
from .helpers import make_divisible
from .trace_utils import _assert
class NonLocalAttn(nn.Module):
def __init__(
se... | --- +++ @@ -1,3 +1,9 @@+""" Bilinear-Attention-Transform and Non-Local Attention
+
+Paper: `Non-Local Neural Networks With Grouped Bilinear Attentional Transforms`
+ - https://openaccess.thecvf.com/content_CVPR_2020/html/Chi_Non-Local_Neural_Networks_With_Grouped_Bilinear_Attentional_Transforms_CVPR_2020_paper.html
... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/non_local_attn.py |
Add verbose docstrings with examples |
import sys
import numpy as np
import torch
from clu import checkpoint
arch_depths = {
'nest_base': [2, 2, 20],
'nest_small': [2, 2, 20],
'nest_tiny': [2, 2, 8],
}
def convert_nest(checkpoint_path, arch):
assert arch in ['nest_base', 'nest_small', 'nest_tiny'], "Your `arch` is not supported"
... | --- +++ @@ -1,3 +1,7 @@+"""
+Convert weights from https://github.com/google-research/nested-transformer
+NOTE: You'll need https://github.com/google/CommonLoopUtils, not included in requirements.txt
+"""
import sys
@@ -15,6 +19,14 @@
def convert_nest(checkpoint_path, arch):
+ """
+ Expects path to checkp... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/convert/convert_nest_flax.py |
Add docstrings for internal functions |
import torch
from torch import nn as nn
from torch.nn import functional as F
def swish(x, inplace: bool = False):
return x.mul_(x.sigmoid()) if inplace else x.mul(x.sigmoid())
class Swish(nn.Module):
def __init__(self, inplace: bool = False):
super().__init__()
self.inplace = inplace
d... | --- +++ @@ -1,3 +1,10 @@+""" Activations
+
+A collection of activations fn and modules with a common interface so that they can
+easily be swapped. All have an `inplace` arg even if not used.
+
+Hacked together by / Copyright 2020 Ross Wightman
+"""
import torch
from torch import nn as nn
@@ -5,6 +12,8 @@
def s... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/activations.py |
Add structured docstrings to improve clarity | import math
import torch
from torch.utils.data import Sampler
import torch.distributed as dist
class OrderedDistributedSampler(Sampler):
def __init__(self, dataset, num_replicas=None, rank=None):
if num_replicas is None:
if not dist.is_available():
raise RuntimeError("Requires... | --- +++ @@ -5,6 +5,19 @@
class OrderedDistributedSampler(Sampler):
+ """Sampler that restricts data loading to a subset of the dataset.
+ It is especially useful in conjunction with
+ :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
+ process can pass a DistributedSampler instance ... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/distributed_sampler.py |
Generate docstrings for exported functions | import torch
from torch import nn
class LayerScale(nn.Module):
def __init__(
self,
dim: int,
init_values: float = 1e-5,
inplace: bool = False,
device=None,
dtype=None,
) -> None:
super().__init__()
self.init_values = init_... | --- +++ @@ -3,6 +3,8 @@
class LayerScale(nn.Module):
+ """ LayerScale on tensors with channels in last-dim.
+ """
def __init__(
self,
dim: int,
@@ -26,6 +28,8 @@
class LayerScale2d(nn.Module):
+ """ LayerScale for tensors with torch 2D NCHW layout.
+ """
def __ini... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/layer_scale.py |
Document this script properly | from typing import List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from .helpers import to_2tuple, make_divisible
from .weight_init import trunc_normal_
from .trace_utils import _assert
def rel_logits_1d(q, rel_k, permute_mask: List[int]):
B, H, W, dim = q.shape
x = ... | --- +++ @@ -1,3 +1,19 @@+""" Bottleneck Self Attention (Bottleneck Transformers)
+
+Paper: `Bottleneck Transformers for Visual Recognition` - https://arxiv.org/abs/2101.11605
+
+@misc{2101.11605,
+Author = {Aravind Srinivas and Tsung-Yi Lin and Niki Parmar and Jonathon Shlens and Pieter Abbeel and Ashish Vaswani},
+Tit... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/bottleneck_attn.py |
Add docstrings that explain logic | from typing import Optional, Tuple, Type, Union
import math
from torch import nn
import torch.nn.functional as F
from .create_act import create_act_layer
from .helpers import make_divisible
class EcaModule(nn.Module):
def __init__(
self,
channels: Optional[int] = None,
kernel... | --- +++ @@ -1,3 +1,38 @@+"""
+ECA module from ECAnet
+
+paper: ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks
+https://arxiv.org/abs/1910.03151
+
+Original ECA model borrowed from https://github.com/BangguWu/ECANet
+
+Modified circular ECA implementation and adaption for use in timm package... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/eca.py |
Help me comply with documentation standards | import math
import random
from typing import Dict, List, Tuple, Union
import torch
def mix_batch_variable_size(
imgs: List[torch.Tensor],
*,
mixup_alpha: float = 0.8,
cutmix_alpha: float = 1.0,
switch_prob: float = 0.5,
local_shuffle: int = 4,
) -> Tuple[List[torch.Ten... | --- +++ @@ -1,3 +1,18 @@+"""Variable‑size Mixup / CutMix utilities for NaFlex data loaders.
+
+This module provides:
+
+* `mix_batch_variable_size` – pixel‑level Mixup/CutMix that operates on a
+ list of images whose spatial sizes differ, mixing only their central overlap
+ so no resizing is required.
+* `pairwise_mi... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/naflex_mixup.py |
Document functions with clear intent | from enum import Enum
from typing import Union
import torch
class Format(str, Enum):
NCHW = 'NCHW'
NHWC = 'NHWC'
NCL = 'NCL'
NLC = 'NLC'
FormatT = Union[str, Format]
def get_spatial_dim(fmt: FormatT):
fmt = Format(fmt)
if fmt is Format.NLC:
dim = (1,)
elif fmt is Format.NCL:
... | --- +++ @@ -15,6 +15,14 @@
def get_spatial_dim(fmt: FormatT):
+ """Return spatial dimension indices for a given tensor format.
+
+ Args:
+ fmt: Tensor format (NCHW, NHWC, NCL, or NLC).
+
+ Returns:
+ Tuple of spatial dimension indices.
+ """
fmt = Format(fmt)
if fmt is Format.NLC... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/format.py |
Add standardized docstrings across the file | import numpy as np
import torch
def one_hot(x, num_classes, on_value=1., off_value=0.):
x = x.long().view(-1, 1)
return torch.full((x.size()[0], num_classes), off_value, device=x.device).scatter_(1, x, on_value)
def mixup_target(target, num_classes, lam=1., smoothing=0.0):
off_value = smoothing / num_cl... | --- +++ @@ -1,3 +1,15 @@+""" Mixup and Cutmix
+
+Papers:
+mixup: Beyond Empirical Risk Minimization (https://arxiv.org/abs/1710.09412)
+
+CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features (https://arxiv.org/abs/1905.04899)
+
+Code Reference:
+CutMix: https://github.com/clovaai/CutMix... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/mixup.py |
Write docstrings for algorithm functions | import random
import math
import re
from functools import partial
from typing import Dict, List, Optional, Union
from PIL import Image, ImageOps, ImageEnhance, ImageChops, ImageFilter
import PIL
import numpy as np
_PIL_VER = tuple([int(x) for x in PIL.__version__.split('.')[:2]])
_FILL = (128, 128, 128)
_LEVEL_DEN... | --- +++ @@ -1,3 +1,25 @@+""" AutoAugment, RandAugment, AugMix, and 3-Augment for PyTorch
+
+This code implements the searched ImageNet policies with various tweaks and improvements and
+does not include any of the search code.
+
+AA and RA Implementation adapted from:
+ https://github.com/tensorflow/tpu/blob/master/... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/auto_augment.py |
Write docstrings describing each step | import torch
from itertools import product
class RegularGridInterpolator:
def __init__(self, points, values):
self.points = points
self.values = values
assert isinstance(self.points, tuple) or isinstance(self.points, list)
assert isinstance(self.values, torch.Tensor)
sel... | --- +++ @@ -1,8 +1,19 @@+""" Interpolation helpers for timm layers
+
+RegularGridInterpolator from https://github.com/sbarratt/torch_interpolations
+Copyright Shane Barratt, Apache 2.0 license
+"""
import torch
from itertools import product
class RegularGridInterpolator:
+ """ Interpolate data defined on a re... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/interpolate.py |
Generate helpful docstrings for debugging |
import math
import random
import warnings
from functools import partial
from typing import Any, Iterator, List, Tuple, Dict, Optional, Union, Callable
import torch
from torch.utils.data import Dataset, IterableDataset, DataLoader
from PIL import Image
from .naflex_transforms import Patchify
from timm.layers import t... | --- +++ @@ -1,3 +1,17 @@+""" Dynamic Sequence Length Datasets for Variable Resolution Image Processing
+
+Implements two dataset wrappers:
+1. NaFlexMapDatasetWrapper - Map-style dataset that returns batches with variable sequence lengths
+TODO: 2. NaFlexIterableDatasetWrapper - Iterable dataset that yields batches wit... | https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/naflex_dataset.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.