file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
rllib/offline/json_writer.py
Python
from datetime import datetime import json import logging import numpy as np import os from six.moves.urllib.parse import urlparse import time try: from smart_open import smart_open except ImportError: smart_open = None from ray.rllib.policy.sample_batch import MultiAgentBatch from ray.rllib.offline.io_context...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/offline/mixed_input.py
Python
import numpy as np from ray.rllib.offline.input_reader import InputReader from ray.rllib.offline.json_reader import JsonReader from ray.rllib.utils.annotations import override, DeveloperAPI @DeveloperAPI class MixedInput(InputReader): """Mixes input from a number of other input sources. Examples: >>...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/offline/off_policy_estimator.py
Python
from collections import namedtuple import logging from ray.rllib.policy.sample_batch import MultiAgentBatch from ray.rllib.utils.annotations import DeveloperAPI logger = logging.getLogger(__name__) OffPolicyEstimate = namedtuple("OffPolicyEstimate", ["estimator_name", "metrics"]) @De...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/offline/output_writer.py
Python
from ray.rllib.utils.annotations import override from ray.rllib.utils.annotations import PublicAPI @PublicAPI class OutputWriter: """Writer object for saving experiences from policy evaluation.""" @PublicAPI def write(self, sample_batch): """Save a batch of experiences. Arguments: ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/offline/shuffled_input.py
Python
import logging import random from ray.rllib.offline.input_reader import InputReader from ray.rllib.utils.annotations import override, DeveloperAPI logger = logging.getLogger(__name__) @DeveloperAPI class ShuffledInput(InputReader): """Randomizes data over a sliding window buffer of N batches. This increase...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/offline/wis_estimator.py
Python
from ray.rllib.offline.off_policy_estimator import OffPolicyEstimator, \ OffPolicyEstimate from ray.rllib.utils.annotations import override class WeightedImportanceSamplingEstimator(OffPolicyEstimator): """The weighted step-wise IS estimator. Step-wise WIS estimator in https://arxiv.org/pdf/1511.03722.pd...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/__init__.py
Python
from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.optimizers.async_replay_optimizer import AsyncReplayOptimizer from ray.rllib.optimizers.async_samples_optimizer import AsyncSamplesOptimizer from ray.rllib.optimizers.async_gradients_optimizer import \ AsyncGradientsOptimizer from ray....
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/aso_aggregator.py
Python
"""Helper class for AsyncSamplesOptimizer.""" import numpy as np import random import ray from ray.rllib.utils.actors import TaskPool from ray.rllib.utils.annotations import override from ray.rllib.utils.memory import ray_get_and_free class Aggregator: """An aggregator collects and processes samples from worker...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/aso_learner.py
Python
"""Helper class for AsyncSamplesOptimizer.""" import threading from six.moves import queue from ray.rllib.evaluation.metrics import get_learner_stats from ray.rllib.optimizers.aso_minibatch_buffer import MinibatchBuffer from ray.rllib.utils.timer import TimerStat from ray.rllib.utils.window_stat import WindowStat ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/aso_minibatch_buffer.py
Python
"""Helper class for AsyncSamplesOptimizer.""" class MinibatchBuffer: """Ring buffer of recent data batches for minibatch SGD. This is for use with AsyncSamplesOptimizer. """ def __init__(self, inqueue, size, timeout, num_passes, init_num_passes=1): """Initialize a minibatch buffer. ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/aso_multi_gpu_learner.py
Python
"""Helper class for AsyncSamplesOptimizer.""" import logging import threading import math from six.moves import queue from ray.rllib.evaluation.metrics import get_learner_stats from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID from ray.rllib.optimizers.aso_learner import LearnerThread from ray.rllib.optimi...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/aso_tree_aggregator.py
Python
"""Helper class for AsyncSamplesOptimizer.""" import collections import logging import os import time import ray from ray.rllib.utils.actors import TaskPool, create_colocated from ray.rllib.utils.annotations import override from ray.rllib.optimizers.aso_aggregator import Aggregator, \ AggregationWorkerBase from r...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/async_gradients_optimizer.py
Python
import ray from ray.rllib.evaluation.metrics import get_learner_stats from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.utils.annotations import override from ray.rllib.utils.timer import TimerStat from ray.rllib.utils.memory import ray_get_and_free class AsyncGradientsOptimizer(PolicyO...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/async_replay_optimizer.py
Python
"""Implements Distributed Prioritized Experience Replay. https://arxiv.org/abs/1803.00933""" import collections import os import random import time import threading import numpy as np from six.moves import queue import ray from ray.rllib.evaluation.metrics import get_learner_stats from ray.rllib.policy.sample_batch...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/async_samples_optimizer.py
Python
"""Implements the IMPALA asynchronous sampling architecture. https://arxiv.org/abs/1802.01561""" import logging import time from ray.rllib.optimizers.aso_aggregator import SimpleAggregator from ray.rllib.optimizers.aso_tree_aggregator import TreeAggregator from ray.rllib.optimizers.aso_learner import LearnerThread f...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/microbatch_optimizer.py
Python
import logging import ray from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.policy.sample_batch import SampleBatch, DEFAULT_POLICY_ID, \ MultiAgentBatch from ray.rllib.utils.annotations import override from ray.rllib.utils.filter import RunningStat from ray.rllib.utils.timer import T...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/multi_gpu_impl.py
Python
from collections import namedtuple import logging from ray.rllib.utils.debug import log_once, summarize from ray.rllib.utils import try_import_tf tf = try_import_tf() # Variable scope in which created variables will be placed under TOWER_SCOPE_NAME = "tower" logger = logging.getLogger(__name__) class LocalSyncPar...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/multi_gpu_optimizer.py
Python
import logging import math import numpy as np from collections import defaultdict import ray from ray.rllib.evaluation.metrics import LEARNER_STATS_KEY from ray.rllib.policy.tf_policy import TFPolicy from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.optimizers.multi_gpu_impl import Local...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/policy_optimizer.py
Python
import logging from ray.rllib.utils.annotations import DeveloperAPI from ray.rllib.evaluation.metrics import collect_episodes, summarize_episodes logger = logging.getLogger(__name__) @DeveloperAPI class PolicyOptimizer: """Policy optimizers encapsulate distributed RL optimization strategies. Policy optimiz...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/replay_buffer.py
Python
import numpy as np import random import sys from ray.rllib.optimizers.segment_tree import SumSegmentTree, MinSegmentTree from ray.rllib.utils.annotations import DeveloperAPI from ray.rllib.utils.compression import unpack_if_needed from ray.rllib.utils.window_stat import WindowStat @DeveloperAPI class ReplayBuffer: ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/rollout.py
Python
import logging import ray from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.utils.memory import ray_get_and_free logger = logging.getLogger(__name__) def collect_samples(agents, sample_batch_size, num_envs_per_worker, train_batch_size): """Collects at least train_batch_siz...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/segment_tree.py
Python
import operator class SegmentTree: def __init__(self, capacity, operation, neutral_element): """Build a Segment Tree data structure. https://en.wikipedia.org/wiki/Segment_tree Can be used as regular array, but with two important differences: a) setting item's value is ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/sync_batch_replay_optimizer.py
Python
import random import ray from ray.rllib.evaluation.metrics import get_learner_stats from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.policy.sample_batch import SampleBatch, DEFAULT_POLICY_ID, \ MultiAgentBatch from ray.rllib.utils.annotations import override from ray.rllib.utils.tim...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/sync_replay_optimizer.py
Python
import logging import collections import numpy as np import ray from ray.rllib.optimizers.replay_buffer import ReplayBuffer, \ PrioritizedReplayBuffer from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.evaluation.metrics import get_learner_stats from ray.rllib.policy.sample_batch impo...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/sync_samples_optimizer.py
Python
import logging import random from collections import defaultdict import ray from ray.rllib.evaluation.metrics import LEARNER_STATS_KEY from ray.rllib.optimizers.multi_gpu_optimizer import _averaged from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.policy.sample_batch import SampleBatch, ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/optimizers/tests/test_segment_tree.py
Python
import numpy as np from ray.rllib.optimizers.segment_tree import SumSegmentTree, MinSegmentTree def test_tree_set(): tree = SumSegmentTree(4) tree[2] = 1.0 tree[3] = 3.0 assert np.isclose(tree.sum(), 4.0) assert np.isclose(tree.sum(0, 2), 0.0) assert np.isclose(tree.sum(0, 3), 1.0) asse...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/__init__.py
Python
from ray.rllib.policy.policy import Policy from ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.policy.tf_policy import TFPolicy from ray.rllib.policy.torch_policy_template import build_torch_policy from ray.rllib.policy.tf_policy_template import build_tf_policy __all__ = [ "Policy", "TFPolicy"...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/dynamic_tf_policy.py
Python
"""Graph mode TF policy built using build_tf_policy().""" from collections import OrderedDict import logging import numpy as np from ray.rllib.policy.policy import Policy from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.tf_policy import TFPolicy from ray.rllib.models.catalog import ModelCat...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/eager_tf_policy.py
Python
"""Eager mode TF policy built using build_tf_policy(). It supports both traced and non-traced eager execution modes.""" import logging import functools import numpy as np from ray.rllib.evaluation.episode import _flatten_action from ray.rllib.models.catalog import ModelCatalog from ray.rllib.policy.policy import Pol...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/policy.py
Python
from abc import ABCMeta, abstractmethod from collections import namedtuple import gym import numpy as np from ray.rllib.utils.annotations import DeveloperAPI # By convention, metrics from optimizing the loss can be reported in the # `grad_info` dict returned by learn_on_batch() / compute_grads() via this key. LEARNER...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/rnn_sequencing.py
Python
"""RNN utils for RLlib. The main trick here is that we add the time dimension at the last moment. The non-LSTM layers of the model see their inputs as one flat batch. Before the LSTM cell, we reshape the input to add the expected time dimension. During postprocessing, we dynamically pad the experience batches so that ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/sample_batch.py
Python
import six import collections import numpy as np from ray.rllib.utils.annotations import PublicAPI, DeveloperAPI from ray.rllib.utils.compression import pack, unpack, is_compressed from ray.rllib.utils.memory import concat_aligned # Default policy id for single agent environments DEFAULT_POLICY_ID = "default_policy" ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/tests/test_policy.py
Python
import random from ray.rllib.policy.policy import Policy class TestPolicy(Policy): """ A dummy Policy that returns a random (batched) int for compute_actions and implements all other abstract methods of Policy with "pass". """ def compute_actions(self, obs_batch, ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/tf_policy.py
Python
import errno import logging import os import numpy as np import ray import ray.experimental.tf_utils from ray.rllib.policy.policy import Policy, LEARNER_STATS_KEY, \ ACTION_PROB, ACTION_LOGP from ray.rllib.policy.rnn_sequencing import chop_into_sequences from ray.rllib.policy.sample_batch import SampleBatch from r...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/tf_policy_template.py
Python
from ray.rllib.policy.dynamic_tf_policy import DynamicTFPolicy from ray.rllib.policy import eager_tf_policy from ray.rllib.policy.policy import Policy, LEARNER_STATS_KEY from ray.rllib.policy.tf_policy import TFPolicy from ray.rllib.utils import add_mixins from ray.rllib.utils.annotations import override, DeveloperAPI ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/torch_policy.py
Python
import numpy as np from ray.rllib.policy.policy import Policy, LEARNER_STATS_KEY from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.utils import try_import_torch from ray.rllib.utils.annotations import override, DeveloperAPI from ray.rllib.utils.tracking_dict import UsageTrackingDict from ray.rllib.u...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/policy/torch_policy_template.py
Python
from ray.rllib.policy.policy import Policy from ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.models.catalog import ModelCatalog from ray.rllib.utils import add_mixins from ray.rllib.utils.annotations import override, DeveloperAPI @DeveloperAPI def build_torch_policy(name, los...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/rollout.py
Python
#!/usr/bin/env python import argparse import collections import json import os import pickle import shelve from pathlib import Path import gym import ray from ray.rllib.agents.registry import get_agent_class from ray.rllib.env import MultiAgentEnv from ray.rllib.env.base_env import _DUMMY_AGENT_ID from ray.rllib.eval...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/scripts.py
Python
#!/usr/bin/env python import argparse from ray.rllib import train from ray.rllib import rollout EXAMPLE_USAGE = """ Example usage for training: rllib train --run DQN --env CartPole-v0 Example usage for rollout: rllib rollout /trial_dir/checkpoint_1/checkpoint-1 --run DQN """ def cli(): parser = argpar...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/mock_worker.py
Python
import numpy as np from ray.rllib.evaluation import SampleBatch from ray.rllib.utils.filter import MeanStdFilter class _MockWorker: def __init__(self, sample_count=10): self._weights = np.array([-10, -10, -10, -10]) self._grad = np.array([1, 1, 1, 1]) self._sample_count = sample_count ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/multiagent_pendulum.py
Python
"""Integration test: (1) pendulum works, (2) single-agent multi-agent works.""" import ray from ray.rllib.tests.test_multi_agent_env import make_multiagent from ray.tune import run_experiments from ray.tune.registry import register_env if __name__ == "__main__": ray.init() MultiPendulum = make_multiagent("Pen...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/run_regression_tests.py
Python
#!/usr/bin/env python # Runs one or more regression tests. Retries tests up to 3 times. # # Example usage: # ./run_regression_tests.sh regression-tests/cartpole-es.yaml import yaml import sys import ray from ray.tune import run_experiments if __name__ == "__main__": ray.init() for test in sys.argv[1:]: ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_avail_actions_qmix.py
Python
import numpy as np from gym.spaces import Tuple, Discrete, Dict, Box import ray from ray.tune import register_env from ray.rllib.env.multi_agent_env import MultiAgentEnv from ray.rllib.agents.qmix import QMixTrainer class AvailActionsTestEnv(MultiAgentEnv): action_space = Discrete(10) observation_space = Dic...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_catalog.py
Python
import gym import numpy as np import unittest from gym.spaces import Box, Discrete, Tuple import ray from ray.rllib.models import ModelCatalog, MODEL_DEFAULTS from ray.rllib.models.model import Model from ray.rllib.models.tf.tf_action_dist import TFActionDistribution from ray.rllib.models.preprocessors import (NoPrep...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_checkpoint_restore.py
Python
#!/usr/bin/env python import os import shutil import gym import numpy as np import ray from ray.rllib.agents.registry import get_agent_class from ray.tune.trial import ExportFormat def get_mean_action(alg, obs): out = [] for _ in range(2000): out.append(float(alg.compute_action(obs))) return np....
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_dependency.py
Python
#!/usr/bin/env python import os import sys os.environ["RLLIB_TEST_NO_TF_IMPORT"] = "1" if __name__ == "__main__": from ray.rllib.agents.a3c import A2CTrainer assert "tensorflow" not in sys.modules, "TF initially present" # note: no ray.init(), to test it works without Ray trainer = A2CTrainer( ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_eager_support.py
Python
import unittest import ray from ray import tune from ray.rllib.agents.registry import get_agent_class def check_support(alg, config, test_trace=True): config["eager"] = True if alg in ["APEX_DDPG", "TD3", "DDPG", "SAC"]: config["env"] = "Pendulum-v0" else: config["env"] = "CartPole-v0" ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_env_with_subprocess.py
Python
"""Tests that envs clean up after themselves on agent exit.""" from gym.spaces import Discrete import atexit import gym import os import subprocess import tempfile import time import ray from ray.tune import run_experiments from ray.tune.registry import register_env # Dummy command to run as a subprocess with a uniq...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_evaluators.py
Python
import unittest import ray from ray.rllib.agents.dqn import DQNTrainer from ray.rllib.agents.a3c import A3CTrainer from ray.rllib.agents.dqn.dqn_policy import _adjust_nstep from ray.tune.registry import register_env import gym class EvalTest(unittest.TestCase): def testDqnNStep(self): obs = [1, 2, 3, 4, ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_external_env.py
Python
import gym import numpy as np import random import unittest import uuid import ray from ray.rllib.agents.dqn import DQNTrainer from ray.rllib.agents.pg import PGTrainer from ray.rllib.evaluation.rollout_worker import RolloutWorker from ray.rllib.env.external_env import ExternalEnv from ray.rllib.tests.test_rollout_wor...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_external_multi_agent_env.py
Python
import gym import numpy as np import random import unittest import ray from ray.rllib.agents.pg.pg_tf_policy import PGTFPolicy from ray.rllib.optimizers import SyncSamplesOptimizer from ray.rllib.evaluation.rollout_worker import RolloutWorker from ray.rllib.evaluation.worker_set import WorkerSet from ray.rllib.env.ext...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_filters.py
Python
import unittest import numpy as np import ray from ray.rllib.utils.filter import RunningStat, MeanStdFilter from ray.rllib.utils import FilterManager from ray.rllib.tests.mock_worker import _MockWorker class RunningStatTest(unittest.TestCase): def testRunningStat(self): for shp in ((), (3, ), (3, 4)): ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_ignore_worker_failure.py
Python
import gym import unittest import ray from ray.rllib import _register_all from ray.rllib.agents.registry import get_agent_class from ray.tune.registry import register_env class FaultInjectEnv(gym.Env): def __init__(self, config): self.env = gym.make("CartPole-v0") self.action_space = self.env.act...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_io.py
Python
import glob import gym import json import numpy as np import os import random import shutil import tempfile import time import unittest import ray from ray.rllib.agents.pg import PGTrainer from ray.rllib.agents.pg.pg_tf_policy import PGTFPolicy from ray.rllib.evaluation import SampleBatch from ray.rllib.offline import...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_legacy.py
Python
from ray.rllib.agents.ppo import PPOAgent from ray import tune import ray if __name__ == "__main__": ray.init() # Test legacy *Agent classes work (renamed to Trainer) tune.run( PPOAgent, config={"env": "CartPole-v0"}, stop={"training_iteration": 2})
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_local.py
Python
import unittest from ray.rllib.agents.ppo import PPOTrainer, DEFAULT_CONFIG import ray class LocalModeTest(unittest.TestCase): def testLocal(self): ray.init(local_mode=True) cf = DEFAULT_CONFIG.copy() agent = PPOTrainer(cf, "CartPole-v0") print(agent.train()) if __name__ == "__m...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_lstm.py
Python
import gym import numpy as np import pickle import unittest import ray from ray.rllib.agents.ppo import PPOTrainer from ray.rllib.policy.rnn_sequencing import chop_into_sequences, \ add_time_dimension from ray.rllib.models import ModelCatalog from ray.rllib.models.tf.misc import linear, normc_initializer from ray....
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_multi_agent_env.py
Python
import gym import random import unittest import ray from ray.rllib.agents.pg import PGTrainer from ray.rllib.agents.pg.pg_tf_policy import PGTFPolicy from ray.rllib.agents.dqn.dqn_policy import DQNTFPolicy from ray.rllib.optimizers import (SyncSamplesOptimizer, SyncReplayOptimizer, As...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_nested_spaces.py
Python
import pickle from gym import spaces from gym.envs.registration import EnvSpec import gym import unittest import ray from ray.rllib.agents.a3c import A2CTrainer from ray.rllib.agents.pg import PGTrainer from ray.rllib.agents.pg.pg_tf_policy import PGTFPolicy from ray.rllib.env import MultiAgentEnv from ray.rllib.env....
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_optimizers.py
Python
import gym import numpy as np import time import unittest import ray from ray.rllib.agents.ppo import PPOTrainer from ray.rllib.agents.ppo.ppo_policy import PPOTFPolicy from ray.rllib.evaluation import SampleBatch from ray.rllib.evaluation.rollout_worker import RolloutWorker from ray.rllib.evaluation.worker_set import...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_perf.py
Python
import gym import time import unittest import ray from ray.rllib.evaluation.rollout_worker import RolloutWorker from ray.rllib.tests.test_rollout_worker import MockPolicy class TestPerf(unittest.TestCase): # Tested on Intel(R) Core(TM) i7-4600U CPU @ 2.10GHz # 11/23/18: Samples per second 8501.125113727468 ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_reproducibility.py
Python
import unittest import ray from ray.rllib.agents.dqn import DQNTrainer from ray.tune.registry import register_env import numpy as np import gym class TestReproducibility(unittest.TestCase): def testReproducingTrajectory(self): class PickLargest(gym.Env): def __init__(self): se...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_rollout.sh
Shell
#!/bin/bash -e TRAIN=/ray/rllib/train.py if [ ! -e "$TRAIN" ]; then TRAIN=../train.py fi ROLLOUT=/ray/rllib/rollout.py if [ ! -e "$ROLLOUT" ]; then ROLLOUT=../rollout.py fi TMP=`mktemp -d` echo "Saving results to $TMP" $TRAIN --local-dir=$TMP --run=IMPALA --checkpoint-freq=1 \ --config='{"num_workers": 1...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_rollout_worker.py
Python
import gym import numpy as np import random import time import unittest from collections import Counter import ray from ray.rllib.agents.pg import PGTrainer from ray.rllib.agents.a3c import A2CTrainer from ray.rllib.evaluation.rollout_worker import RolloutWorker from ray.rllib.evaluation.metrics import collect_metrics...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/tests/test_supported_spaces.py
Python
import unittest import traceback import gym from gym.spaces import Box, Discrete, Tuple, Dict, MultiDiscrete from gym.envs.registration import EnvSpec import numpy as np import sys import ray from ray.rllib.agents.registry import get_agent_class from ray.rllib.models.tf.fcnet_v2 import FullyConnectedNetwork as FCNetV...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/train.py
Python
#!/usr/bin/env python import argparse import yaml import ray from ray.cluster_utils import Cluster from ray.tune.config_parser import make_parser from ray.tune.result import DEFAULT_RESULTS_DIR from ray.tune.resources import resources_to_json from ray.tune.tune import _make_scheduler, run_experiments from ray.rllib.u...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/__init__.py
Python
from ray.rllib.utils.annotations import override, PublicAPI, DeveloperAPI from ray.rllib.utils.framework import try_import_tf, try_import_tfp, \ try_import_torch from ray.rllib.utils.deprecation import deprecation_warning, renamed_agent, \ renamed_class, renamed_function from ray.rllib.utils.filter_manager impo...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/actors.py
Python
import logging import os import ray logger = logging.getLogger(__name__) class TaskPool: """Helper class for tracking the status of many in-flight actor tasks.""" def __init__(self): self._tasks = {} self._objects = {} self._fetching = [] def add(self, worker, all_obj_ids): ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/annotations.py
Python
def override(cls): """Annotation for documenting method overrides. Arguments: cls (type): The superclass that provides the overriden method. If this cls does not actually have the method, an error is raised. """ def check_override(method): if method.__name__ not in dir(cls)...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/compression.py
Python
from ray.rllib.utils.annotations import DeveloperAPI import logging import time import base64 import numpy as np import pyarrow from six import string_types logger = logging.getLogger(__name__) try: import lz4.frame LZ4_ENABLED = True except ImportError: logger.warning("lz4 not available, disabling sampl...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/debug.py
Python
import numpy as np import pprint import time from ray.rllib.policy.sample_batch import SampleBatch, MultiAgentBatch _logged = set() _disabled = False _periodic_log = False _last_logged = 0.0 _printer = pprint.PrettyPrinter(indent=2, width=60) def log_once(key): """Returns True if this is the "first" call for a ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/deprecation.py
Python
import logging logger = logging.getLogger(__name__) def deprecation_warning(old, new=None): logger.warning( "DeprecationWarning: `{}` has been deprecated.".format(old) + (" Use `{}` instead." if new else "") + " This will raise an error in the future!" ) def renamed_class(cls, old_...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/error.py
Python
from ray.rllib.utils.annotations import PublicAPI @PublicAPI class UnsupportedSpaceException(Exception): """Error for an unsupported action or observation space.""" pass
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/explained_variance.py
Python
from ray.rllib.utils import try_import_tf, try_import_torch tf = try_import_tf() torch, nn = try_import_torch() def explained_variance(y, pred, framework="tf"): if framework == "tf": _, y_var = tf.nn.moments(y, axes=[0]) _, diff_var = tf.nn.moments(y - pred, axes=[0]) return tf.maximum(-1...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/filter.py
Python
import logging import numpy as np import threading logger = logging.getLogger(__name__) class Filter: """Processes input, possibly statefully.""" def apply_changes(self, other, *args, **kwargs): """Updates self with "new state" from other filter.""" raise NotImplementedError def copy(se...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/filter_manager.py
Python
import ray from ray.rllib.utils.annotations import DeveloperAPI from ray.rllib.utils.memory import ray_get_and_free @DeveloperAPI class FilterManager: """Manages filters and coordination across remote evaluators that expose `get_filters` and `sync_filters`. """ @staticmethod @DeveloperAPI ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/framework.py
Python
import logging import os logger = logging.getLogger(__name__) def try_import_tf(): """ Returns: The tf module (either from tf2.0.compat.v1 OR as tf1.x. """ if "RLLIB_TEST_NO_TF_IMPORT" in os.environ: logger.warning("Not importing TensorFlow for test purposes") return None ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/memory.py
Python
import numpy as np import time import ray FREE_DELAY_S = 10.0 MAX_FREE_QUEUE_SIZE = 100 _last_free_time = 0.0 _to_free = [] def ray_get_and_free(object_ids): """Call ray.get and then queue the object ids for deletion. This function should be used whenever possible in RLlib, to optimize memory usage. Th...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/numpy.py
Python
import numpy as np SMALL_NUMBER = 1e-6 # Some large int number. May be increased here, if needed. LARGE_INTEGER = 100000000 # Min and Max outputs (clipped) from an NN-output layer interpreted as the # log(x) of some x (e.g. a stddev of a normal # distribution). MIN_LOG_NN_OUTPUT = -20 MAX_LOG_NN_OUTPUT = 2 def sigm...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/policy_client.py
Python
import logging import pickle from ray.rllib.utils.annotations import PublicAPI logger = logging.getLogger(__name__) try: import requests # `requests` is not part of stdlib. except ImportError: requests = None logger.warning( "Couldn't import `requests` library. Be sure to install it on" ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/policy_server.py
Python
import pickle import traceback from http.server import SimpleHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn from ray.rllib.utils.annotations import PublicAPI from ray.rllib.utils.policy_client import PolicyClient @PublicAPI class PolicyServer(ThreadingMixIn, HTTPServer): """REST server t...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/schedules.py
Python
"""This file is used for specifying various schedules that evolve over time throughout the execution of the algorithm, such as: - learning rate for the optimizer - exploration epsilon for the epsilon greedy exploration strategy - beta parameter for beta parameter in prioritized replay Each schedule has a function `...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/seed.py
Python
import numpy as np import random from ray.rllib.utils import try_import_tf tf = try_import_tf() def seed(np_seed=0, random_seed=0, tf_seed=0): np.random.seed(np_seed) random.seed(random_seed) tf.set_random_seed(tf_seed)
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/test_utils.py
Python
import numpy as np from ray.rllib.utils.framework import try_import_tf tf = try_import_tf() def check(x, y, decimals=5, atol=None, rtol=None, false=False): """ Checks two structures (dict, tuple, list, np.array, float, int, etc..) for (almost) numeric identity. All numbers in the two structures have...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/tf_ops.py
Python
from ray.rllib.utils import try_import_tf tf = try_import_tf() def huber_loss(x, delta=1.0): """Reference: https://en.wikipedia.org/wiki/Huber_loss""" return tf.where( tf.abs(x) < delta, tf.square(x) * 0.5, delta * (tf.abs(x) - 0.5 * delta)) def reduce_mean_ignore_inf(x, axis): """Same ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/tf_run_builder.py
Python
import logging import os import time from ray.rllib.utils.debug import log_once from ray.rllib.utils import try_import_tf tf = try_import_tf() logger = logging.getLogger(__name__) class TFRunBuilder: """Used to incrementally build up a TensorFlow run. This is particularly useful for batching ops from multi...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/timer.py
Python
import numpy as np import time class TimerStat: """A running stat for conveniently logging the duration of a code block. Example: wait_timer = TimerStat() with wait_timer: ray.wait(...) Note that this class is *not* thread-safe. """ def __init__(self, window_size=10)...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/torch_ops.py
Python
from ray.rllib.utils.framework import try_import_torch torch, _ = try_import_torch() def sequence_mask(lengths, maxlen, dtype=torch.bool): """ Exact same behavior as tf.sequence_mask. Thanks to Dimitris Papatheodorou (https://discuss.pytorch.org/t/pytorch-equivalent-for-tf-sequence-mask/39036). "...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/tracking_dict.py
Python
class UsageTrackingDict(dict): """Dict that tracks which keys have been accessed. It can also intercept gets and allow an arbitrary callback to be applied (i.e., to lazily convert numpy arrays to Tensors). We make the simplifying assumption only __getitem__ is used to access values. """ d...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
rllib/utils/window_stat.py
Python
import numpy as np class WindowStat: def __init__(self, name, n): self.name = name self.items = [None] * n self.idx = 0 self.count = 0 def push(self, obj): self.items[self.idx] = obj self.idx += 1 self.count += 1 self.idx %= len(self.items) ...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
setup_hooks.sh
Shell
#!/bin/bash ln -s $PWD/scripts/pre-push $PWD/.git/hooks/pre-push
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/buffer.h
C/C++ Header
#ifndef RAY_COMMON_BUFFER_H #define RAY_COMMON_BUFFER_H #include <cstdint> #include <cstdio> #include "plasma/client.h" #include "ray/common/status.h" namespace arrow { class Buffer; } namespace ray { /// The interface that represents a buffer of bytes. class Buffer { public: /// Pointer to the data. virtual u...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/client_connection.cc
C++
#include "client_connection.h" #include <stdio.h> #include <boost/bind.hpp> #include <sstream> #include "ray/common/ray_config.h" #include "ray/util/util.h" namespace ray { ray::Status TcpConnect(boost::asio::ip::tcp::socket &socket, const std::string &ip_address_string, int port) { // Disa...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/client_connection.h
C/C++ Header
#ifndef RAY_COMMON_CLIENT_CONNECTION_H #define RAY_COMMON_CLIENT_CONNECTION_H #include <deque> #include <memory> #include <boost/asio.hpp> #include <boost/asio/error.hpp> #include <boost/enable_shared_from_this.hpp> #include "ray/common/id.h" #include "ray/common/status.h" namespace ray { /// Connect a TCP socket....
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/common_protocol.cc
C++
#include "common_protocol.h" #include "ray/util/logging.h" std::string string_from_flatbuf(const flatbuffers::String &string) { return std::string(string.data(), string.size()); } std::vector<std::string> string_vec_from_flatbuf( const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> &flatbuf_vec)...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/common_protocol.h
C/C++ Header
#ifndef COMMON_PROTOCOL_H #define COMMON_PROTOCOL_H #include <flatbuffers/flatbuffers.h> #include <unordered_set> #include "ray/common/id.h" #include "ray/util/logging.h" /// Convert an unique ID to a flatbuffer string. /// /// @param fbb Reference to the flatbuffer builder. /// @param id The ID to be converted. ///...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/constants.h
C/C++ Header
#ifndef RAY_CONSTANTS_H_ #define RAY_CONSTANTS_H_ #include <limits.h> #include <stdint.h> /// Length of Ray full-length IDs in bytes. constexpr size_t kUniqueIDSize = 20; /// Length of plasma ID in bytes. constexpr size_t kPlasmaIdSize = 20; /// An ObjectID's bytes are split into the task ID itself and the index of...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/grpc_util.h
C/C++ Header
#ifndef RAY_COMMON_GRPC_UTIL_H #define RAY_COMMON_GRPC_UTIL_H #include <google/protobuf/map.h> #include <google/protobuf/repeated_field.h> #include <grpcpp/grpcpp.h> #include <sstream> #include "status.h" namespace ray { /// Wrap a protobuf message. template <class Message> class MessageWrapper { public: /// Co...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/id.cc
C++
#include "ray/common/id.h" #include <limits.h> #include <algorithm> #include <chrono> #include <mutex> #include <random> #include "ray/common/constants.h" #include "ray/common/status.h" #include "ray/util/util.h" extern "C" { #include "ray/thirdparty/sha256.h" } // Definitions for computing hash digests. #define D...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
src/ray/common/id.h
C/C++ Header
#ifndef RAY_ID_H_ #define RAY_ID_H_ #include <inttypes.h> #include <limits.h> #include <chrono> #include <cstring> #include <mutex> #include <random> #include <string> #include "plasma/common.h" #include "ray/common/constants.h" #include "ray/util/logging.h" #include "ray/util/util.h" #include "ray/util/visibility.h...
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta