instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write docstrings for backend logic
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -31,6 +31,7 @@ class SPMDGPUExecutor(ExecutorBase): + """SPMD-based multi-GPU executor implementations.""" def __init__( self, @@ -94,6 +95,15 @@ self.worker.load_model() def determine_num_available_blocks(self) -> Tuple[int, int]: + """Determine the number of ava...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_4_2/spmd_gpu_executor.py
Write Python docstrings for this snippet
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -36,6 +36,65 @@ class ModelConfig(ModelConfig): + """Configuration for the model. + + Args: + model: Name or path of the huggingface model to use. + tokenizer: Name or path of the huggingface tokenizer to use. + tokenizer_mode: Tokenizer mode. "auto" will use the fast tokenizer...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_5_4/config.py
Improve documentation using docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor ar...
--- +++ @@ -70,6 +70,7 @@ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding): + """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): self.sca...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/models/llama/megatron/layers/parallel_attention.py
Write proper docstrings for these functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -41,6 +41,35 @@ class LLMEngine(LLMEngine): + """An LLM engine that receives requests and generates texts. + + This is the main class for the vLLM engine. It receives requests + from clients and generates texts from the LLM. It includes a tokenizer, a + language model (possibly distributed ac...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_4_2/llm_engine_sp.py
Add docstrings including usage examples
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -39,6 +39,33 @@ class LLMEngine: + """An LLM engine that receives requests and generates texts. + + This is the main class for the vLLM engine. It receives requests + from clients and generates texts from the LLM. It includes a tokenizer, a + language model (possibly distributed across multip...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_3_1/llm_engine_sp.py
Add structured docstrings to improve clarity
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -31,6 +31,58 @@ class LLM: + """An LLM for generating texts from given prompts and sampling parameters. + + This class includes a tokenizer, a language model (possibly distributed + across multiple GPUs), and GPU memory space allocated for intermediate + states (aka KV cache). Given a batch o...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_3_1/llm.py
Write beginner-friendly docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -32,6 +32,7 @@ class SPMDGPUExecutor(ExecutorBase): + """SPMD-based multi-GPU executor implementations.""" def __init__( self, @@ -104,6 +105,15 @@ self.worker.load_model() def determine_num_available_blocks(self) -> Tuple[int, int]: + """Determine the number of a...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_5_4/spmd_gpu_executor.py
Document functions with detailed explanations
#!/usr/bin/env python # Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
--- +++ @@ -14,6 +14,7 @@ # limitations under the License. # -*- coding: utf-8 -*- +"""File-system agnostic IO APIs""" import os import tempfile import hashlib @@ -34,6 +35,15 @@ def get_local_temp_path(hdfs_path: str, cache_dir: str) -> str: + """Return a local temp path that joins cache_dir and basename ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/fs.py
Fully document this Python code with docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import os from typing import Optional import torch import torch.distribut...
--- +++ @@ -3,6 +3,7 @@ # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +"""Model and data parallel groups.""" import os from typing import Optional @@ -72,6 +73,10 @@ pipeline_model_parallel_size: ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_6_3/parallel_state.py
Write docstrings for algorithm functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -26,6 +26,7 @@ def _megatron_calc_global_rank(tp_rank: int = 0, dp_rank: int = 0, pp_rank: int = 0): + """given TP,DP,PP rank to get the global rank.""" args = get_args() tp_size = mpu.get_tensor_model_parallel_world_size() @@ -42,6 +43,12 @@ def _megatron_calc_layer_map(config): + ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/models/llama/megatron/checkpoint_utils/llama_saver.py
Write docstrings for data processing functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import os import torch import torch.distributed from typing import Optiona...
--- +++ @@ -3,6 +3,7 @@ # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +"""Model and data parallel groups.""" import os import torch import torch.distributed @@ -67,6 +68,10 @@ pipeline_model_parall...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_4_2/parallel_state.py
Add clean documentation to messy code
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,10 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Implement base data transfer protocol between any two functions, modules. +We can subclass Protocol to defi...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/protocol.py
Add structured docstrings to improve clarity
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/worker.py +"""A GPU worker class.""" import gc import os from typing import Dict, List, Optional, Tuple, Type, U...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_6_3/worker.py
Create simple docstrings for beginners
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -23,6 +23,10 @@ # NOTE(sgm): for opensource megatron-core class NVMegatronRayWorkerGroup(RayWorkerGroup, MegatronWorkerGroup): + """ + MegatronWorkerGroup will query each worker of its megatron rank info and store it inside the WorkerGroup + so that the dispatcher can use it to dispatch data. + ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/single_controller/ray/megatron.py
Write docstrings including parameters and return values
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import torch import torch.distributed import vllm.model_executor.paralle...
--- +++ @@ -3,6 +3,7 @@ # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +"""Model and data parallel groups.""" import torch import torch.distributed @@ -105,19 +106,24 @@ def get_tensor_model_parall...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_3_1/parallel_state.py
Add documentation for all methods
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -35,6 +35,65 @@ class ModelConfig(ModelConfig): + """Configuration for the model. + + Args: + model: Name or path of the huggingface model to use. + tokenizer: Name or path of the huggingface tokenizer to use. + tokenizer_mode: Tokenizer mode. "auto" will use the fast tokenizer...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_4_2/config.py
Add docstrings for utility scripts
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import os import torch import torch.distributed from typing import Optiona...
--- +++ @@ -3,6 +3,7 @@ # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +"""Model and data parallel groups.""" import os import torch import torch.distributed @@ -69,6 +70,10 @@ pipeline_model_parall...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_5_4/parallel_state.py
Create structured documentation for my script
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -19,6 +19,12 @@ def _megatron_calc_layer_map(config): + """Calculate the mapping of global layer_idx to local layer_idx + Returns: + layer_map (Dict: int -> tuple(int, int, int)): + mapping from the global layer index to + a tuple of (pp_rank, virtual_pp_rank, layer_idx...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/models/llama/megatron/checkpoint_utils/llama_loader.py
Add docstrings to existing functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/worker.py +"""A GPU worker class.""" import os import gc from typing import Dict, List, Tuple, Optional, Union, ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_5_4/worker.py
Add detailed documentation for each class
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader +"""Utilities for selecting and loading models.""" from typing import Dict, Union, Optional, ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_4_2/model_loader.py
Add minimal docstrings for each function
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -290,8 +290,15 @@ return worker_group def spawn(self, prefix_set): + """ + spawn to a dictionary of worker groups, each with a subset of method with prefix. + + """ def _rebind_actor_methods(worker_group, actor_name): + """ + bind the metho...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/single_controller/ray/base.py
Generate NumPy-style docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -25,18 +25,44 @@ def exists(path: str, **kwargs) -> bool: + r"""Works like os.path.exists() but supports hdfs. + + Test whether a path exists. Returns False for broken symbolic links. + + Args: + path (str): path to test + + Returns: + bool: True if the path exists, False otherw...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/hdfs_io.py
Write docstrings that follow conventions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -132,6 +132,13 @@ @contextmanager def meta_device_init(): + """ + Create model parameters with meta device. + + Note buffers in model will still be initialized in default device (e.g., CPU), + since the buffers can be non-persistent and filled with expected values that can + NOT be captured...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/fsdp_utils.py
Add docstrings to make code maintainable
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -72,6 +72,9 @@ def dispatch_megatron_compute(worker_group, *args, **kwargs): + """ + User passes in dp data. The data is dispatched to all tp/pp ranks with the same dp + """ from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup assert isinstance(worker_group...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/single_controller/base/decorator.py
Add docstrings to improve collaboration
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -44,6 +44,35 @@ class LLMEngine(LLMEngine): + """An LLM engine that receives requests and generates texts. + + This is the main class for the vLLM engine. It receives requests + from clients and generates texts from the LLM. It includes a tokenizer, a + language model (possibly distributed ac...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_5_4/llm_engine_sp.py
Please document this code using docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader +"""Utilities for selecting and loading models.""" import contextlib from typing import Dict...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_3_1/model_loader.py
Generate helpful docstrings for debugging
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models +"""Utilities for selecting and loading models.""" from typing import Dict, Optional, Union impo...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_6_3/model_loader.py
Add well-formatted docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -49,6 +49,14 @@ class FlopsCounter: + """ + Used to count mfu during training loop + + Example: + flops_counter = FlopsCounter(config) + flops_achieved, flops_promised = flops_counter.estimate_flops(tokens_list, delta_time) + + """ def __init__(self, config: PretrainedCon...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/flops_counter.py
Help me add docstrings to my project
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/worker.py +"""A GPU worker class.""" import os import gc from typing import Dict, List, Tuple, Optional, Union, ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/third_party/vllm/vllm_v_0_3_1/worker.py
Write docstrings for utility functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache....
--- +++ @@ -12,6 +12,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Utilities for using tensor_parallel in megatron +""" from typing import Dict import torch from torch.nn i...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/megatron/tensor_parallel.py
Help me document legacy Python code
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +This file contains utilities to manipulate torch memory buffers +""" from typing import Dict, List @@ -...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/memory_buffer.py
Write docstrings for utility functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -150,6 +150,21 @@ def get_seqlen_balanced_partitions(seqlen_list: List[int], k_partitions: int, equal_size: bool): + """ get order of seq lengths to make partitions balanced, this is + used in balacing sum of seqlength across dp ranks and microbatches + Parameters: + seqlen_list (List...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/seqlen_balancing.py
Add docstrings that explain inputs and outputs
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,12 +11,24 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Contain small python utility functions +""" from typing import Dict from types import SimpleNamespace ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/py_functional.py
Add docstrings for internal functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Contain small torch utilities +""" from typing import Dict, Union, List, Optional @@ -29,12 +32,24 @@ ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/torch_functional.py
Expand my code with proper documentation strings
import re import random import ast import operator def extract_solution(solution_str): # Remove everything before the first "Assistant:" if "Assistant:" in solution_str: solution_str = solution_str.split("Assistant:", 1)[1] elif "<|im_start|>assistant" in solution_str: solution_str = solut...
--- +++ @@ -5,6 +5,7 @@ def extract_solution(solution_str): + """Extract the equation from the solution string.""" # Remove everything before the first "Assistant:" if "Assistant:" in solution_str: solution_str = solution_str.split("Assistant:", 1)[1] @@ -25,6 +26,7 @@ def validate_equatio...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/reward_score/countdown.py
Add docstrings for internal functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,11 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Utilities for DeepSpeed Ulysses Sequence Parallelism. +DeepSpeed Ulysses Paper: https://arxiv.org/abs/2309....
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/ulysses.py
Provide clean and structured docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,10 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +FSDP PPO Trainer with Ray-based single controller. +This trainer supports model-agonistic model initializat...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/trainer/ppo/ray_trainer.py
Auto-generate documentation strings for this file
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Utilities to create common models from huggingface +""" import os import warnings from typing import Dict...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/model.py
Add docstrings that explain purpose and usage
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Note that we don't combine the main with ray_trainer as ray_trainer is used by other main. +""" from verl...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/trainer/main_ppo.py
Generate docstrings with parameter types
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Single Process Actor +""" import itertools from typing import Iterable, Tuple @@ -41,6 +44,7 @@ ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/actor/dp_actor.py
Include argument descriptions in docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org...
--- +++ @@ -12,6 +12,11 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Core functions to implement PPO algorithms. +The function implemented in this file should be used by traine...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/trainer/ppo/core_algos.py
Add verbose docstrings with examples
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +The base class for Actor +""" from abc import ABC, abstractmethod from typing import Iterable, Dict @@ -...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/actor/base.py
Create docstrings for API functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,13 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Megatron Actor. +In megatron actor, the differences are: +1. We only make minibatch + +Note that our model ...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/actor/megatron_actor.py
Add docstrings to incomplete code
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +The main entry point to run the PPO algorithm +""" import os import logging @@ -58,6 +61,10 @@ class...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/megatron_workers.py
Provide clean and structured docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,12 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +SFT dataset +- We assume user pass a single parquet file. +- We load all the data into the memory. +Each pa...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/dataset/sft_dataset.py
Add inline docstrings for readability
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +The base class for reward model +""" from abc import ABC, abstractmethod @@ -24,4 +27,19 @@ @abst...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/reward_model/base.py
Add minimal docstrings for each function
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -56,6 +56,9 @@ class RLHFDataset(Dataset): + """ + We assume the dataset contains a column that contains prompts and other information + """ def __init__(self, parquet_files: Union[str, List[str]], @@ -115,6 +118,9 @@ return len(self.dataframe) def __getit...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/dataset/rl_dataset.py
Generate docstrings with parameter types
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,12 +11,19 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Utils for tokenization.""" import warnings __all__ = ['hf_tokenizer'] def set_pad_token_id(tokenize...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/utils/tokenizer.py
Generate docstrings for exported functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +This file contains a Megatron style Hybrid Engine that shares the weights of the actor with the inference en...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/sharding_manager/megatron_vllm.py
Generate NumPy-style docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +The main entry point to run the PPO algorithm +""" import logging import os @@ -42,6 +45,10 @@ class...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/fsdp_workers.py
Provide docstrings following PEP 257
import copy AUDIO_FORMATS = ("m4a", "mp3", "opus", "wav", "flac") CAPTION_MODES = ("auto_only", "manual_only", "prefer_manual", "prefer_auto") CODEC_FILTER_MAP = { 'h264': "[vcodec~='^(h264|avc)']", 'h265': "[vcodec~='^(h265|hevc)']", 'av1': "[vcodec~='^av0?1']", 'vp9': "[vcodec~='^vp0?9']", } def...
--- +++ @@ -22,6 +22,21 @@ def get_format(download_type: str, codec: str, format: str, quality: str) -> str: + """ + Returns yt-dlp format selector. + + Args: + download_type (str): selected content type (video, audio, captions, thumbnail) + codec (str): selected video codec (auto, h264, h265, av...
https://raw.githubusercontent.com/alexta69/metube/HEAD/app/dl_formats.py
Write beginner-friendly docstrings
#!/usr/bin/env python3 # pylint: disable=no-member,method-hidden import os import sys import asyncio from pathlib import Path from aiohttp import web from aiohttp.log import access_logger import ssl import socket import socketio import logging import json import pathlib import re from watchfiles import DefaultFilter, ...
--- +++ @@ -117,6 +117,11 @@ ) def frontend_safe(self) -> dict: + """Return only the config keys that are safe to expose to browser clients. + + Sensitive or server-only keys (YTDL_OPTIONS, file-system paths, TLS + settings, etc.) are intentionally excluded. + """ return ...
https://raw.githubusercontent.com/alexta69/metube/HEAD/app/main.py
Generate consistent documentation across files
import os import shutil import yt_dlp from collections import OrderedDict import shelve import time import asyncio import multiprocessing import logging import re import types import dbm import subprocess from typing import Any from functools import lru_cache import yt_dlp.networking.impersonate from yt_dlp.utils impo...
--- +++ @@ -24,6 +24,7 @@ @lru_cache(maxsize=None) def _compile_outtmpl_pattern(field: str) -> re.Pattern: + """Compile a regex pattern to match a specific field in an output template, including optional format specifiers.""" conversion_types = f"[{re.escape(STR_FORMAT_TYPES)}]" return re.compile(STR_FO...
https://raw.githubusercontent.com/alexta69/metube/HEAD/app/ytdl.py
Add well-formatted docstrings
from typing import Any, ClassVar, TypeVar import torch as th from gymnasium import spaces from torch.nn import functional as F from stable_baselines3.common.buffers import RolloutBuffer from stable_baselines3.common.on_policy_algorithm import OnPolicyAlgorithm from stable_baselines3.common.policies import ActorCritic...
--- +++ @@ -14,6 +14,48 @@ class A2C(OnPolicyAlgorithm): + """ + Advantage Actor Critic (A2C) + + Paper: https://arxiv.org/abs/1602.01783 + Code: This implementation borrows code from https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-gail and + and Stable Baselines (https://github.com/hill-a/stable...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/a2c/a2c.py
Add docstrings that explain purpose and usage
import io import pathlib import sys import time import warnings from copy import deepcopy from typing import Any, TypeVar import numpy as np import torch as th from gymnasium import spaces from stable_baselines3.common.base_class import BaseAlgorithm from stable_baselines3.common.buffers import DictReplayBuffer, NSte...
--- +++ @@ -25,6 +25,56 @@ class OffPolicyAlgorithm(BaseAlgorithm): + """ + The base for Off-Policy algorithms (ex: SAC/TD3) + + :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...) + :param env: The environment to learn from + (if registered in Gym, can be str. Can be None ...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/off_policy_algorithm.py
Generate consistent docstrings
import warnings import numpy as np import torch as th from gymnasium import spaces from torch.nn import functional as F def is_image_space_channels_first(observation_space: spaces.Box) -> bool: smallest_dimension = np.argmin(observation_space.shape).item() if smallest_dimension == 1: warnings.warn("T...
--- +++ @@ -7,6 +7,16 @@ def is_image_space_channels_first(observation_space: spaces.Box) -> bool: + """ + Check if an image observation space (see ``is_image_space``) + is channels-first (CxHxW, True) or channels-last (HxWxC, False). + + Use a heuristic that channel dimension is the smallest of the thr...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/preprocessing.py
Add docstrings for better understanding
from collections.abc import Callable import numpy as np import pandas as pd # import matplotlib # matplotlib.use('TkAgg') # Can change to 'Agg' for non-interactive mode from matplotlib import pyplot as plt from stable_baselines3.common.monitor import load_results X_TIMESTEPS = "timesteps" X_EPISODES = "episodes" X...
--- +++ @@ -17,18 +17,43 @@ def rolling_window(array: np.ndarray, window: int) -> np.ndarray: + """ + Apply a rolling window to a np.ndarray + + :param array: the input Array + :param window: length of the rolling window + :return: rolling window on the input array + """ shape = array.shape[:...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/results_plotter.py
Generate docstrings for this script
import sys import time import warnings from typing import Any, TypeVar import numpy as np import torch as th from gymnasium import spaces from stable_baselines3.common.base_class import BaseAlgorithm from stable_baselines3.common.buffers import DictRolloutBuffer, RolloutBuffer from stable_baselines3.common.callbacks ...
--- +++ @@ -19,6 +19,41 @@ class OnPolicyAlgorithm(BaseAlgorithm): + """ + The base for On-Policy algorithms (ex: A2C/PPO). + + :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...) + :param env: The environment to learn from (if registered in Gym, can be str) + :param learning_rate: The...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/on_policy_algorithm.py
Add well-formatted docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,14 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +In single GPU rollout, the sequences are generated directly by sampling from the model. +The output will co...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/rollout/naive/naive_rollout.py
Add docstrings following best practices
import os import warnings from abc import ABC, abstractmethod from collections.abc import Callable from typing import TYPE_CHECKING, Any import gymnasium as gym import numpy as np from stable_baselines3.common.logger import Logger try: from tqdm import TqdmExperimentalWarning # Remove experimental warning ...
--- +++ @@ -29,6 +29,11 @@ class BaseCallback(ABC): + """ + Base class for callback. + + :param verbose: Verbosity level: 0 for no output, 1 for info messages, 2 for debug messages + """ # The RL model # Type hint as string to avoid circular import @@ -61,6 +66,10 @@ # Type hint as str...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/callbacks.py
Add return value explanations in docstrings
from typing import SupportsFloat import gymnasium as gym import numpy as np from gymnasium import spaces from stable_baselines3.common.type_aliases import AtariResetReturn, AtariStepReturn try: import cv2 cv2.ocl.setUseOpenCL(False) except ImportError: cv2 = None # type: ignore[assignment] class Stic...
--- +++ @@ -15,6 +15,15 @@ class StickyActionEnv(gym.Wrapper[np.ndarray, int, np.ndarray, int]): + """ + Sticky action. + + Paper: https://arxiv.org/abs/1709.06009 + Official implementation: https://github.com/mgbellemare/Arcade-Learning-Environment + + :param env: Environment to wrap + :param act...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/atari_wrappers.py
Write docstrings that follow conventions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +The base tokenizer class, required for any hybrid engine based rollout or inference with vLLM. +""" from ab...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/rollout/tokenizer.py
Write docstrings for backend logic
import datetime import json import os import sys import tempfile import warnings from collections import defaultdict from collections.abc import Mapping, Sequence from io import TextIOBase from typing import Any, TextIO import matplotlib.figure import numpy as np import pandas import torch as th try: from torch.u...
--- +++ @@ -33,6 +33,12 @@ class Video: + """ + Video data class storing the video frames and the frame per seconds + + :param frames: frames to create the video from + :param fps: frames per second + """ def __init__(self, frames: th.Tensor, fps: float): self.frames = frames @@ -40,6...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/logger.py
Add docstrings explaining edge cases
import collections import copy import warnings from abc import ABC, abstractmethod from functools import partial from typing import Any, TypeVar import numpy as np import torch as th from gymnasium import spaces from torch import nn from stable_baselines3.common.distributions import ( BernoulliDistribution, ...
--- +++ @@ -1,3 +1,4 @@+"""Policies: abstract base class and concrete implementations.""" import collections import copy @@ -36,6 +37,26 @@ class BaseModel(nn.Module): + """ + The base model object: makes predictions in response to observations. + + In the case of policies, the prediction is an action....
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/policies.py
Add well-formatted docstrings
import base64 import functools import io import json import os import pathlib import pickle import warnings import zipfile from typing import Any import cloudpickle import torch as th import stable_baselines3 as sb3 from stable_baselines3.common.type_aliases import TensorDict from stable_baselines3.common.utils impo...
--- +++ @@ -1,3 +1,7 @@+""" +Save util taken from stable_baselines +used to serialize data (class parameters) of model classes +""" import base64 import functools @@ -19,6 +23,17 @@ def recursive_getattr(obj: Any, attr: str, *args) -> Any: + """ + Recursive version of getattr + taken from https://stack...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/save_util.py
Help me document legacy Python code
import warnings from typing import Any, ClassVar, TypeVar import numpy as np import torch as th from gymnasium import spaces from torch.nn import functional as F from stable_baselines3.common.buffers import ReplayBuffer from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm from stable_baselines...
--- +++ @@ -17,6 +17,51 @@ class DQN(OffPolicyAlgorithm): + """ + Deep Q-Network (DQN) + + Paper: https://arxiv.org/abs/1312.5602, https://www.nature.com/articles/nature14236 + Default hyperparameters are taken from the Nature paper, + except for the optimizer and learning rate that were taken from S...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/dqn/dqn.py
Add docstrings to clarify complex logic
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,19 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +The vllm_rollout that can be applied in different backend +When working with FSDP: +- Use DTensor weight lo...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/rollout/vllm_rollout/vllm_rollout.py
Generate docstrings for script automation
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Contains a resharding manager that binds weights from FSDP zero3 to XPerfGPT +""" from typing import Option...
https://raw.githubusercontent.com/Jiayi-Pan/TinyZero/HEAD/verl/workers/sharding_manager/fsdp_ulysses.py
Generate docstrings for each module
import gymnasium as gym import torch as th from gymnasium import spaces from torch import nn from stable_baselines3.common.preprocessing import get_flattened_obs_dim, is_image_space from stable_baselines3.common.type_aliases import TensorDict from stable_baselines3.common.utils import get_device class BaseFeaturesEx...
--- +++ @@ -9,6 +9,12 @@ class BaseFeaturesExtractor(nn.Module): + """ + Base class that represents a features extractor. + + :param observation_space: The observation space of the environment + :param features_dim: Number of features extracted. + """ def __init__(self, observation_space: gym....
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/torch_layers.py
Write docstrings describing each step
import warnings from abc import ABC, abstractmethod from collections.abc import Generator from typing import Any import numpy as np import torch as th from gymnasium import spaces from stable_baselines3.common.preprocessing import get_action_dim, get_obs_shape from stable_baselines3.common.type_aliases import ( D...
--- +++ @@ -25,6 +25,16 @@ class BaseBuffer(ABC): + """ + Base class that represent a buffer (rollout or replay) + + :param buffer_size: Max number of element in the buffer + :param observation_space: Observation space + :param action_space: Action space + :param device: PyTorch device + to...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/buffers.py
Help me document legacy Python code
import io import pathlib import time import warnings from abc import ABC, abstractmethod from collections import deque from collections.abc import Iterable from typing import Any, ClassVar, TypeVar import gymnasium as gym import numpy as np import torch as th from gymnasium import spaces from stable_baselines3.commo...
--- +++ @@ -1,3 +1,4 @@+"""Abstract base classes for RL algorithms.""" import io import pathlib @@ -45,6 +46,12 @@ def maybe_make_env(env: GymEnv | str, verbose: int) -> GymEnv: + """If env is a string, make the environment; otherwise, return env. + + :param env: The environment to learn from. + :param...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/base_class.py
Add docstrings that explain inputs and outputs
from collections.abc import Callable, Iterable from typing import Any import torch from torch.optim import Optimizer class RMSpropTFLike(Optimizer): def __init__( self, params: Iterable[torch.nn.Parameter], lr: float = 1e-2, alpha: float = 0.99, eps: float = 1e-8, ...
--- +++ @@ -6,6 +6,43 @@ class RMSpropTFLike(Optimizer): + r"""Implements RMSprop algorithm with closer match to Tensorflow version. + + For reproducibility with original stable-baselines. Use this + version with e.g. A2C for stabler learning than with the PyTorch + RMSProp. Based on the PyTorch v1.5.0 ...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/sb2_compat/rmsprop_tf_like.py
Annotate my code with docstrings
import copy from abc import ABC, abstractmethod from collections.abc import Iterable import numpy as np from numpy.typing import DTypeLike class ActionNoise(ABC): def __init__(self) -> None: super().__init__() def reset(self) -> None: pass @abstractmethod def __call__(self) -> np.n...
--- +++ @@ -7,11 +7,17 @@ class ActionNoise(ABC): + """ + The action noise base class + """ def __init__(self) -> None: super().__init__() def reset(self) -> None: + """ + Call end of episode reset for the noise + """ pass @abstractmethod @@ -20,6...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/noise.py
Fill in missing docstrings in my code
import os import os.path from collections.abc import Callable import numpy as np from gymnasium import error, logger from stable_baselines3.common.vec_env.base_vec_env import VecEnv, VecEnvObs, VecEnvStepReturn, VecEnvWrapper from stable_baselines3.common.vec_env.dummy_vec_env import DummyVecEnv from stable_baselines...
--- +++ @@ -11,6 +11,23 @@ class VecVideoRecorder(VecEnvWrapper): + """ + Wraps a VecEnv or VecEnvWrapper object to record rendered image as mp4 video. + It requires ffmpeg or avconv to be installed on the machine. + + Note: for now it only allows to record one video and all videos + must have at lea...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/vec_video_recorder.py
Add docstrings to make code maintainable
__all__ = ["Monitor", "ResultsWriter", "get_monitor_files", "load_results"] import csv import json import os import time from glob import glob from typing import Any, SupportsFloat import gymnasium as gym import pandas from gymnasium.core import ActType, ObsType class Monitor(gym.Wrapper[ObsType, ActType, ObsType, ...
--- +++ @@ -13,6 +13,18 @@ class Monitor(gym.Wrapper[ObsType, ActType, ObsType, ActType]): + """ + A monitor wrapper for Gym environments, it is used to know the episode reward, length, time and other data. + + :param env: The environment + :param filename: the location to save a log file, can be None f...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/monitor.py
Annotate my code with docstrings
import gymnasium as gym import numpy as np from gymnasium import spaces from stable_baselines3.common.type_aliases import GymStepReturn class SimpleMultiObsEnv(gym.Env): def __init__( self, num_col: int = 4, num_row: int = 4, random_start: bool = True, discrete_actions: b...
--- +++ @@ -6,6 +6,32 @@ class SimpleMultiObsEnv(gym.Env): + """ + Base class for GridWorld-based MultiObs Environments 4x4 grid world. + + .. code-block:: text + + ____________ + | 0 1 2 3| + | 4|¯5¯¯6¯| 7| + | 8|_9_10_|11| + |12 13 14 15| + ¯¯¯¯¯¯¯¯¯¯¯¯¯¯ + + ...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/envs/multi_input_envs.py
Create documentation for each function signature
import numpy as np class RunningMeanStd: def __init__(self, epsilon: float = 1e-4, shape: tuple[int, ...] = ()): self.mean = np.zeros(shape, np.float64) self.var = np.ones(shape, np.float64) self.count = epsilon def copy(self) -> "RunningMeanStd": new_object = RunningMeanStd(s...
--- +++ @@ -3,11 +3,21 @@ class RunningMeanStd: def __init__(self, epsilon: float = 1e-4, shape: tuple[int, ...] = ()): + """ + Calculates the running mean and std of a data stream + https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm + + :param epsilo...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/running_mean_std.py
Create simple docstrings for beginners
import warnings from typing import Any, ClassVar, TypeVar import numpy as np import torch as th from gymnasium import spaces from torch.nn import functional as F from stable_baselines3.common.buffers import RolloutBuffer from stable_baselines3.common.on_policy_algorithm import OnPolicyAlgorithm from stable_baselines3...
--- +++ @@ -16,6 +16,60 @@ class PPO(OnPolicyAlgorithm): + """ + Proximal Policy Optimization algorithm (PPO) (clip version) + + Paper: https://arxiv.org/abs/1707.06347 + Code: This implementation borrows code from OpenAI Spinning Up (https://github.com/openai/spinningup/) + https://github.com/ikostr...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/ppo/ppo.py
Write Python docstrings for this snippet
from typing import Any, Generic, TypeVar import gymnasium as gym import numpy as np from gymnasium import spaces from stable_baselines3.common.type_aliases import GymStepReturn T = TypeVar("T", int, np.ndarray) class IdentityEnv(gym.Env, Generic[T]): def __init__(self, dim: int | None = None, space: spaces.Spa...
--- +++ @@ -11,6 +11,16 @@ class IdentityEnv(gym.Env, Generic[T]): def __init__(self, dim: int | None = None, space: spaces.Space | None = None, ep_length: int = 100): + """ + Identity environment for testing purposes + + :param dim: the size of the action and observation dimension you want ...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/envs/identity_env.py
Document helper functions with docstrings
from typing import Any import torch as th from gymnasium import spaces from torch import nn from stable_baselines3.common.policies import BasePolicy from stable_baselines3.common.torch_layers import ( BaseFeaturesExtractor, CombinedExtractor, FlattenExtractor, NatureCNN, create_mlp, ) from stable_...
--- +++ @@ -16,6 +16,16 @@ class QNetwork(BasePolicy): + """ + Action-Value (Q-Value) network for DQN + + :param observation_space: Observation space + :param action_space: Action space + :param net_arch: The specification of the policy and value networks. + :param activation_fn: Activation functi...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/dqn/policies.py
Help me comply with documentation standards
from collections import OrderedDict from typing import Any import numpy as np from gymnasium import Env, spaces from gymnasium.envs.registration import EnvSpec from stable_baselines3.common.type_aliases import GymStepReturn class BitFlippingEnv(Env): spec = EnvSpec("BitFlippingEnv-v0", "no-entry-point") st...
--- +++ @@ -9,6 +9,23 @@ class BitFlippingEnv(Env): + """ + Simple bit flipping env, useful to test HER. + The goal is to flip all the bits to get a vector of ones. + In the continuous variant, if the ith action component has a value > 0, + then the ith bit will be flipped. Uses a ``MultiBinary`` obs...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/envs/bit_flipping_env.py
Add docstrings that explain purpose and usage
import warnings from typing import Any import gymnasium as gym import numpy as np from gymnasium import spaces from stable_baselines3.common.preprocessing import check_for_nested_spaces, is_image_space_channels_first from stable_baselines3.common.vec_env import DummyVecEnv, VecCheckNan def _is_oneof_space(space: sp...
--- +++ @@ -10,6 +10,10 @@ def _is_oneof_space(space: spaces.Space) -> bool: + """ + Return True if the provided space is a OneOf space, + False if not or if the current version of Gym doesn't support this space. + """ try: return isinstance(space, spaces.OneOf) # type: ignore[attr-define...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/env_checker.py
Generate helpful docstrings for debugging
from typing import Any import torch as th from gymnasium import spaces from torch import nn from stable_baselines3.common.distributions import SquashedDiagGaussianDistribution, StateDependentNoiseDistribution from stable_baselines3.common.policies import BasePolicy, ContinuousCritic from stable_baselines3.common.prep...
--- +++ @@ -23,6 +23,27 @@ class Actor(BasePolicy): + """ + Actor network (policy) for SAC. + + :param observation_space: Observation space + :param action_space: Action space + :param net_arch: Network architecture + :param features_extractor: Network to extract features + (a CNN when usin...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/sac/policies.py
Add inline docstrings for readability
import glob import os import platform import random import re import warnings from collections import deque from collections.abc import Iterable import cloudpickle import gymnasium as gym import numpy as np import torch as th from gymnasium import spaces import stable_baselines3 as sb3 # Check if tensorboard is avai...
--- +++ @@ -26,6 +26,12 @@ def set_random_seed(seed: int, using_cuda: bool = False) -> None: + """ + Seed the different random generators. + + :param seed: + :param using_cuda: + """ # Seed python RNG random.seed(seed) # Seed numpy RNG @@ -41,17 +47,44 @@ # From stable baselines def...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/utils.py
Create simple docstrings for beginners
import librosa import librosa.filters import numpy as np # import tensorflow as tf from scipy import signal from scipy.io import wavfile from hparams import hparams as hp def load_wav(path, sr): return librosa.core.load(path, sr=sr)[0] def save_wav(wav, path, sr): wav *= 32767 / max(0.01, np.max(np.abs(wav)))...
--- +++ @@ -63,6 +63,8 @@ ########################################################## #Those are only correct when using lws!!! (This was messing with Wavenet quality for a long time!) def num_frames(length, fsize, fshift): + """Compute number of time frames of spectrogram + """ pad = (fsize - fshift) ...
https://raw.githubusercontent.com/Rudrabha/Wav2Lip/HEAD/audio.py
Write docstrings for algorithm functions
from abc import ABC, abstractmethod from typing import Any, Optional, TypeVar import numpy as np import torch as th from gymnasium import spaces from torch import nn from torch.distributions import Bernoulli, Categorical, Normal from torch.distributions import Distribution as TorchDistribution from stable_baselines3...
--- +++ @@ -1,3 +1,4 @@+"""Probability distributions.""" from abc import ABC, abstractmethod from typing import Any, Optional, TypeVar @@ -23,6 +24,7 @@ class Distribution(ABC): + """Abstract base class for distributions.""" distribution: TorchDistribution | list[TorchDistribution] @@ -31,35 +33,90 ...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/distributions.py
Add docstrings following best practices
import logging import glob from tqdm import tqdm import numpy as np import torch import cv2 class FaceDetector(object): def __init__(self, device, verbose): self.device = device self.verbose = verbose if verbose: if 'cpu' in device: logger = logging.getLogger(...
--- +++ @@ -7,6 +7,13 @@ class FaceDetector(object): + """An abstract class representing a face detector. + + Any other face detection implementation must subclass it. All subclasses + must implement ``detect_from_image``, that return a list of detected + bounding boxes. Optionally, for speed considerat...
https://raw.githubusercontent.com/Rudrabha/Wav2Lip/HEAD/face_detection/detection/core.py
Generate docstrings with examples
import inspect import warnings from abc import ABC, abstractmethod from collections.abc import Iterable, Sequence from copy import deepcopy from typing import Any, Union import cloudpickle import gymnasium as gym import numpy as np from gymnasium import spaces # Define type aliases here to avoid circular import # Use...
--- +++ @@ -22,6 +22,15 @@ def tile_images(images_nhwc: Sequence[np.ndarray]) -> np.ndarray: # pragma: no cover + """ + Tile N images into one big PxQ image + (P,Q) are chosen to be as close as possible, and if N + is square, then P=Q. + + :param images_nhwc: list or array of images, ndim=4 once tur...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/base_vec_env.py
Improve documentation using docstrings
from typing import Any import torch as th from gymnasium import spaces from torch import nn from stable_baselines3.common.policies import BasePolicy, ContinuousCritic from stable_baselines3.common.preprocessing import get_action_dim from stable_baselines3.common.torch_layers import ( BaseFeaturesExtractor, Co...
--- +++ @@ -18,6 +18,19 @@ class Actor(BasePolicy): + """ + Actor network (policy) for TD3. + + :param observation_space: Observation space + :param action_space: Action space + :param net_arch: Network architecture + :param features_extractor: Network to extract features + (a CNN when usin...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/td3/policies.py
Document my Python code with docstrings
import os from collections.abc import Callable from typing import Any import gymnasium as gym from stable_baselines3.common.atari_wrappers import AtariWrapper from stable_baselines3.common.monitor import Monitor from stable_baselines3.common.vec_env import DummyVecEnv, SubprocVecEnv, VecEnv from stable_baselines3.com...
--- +++ @@ -11,6 +11,13 @@ def unwrap_wrapper(env: gym.Env, wrapper_class: type[gym.Wrapper]) -> gym.Wrapper | None: + """ + Retrieve a ``VecEnvWrapper`` object by recursively searching. + + :param env: Environment to unwrap + :param wrapper_class: Wrapper to look for + :return: Environment unwrapped...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/env_util.py
Write beginner-friendly docstrings
from copy import deepcopy from typing import TypeVar from stable_baselines3.common.vec_env.base_vec_env import CloudpickleWrapper, VecEnv, VecEnvWrapper from stable_baselines3.common.vec_env.dummy_vec_env import DummyVecEnv from stable_baselines3.common.vec_env.stacked_observations import StackedObservations from stab...
--- +++ @@ -17,6 +17,13 @@ def unwrap_vec_wrapper(env: VecEnv, vec_wrapper_class: type[VecEnvWrapperT]) -> VecEnvWrapperT | None: + """ + Retrieve a ``VecEnvWrapper`` object by recursively searching. + + :param env: The ``VecEnv`` that is going to be unwrapped + :param vec_wrapper_class: The desired ``V...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/__init__.py
Add documentation for all methods
import warnings from inspect import signature from typing import Union import gymnasium try: import gym gym_installed = True except ImportError: gym_installed = False def _patch_env(env: Union["gym.Env", gymnasium.Env]) -> gymnasium.Env: # pragma: no cover # Gymnasium env, no patching to be done ...
--- +++ @@ -13,6 +13,17 @@ def _patch_env(env: Union["gym.Env", gymnasium.Env]) -> gymnasium.Env: # pragma: no cover + """ + Adapted from https://github.com/thu-ml/tianshou. + + Takes an environment and patches it to return Gymnasium env. + This function takes the environment object and returns a patch...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/patch_gym.py
Add docstrings with type hints explained
from __future__ import print_function import os import sys import cv2 import random import datetime import time import math import argparse import numpy as np import torch try: from iou import IOU except BaseException: # IOU cython speedup 10x def IOU(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2): sa = a...
--- +++ @@ -65,6 +65,17 @@ def encode(matched, priors, variances): + """Encode the variances from the priorbox layers into the ground truth boxes + we have matched (based on jaccard overlap) with the prior boxes. + Args: + matched: (tensor) Coords of ground truth for each prior in point-form + ...
https://raw.githubusercontent.com/Rudrabha/Wav2Lip/HEAD/face_detection/detection/sfd/bbox.py
Turn comments into proper docstrings
import warnings from collections import OrderedDict from collections.abc import Callable, Sequence from copy import deepcopy from typing import Any import gymnasium as gym import numpy as np from stable_baselines3.common.vec_env.base_vec_env import VecEnv, VecEnvIndices, VecEnvObs, VecEnvStepReturn from stable_baseli...
--- +++ @@ -13,6 +13,17 @@ class DummyVecEnv(VecEnv): + """ + Creates a simple vectorized wrapper for multiple environments, calling each environment in sequence on the current + Python process. This is useful for computationally simple environment such as ``Cartpole-v1``, + as the overhead of multiproc...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/dummy_vec_env.py
Create structured documentation for my script
import multiprocessing as mp import warnings from collections.abc import Callable, Sequence from typing import Any import gymnasium as gym import numpy as np from gymnasium import spaces from stable_baselines3.common.vec_env.base_vec_env import ( CloudpickleWrapper, VecEnv, VecEnvIndices, VecEnvObs, ...
--- +++ @@ -77,6 +77,28 @@ class SubprocVecEnv(VecEnv): + """ + Creates a multiprocess vectorized wrapper for multiple environments, distributing each environment to its own + process, allowing significant speed up when the environment is computationally complex. + + For performance reasons, if your env...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/subproc_vec_env.py
Improve documentation using docstrings
import mimetypes import os import time import warnings from typing import ( overload, TYPE_CHECKING, Optional, Union, Iterator, Generator, Iterable, Dict, ) from urllib.parse import urlparse from functools import partial from docarray import DocumentArray if TYPE_CHECKING: import nu...
--- +++ @@ -24,6 +24,14 @@ class Client: def __init__(self, server: str, credential: dict = {}, **kwargs): + """Create a Clip client object that connects to the Clip server. + Server scheme is in the format of ``scheme://netloc:port``, where + - scheme: one of grpc, websocket, http, grpc...
https://raw.githubusercontent.com/jina-ai/clip-as-service/HEAD/client/clip_client/client.py
Generate consistent docstrings
import warnings from collections.abc import Mapping from typing import Any, Generic, TypeVar import numpy as np from gymnasium import spaces from stable_baselines3.common.preprocessing import is_image_space, is_image_space_channels_first TObs = TypeVar("TObs", np.ndarray, dict[str, np.ndarray]) class StackedObserv...
--- +++ @@ -11,6 +11,19 @@ class StackedObservations(Generic[TObs]): + """ + Frame stacking wrapper for data. + + Dimension to stack over is either first (channels-first) or last (channels-last), which is detected automatically using + ``common.preprocessing.is_image_space_channels_first`` if observatio...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/stacked_observations.py
Add minimal docstrings for each function
from typing import Any import numpy as np from gymnasium import spaces from stable_baselines3.common.preprocessing import check_for_nested_spaces from stable_baselines3.common.vec_env.base_vec_env import VecEnvObs def dict_to_obs(obs_space: spaces.Space, obs_dict: dict[Any, np.ndarray]) -> VecEnvObs: if isinst...
--- +++ @@ -1,3 +1,6 @@+""" +Helpers for dealing with vectorized environments. +""" from typing import Any @@ -9,6 +12,16 @@ def dict_to_obs(obs_space: spaces.Space, obs_dict: dict[Any, np.ndarray]) -> VecEnvObs: + """ + Convert an internal representation raw_obs into the appropriate type + specified ...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/util.py
Provide docstrings following PEP 257
import inspect import pickle from copy import deepcopy from typing import Any import numpy as np from gymnasium import spaces from stable_baselines3.common import utils from stable_baselines3.common.preprocessing import is_image_space from stable_baselines3.common.running_mean_std import RunningMeanStd from stable_ba...
--- +++ @@ -13,6 +13,21 @@ class VecNormalize(VecEnvWrapper): + """ + A moving average, normalizing wrapper for vectorized environment. + has support for saving/loading moving average, + + :param venv: the vectorized environment to wrap + :param training: Whether to update or not the moving average +...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/vec_normalize.py
Write documentation strings for class attributes
import warnings import numpy as np from gymnasium import spaces from stable_baselines3.common.vec_env.base_vec_env import VecEnv, VecEnvObs, VecEnvStepReturn, VecEnvWrapper class VecCheckNan(VecEnvWrapper): def __init__(self, venv: VecEnv, raise_exception: bool = False, warn_once: bool = True, check_inf: bool ...
--- +++ @@ -7,6 +7,15 @@ class VecCheckNan(VecEnvWrapper): + """ + NaN and inf checking wrapper for vectorized environment, will raise a warning by default, + allowing you to know from what the NaN of inf originated from. + + :param venv: the vectorized environment to wrap + :param raise_exception: W...
https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/vec_check_nan.py