repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
ray | ray-master/rllib/examples/custom_train_fn.py | """Example of a custom training workflow. Run this for a demo.
This example shows:
- using Tune trainable functions to implement custom training workflows
You can visualize experiment results in ~/ray_results using TensorBoard.
"""
import argparse
import os
import ray
from ray import tune
from ray.rllib.algorithms... | 1,891 | 26.823529 | 81 | py |
ray | ray-master/rllib/examples/bare_metal_policy_with_custom_view_reqs.py | import argparse
import os
import ray
from ray.rllib.algorithms.algorithm import Algorithm
from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
from ray.rllib.examples.policy.bare_metal_policy_with_custom_view_reqs import (
BareMetalPolicyWithCustomViewReqs,
)
from ray import air, tune
def get_cli_ar... | 2,682 | 28.483516 | 84 | py |
ray | ray-master/rllib/examples/nested_action_spaces.py | import argparse
from gymnasium.spaces import Dict, Tuple, Box, Discrete
import os
import ray
from ray import air, tune
from ray.tune.registry import register_env
from ray.rllib.examples.env.nested_space_repeat_after_me_env import (
NestedSpaceRepeatAfterMeEnv,
)
from ray.rllib.utils.test_utils import check_learnin... | 3,058 | 29.59 | 86 | py |
ray | ray-master/rllib/examples/batch_norm_model.py | """Example of using a custom model with batch norm."""
import argparse
import os
import ray
from ray import air, tune
from ray.rllib.examples.models.batch_norm_model import (
BatchNormModel,
KerasBatchNormModel,
TorchBatchNormModel,
)
from ray.rllib.models import ModelCatalog
from ray.rllib.utils.framewor... | 2,688 | 26.721649 | 88 | py |
ray | ray-master/rllib/examples/restore_1_of_n_agents_from_checkpoint.py | """Simple example of how to restore only one of n agents from a trained
multi-agent Algorithm using Ray tune.
Control the number of agents and policies via --num-agents and --num-policies.
"""
import argparse
import gymnasium as gym
import os
import random
import ray
from ray import air
from ray import tune
from ray... | 4,357 | 31.522388 | 88 | py |
ray | ray-master/rllib/examples/checkpoint_by_custom_criteria.py | import argparse
import os
import ray
from ray import air, tune
from ray.tune.registry import get_trainable_cls
parser = argparse.ArgumentParser()
parser.add_argument(
"--run", type=str, default="PPO", help="The RLlib-registered algorithm to use."
)
parser.add_argument("--num-cpus", type=int, default=0)
parser.add... | 3,859 | 35.761905 | 85 | py |
ray | ray-master/rllib/examples/custom_eval.py | """Example of customizing evaluation with RLlib.
Pass --custom-eval to run with a custom evaluation function too.
Here we define a custom evaluation method that runs a specific sweep of env
parameters (SimpleCorridor corridor lengths).
------------------------------------------------------------------------
Sample o... | 7,111 | 33.692683 | 87 | py |
ray | ray-master/rllib/examples/centralized_critic_2.py | """An example of implementing a centralized critic with ObservationFunction.
The advantage of this approach is that it's very simple and you don't have to
change the algorithm at all -- just use callbacks and a custom model.
However, it is a bit less principled in that you have to change the agent
observation spaces t... | 5,209 | 31.360248 | 87 | py |
ray | ray-master/rllib/examples/two_trainer_workflow.py | """Example of using a custom training workflow.
Here we create a number of CartPole agents, some of which are trained with
DQN, and some of which are trained with PPO. Both are executed concurrently
via a custom training workflow.
"""
import argparse
import os
import ray
from ray import air, tune
from ray.rllib.algo... | 8,859 | 38.030837 | 88 | py |
ray | ray-master/rllib/examples/custom_vector_env.py | import argparse
import os
import ray
from ray import air, tune
from ray.rllib.examples.env.mock_env import MockVectorEnv
from ray.rllib.utils.framework import try_import_tf, try_import_torch
from ray.rllib.utils.test_utils import check_learning_achieved
from ray.tune.registry import get_trainable_cls
tf1, tf, tfv = t... | 2,240 | 28.88 | 87 | py |
ray | ray-master/rllib/examples/iterated_prisoners_dilemma_env.py | ##########
# Contribution by the Center on Long-Term Risk:
# https://github.com/longtermrisk/marltoolbox
##########
import argparse
import os
import ray
from ray import air, tune
from ray.rllib.algorithms.pg import PG
from ray.rllib.examples.env.matrix_sequential_social_dilemma import (
IteratedPrisonersDilemma,
)... | 2,472 | 26.786517 | 85 | py |
ray | ray-master/rllib/examples/parametric_actions_cartpole_embeddings_learnt_by_model.py | """Example of handling variable length and/or parametric action spaces.
This is a toy example of the action-embedding based approach for handling large
discrete action spaces (potentially infinite in size), similar to this:
https://neuro.cs.ut.ee/the-use-of-embeddings-in-openai-five/
This currently works with RL... | 3,177 | 31.10101 | 84 | py |
ray | ray-master/rllib/examples/custom_input_api.py | """Example of creating a custom input api
Custom input apis are useful when your data source is in a custom format or
when it is necessary to use an external data loading mechanism.
In this example, we train an rl agent on user specified input data.
Instead of using the built in JsonReader, we will create our own cust... | 4,023 | 30.936508 | 87 | py |
ray | ray-master/rllib/examples/attention_net.py | """
Example of using an RL agent (default: PPO) with an AttentionNet model,
which is useful for environments where state is important but not explicitly
part of the observations.
For example, in the "repeat after me" environment (default here), the agent
needs to repeat an observation from n timesteps before.
Attentio... | 8,065 | 34.53304 | 84 | py |
ray | ray-master/rllib/examples/remote_envs_with_inference_done_on_main_node.py | """
This script demonstrates how one can specify n (vectorized) envs
as ray remote (actors), such that stepping through these occurs in parallel.
Also, actions for each env step will be calculated on the "main" node.
This can be useful if the "main" node is a GPU machine and we would like to
speed up batched action ca... | 6,218 | 33.55 | 83 | py |
ray | ray-master/rllib/examples/vizdoom_with_attention_net.py | import argparse
import os
from ray.tune.registry import get_trainable_cls
parser = argparse.ArgumentParser()
parser.add_argument(
"--run", type=str, default="PPO", help="The RLlib-registered algorithm to use."
)
parser.add_argument("--num-cpus", type=int, default=0)
parser.add_argument(
"--framework",
cho... | 2,671 | 29.022472 | 83 | py |
ray | ray-master/rllib/examples/parallel_evaluation_and_training.py | import argparse
import os
from ray.rllib.algorithms.callbacks import DefaultCallbacks
from ray.rllib.utils.test_utils import check_learning_achieved
from ray.tune.registry import get_trainable_cls
parser = argparse.ArgumentParser()
parser.add_argument(
"--evaluation-duration",
type=lambda v: v if v == "auto"... | 6,641 | 38.301775 | 88 | py |
ray | ray-master/rllib/examples/custom_model_api.py | import argparse
from gymnasium.spaces import Box, Discrete
import numpy as np
from ray.rllib.examples.models.custom_model_api import (
DuelingQModel,
TorchDuelingQModel,
ContActionQModel,
TorchContActionQModel,
)
from ray.rllib.models.catalog import ModelCatalog, MODEL_DEFAULTS
from ray.rllib.policy.sa... | 3,831 | 34.155963 | 73 | py |
ray | ray-master/rllib/examples/multi-agent-leela-chess-zero.py | from ray.rllib.algorithms.leela_chess_zero import LeelaChessZeroConfig
from ray.rllib.examples.env.pettingzoo_chess import MultiAgentChess
from ray.rllib.policy.policy import PolicySpec
p0 = (
LeelaChessZeroConfig()
.training(
mcts_config={
"num_simulations": 20,
"turn_based_fl... | 1,504 | 27.942308 | 82 | py |
ray | ray-master/rllib/examples/attention_net_supervised.py | from gymnasium.spaces import Box, Discrete
import numpy as np
from rllib.models.tf.attention_net import TrXLNet
from ray.rllib.utils.framework import try_import_tf
tf1, tf, tfv = try_import_tf()
def bit_shift_generator(seq_length, shift, batch_size):
while True:
values = np.array([0.0, 1.0], dtype=np.fl... | 2,364 | 29.714286 | 86 | py |
ray | ray-master/rllib/examples/custom_env.py | """
Example of a custom gym environment and model. Run this for a demo.
This example shows:
- using a custom environment
- using a custom model
- using Tune for grid search to try different learning rates
You can visualize experiment results in ~/ray_results using TensorBoard.
Run example with defaults:
$ pyth... | 7,389 | 32.438914 | 86 | py |
ray | ray-master/rllib/examples/preprocessing_disabled.py | """
Example for using _disable_preprocessor_api=True to disable all preprocessing.
This example shows:
- How a complex observation space from the env is handled directly by the
model.
- Complex observations are flattened into lists of tensors and as such
stored by the SampleCollectors.
- This has the adv... | 3,888 | 30.362903 | 84 | py |
ray | ray-master/rllib/examples/parametric_actions_cartpole.py | """Example of handling variable length and/or parametric action spaces.
This is a toy example of the action-embedding based approach for handling large
discrete action spaces (potentially infinite in size), similar to this:
https://neuro.cs.ut.ee/the-use-of-embeddings-in-openai-five/
This currently works with RL... | 3,460 | 30.18018 | 88 | py |
ray | ray-master/rllib/examples/multi_agent_custom_policy.py | """Example of running a custom hand-coded policy alongside trainable policies.
This example has two policies:
(1) a simple simple policy trained with PPO optimizer
(2) a hand-coded policy that acts at random in the env (doesn't learn)
In the console output, you can see the PPO policy does much better than ran... | 3,969 | 32.644068 | 88 | py |
ray | ray-master/rllib/examples/self_play_with_open_spiel.py | """Example showing how one can implement a simple self-play training workflow.
Uses the open spiel adapter of RLlib with the "connect_four" game and
a multi-agent setup with a "main" policy and n "main_v[x]" policies
(x=version number), which are all at-some-point-frozen copies of
"main". At the very beginning, "main"... | 14,050 | 37.922438 | 87 | py |
ray | ray-master/rllib/examples/complex_struct_space.py | """Example of using variable-length Repeated / struct observation spaces.
This example shows:
- using a custom environment with Repeated / struct observations
- using a custom model to view the batched list observations
For PyTorch / TF eager mode, use the `--framework=[torch|tf2]` flag.
"""
import argparse
impo... | 1,679 | 27.474576 | 75 | py |
ray | ray-master/rllib/examples/offline_rl.py | """Example on how to use CQL to learn from an offline json file.
Important node: Make sure that your offline data file contains only
a single timestep per line to mimic the way SAC pulls samples from
the buffer.
Generate the offline json file by running an SAC algo until it reaches expert
level on your command line. ... | 5,934 | 37.044872 | 87 | py |
ray | ray-master/rllib/examples/self_play_league_based_with_open_spiel.py | """Example showing how one can implement a league-based training workflow.
Uses the open spiel adapter of RLlib with the "markov_soccer" game and
a simplified multi-agent, league-based setup:
https://deepmind.com/blog/article/AlphaStar-Grandmaster-level-in- \
StarCraft-II-using-multi-agent-reinforcement-learning
Our ... | 17,141 | 40.306024 | 88 | py |
ray | ray-master/rllib/examples/custom_logger.py | """
This example script demonstrates how one can define a custom logger
object for any RLlib Algorithm via the Algorithm's config's `logger_config` property.
By default (logger_config=None), RLlib will construct a tune
UnifiedLogger object, which logs JSON, CSV, and TBX output.
Below examples include:
- Disable loggin... | 4,551 | 31.514286 | 88 | py |
ray | ray-master/rllib/examples/trajectory_view_api.py | import argparse
import numpy as np
import ray
from ray import air, tune
from ray.rllib.algorithms.algorithm import Algorithm
from ray.rllib.examples.env.stateless_cartpole import StatelessCartPole
from ray.rllib.examples.models.trajectory_view_utilizing_models import (
FrameStackingCartPoleModel,
TorchFrameSta... | 4,542 | 30.769231 | 88 | py |
ray | ray-master/rllib/examples/two_step_game.py | """The two-step game from QMIX: https://arxiv.org/pdf/1803.11485.pdf
Configurations you can try:
- normal policy gradients (PG)
- MADDPG
- QMIX
See also: centralized_critic.py for centralized critic PPO on this game.
"""
import argparse
from gymnasium.spaces import Dict, Discrete, Tuple, MultiDiscrete
im... | 5,019 | 28.186047 | 86 | py |
ray | ray-master/rllib/examples/multi_agent_cartpole.py | """Simple example of setting up a multi-agent policy mapping.
Control the number of agents and policies via --num-agents and --num-policies.
This works with hundreds of agents and policies, but note that initializing
many TF policies will take some time.
Also, TF evals might slow down with large numbers of policies.... | 4,238 | 32.117188 | 88 | py |
ray | ray-master/rllib/examples/env_rendering_and_recording.py | import argparse
import gymnasium as gym
import numpy as np
import ray
from gymnasium.spaces import Box, Discrete
from ray import air, tune
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.env.multi_agent_env import make_multi_agent
parser = argparse.ArgumentParser()
parser.add_argument(
"--framework"... | 4,960 | 36.022388 | 88 | py |
ray | ray-master/rllib/examples/custom_recurrent_rnn_tokenizer.py | """Example of define custom tokenizers for recurrent models in RLModules.
This example shows the following steps:
- Define a custom tokenizer for a recurrent encoder.
- Define a model config that builds the custom tokenizer.
- Modify the default PPOCatalog to use the custom tokenizer config.
- Run a training that uses... | 6,977 | 33.716418 | 87 | py |
ray | ray-master/rllib/examples/custom_rnn_model.py | """Example of using a custom RNN keras model."""
import argparse
import os
import ray
from ray import air, tune
from ray.tune.registry import register_env
from ray.rllib.examples.env.repeat_after_me_env import RepeatAfterMeEnv
from ray.rllib.examples.env.repeat_initial_obs_env import RepeatInitialObsEnv
from ray.rlli... | 4,232 | 32.070313 | 87 | py |
ray | ray-master/rllib/examples/custom_keras_model.py | """Example of using a custom ModelV2 Keras-style model."""
import argparse
import os
import ray
from ray import air, tune
from ray.rllib.algorithms.callbacks import DefaultCallbacks
from ray.rllib.algorithms.dqn.dqn import DQNConfig
from ray.rllib.algorithms.dqn.distributional_q_tf_model import DistributionalQTFModel... | 5,384 | 33.967532 | 87 | py |
ray | ray-master/rllib/examples/curriculum_learning.py | """
Example of a curriculum learning setup using the `TaskSettableEnv` API
and the env_task_fn config.
This example shows:
- Writing your own curriculum-capable environment using gym.Env.
- Defining a env_task_fn that determines, whether and which new task
the env(s) should be set to (using the TaskSettableEnv... | 4,615 | 32.693431 | 86 | py |
ray | ray-master/rllib/examples/coin_game_env.py | ##########
# Contribution by the Center on Long-Term Risk:
# https://github.com/longtermrisk/marltoolbox
##########
import argparse
import os
import ray
from ray import air, tune
from ray.rllib.algorithms.ppo import PPO
from ray.rllib.examples.env.coin_game_non_vectorized_env import CoinGame, AsymCoinGame
parser = ar... | 2,670 | 28.351648 | 86 | py |
ray | ray-master/rllib/examples/custom_metrics_and_callbacks.py | """Example of using RLlib's debug callbacks.
Here we use callbacks to track the average CartPole pole angle magnitude as a
custom metric.
We then use `keep_per_episode_custom_metrics` to keep the per-episode values
of our custom metrics and do our own summarization of them.
"""
from typing import Dict, Tuple
import ... | 6,386 | 32.973404 | 87 | py |
ray | ray-master/rllib/examples/multi_agent_two_trainers.py | """Example of using two different training methods at once in multi-agent.
Here we create a number of CartPole agents, some of which are trained with
DQN, and some of which are trained with PPO. We periodically sync weights
between the two algorithms (note that no such syncing is needed when using just
a single traini... | 5,951 | 30.492063 | 87 | py |
ray | ray-master/rllib/examples/lstm_auto_wrapping.py | import numpy as np
import ray
import ray.rllib.algorithms.ppo as ppo
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.catalog import ModelCatalog
from ray.rllib.utils.framework import try_import_torch
torch, _ = try_import_torch()
# __sphinx_doc_begin__
# The custom model that wi... | 2,120 | 31.630769 | 82 | py |
ray | ray-master/rllib/examples/custom_model_loss_and_metrics.py | """Example of using custom_loss() with an imitation learning loss.
The default input file is too small to learn a good policy, but you can
generate new experiences for IL training as follows:
To generate experiences:
$ ./train.py --run=PG --config='{"output": "/tmp/cartpole"}' --env=CartPole-v1
To train on experienc... | 3,867 | 32.059829 | 87 | py |
ray | ray-master/rllib/examples/centralized_critic.py | """An example of customizing PPO to leverage a centralized critic.
Here the model and policy are hard-coded to implement a centralized critic
for TwoStepGame, but you can adapt this for your own use cases.
Compared to simply running `rllib/examples/two_step_game.py --run=PPO`,
this centralized critic version reaches ... | 10,819 | 34.12987 | 88 | py |
ray | ray-master/rllib/examples/rock_paper_scissors_multiagent.py | """A simple multi-agent env with two agents playing rock paper scissors.
This demonstrates running the following policies in competition:
(1) heuristic policy of repeating the same move
(2) heuristic policy of beating the last opponent move
(3) LSTM/feedforward PG policies
(4) LSTM policy with custom e... | 6,856 | 30.454128 | 88 | py |
ray | ray-master/rllib/examples/fractional_gpus.py | """Example of a custom gym environment and model. Run this for a demo.
This example shows:
- using a custom environment
- using a custom model
- using Tune for grid search
You can visualize experiment results in ~/ray_results using TensorBoard.
"""
import argparse
import ray
from ray import air, tune
from ray.... | 4,769 | 35.976744 | 88 | py |
ray | ray-master/rllib/examples/multi_agent_different_spaces_for_agents.py | """
Example showing how one can create a multi-agent env, in which the different agents
have different observation and action spaces.
These spaces do NOT necessarily have to be specified manually by the user. Instead,
RLlib will try to automatically infer them from the env provided spaces dicts
(agentID -> obs/act spac... | 5,529 | 32.313253 | 87 | py |
ray | ray-master/rllib/examples/cartpole_lstm.py | import argparse
import os
from ray.rllib.examples.env.stateless_cartpole import StatelessCartPole
from ray.rllib.utils.test_utils import check_learning_achieved
from ray.tune.registry import get_trainable_cls
parser = argparse.ArgumentParser()
parser.add_argument(
"--run", type=str, default="PPO", help="The RLlib... | 2,581 | 29.376471 | 88 | py |
ray | ray-master/rllib/examples/recommender_system_with_recsim_and_slateq.py | """Using an RLlib-ready RecSim environment and the SlateQ algorithm
for solving recommendation system problems.
This example supports three different RecSim (RLlib-ready) environments,
configured via the --env option:
- "long-term-satisfaction"
- "interest-exploration"
- "interest-evolution"
"""
import argparse
impor... | 6,459 | 29.909091 | 86 | py |
ray | ray-master/rllib/examples/mobilenet_v2_with_lstm.py | # Explains/tests Issues:
# https://github.com/ray-project/ray/issues/6928
# https://github.com/ray-project/ray/issues/6732
import argparse
from gymnasium.spaces import Discrete, Box
import numpy as np
import os
from ray import air, tune
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.examples.env.random... | 2,881 | 29.659574 | 86 | py |
ray | ray-master/rllib/examples/deterministic_training.py | """
Example of a fully deterministic, repeatable RLlib train run using
the "seed" config key.
"""
import argparse
import ray
from ray import air, tune
from ray.rllib.examples.env.env_using_remote_actor import (
CartPoleWithRemoteParamServer,
ParameterStorage,
)
from ray.rllib.policy.sample_batch import DEFAULT... | 3,363 | 32.306931 | 85 | py |
ray | ray-master/rllib/examples/trajectory_view_api_rlm.py | import argparse
import ray
from ray import air, tune
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.core.rl_module.rl_module import SingleAgentRLModuleSpec
from ray.rllib.examples.env.stateless_cartpole import StatelessCartPole
from ray.rllib.examples.rl_module.frame_stacking_rlm import (
TorchFram... | 2,599 | 27.26087 | 88 | py |
ray | ray-master/rllib/examples/replay_buffer_api.py | # __sphinx_doc_replay_buffer_api_example_script_begin__
"""Simple example of how to modify replay buffer behaviour.
We modify R2D2 to utilize prioritized replay but supplying it with the
PrioritizedMultiAgentReplayBuffer instead of the standard MultiAgentReplayBuffer.
This is possible because R2D2 uses the DQN trainin... | 2,407 | 30.272727 | 88 | py |
ray | ray-master/rllib/examples/hierarchical_training.py | """Example of hierarchical training using the multi-agent API.
The example env is that of a "windy maze". The agent observes the current wind
direction and can either choose to stand still, or move in that direction.
You can try out the env directly with:
$ python hierarchical_training.py --flat
A simple hierar... | 4,330 | 31.320896 | 88 | py |
ray | ray-master/rllib/examples/unity3d_env_local.py | """
Example of running an RLlib Algorithm against a locally running Unity3D editor
instance (available as Unity3DEnv inside RLlib).
For a distributed cloud setup example with Unity,
see `examples/serving/unity3d_[server|client].py`
To run this script against a local Unity3D engine:
1) Install Unity3D and `pip install ... | 6,412 | 30.131068 | 88 | py |
ray | ray-master/rllib/examples/rnnsac_stateless_cartpole.py | import json
import os
from pathlib import Path
import ray
from ray import air, tune
from ray.tune.registry import get_trainable_cls
from ray.rllib.examples.env.stateless_cartpole import StatelessCartPole
param_space = {
"num_gpus": int(os.environ.get("RLLIB_NUM_GPUS", "0")),
"framework": "torch",
"num_w... | 3,692 | 26.559701 | 87 | py |
ray | ray-master/rllib/examples/custom_fast_model.py | """Example of using a custom image env and model.
Both the model and env are trivial (and super-fast), so they are useful
for running perf microbenchmarks.
"""
import argparse
import os
import ray
from ray import air, tune
from ray.rllib.algorithms.impala import ImpalaConfig
from ray.rllib.examples.env.fast_image_en... | 2,134 | 28.652778 | 84 | py |
ray | ray-master/rllib/examples/autoregressive_action_dist.py | """
Example of specifying an autoregressive action distribution.
In an action space with multiple components (e.g., Tuple(a1, a2)), you might
want a2 to be sampled based on the sampled value of a1, i.e.,
a2_sampled ~ P(a2 | a1_sampled, obs). Normally, a1 and a2 would be sampled
independently.
To do this, you need bot... | 7,272 | 33.469194 | 88 | py |
ray | ray-master/rllib/examples/remote_base_env_with_custom_api.py | """
This script demonstrates how one can specify custom env APIs in
combination with RLlib's `remote_worker_envs` setting, which
parallelizes individual sub-envs within a vector env by making each
one a ray Actor.
You can access your Env's API via a custom callback as shown below.
"""
import argparse
import gymnasium ... | 4,990 | 32.722973 | 88 | py |
ray | ray-master/rllib/examples/action_masking.py | """Example showing how to use "action masking" in RLlib.
"Action masking" allows the agent to select actions based on the current
observation. This is useful in many practical scenarios, where different
actions are available in different time steps.
Blog post explaining action masking: https://boring-guy.sh/posts/mask... | 6,601 | 33.030928 | 88 | py |
ray | ray-master/rllib/examples/policy/cliff_walking_wall_policy.py | import gymnasium as gym
from typing import Dict, Union, List, Tuple, Optional
import numpy as np
from ray.rllib.policy.policy import Policy, ViewRequirement
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.models.torch.torch_action_dist import TorchCategorical
from ray.rllib.utils.typing import Alg... | 4,165 | 40.66 | 86 | py |
ray | ray-master/rllib/examples/catalog/custom_action_distribution.py | """
This example shows two modifications:
1. How to write a custom action distribution
2. How to inject a custom action distribution into a Catalog
"""
# __sphinx_doc_begin__
import torch
import gymnasium as gym
from ray.rllib.algorithms.ppo.ppo import PPOConfig
from ray.rllib.algorithms.ppo.ppo_catalog import PPOCata... | 2,745 | 31.690476 | 86 | py |
ray | ray-master/rllib/examples/documentation/saving_and_loading_algos_and_policies.py | # flake8: noqa
# __create-algo-checkpoint-begin__
# Create a PPO algorithm object using a config object ..
from ray.rllib.algorithms.ppo import PPOConfig
my_ppo_config = PPOConfig().environment("CartPole-v1")
my_ppo = my_ppo_config.build()
# .. train one iteration ..
my_ppo.train()
# .. and call `save()` to create a... | 9,732 | 31.016447 | 88 | py |
ray | ray-master/rllib/examples/models/rnn_spy_model.py | import numpy as np
import pickle
import ray
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.recurrent_net import RecurrentNetwork
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_import_tf
tf1, tf, t... | 4,692 | 32.049296 | 85 | py |
ray | ray-master/rllib/examples/models/batch_norm_model.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import (
SlimFC,
normc_initializer as torch_normc_initializer,
)
from ray.rllib.models.torch.torch_modelv2... | 9,028 | 37.097046 | 82 | py |
ray | ray-master/rllib/examples/models/autoregressive_action_model.py | from gymnasium.spaces import Discrete, Tuple
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import normc_initializer as normc_init_torch
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.torch.torch_modelv2... | 5,721 | 34.320988 | 82 | py |
ray | ray-master/rllib/examples/models/rnn_model.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.preprocessors import get_preprocessor
from ray.rllib.models.tf.recurrent_net import RecurrentNetwork
from ray.rllib.models.torch.recurrent_net import RecurrentNetwork as TorchRNN
from ray.rllib.utils.annotations import override
from ... | 5,133 | 35.15493 | 85 | py |
ray | ray-master/rllib/examples/models/neural_computer.py | from collections import OrderedDict
import gymnasium as gym
from typing import Union, Dict, List, Tuple
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.utils.framework import try_import_torch
from ray.rllib.utils.typing import ModelConfigDict,... | 8,580 | 33.740891 | 87 | py |
ray | ray-master/rllib/examples/models/modelv3.py | import numpy as np
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.framework import try_import_tf, try_import_torch
tf1, tf, tfv = try_import_tf()
torch, nn = try_import_torch()
class RNNModel(tf.keras.models.Model if tf else object):
"""Example of using the Keras functional API to de... | 2,068 | 32.918033 | 83 | py |
ray | ray-master/rllib/examples/models/custom_model_api.py | from gymnasium.spaces import Box
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.fcnet import (
FullyConnectedNetwork as TorchFullyConnectedNetwork,
)
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.to... | 7,643 | 42.186441 | 84 | py |
ray | ray-master/rllib/examples/models/parametric_actions_model.py | from gymnasium.spaces import Box
from ray.rllib.algorithms.dqn.distributional_q_tf_model import DistributionalQTFModel
from ray.rllib.algorithms.dqn.dqn_torch_model import DQNTorchModel
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC... | 7,317 | 35.40796 | 88 | py |
ray | ray-master/rllib/examples/models/trajectory_view_utilizing_models.py | from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.policy.view_requirement import ViewRequirement
from ray.rllib.utils.framework import try_import_tf, try_import_torch
from ray.rllib.utils.tf_ut... | 5,341 | 40.410853 | 87 | py |
ray | ray-master/rllib/examples/models/eager_model.py | import random
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_import_tf
tf1, tf, tfv = try_import_tf()
class EagerM... | 2,216 | 33.640625 | 82 | py |
ray | ray-master/rllib/examples/models/action_mask_model.py | from gymnasium.spaces import Dict
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC
from ray.rllib.utils.framework impor... | 4,277 | 32.952381 | 86 | py |
ray | ray-master/rllib/examples/models/fast_model.py | from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_import_tf, try_import_... | 2,825 | 34.325 | 88 | py |
ray | ray-master/rllib/examples/models/shared_weights_model.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_im... | 6,957 | 32.776699 | 82 | py |
ray | ray-master/rllib/examples/models/centralized_critic_models.py | from gymnasium.spaces import Box
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.mode... | 6,901 | 36.923077 | 88 | py |
ray | ray-master/rllib/examples/models/custom_loss_model.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2, restore_original_dimensions
from ray.rllib.models.tf.tf_action_dist import Categorical
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.torch.torch_action_dist import T... | 6,120 | 39.269737 | 86 | py |
ray | ray-master/rllib/examples/models/mobilenet_v2_with_lstm_models.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.recurrent_net import RecurrentNetwork
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.torch.recurrent_net import RecurrentNetwork as TorchRNN
from ray.rllib.utils.annotations import override
from ray.rllib.uti... | 5,775 | 35.1 | 87 | py |
ray | ray-master/rllib/examples/models/simple_rpg_model.py | from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork as TFFCNet
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFCNet
from ray.rllib.utils.framework import try_import_tf, try_... | 2,617 | 39.276923 | 86 | py |
ray | ray-master/rllib/examples/models/autoregressive_action_dist.py | from ray.rllib.models.tf.tf_action_dist import Categorical, ActionDistribution
from ray.rllib.models.torch.torch_action_dist import (
TorchCategorical,
TorchDistributionWrapper,
)
from ray.rllib.utils.framework import try_import_tf, try_import_torch
tf1, tf, tfv = try_import_tf()
torch, nn = try_import_torch()... | 4,979 | 32.422819 | 87 | py |
ray | ray-master/rllib/examples/serving/unity3d_server.py | """
Example of running a Unity3D (MLAgents) Policy server that can learn
Policies via sampling inside many connected Unity game clients (possibly
running in the cloud on n nodes).
For a locally running Unity3D example, see:
`examples/unity3d_env_local.py`
To run this script against one or more possibly cloud-based cli... | 6,336 | 33.628415 | 86 | py |
ray | ray-master/rllib/examples/serving/cartpole_server.py | #!/usr/bin/env python
"""
Example of running an RLlib policy server, allowing connections from
external environment running clients. The server listens on
(a simple CartPole env
in this case) against an RLlib policy server listening on one or more
HTTP-speaking ports. See `cartpole_client.py` in this same directory for... | 9,356 | 33.149635 | 88 | py |
ray | ray-master/rllib/examples/rl_module/frame_stacking_rlm.py | from ray.rllib.core.rl_module.rl_module import RLModuleConfig
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.algorithms.ppo.ppo_rl_module import PPORLModule
from ray.rllib.algorithms.ppo.torch.ppo_torch_rl_module import PPOTorchRLModule
from ray.rllib.algorithms.ppo.tf.ppo_tf_rl_module import PPOT... | 4,109 | 40.515152 | 87 | py |
ray | ray-master/rllib/examples/export/onnx_torch.py | from packaging.version import Version
import numpy as np
import ray
import ray.rllib.algorithms.ppo as ppo
import onnxruntime
import os
import shutil
import torch
if __name__ == "__main__":
# Configure our PPO Algorithm.
config = (
ppo.PPOConfig()
.rollouts(num_rollout_workers=1)
.frame... | 2,174 | 27.246753 | 74 | py |
ray | ray-master/rllib/examples/export/cartpole_dqn_export.py | #!/usr/bin/env python
import numpy as np
import os
import ray
from ray.rllib.policy.policy import Policy
from ray.rllib.utils.framework import try_import_tf
from ray.tune.registry import get_trainable_cls
tf1, tf, tfv = try_import_tf()
ray.init()
def train_and_export_policy_and_model(algo_name, num_steps, model_d... | 2,456 | 33.125 | 88 | py |
ray | ray-master/rllib/examples/bandit/tune_lin_ts_train_wheel_env.py | """ Example of using Linear Thompson Sampling on WheelBandit environment.
For more information on WheelBandit, see https://arxiv.org/abs/1802.09127 .
"""
import argparse
from matplotlib import pyplot as plt
import numpy as np
import time
import ray
from ray import air, tune
from ray.rllib.algorithms.bandit.bandit... | 3,034 | 29.049505 | 86 | py |
ray | ray-master/rllib/examples/bandit/tune_lin_ucb_train_recsim_env.py | """Example of using LinUCB on a RecSim environment. """
import argparse
from matplotlib import pyplot as plt
import pandas as pd
import time
from ray import air, tune
from ray.rllib.algorithms.bandit import BanditLinUCBConfig
import ray.rllib.examples.env.recommender_system_envs_with_recsim # noqa
if __name__ == "... | 2,583 | 29.4 | 86 | py |
ray | ray-master/rllib/examples/bandit/lin_ts_train_wheel_env.py | """ Example of using Linear Thompson Sampling on WheelBandit environment.
For more information on WheelBandit, see https://arxiv.org/abs/1802.09127 .
"""
import argparse
import numpy as np
from matplotlib import pyplot as plt
from ray.rllib.algorithms.bandit.bandit import BanditLinTSConfig
from ray.rllib.examples... | 1,970 | 27.565217 | 86 | py |
ray | ray-master/rllib/examples/bandit/tune_lin_ucb_train_recommendation.py | """ Example of using LinUCB on a recommendation environment with parametric
actions. """
import argparse
from matplotlib import pyplot as plt
import os
import pandas as pd
import time
import ray
from ray import air, tune
from ray.rllib.algorithms.bandit import BanditLinUCBConfig
from ray.tune import register_env
... | 3,188 | 27.990909 | 81 | py |
ray | ray-master/rllib/examples/env/greyscale_env.py | """
Example of interfacing with an environment that produces 2D observations.
This example shows how turning 2D observations with shape (A, B) into a 3D
observations with shape (C, D, 1) can enable usage of RLlib's default models.
RLlib's default Catalog class does not provide default models for 2D observation
spaces,... | 3,631 | 29.016529 | 87 | py |
ray | ray-master/rllib/examples/tune/framework.py | #!/usr/bin/env python3
""" Benchmarking TF against PyTorch on an example task using Ray Tune.
"""
import logging
from pprint import pformat
import ray
from ray import air, tune
from ray.rllib.algorithms.appo import APPOConfig
from ray.tune import CLIReporter
logging.basicConfig(level=logging.WARN)
logger = logging.g... | 2,550 | 25.298969 | 70 | py |
ray | ray-master/rllib/examples/learner/multi_agent_cartpole_ppo.py | """Simple example of setting up a multi-agent policy mapping.
Control the number of agents and policies via --num-agents and --num-policies.
This works with hundreds of agents and policies, but note that initializing
many TF policies will take some time.
Also, TF evals might slow down with large numbers of policies.... | 3,822 | 29.830645 | 87 | py |
ray | ray-master/rllib/examples/learner/ppo_tuner.py | import argparse
import ray
from ray import air, tune
from ray.rllib.algorithms.ppo import PPOConfig
RESOURCE_CONFIG = {
"remote-cpu": {"num_learner_workers": 1},
"remote-gpu": {"num_learner_workers": 1, "num_gpus_per_learner_worker": 1},
"multi-gpu-ddp": {
"num_learner_workers": 2,
"num_gp... | 1,423 | 22.344262 | 85 | py |
ray | ray-master/rllib/examples/learner/train_w_bc_finetune_w_ppo.py | """
This example shows how to pretrain an RLModule using behavioral cloning from offline
data and, thereafter training it online with PPO.
"""
import gymnasium as gym
import shutil
import tempfile
import torch
from typing import Mapping
import ray
from ray import tune
from ray.air import RunConfig, FailureConfig
from... | 5,805 | 32.755814 | 88 | py |
ray | ray-master/rllib/examples/learner/ppo_load_rl_modules.py | import argparse
import gymnasium as gym
import shutil
import tempfile
import ray
from ray import air, tune
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.algorithms.ppo.ppo_catalog import PPOCatalog
from ray.rllib.algorithms.ppo.tf.ppo_tf_rl_module import PPOTfRLModule
from ray.rllib.algorithms.ppo.torc... | 2,384 | 29.974026 | 85 | py |
ray | ray-master/rllib/examples/inference_and_serving/policy_inference_after_training_with_dt.py | """
Example showing how you can use your trained Decision Transformer (DT) policy for
inference (computing actions) in an environment.
"""
import argparse
from pathlib import Path
import gymnasium as gym
import os
import ray
from ray import air, tune
from ray.rllib.algorithms.algorithm import Algorithm
from ray.rllib... | 5,601 | 29.950276 | 83 | py |
ray | ray-master/rllib/examples/inference_and_serving/serve_and_rllib.py | """This example script shows how one can use Ray Serve to serve an already
trained RLlib Policy (and its model) to serve action computations.
For a complete tutorial, also see:
https://docs.ray.io/en/master/serve/tutorials/rllib.html
"""
import argparse
import gymnasium as gym
import requests
from starlette.requests ... | 3,880 | 30.298387 | 84 | py |
ray | ray-master/rllib/examples/inference_and_serving/policy_inference_after_training_with_attention.py | """
Example showing how you can use your trained policy for inference
(computing actions) in an environment.
Includes options for LSTM-based models (--use-lstm), attention-net models
(--use-attention), and plain (non-recurrent) models.
"""
import argparse
import gymnasium as gym
import numpy as np
import os
import ra... | 6,079 | 31.169312 | 83 | py |
ray | ray-master/rllib/examples/inference_and_serving/policy_inference_after_training_with_lstm.py | """
Example showing how you can use your trained policy for inference
(computing actions) in an environment.
Includes options for LSTM-based models (--use-lstm), attention-net models
(--use-attention), and plain (non-recurrent) models.
"""
import argparse
import gymnasium as gym
import numpy as np
import os
import ra... | 5,301 | 29.297143 | 87 | py |
ray | ray-master/rllib/examples/inference_and_serving/policy_inference_after_training.py | """
Example showing how you can use your trained policy for inference
(computing actions) in an environment.
Includes options for LSTM-based models (--use-lstm), attention-net models
(--use-attention), and plain (non-recurrent) models.
"""
import argparse
import gymnasium as gym
import os
import ray
from ray import a... | 3,712 | 28.23622 | 83 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.