3 |
4 | {% block breadcrumbs %}
5 | - »
6 | {% for doc in parents %}
7 | - {{ doc.title }} »
8 | {% endfor %}
9 | - {{ title }}
10 | {% endblock %}
11 | -
12 | Doc suggestion?
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/python/ray/autoscaler/log_timer.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | import datetime
6 | import logging
7 |
8 | logger = logging.getLogger(__name__)
9 |
10 |
11 | class LogTimer(object):
12 | def __init__(self, message):
13 | self._message = message
14 |
15 | def __enter__(self):
16 | self._start_time = datetime.datetime.utcnow()
17 |
18 | def __exit__(self, *_):
19 | td = datetime.datetime.utcnow() - self._start_time
20 | logger.info(self._message +
21 | " [LogTimer={:.0f}ms]".format(td.total_seconds() * 1000))
22 |
--------------------------------------------------------------------------------
/python/ray/tests/project_files/session-tests/git-repo-pass/.rayproject/cluster.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | # A unique identifier for the head node and workers of this cluster.
4 | cluster_name: git-repo-pass
5 |
6 | # The maximum number of workers nodes to launch in addition to the head
7 | # node. This takes precedence over min_workers. min_workers defaults to 0.
8 | max_workers: 1
9 |
10 | # Cloud-provider specific configuration.
11 | provider:
12 | type: aws
13 | region: us-west-2
14 | availability_zone: us-west-2a
15 |
16 | # How Ray will authenticate with newly launched nodes.
17 | auth:
18 | ssh_user: ubuntu
19 |
--------------------------------------------------------------------------------
/doc/site/README.md:
--------------------------------------------------------------------------------
1 | # Ray Website
2 |
3 | ## Development instructions
4 |
5 | With Ruby >= 2.1 installed, run:
6 |
7 | ```
8 | gem install jekyll bundler
9 | bundle install
10 | ```
11 |
12 | To view the site, run:
13 |
14 | ```
15 | bundle exec jekyll serve
16 | ```
17 |
18 | To view the site with Google Analytics, run:
19 |
20 | ```
21 | JEKYLL_ENV=production bundle exec jekyll serve
22 | ```
23 |
24 | ## Deployment
25 |
26 | To deploy the site, run
27 |
28 | ```
29 | cd ~
30 | git clone git@github.com:ray-project/ray-project.github.io.git
31 | cd ray-project.github.io
32 | cp -r ~/ray/site/* .
33 | ```
34 |
35 | and commit as well as push the desired changes.
36 |
--------------------------------------------------------------------------------
/java/test/src/main/java/org/ray/api/test/MultiLanguageClusterTest.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.test;
2 |
3 | import org.ray.api.Ray;
4 | import org.ray.api.RayObject;
5 | import org.ray.api.annotation.RayRemote;
6 | import org.testng.Assert;
7 | import org.testng.annotations.Test;
8 |
9 | public class MultiLanguageClusterTest extends BaseMultiLanguageTest {
10 |
11 | @RayRemote
12 | public static String echo(String word) {
13 | return word;
14 | }
15 |
16 | @Test
17 | public void testMultiLanguageCluster() {
18 | RayObject
obj = Ray.call(MultiLanguageClusterTest::echo, "hello");
19 | Assert.assertEquals("hello", obj.get());
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/python/ray/experimental/array/distributed/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | from . import random
6 | from . import linalg
7 | from .core import (BLOCK_SIZE, DistArray, assemble, zeros, ones, copy, eye,
8 | triu, tril, blockwise_dot, dot, transpose, add, subtract,
9 | numpy_to_dist, subblocks)
10 |
11 | __all__ = [
12 | "random", "linalg", "BLOCK_SIZE", "DistArray", "assemble", "zeros", "ones",
13 | "copy", "eye", "triu", "tril", "blockwise_dot", "dot", "transpose", "add",
14 | "subtract", "numpy_to_dist", "subblocks"
15 | ]
16 |
--------------------------------------------------------------------------------
/python/ray/tests/project_files/session-tests/with-docker-fail/.rayproject/cluster.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | # A unique identifier for the head node and workers of this cluster.
4 | cluster_name: with-docker-fail
5 |
6 | # The maximum number of workers nodes to launch in addition to the head
7 | # node. This takes precedence over min_workers. min_workers defaults to 0.
8 | max_workers: 1
9 |
10 | # Cloud-provider specific configuration.
11 | provider:
12 | type: aws
13 | region: us-west-2
14 | availability_zone: us-west-2a
15 |
16 | # How Ray will authenticate with newly launched nodes.
17 | auth:
18 | ssh_user: ubuntu
19 |
--------------------------------------------------------------------------------
/java/runtime/src/main/java/org/ray/runtime/object/RayObjectImpl.java:
--------------------------------------------------------------------------------
1 | package org.ray.runtime.object;
2 |
3 | import java.io.Serializable;
4 | import org.ray.api.Ray;
5 | import org.ray.api.RayObject;
6 | import org.ray.api.id.ObjectId;
7 |
8 | /**
9 | * Implementation of {@link RayObject}.
10 | */
11 | public final class RayObjectImpl implements RayObject, Serializable {
12 |
13 | private final ObjectId id;
14 |
15 | public RayObjectImpl(ObjectId id) {
16 | this.id = id;
17 | }
18 |
19 | @Override
20 | public T get() {
21 | return Ray.get(id);
22 | }
23 |
24 | @Override
25 | public ObjectId getId() {
26 | return id;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/python/ray/dashboard/client/src/App.tsx:
--------------------------------------------------------------------------------
1 | import CssBaseline from "@material-ui/core/CssBaseline";
2 | import React from "react";
3 | import { BrowserRouter, Route } from "react-router-dom";
4 | import Dashboard from "./Dashboard";
5 | import Errors from "./Errors";
6 | import Logs from "./Logs";
7 |
8 | class App extends React.Component {
9 | render() {
10 | return (
11 |
12 |
13 |
14 |
15 |
16 |
17 | );
18 | }
19 | }
20 |
21 | export default App;
22 |
--------------------------------------------------------------------------------
/python/ray/tests/project_files/session-tests/invalid-config-fail/.rayproject/cluster.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | # A unique identifier for the head node and workers of this cluster.
4 | cluster_name: invalid-config-fail
5 |
6 | # The maximum number of workers nodes to launch in addition to the head
7 | # node. This takes precedence over min_workers. min_workers defaults to 0.
8 | max_workers: 1
9 |
10 | # Cloud-provider specific configuration.
11 | provider:
12 | type: aws
13 | region: us-west-2
14 | availability_zone: us-west-2a
15 |
16 | # How Ray will authenticate with newly launched nodes.
17 | auth:
18 | ssh_user: ubuntu
19 |
--------------------------------------------------------------------------------
/rllib/agents/ddpg/noop_model.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | from ray.rllib.models.tf.tf_modelv2 import TFModelV2
6 | from ray.rllib.utils.annotations import override
7 | from ray.rllib.utils import try_import_tf
8 |
9 | tf = try_import_tf()
10 |
11 |
12 | class NoopModel(TFModelV2):
13 | """Trivial model that just returns the obs flattened.
14 |
15 | This is the model used if use_state_preprocessor=False."""
16 |
17 | @override(TFModelV2)
18 | def forward(self, input_dict, state, seq_lens):
19 | return tf.cast(input_dict["obs_flat"], tf.float32), state
20 |
--------------------------------------------------------------------------------
/doc/examples/lbfgs/.rayproject/project.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | name: ray-example-lbfgs
4 |
5 | description: "Parallelizing the L-BFGS algorithm in ray"
6 | tags: ["ray-example", "optimization", "lbfgs"]
7 | documentation: https://ray.readthedocs.io/en/latest/auto_examples/plot_lbfgs.html
8 |
9 | cluster: .rayproject/cluster.yaml
10 |
11 | environment:
12 | requirements: .rayproject/requirements.txt
13 |
14 | commands:
15 | - name: run
16 | command: python driver.py
17 | help: "Run the L-BFGS example"
18 |
19 | output_files: [
20 | # Save the logs from the latest run in snapshots.
21 | "/tmp/ray/session_latest/logs"
22 | ]
23 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/cluster/ResourceManager.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.cluster;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import org.ray.api.Ray;
6 | import org.ray.api.RayActor;
7 | import org.ray.streaming.core.runtime.StreamWorker;
8 |
9 | public class ResourceManager {
10 |
11 | public List> createWorker(int workerNum) {
12 | List> workers = new ArrayList<>();
13 | for (int i = 0; i < workerNum; i++) {
14 | RayActor worker = Ray.createActor(StreamWorker::new);
15 | workers.add(worker);
16 | }
17 | return workers;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/java/test/src/main/java/org/ray/api/benchmark/RemoteResult.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.benchmark;
2 |
3 | import java.io.Serializable;
4 |
5 | public class RemoteResult implements Serializable {
6 |
7 | private static final long serialVersionUID = -3825949468039358540L;
8 |
9 | private long finishTime;
10 |
11 | private T result;
12 |
13 | public long getFinishTime() {
14 | return finishTime;
15 | }
16 |
17 | public void setFinishTime(long finishTime) {
18 | this.finishTime = finishTime;
19 | }
20 |
21 | public T getResult() {
22 | return result;
23 | }
24 |
25 | public void setResult(T result) {
26 | this.result = result;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/java/test/src/main/java/org/ray/api/benchmark/RemoteResultWrapper.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.benchmark;
2 |
3 | import org.ray.api.RayObject;
4 |
5 | public class RemoteResultWrapper {
6 |
7 | private long startTime;
8 |
9 | private RayObject> rayObject;
10 |
11 | public long getStartTime() {
12 | return startTime;
13 | }
14 |
15 | public void setStartTime(long startTime) {
16 | this.startTime = startTime;
17 | }
18 |
19 | public RayObject> getRayObject() {
20 | return rayObject;
21 | }
22 |
23 | public void setRayObject(RayObject> rayObject) {
24 | this.rayObject = rayObject;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/python/ray/experimental/array/distributed/random.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | import numpy as np
6 | import ray.experimental.array.remote as ra
7 | import ray
8 |
9 | from .core import DistArray
10 |
11 |
12 | @ray.remote
13 | def normal(shape):
14 | num_blocks = DistArray.compute_num_blocks(shape)
15 | objectids = np.empty(num_blocks, dtype=object)
16 | for index in np.ndindex(*num_blocks):
17 | objectids[index] = ra.random.normal.remote(
18 | DistArray.compute_block_shape(index, shape))
19 | result = DistArray(shape, objectids)
20 | return result
21 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/atari-impala.yaml:
--------------------------------------------------------------------------------
1 | # Runs on a g3.16xl node with 3 m4.16xl workers
2 | # See https://github.com/ray-project/rl-experiments for results
3 | atari-impala:
4 | env:
5 | grid_search:
6 | - BreakoutNoFrameskip-v4
7 | - BeamRiderNoFrameskip-v4
8 | - QbertNoFrameskip-v4
9 | - SpaceInvadersNoFrameskip-v4
10 | run: IMPALA
11 | config:
12 | sample_batch_size: 50
13 | train_batch_size: 500
14 | num_workers: 32
15 | num_envs_per_worker: 5
16 | clip_rewards: True
17 | lr_schedule: [
18 | [0, 0.0005],
19 | [20000000, 0.000000000001],
20 | ]
21 |
--------------------------------------------------------------------------------
/src/ray/thirdparty/hiredis/.travis.yml:
--------------------------------------------------------------------------------
1 | language: c
2 | sudo: false
3 | compiler:
4 | - gcc
5 | - clang
6 |
7 | addons:
8 | apt:
9 | packages:
10 | - libc6-dbg
11 | - libc6-dev
12 | - libc6:i386
13 | - libc6-dev-i386
14 | - libc6-dbg:i386
15 | - gcc-multilib
16 | - valgrind
17 |
18 | env:
19 | - CFLAGS="-Werror"
20 | - PRE="valgrind --track-origins=yes --leak-check=full"
21 | - TARGET="32bit" TARGET_VARS="32bit-vars" CFLAGS="-Werror"
22 | - TARGET="32bit" TARGET_VARS="32bit-vars" PRE="valgrind --track-origins=yes --leak-check=full"
23 |
24 | script: make $TARGET CFLAGS="$CFLAGS" && make check PRE="$PRE" && make $TARGET_VARS hiredis-example
25 |
--------------------------------------------------------------------------------
/java/runtime/src/main/java/org/ray/runtime/functionmanager/FunctionDescriptor.java:
--------------------------------------------------------------------------------
1 | package org.ray.runtime.functionmanager;
2 |
3 | import java.util.List;
4 | import org.ray.runtime.generated.Common.Language;
5 |
6 | /**
7 | * Base interface of a Ray task's function descriptor.
8 | *
9 | * A function descriptor is a list of strings that can uniquely describe a function. It's used to
10 | * load a function in workers.
11 | */
12 | public interface FunctionDescriptor {
13 |
14 | /**
15 | * @return A list of strings represents the functions.
16 | */
17 | List toList();
18 |
19 | /**
20 | * @return The language of the function.
21 | */
22 | Language getLanguage();
23 | }
24 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/core/processor/SourceProcessor.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.core.processor;
2 |
3 | import org.ray.streaming.operator.impl.SourceOperator;
4 |
5 | /**
6 | * The processor for the stream sources, containing a SourceOperator.
7 | *
8 | * @param The type of source data.
9 | */
10 | public class SourceProcessor extends StreamProcessor> {
11 |
12 | public SourceProcessor(SourceOperator operator) {
13 | super(operator);
14 | }
15 |
16 | @Override
17 | public void process(Long batchId) {
18 | this.operator.process(batchId);
19 | }
20 |
21 | @Override
22 | public void close() {
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/python/ray/experimental/serve/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import os
2 | import tempfile
3 |
4 | import pytest
5 |
6 | import ray
7 | from ray.experimental import serve
8 |
9 |
10 | @pytest.fixture(scope="session")
11 | def serve_instance():
12 | _, new_db_path = tempfile.mkstemp(suffix=".test.db")
13 | serve.init(kv_store_path=new_db_path, blocking=True)
14 | yield
15 | os.remove(new_db_path)
16 |
17 |
18 | @pytest.fixture(scope="session")
19 | def ray_instance():
20 | ray_already_initialized = ray.is_initialized()
21 | if not ray_already_initialized:
22 | ray.init(object_store_memory=int(1e8))
23 | yield
24 | if not ray_already_initialized:
25 | ray.shutdown()
26 |
--------------------------------------------------------------------------------
/python/ray/projects/templates/project_template.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | name: {{name}}
4 |
5 | # description: A short description of the project.
6 | # The URL of the repo this project is part of.
7 | {{repo_string}}
8 |
9 | cluster: {{cluster}}
10 |
11 | environment:
12 | # dockerfile: The dockerfile to be built and ran the commands with.
13 | # dockerimage: The docker image to be used to run the project in, e.g. ubuntu:18.04.
14 | requirements: {{requirements}}
15 |
16 | shell: # Shell commands to be ran for environment setup.
17 | - echo "Setting up the environment"
18 |
19 | commands:
20 | - name: default
21 | command: echo "Starting ray job"
22 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/api/partition/impl/RoundRobinPartition.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.api.partition.impl;
2 |
3 | import org.ray.streaming.api.partition.Partition;
4 |
5 | /**
6 | * Partition record to downstream tasks in a round-robin matter.
7 | *
8 | * @param Type of the input record.
9 | */
10 | public class RoundRobinPartition implements Partition {
11 |
12 | private int seq;
13 |
14 | public RoundRobinPartition() {
15 | this.seq = 0;
16 | }
17 |
18 | @Override
19 | public int[] partition(T value, int[] taskIds) {
20 | int length = taskIds.length;
21 | int taskId = taskIds[seq++ % length];
22 | return new int[]{taskId};
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/atari-impala-large.yaml:
--------------------------------------------------------------------------------
1 | # Runs on a g3.16xl node with 5 m5.24xl workers
2 | # Takes roughly 10 minutes.
3 | atari-impala:
4 | env:
5 | grid_search:
6 | - BreakoutNoFrameskip-v4
7 | - BeamRiderNoFrameskip-v4
8 | - QbertNoFrameskip-v4
9 | - SpaceInvadersNoFrameskip-v4
10 | run: IMPALA
11 | stop:
12 | timesteps_total: 3000000
13 | config:
14 | sample_batch_size: 50
15 | train_batch_size: 500
16 | num_workers: 128
17 | num_envs_per_worker: 5
18 | clip_rewards: True
19 | lr_schedule: [
20 | [0, 0.0005],
21 | [20000000, 0.000000000001],
22 | ]
23 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/pong-dqn.yaml:
--------------------------------------------------------------------------------
1 | # You can expect ~20 reward within 1.1m timesteps / 2.1 hours on a K80 GPU
2 | pong-deterministic-dqn:
3 | env: PongDeterministic-v4
4 | run: DQN
5 | stop:
6 | episode_reward_mean: 20
7 | time_total_s: 7200
8 | config:
9 | num_gpus: 1
10 | gamma: 0.99
11 | lr: .0001
12 | learning_starts: 10000
13 | buffer_size: 50000
14 | sample_batch_size: 4
15 | train_batch_size: 32
16 | schedule_max_timesteps: 2000000
17 | exploration_final_eps: .01
18 | exploration_fraction: .1
19 | model:
20 | grayscale: True
21 | zero_mean: False
22 | dim: 42
23 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/pong-impala-fast.yaml:
--------------------------------------------------------------------------------
1 | # This can reach 18-19 reward in ~3 minutes on p3.16xl head w/m4.16xl workers
2 | # 128 workers -> 3 minutes (best case)
3 | # 64 workers -> 4 minutes
4 | # 32 workers -> 7 minutes
5 | # See also: pong-impala.yaml, pong-impala-vectorized.yaml
6 | pong-impala-fast:
7 | env: PongNoFrameskip-v4
8 | run: IMPALA
9 | config:
10 | sample_batch_size: 50
11 | train_batch_size: 1000
12 | num_workers: 128
13 | num_envs_per_worker: 5
14 | broadcast_interval: 5
15 | max_sample_requests_in_flight_per_worker: 1
16 | num_data_loader_buffers: 4
17 | num_gpus: 2
18 | model:
19 | dim: 42
20 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/api/partition/Partition.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.api.partition;
2 |
3 | import org.ray.streaming.api.function.Function;
4 |
5 | /**
6 | * Interface of the partitioning strategy.
7 | * @param Type of the input data.
8 | */
9 | @FunctionalInterface
10 | public interface Partition extends Function {
11 |
12 | /**
13 | * Given a record and downstream tasks, determine which task(s) should receive the record.
14 | *
15 | * @param record The record.
16 | * @param taskIds IDs of all downstream tasks.
17 | * @return IDs of the downstream tasks that should receive the record.
18 | */
19 | int[] partition(T record, int[] taskIds);
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/operator/impl/SinkOperator.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.operator.impl;
2 |
3 | import org.ray.streaming.api.function.impl.SinkFunction;
4 | import org.ray.streaming.message.Record;
5 | import org.ray.streaming.operator.OneInputOperator;
6 | import org.ray.streaming.operator.StreamOperator;
7 |
8 |
9 | public class SinkOperator extends StreamOperator> implements
10 | OneInputOperator {
11 |
12 | public SinkOperator(SinkFunction sinkFunction) {
13 | super(sinkFunction);
14 | }
15 |
16 | @Override
17 | public void processElement(Record record) throws Exception {
18 | this.function.sink(record.getValue());
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/ci/travis/upgrade-syn.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Cause the script to exit if a single command fails
4 | set -eo pipefail
5 |
6 | # this stops git rev-parse from failing if we run this from the .git directory
7 | builtin cd "$(dirname "${BASH_SOURCE:-$0}")"
8 |
9 | ROOT="$(git rev-parse --show-toplevel)"
10 | builtin cd "$ROOT"
11 |
12 | find \
13 | python test \
14 | -name '*.py' -type f \
15 | -not -path 'python/ray/cloudpickle/*' \
16 | -exec python -m pyupgrade {} +
17 |
18 | if ! git diff --quiet; then
19 | echo 'Reformatted staged files. Please review and stage the changes.'
20 | echo 'Files updated:'
21 | echo
22 |
23 | git --no-pager diff --name-only
24 |
25 | exit 1
26 | fi
27 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/api/partition/impl/KeyPartition.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.api.partition.impl;
2 |
3 | import org.ray.streaming.api.partition.Partition;
4 | import org.ray.streaming.message.KeyRecord;
5 |
6 | /**
7 | * Partition the record by the key.
8 | *
9 | * @param Type of the partition key.
10 | * @param Type of the input record.
11 | */
12 | public class KeyPartition implements Partition> {
13 |
14 | @Override
15 | public int[] partition(KeyRecord keyRecord, int[] taskIds) {
16 | int length = taskIds.length;
17 | int taskId = taskIds[Math.abs(keyRecord.getKey().hashCode() % length)];
18 | return new int[]{taskId};
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/ray/common/task/task_common.h:
--------------------------------------------------------------------------------
1 | #ifndef RAY_COMMON_TASK_TASK_COMMON_H
2 | #define RAY_COMMON_TASK_TASK_COMMON_H
3 |
4 | #include "ray/protobuf/common.pb.h"
5 |
6 | namespace ray {
7 |
8 | // NOTE(hchen): Below we alias `ray::rpc::Language|TaskType)` in `ray` namespace.
9 | // The reason is because other code should use them as if they were defined in this
10 | // `task_common.h` file, shouldn't care about the implementation detail that they
11 | // are defined in protobuf.
12 |
13 | /// See `common.proto` for definition of `Language` enum.
14 | using Language = rpc::Language;
15 | /// See `common.proto` for definition of `TaskType` enum.
16 | using TaskType = rpc::TaskType;
17 |
18 | } // namespace ray
19 |
20 | #endif
21 |
--------------------------------------------------------------------------------
/python/ray/autoscaler/kubernetes/kubectl-rsync.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Helper script to use kubectl as a remote shell for rsync to sync files
4 | # to/from pods that have rsync installed. Taken from:
5 | # https://serverfault.com/questions/741670/rsync-files-to-a-kubernetes-pod/746352
6 |
7 | if [ -z "$KRSYNC_STARTED" ]; then
8 | export KRSYNC_STARTED=true
9 | exec rsync --blocking-io --rsh "$0" $@
10 | fi
11 |
12 | # Running as --rsh
13 | namespace=''
14 | pod=$1
15 | shift
16 |
17 | # If use uses pod@namespace rsync passes as: {us} -l pod namespace ...
18 | if [ "X$pod" = "X-l" ]; then
19 | pod=$1
20 | shift
21 | namespace="-n $1"
22 | shift
23 | fi
24 |
25 | exec kubectl $namespace exec -i $pod -- "$@"
26 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/halfcheetah-ppo.yaml:
--------------------------------------------------------------------------------
1 | halfcheetah-ppo:
2 | env: HalfCheetah-v2
3 | run: PPO
4 | stop:
5 | episode_reward_mean: 9800
6 | time_total_s: 10800
7 | config:
8 | gamma: 0.99
9 | lambda: 0.95
10 | kl_coeff: 1.0
11 | num_sgd_iter: 32
12 | lr: .0003
13 | vf_loss_coeff: 0.5
14 | clip_param: 0.2
15 | sgd_minibatch_size: 4096
16 | train_batch_size: 65536
17 | num_workers: 16
18 | num_gpus: 1
19 | grad_clip: 0.5
20 | num_envs_per_worker:
21 | grid_search: [16, 32]
22 | batch_mode: truncate_episodes
23 | observation_filter: MeanStdFilter
24 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Why are these changes needed?
4 |
5 |
6 |
7 | ## Related issue number
8 |
9 |
10 |
11 | ## Checks
12 |
13 | - [ ] I've run `scripts/format.sh` to lint the changes in this PR.
14 | - [ ] I've included any doc changes needed for https://ray.readthedocs.io/en/latest/.
15 | - [ ] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failure rates at https://ray-travis-tracker.herokuapp.com/.
16 |
--------------------------------------------------------------------------------
/java/api/pom_template.xml:
--------------------------------------------------------------------------------
1 |
2 | {auto_gen_header}
3 |
6 |
7 | org.ray
8 | ray-superpom
9 | 0.1-SNAPSHOT
10 |
11 | 4.0.0
12 |
13 | ray-api
14 | ray api
15 | java api for ray
16 |
17 | jar
18 |
19 |
20 | {generated_bzl_deps}
21 |
22 |
23 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/operator/impl/MapOperator.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.operator.impl;
2 |
3 | import org.ray.streaming.api.function.impl.MapFunction;
4 | import org.ray.streaming.message.Record;
5 | import org.ray.streaming.operator.OneInputOperator;
6 | import org.ray.streaming.operator.StreamOperator;
7 |
8 |
9 | public class MapOperator extends StreamOperator> implements
10 | OneInputOperator {
11 |
12 | public MapOperator(MapFunction mapFunction) {
13 | super(mapFunction);
14 | }
15 |
16 | @Override
17 | public void processElement(Record record) throws Exception {
18 | this.collect(new Record(this.function.map(record.getValue())));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/python/ray/tests/project_files/session-tests/git-repo-pass/.rayproject/project.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | name: git-repo-pass
4 |
5 | # description: A short description of the project.
6 | repo: https://github.com/ray-project/not-exist
7 |
8 | cluster: .rayproject/cluster.yaml
9 |
10 | environment:
11 | # dockerfile: The dockerfile to be built and ran the commands with.
12 | # dockerimage: The docker image to be used to run the project in, e.g. ubuntu:18.04.
13 | requirements: .rayproject/requirements.txt
14 |
15 | shell: # Shell commands to be ran for environment setup.
16 | - echo "Setting up the environment"
17 |
18 | commands:
19 | - name: default
20 | command: echo "Starting ray job"
21 |
--------------------------------------------------------------------------------
/python/ray/tune/tests/test_dependency.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from __future__ import absolute_import
4 | from __future__ import division
5 | from __future__ import print_function
6 |
7 | import sys
8 |
9 | import ray
10 | from ray.tune import register_trainable, run_experiments
11 |
12 |
13 | def f(config, reporter):
14 | reporter(timesteps_total=1)
15 |
16 |
17 | if __name__ == "__main__":
18 | ray.init()
19 | register_trainable("my_class", f)
20 | run_experiments({
21 | "test": {
22 | "run": "my_class",
23 | "stop": {
24 | "training_iteration": 1
25 | }
26 | }
27 | })
28 | assert "ray.rllib" not in sys.modules, "RLlib should not be imported"
29 |
--------------------------------------------------------------------------------
/ci/jenkins_tests/miscellaneous/test_wait_hanging.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | import ray
6 |
7 |
8 | @ray.remote
9 | def f():
10 | return 0
11 |
12 |
13 | @ray.remote
14 | def g():
15 | import time
16 | start = time.time()
17 | while time.time() < start + 1:
18 | ray.get([f.remote() for _ in range(10)])
19 |
20 |
21 | # 10MB -> hangs after ~5 iterations
22 | # 20MB -> hangs after ~20 iterations
23 | # 50MB -> hangs after ~50 iterations
24 | ray.init(redis_max_memory=1024 * 1024 * 50)
25 |
26 | i = 0
27 | for i in range(100):
28 | i += 1
29 | a = g.remote()
30 | [ok], _ = ray.wait([a])
31 | print("iter", i)
32 |
--------------------------------------------------------------------------------
/python/ray/tests/project_files/session-tests/project-pass/.rayproject/project.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | name: project-pass
4 |
5 | # description: A short description of the project.
6 | # repo: The URL of the repo this project is part of.
7 |
8 | cluster: .rayproject/cluster.yaml
9 |
10 | environment:
11 | # dockerfile: The dockerfile to be built and ran the commands with.
12 | # dockerimage: The docker image to be used to run the project in, e.g. ubuntu:18.04.
13 | requirements: .rayproject/requirements.txt
14 |
15 | shell: # Shell commands to be ran for environment setup.
16 | - echo "Setting up the environment"
17 |
18 | commands:
19 | - name: default
20 | command: echo "Starting ray job"
21 |
--------------------------------------------------------------------------------
/rllib/tests/test_dependency.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from __future__ import absolute_import
4 | from __future__ import division
5 | from __future__ import print_function
6 |
7 | import os
8 | import sys
9 |
10 | os.environ["RLLIB_TEST_NO_TF_IMPORT"] = "1"
11 |
12 | if __name__ == "__main__":
13 | from ray.rllib.agents.a3c import A2CTrainer
14 | assert "tensorflow" not in sys.modules, "TF initially present"
15 |
16 | # note: no ray.init(), to test it works without Ray
17 | trainer = A2CTrainer(
18 | env="CartPole-v0", config={
19 | "use_pytorch": True,
20 | "num_workers": 0
21 | })
22 | trainer.train()
23 |
24 | assert "tensorflow" not in sys.modules, "TF should not be imported"
25 |
--------------------------------------------------------------------------------
/doc/source/rllib-package-ref.rst:
--------------------------------------------------------------------------------
1 | RLlib Package Reference
2 | =======================
3 |
4 | ray.rllib.policy
5 | ----------------
6 |
7 | .. automodule:: ray.rllib.policy
8 | :members:
9 |
10 | ray.rllib.env
11 | -------------
12 |
13 | .. automodule:: ray.rllib.env
14 | :members:
15 |
16 | ray.rllib.evaluation
17 | --------------------
18 |
19 | .. automodule:: ray.rllib.evaluation
20 | :members:
21 |
22 | ray.rllib.models
23 | ----------------
24 |
25 | .. automodule:: ray.rllib.models
26 | :members:
27 |
28 | ray.rllib.optimizers
29 | --------------------
30 |
31 | .. automodule:: ray.rllib.optimizers
32 | :members:
33 |
34 | ray.rllib.utils
35 | ---------------
36 |
37 | .. automodule:: ray.rllib.utils
38 | :members:
39 |
--------------------------------------------------------------------------------
/java/test/src/main/resources/test_cross_language_invocation.py:
--------------------------------------------------------------------------------
1 | # This file is used by CrossLanguageInvocationTest.java to test cross-language
2 | # invocation.
3 |
4 | from __future__ import absolute_import
5 | from __future__ import division
6 | from __future__ import print_function
7 |
8 | import six
9 |
10 | import ray
11 |
12 |
13 | @ray.remote
14 | def py_func(value):
15 | assert isinstance(value, bytes)
16 | return b"Response from Python: " + value
17 |
18 |
19 | @ray.remote
20 | class Counter(object):
21 | def __init__(self, value):
22 | self.value = int(value)
23 |
24 | def increase(self, delta):
25 | self.value += int(delta)
26 | return str(self.value).encode("utf-8") if six.PY3 else str(self.value)
27 |
--------------------------------------------------------------------------------
/python/ray/experimental/serve/examples/echo.py:
--------------------------------------------------------------------------------
1 | """
2 | Example service that prints out http context.
3 | """
4 |
5 | import time
6 |
7 | import requests
8 |
9 | from ray.experimental import serve
10 | from ray.experimental.serve.utils import pformat_color_json
11 |
12 |
13 | def echo(flask_request):
14 | return "hello " + flask_request.args.get("name", "serve!")
15 |
16 |
17 | serve.init(blocking=True)
18 |
19 | serve.create_endpoint("my_endpoint", "/echo", blocking=True)
20 | serve.create_backend(echo, "echo:v1")
21 | serve.link("my_endpoint", "echo:v1")
22 |
23 | while True:
24 | resp = requests.get("http://127.0.0.1:8000/echo").json()
25 | print(pformat_color_json(resp))
26 |
27 | print("...Sleeping for 2 seconds...")
28 | time.sleep(2)
29 |
--------------------------------------------------------------------------------
/python/ray/tests/project_files/session-tests/commands-test/.rayproject/project.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | name: commands-test
4 |
5 | # description: A short description of the project.
6 | repo: https://github.com/ray-project/not-exist
7 |
8 | cluster: .rayproject/cluster.yaml
9 |
10 | environment:
11 | shell:
12 | - echo "Setting up"
13 |
14 | commands:
15 | - name: first
16 | command: echo "Starting ray job with {{a}} and {{b}}"
17 | params:
18 | - name: a
19 | help: "This is the first parameter"
20 | choices: ["1", "2"]
21 | - name: b
22 | help: "This is the second parameter"
23 | choices: ["1", "2"]
24 |
25 | - name: second
26 | command: echo "Some command"
27 |
--------------------------------------------------------------------------------
/doc/examples/resnet/.rayproject/cluster.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | # A unique identifier for the head node and workers of this cluster.
4 | cluster_name: ray-example-resnet
5 |
6 | # The maximum number of workers nodes to launch in addition to the head
7 | # node. This takes precedence over min_workers. min_workers defaults to 0.
8 | max_workers: 1
9 |
10 | # Cloud-provider specific configuration.
11 | provider:
12 | type: aws
13 | region: us-west-2
14 | availability_zone: us-west-2a
15 |
16 | head_node:
17 | InstanceType: m5.2xlarge
18 | ImageId: ami-0b294f219d14e6a82 # Deep Learning AMI (Ubuntu) Version 21.0
19 |
20 | # How Ray will authenticate with newly launched nodes.
21 | auth:
22 | ssh_user: ubuntu
23 |
--------------------------------------------------------------------------------
/rllib/offline/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | from ray.rllib.offline.io_context import IOContext
6 | from ray.rllib.offline.json_reader import JsonReader
7 | from ray.rllib.offline.json_writer import JsonWriter
8 | from ray.rllib.offline.output_writer import OutputWriter, NoopOutput
9 | from ray.rllib.offline.input_reader import InputReader
10 | from ray.rllib.offline.mixed_input import MixedInput
11 | from ray.rllib.offline.shuffled_input import ShuffledInput
12 |
13 | __all__ = [
14 | "IOContext",
15 | "JsonReader",
16 | "JsonWriter",
17 | "NoopOutput",
18 | "OutputWriter",
19 | "InputReader",
20 | "MixedInput",
21 | "ShuffledInput",
22 | ]
23 |
--------------------------------------------------------------------------------
/ci/suppress_output:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Run a command, suppressing output unless it hangs or crashes.
3 |
4 | TMPFILE=`mktemp`
5 | PID=$$
6 |
7 | # Print output to avoid travis killing us
8 | watchdog() {
9 | for i in `seq 5 5 120`; do
10 | sleep 300
11 | echo "This command has been running for more than $i minutes..."
12 | done
13 | echo "Command timed out after 2h, dumping logs:"
14 | cat $TMPFILE
15 | echo "TIMED OUT"
16 | kill -SIGKILL $PID
17 | }
18 |
19 | watchdog & 2>/dev/null
20 | WATCHDOG_PID=$!
21 |
22 | time "$@" >$TMPFILE 2>&1
23 |
24 | CODE=$?
25 | if [ $CODE != 0 ]; then
26 | tail -n 2000 $TMPFILE
27 | echo "FAILED $CODE"
28 | kill $WATCHDOG_PID
29 | exit $CODE
30 | fi
31 |
32 | kill $WATCHDOG_PID
33 | exit 0
34 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/api/stream/UnionStream.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.api.stream;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import org.ray.streaming.operator.StreamOperator;
6 |
7 | /**
8 | * Represents a union DataStream.
9 | *
10 | * @param The type of union data.
11 | */
12 | public class UnionStream extends DataStream {
13 |
14 | private List unionStreams;
15 |
16 | public UnionStream(DataStream input, StreamOperator streamOperator, DataStream other) {
17 | super(input, streamOperator);
18 | this.unionStreams = new ArrayList<>();
19 | this.unionStreams.add(other);
20 | }
21 |
22 | public List getUnionStreams() {
23 | return unionStreams;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/java/test/src/main/java/org/ray/api/RayAlterSuiteListener.java:
--------------------------------------------------------------------------------
1 | package org.ray.api;
2 |
3 | import java.util.List;
4 | import org.ray.api.options.ActorCreationOptions;
5 | import org.testng.IAlterSuiteListener;
6 | import org.testng.xml.XmlGroups;
7 | import org.testng.xml.XmlRun;
8 | import org.testng.xml.XmlSuite;
9 |
10 | public class RayAlterSuiteListener implements IAlterSuiteListener {
11 |
12 | @Override
13 | public void alter(List suites) {
14 | XmlSuite suite = suites.get(0);
15 | if (ActorCreationOptions.DEFAULT_USE_DIRECT_CALL) {
16 | XmlGroups groups = new XmlGroups();
17 | XmlRun run = new XmlRun();
18 | run.onInclude("directCall");
19 | groups.setRun(run);
20 | suite.setGroups(groups);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/python/ray/tune/cluster_info.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | import getpass
6 | import os
7 |
8 |
9 | def get_ssh_user():
10 | """Returns ssh username for connecting to cluster workers."""
11 |
12 | return getpass.getuser()
13 |
14 |
15 | def get_ssh_key():
16 | """Returns ssh key to connecting to cluster workers.
17 |
18 | If the env var TUNE_CLUSTER_SSH_KEY is provided, then this key
19 | will be used for syncing across different nodes.
20 | """
21 | path = os.environ.get("TUNE_CLUSTER_SSH_KEY",
22 | os.path.expanduser("~/ray_bootstrap_key.pem"))
23 | if os.path.exists(path):
24 | return path
25 | return None
26 |
--------------------------------------------------------------------------------
/java/checkstyle-suppressions.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/bazel/BUILD.cython:
--------------------------------------------------------------------------------
1 | # Adapted from grpc/third_party/cython.BUILD
2 |
3 | # Adapted with modifications from tensorflow/third_party/cython.BUILD
4 |
5 | py_library(
6 | name="cython_lib",
7 | srcs=glob(
8 | ["Cython/**/*.py"],
9 | exclude=[
10 | "**/Tests/*.py",
11 | ],
12 | ) + ["cython.py"],
13 | data=glob([
14 | "Cython/**/*.pyx",
15 | "Cython/Utility/*.*",
16 | "Cython/Includes/**/*.pxd",
17 | ]),
18 | srcs_version="PY2AND3",
19 | visibility=["//visibility:public"],
20 | )
21 |
22 | # May not be named "cython", since that conflicts with Cython/ on OSX
23 | filegroup(
24 | name="cython_binary",
25 | srcs=["cython.py"],
26 | visibility=["//visibility:public"],
27 | data=["cython_lib"],
28 | )
29 |
--------------------------------------------------------------------------------
/src/ray/thirdparty/hiredis/examples/example-qt.h:
--------------------------------------------------------------------------------
1 | #ifndef __HIREDIS_EXAMPLE_QT_H
2 | #define __HIREDIS_EXAMPLE_QT_H
3 |
4 | #include
5 |
6 | class ExampleQt : public QObject {
7 |
8 | Q_OBJECT
9 |
10 | public:
11 | ExampleQt(const char * value, QObject * parent = 0)
12 | : QObject(parent), m_value(value) {}
13 |
14 | signals:
15 | void finished();
16 |
17 | public slots:
18 | void run();
19 |
20 | private:
21 | void finish() { emit finished(); }
22 |
23 | private:
24 | const char * m_value;
25 | redisAsyncContext * m_ctx;
26 | RedisQtAdapter m_adapter;
27 |
28 | friend
29 | void getCallback(redisAsyncContext *, void *, void *);
30 | };
31 |
32 | #endif /* !__HIREDIS_EXAMPLE_QT_H */
33 |
--------------------------------------------------------------------------------
/doc/tools/install-prometheus-server.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -x
4 | set -e
5 |
6 | TOOLS_DIR=$(cd "$(dirname "${BASH_SOURCE:-$0}")"; pwd)
7 |
8 | pushd $TOOLS_DIR
9 |
10 | # Download Prometheus server.
11 | unamestr="$(uname)"
12 | if [[ "$unamestr" == "Linux" ]]; then
13 | echo "Downloading Prometheus server for linux system."
14 | PACKAGE_NAME=prometheus-2.8.0.linux-amd64
15 | elif [[ "$unamestr" == "Darwin" ]]; then
16 | echo "Downloading Prometheus server for MacOS system."
17 | PACKAGE_NAME=prometheus-2.8.0.darwin-amd64
18 | else
19 | echo "Downloading abort: Unrecognized platform."
20 | exit -1
21 | fi
22 |
23 | URL=https://github.com/prometheus/prometheus/releases/download/v2.8.0/$PACKAGE_NAME.tar.gz
24 | wget $URL
25 | tar xvfz $PACKAGE_NAME.tar.gz
26 |
27 | popd
28 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/invertedpendulum-td3.yaml:
--------------------------------------------------------------------------------
1 | invertedpendulum-td3:
2 | # This is a TD3 with stopping conditions and network size tuned specifically
3 | # for InvertedPendulum. Should be able to reach 1,000 reward (the maximum
4 | # achievable) in 10,000 to 20,000 steps.
5 | env: InvertedPendulum-v2
6 | run: TD3
7 | stop:
8 | episode_reward_mean: 9999.9
9 | time_total_s: 900 # 15 minutes
10 | timesteps_total: 1000000
11 | config:
12 | # === Model ===
13 | actor_hiddens: [32, 32]
14 | critic_hiddens: [32, 32]
15 |
16 | # === Exploration ===
17 | learning_starts: 1000
18 | pure_exploration_steps: 1000
19 |
20 | # === Evaluation ===
21 | evaluation_interval: 1
22 | evaluation_num_episodes: 5
23 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/pong-ppo.yaml:
--------------------------------------------------------------------------------
1 | # On a single GPU, this achieves maximum reward in ~15-20 minutes.
2 | #
3 | # $ python train.py -f tuned_examples/pong-ppo.yaml
4 | #
5 | pong-ppo:
6 | env: PongNoFrameskip-v4
7 | run: PPO
8 | config:
9 | lambda: 0.95
10 | kl_coeff: 0.5
11 | clip_rewards: True
12 | clip_param: 0.1
13 | vf_clip_param: 10.0
14 | entropy_coeff: 0.01
15 | train_batch_size: 5000
16 | sample_batch_size: 20
17 | sgd_minibatch_size: 500
18 | num_sgd_iter: 10
19 | num_workers: 32
20 | num_envs_per_worker: 5
21 | batch_mode: truncate_episodes
22 | observation_filter: NoFilter
23 | vf_share_layers: true
24 | num_gpus: 1
25 | model:
26 | dim: 42
27 |
--------------------------------------------------------------------------------
/java/api/src/main/java/org/ray/api/options/CallOptions.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.options;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * The options for RayCall.
8 | */
9 | public class CallOptions extends BaseTaskOptions {
10 |
11 | private CallOptions(Map resources) {
12 | super(resources);
13 | }
14 |
15 | /**
16 | * This inner class for building CallOptions.
17 | */
18 | public static class Builder {
19 |
20 | private Map resources = new HashMap<>();
21 |
22 | public Builder setResources(Map resources) {
23 | this.resources = resources;
24 | return this;
25 | }
26 |
27 | public CallOptions createCallOptions() {
28 | return new CallOptions(resources);
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/core/runtime/collector/CollectionCollector.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.core.runtime.collector;
2 |
3 | import java.util.List;
4 | import org.ray.streaming.api.collector.Collector;
5 | import org.ray.streaming.message.Record;
6 |
7 | /**
8 | * Combination of multiple collectors.
9 | *
10 | * @param The type of output data.
11 | */
12 | public class CollectionCollector implements Collector {
13 |
14 | private List collectorList;
15 |
16 | public CollectionCollector(List collectorList) {
17 | this.collectorList = collectorList;
18 | }
19 |
20 | @Override
21 | public void collect(T value) {
22 | for (Collector collector : collectorList) {
23 | collector.collect(new Record(value));
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/java/test/src/main/java/org/ray/api/test/RayConfigTest.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.test;
2 |
3 | import org.ray.runtime.config.RayConfig;
4 | import org.ray.runtime.generated.Common.WorkerType;
5 | import org.testng.Assert;
6 | import org.testng.annotations.Test;
7 |
8 | public class RayConfigTest {
9 |
10 | @Test
11 | public void testCreateRayConfig() {
12 | try {
13 | System.setProperty("ray.job.resource-path", "path/to/ray/job/resource/path");
14 | RayConfig rayConfig = RayConfig.create();
15 | Assert.assertEquals(WorkerType.DRIVER, rayConfig.workerMode);
16 | Assert.assertEquals("path/to/ray/job/resource/path", rayConfig.jobResourcePath);
17 | } finally {
18 | // Unset system properties.
19 | System.clearProperty("ray.job.resource-path");
20 | }
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/python/ray/tune/automlboard/static/css/HomePage.css:
--------------------------------------------------------------------------------
1 | .outer-container {
2 | display: -ms-flexbox;
3 | display: flex;
4 | }
5 | .HomePage-experiment-list-container {
6 | width: 10%;
7 | min-width: 333px;
8 | }
9 | .experiment-view-container {
10 | width: 80%;
11 | }
12 | .experiment-view-right {
13 | width: 10%;
14 | }
15 |
16 |
17 | /* BEGIN css for when experiment list collapsed */
18 | .experiment-page-container {
19 | width: 80%;
20 | margin: 0 auto;
21 | }
22 | .collapsed-expander-container {
23 | float: left;
24 | }
25 |
26 | .expander {
27 | display: inline-block;
28 | background-color: #082142d6;
29 | color: #FFFFFF;
30 | font-size: 16px;
31 | line-height: 24px;
32 | width: 24px;
33 | height: 24px;
34 | text-align: center;
35 | vertical-align: bottom;
36 | }
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/operator/impl/KeyByOperator.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.operator.impl;
2 |
3 | import org.ray.streaming.api.function.impl.KeyFunction;
4 | import org.ray.streaming.message.KeyRecord;
5 | import org.ray.streaming.message.Record;
6 | import org.ray.streaming.operator.OneInputOperator;
7 | import org.ray.streaming.operator.StreamOperator;
8 |
9 | public class KeyByOperator extends StreamOperator> implements
10 | OneInputOperator {
11 |
12 | public KeyByOperator(KeyFunction keyFunction) {
13 | super(keyFunction);
14 | }
15 |
16 | @Override
17 | public void processElement(Record record) throws Exception {
18 | K key = this.function.keyBy(record.getValue());
19 | collect(new KeyRecord<>(key, record.getValue()));
20 | }
21 | }
22 |
23 |
--------------------------------------------------------------------------------
/ci/travis/check-git-clang-format-output.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if [ "$TRAVIS_PULL_REQUEST" == "false" ] ; then
4 | # Not in a pull request, so compare against parent commit
5 | base_commit="HEAD^"
6 | echo "Running clang-format against parent commit $(git rev-parse $base_commit)"
7 | else
8 | base_commit="$TRAVIS_BRANCH"
9 | echo "Running clang-format against branch $base_commit, with hash $(git rev-parse $base_commit)"
10 | fi
11 | output="$(ci/travis/git-clang-format --binary clang-format --commit $base_commit --diff --exclude '(.*thirdparty/|.*redismodule.h|.*.js|.*.java)')"
12 | if [ "$output" == "no modified files to format" ] || [ "$output" == "clang-format did not modify any files" ] ; then
13 | echo "clang-format passed."
14 | exit 0
15 | else
16 | echo "clang-format failed:"
17 | echo "$output"
18 | exit 1
19 | fi
20 |
--------------------------------------------------------------------------------
/rllib/agents/a3c/a2c.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | from ray.rllib.agents.a3c.a3c import DEFAULT_CONFIG as A3C_CONFIG, \
6 | validate_config, get_policy_class
7 | from ray.rllib.agents.a3c.a3c_tf_policy import A3CTFPolicy
8 | from ray.rllib.agents.trainer_template import build_trainer
9 | from ray.rllib.utils import merge_dicts
10 |
11 | A2C_DEFAULT_CONFIG = merge_dicts(
12 | A3C_CONFIG,
13 | {
14 | "sample_batch_size": 20,
15 | "min_iter_time_s": 10,
16 | "sample_async": False,
17 | },
18 | )
19 |
20 | A2CTrainer = build_trainer(
21 | name="A2C",
22 | default_config=A2C_DEFAULT_CONFIG,
23 | default_policy=A3CTFPolicy,
24 | get_policy_class=get_policy_class,
25 | validate_config=validate_config)
26 |
--------------------------------------------------------------------------------
/rllib/offline/output_writer.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | from ray.rllib.utils.annotations import override
6 | from ray.rllib.utils.annotations import PublicAPI
7 |
8 |
9 | @PublicAPI
10 | class OutputWriter(object):
11 | """Writer object for saving experiences from policy evaluation."""
12 |
13 | @PublicAPI
14 | def write(self, sample_batch):
15 | """Save a batch of experiences.
16 |
17 | Arguments:
18 | sample_batch: SampleBatch or MultiAgentBatch to save.
19 | """
20 | raise NotImplementedError
21 |
22 |
23 | class NoopOutput(OutputWriter):
24 | """Output writer that discards its outputs."""
25 |
26 | @override(OutputWriter)
27 | def write(self, sample_batch):
28 | pass
29 |
--------------------------------------------------------------------------------
/java/api/src/main/java/org/ray/api/exception/UnreconstructableException.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.exception;
2 |
3 | import org.ray.api.id.ObjectId;
4 |
5 | /**
6 | * Indicates that an object is lost (either evicted or explicitly deleted) and cannot be
7 | * reconstructed.
8 | *
9 | * Note, this exception only happens for actor objects. If actor's current state is after object's
10 | * creating task, the actor cannot re-run the task to reconstruct the object.
11 | */
12 | public class UnreconstructableException extends RayException {
13 |
14 | public final ObjectId objectId;
15 |
16 | public UnreconstructableException(ObjectId objectId) {
17 | super(String.format(
18 | "Object %s is lost (either evicted or explicitly deleted) and cannot be reconstructed.",
19 | objectId));
20 | this.objectId = objectId;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/java/api/src/main/java/org/ray/api/options/BaseTaskOptions.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.options;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * The options class for RayCall or ActorCreation.
8 | */
9 | public abstract class BaseTaskOptions {
10 | public final Map resources;
11 |
12 | public BaseTaskOptions() {
13 | resources = new HashMap<>();
14 | }
15 |
16 | public BaseTaskOptions(Map resources) {
17 | for (Map.Entry entry : resources.entrySet()) {
18 | if (entry.getValue().compareTo(0.0) <= 0) {
19 | throw new IllegalArgumentException(String.format("Resource capacity should be " +
20 | "positive, but got resource %s = %f.", entry.getKey(), entry.getValue()));
21 | }
22 | }
23 | this.resources = resources;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/java/api/src/main/java/org/ray/api/WaitResult.java:
--------------------------------------------------------------------------------
1 | package org.ray.api;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * Represents the result of a Ray.wait call. It contains 2 lists,
7 | * one containing the locally available objects, one containing the rest.
8 | */
9 | public final class WaitResult {
10 |
11 | private final List> ready;
12 | private final List> unready;
13 |
14 | public WaitResult(List> ready, List> unready) {
15 | this.ready = ready;
16 | this.unready = unready;
17 | }
18 |
19 | /**
20 | * Get the list of ready objects.
21 | */
22 | public List> getReady() {
23 | return ready;
24 | }
25 |
26 | /**
27 | * Get the list of unready objects.
28 | */
29 | public List> getUnready() {
30 | return unready;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/java/runtime/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | ray.logging.level=INFO
2 |
3 | ray.logging.stdout=org.apache.log4j.ConsoleAppender
4 | ray.logging.file=org.apache.log4j.varia.NullAppender
5 |
6 | log4j.rootLogger=${ray.logging.level}, stdout, file
7 |
8 | log4j.appender.stdout=${ray.logging.stdout}
9 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
10 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p %c{1} [%t]: %m%n
11 |
12 | # Set the file appender to null by default. If `ray.redirect-output` config is set to true,
13 | # this appender will be set to a real file appender.
14 | log4j.appender.file=${ray.logging.file}
15 | log4j.appender.file.File=${ray.logging.file.path}
16 | log4j.appender.file.layout=org.apache.log4j.PatternLayout
17 | log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p %c{1} [%t]: %m%n
18 |
--------------------------------------------------------------------------------
/python/ray/tune/schedulers/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | from ray.tune.schedulers.trial_scheduler import TrialScheduler, FIFOScheduler
6 | from ray.tune.schedulers.hyperband import HyperBandScheduler
7 | from ray.tune.schedulers.hb_bohb import HyperBandForBOHB
8 | from ray.tune.schedulers.async_hyperband import (AsyncHyperBandScheduler,
9 | ASHAScheduler)
10 | from ray.tune.schedulers.median_stopping_rule import MedianStoppingRule
11 | from ray.tune.schedulers.pbt import PopulationBasedTraining
12 |
13 | __all__ = [
14 | "TrialScheduler", "HyperBandScheduler", "AsyncHyperBandScheduler",
15 | "ASHAScheduler", "MedianStoppingRule", "FIFOScheduler",
16 | "PopulationBasedTraining", "HyperBandForBOHB"
17 | ]
18 |
--------------------------------------------------------------------------------
/java/test/src/main/java/org/ray/api/test/PlasmaStoreTest.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.test;
2 |
3 | import org.ray.api.Ray;
4 | import org.ray.api.TestUtils;
5 | import org.ray.api.id.ObjectId;
6 | import org.ray.runtime.object.ObjectStore;
7 | import org.testng.Assert;
8 | import org.testng.annotations.Test;
9 |
10 | public class PlasmaStoreTest extends BaseTest {
11 |
12 | @Test
13 | public void testPutWithDuplicateId() {
14 | TestUtils.skipTestUnderSingleProcess();
15 | ObjectId objectId = ObjectId.fromRandom();
16 | ObjectStore objectStore = TestUtils.getRuntime().getObjectStore();
17 | objectStore.put("1", objectId);
18 | Assert.assertEquals(Ray.get(objectId), "1");
19 | objectStore.put("2", objectId);
20 | // Putting the second object with duplicate ID should fail but ignored.
21 | Assert.assertEquals(Ray.get(objectId), "1");
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/python/ray/experimental/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | from .gcs_flush_policy import (set_flushing_policy, GcsFlushPolicy,
6 | SimpleGcsFlushPolicy)
7 | from .named_actors import get_actor, register_actor
8 | from .api import get, wait
9 | from .dynamic_resources import set_resource
10 |
11 |
12 | def TensorFlowVariables(*args, **kwargs):
13 | raise DeprecationWarning(
14 | "'ray.experimental.TensorFlowVariables' is deprecated. Instead, please"
15 | " do 'from ray.experimental.tf_utils import TensorFlowVariables'.")
16 |
17 |
18 | __all__ = [
19 | "TensorFlowVariables", "get_actor", "register_actor", "get", "wait",
20 | "set_flushing_policy", "GcsFlushPolicy", "SimpleGcsFlushPolicy",
21 | "set_resource"
22 | ]
23 |
--------------------------------------------------------------------------------
/python/ray/tests/project_files/session-tests/invalid-config-fail/.rayproject/project.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | name: invalid-config-fail
4 |
5 | # description: A short description of the project.
6 | # repo: The URL of the repo this project is part of.
7 |
8 | cluster: .rayproject/cluster.yaml
9 |
10 | environment:
11 | # NOTE: The following is invalid because you can't have both dockerfile
12 | # and dockerimage
13 | dockerfile: The dockerfile to be built and ran the commands with.
14 | dockerimage: The docker image to be used to run the project in, e.g. ubuntu:18.04.
15 |
16 | requirements: .rayproject/requirements.txt
17 |
18 | shell: # Shell commands to be ran for environment setup.
19 | - echo "Setting up the environment"
20 |
21 | commands:
22 | - name: first-command
23 | command: echo "Starting ray job"
24 |
--------------------------------------------------------------------------------
/ci/travis/install-bazel.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Cause the script to exit if a single command fails
4 | set -e
5 |
6 | platform="unknown"
7 | unamestr="$(uname)"
8 | if [[ "$unamestr" == "Linux" ]]; then
9 | echo "Platform is linux."
10 | platform="linux"
11 | elif [[ "$unamestr" == "Darwin" ]]; then
12 | echo "Platform is macosx."
13 | platform="darwin"
14 | else
15 | echo "Unrecognized platform."
16 | exit 1
17 | fi
18 |
19 | URL="https://github.com/bazelbuild/bazel/releases/download/0.26.1/bazel-0.26.1-installer-${platform}-x86_64.sh"
20 | wget -O install.sh $URL
21 | chmod +x install.sh
22 | ./install.sh --user
23 | rm -f install.sh
24 |
25 | if [[ "$TRAVIS" == "true" ]]; then
26 | # Use bazel disk cache if this script is running in Travis.
27 | mkdir -p $HOME/ray-bazel-cache
28 | echo "build --disk_cache=$HOME/ray-bazel-cache" >> $HOME/.bazelrc
29 | fi
30 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/atari-ppo.yaml:
--------------------------------------------------------------------------------
1 | # Runs on a single g3.16xl node
2 | # See https://github.com/ray-project/rl-experiments for results
3 | atari-ppo:
4 | env:
5 | grid_search:
6 | - BreakoutNoFrameskip-v4
7 | - BeamRiderNoFrameskip-v4
8 | - QbertNoFrameskip-v4
9 | - SpaceInvadersNoFrameskip-v4
10 | run: PPO
11 | config:
12 | lambda: 0.95
13 | kl_coeff: 0.5
14 | clip_rewards: True
15 | clip_param: 0.1
16 | vf_clip_param: 10.0
17 | entropy_coeff: 0.01
18 | train_batch_size: 5000
19 | sample_batch_size: 100
20 | sgd_minibatch_size: 500
21 | num_sgd_iter: 10
22 | num_workers: 10
23 | num_envs_per_worker: 5
24 | batch_mode: truncate_episodes
25 | observation_filter: NoFilter
26 | vf_share_layers: true
27 | num_gpus: 1
28 |
--------------------------------------------------------------------------------
/java/runtime/src/main/java/org/ray/runtime/object/NativeRayObject.java:
--------------------------------------------------------------------------------
1 | package org.ray.runtime.object;
2 |
3 | import com.google.common.base.Preconditions;
4 |
5 | /**
6 | * Binary representation of a ray object. See `RayObject` class in C++ for details.
7 | */
8 | public class NativeRayObject {
9 |
10 | public byte[] data;
11 | public byte[] metadata;
12 |
13 | public NativeRayObject(byte[] data, byte[] metadata) {
14 | Preconditions.checkState(bufferLength(data) > 0 || bufferLength(metadata) > 0);
15 | this.data = data;
16 | this.metadata = metadata;
17 | }
18 |
19 | private static int bufferLength(byte[] buffer) {
20 | if (buffer == null) {
21 | return 0;
22 | }
23 | return buffer.length;
24 | }
25 |
26 | @Override
27 | public String toString() {
28 | return ": " + bufferLength(data) + ", : " + bufferLength(metadata);
29 | }
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/bazel/ray_deps_build_all.bzl:
--------------------------------------------------------------------------------
1 | load("@com_github_ray_project_ray//java:dependencies.bzl", "gen_java_deps")
2 | load("@com_github_nelhage_rules_boost//:boost/boost.bzl", "boost_deps")
3 | load("@com_github_jupp0r_prometheus_cpp//:repositories.bzl", "prometheus_cpp_repositories")
4 | load("@com_github_ray_project_ray//bazel:python_configure.bzl", "python_configure")
5 | load("@com_github_checkstyle_java//:repo.bzl", "checkstyle_deps")
6 | load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
7 | load("@build_stack_rules_proto//java:deps.bzl", "java_proto_compile")
8 | load("@build_stack_rules_proto//python:deps.bzl", "python_proto_compile")
9 |
10 |
11 | def ray_deps_build_all():
12 | gen_java_deps()
13 | checkstyle_deps()
14 | boost_deps()
15 | prometheus_cpp_repositories()
16 | python_configure(name = "local_config_python")
17 | grpc_deps()
18 | java_proto_compile()
19 | python_proto_compile()
20 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/core/processor/OneInputProcessor.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.core.processor;
2 |
3 | import org.ray.streaming.message.Record;
4 | import org.ray.streaming.operator.OneInputOperator;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | public class OneInputProcessor extends StreamProcessor, OneInputOperator> {
9 |
10 | private static final Logger LOGGER = LoggerFactory.getLogger(OneInputProcessor.class);
11 |
12 | public OneInputProcessor(OneInputOperator operator) {
13 | super(operator);
14 | }
15 |
16 | @Override
17 | public void process(Record record) {
18 | try {
19 | this.operator.processElement(record);
20 | } catch (Exception e) {
21 | throw new RuntimeException(e);
22 | }
23 | }
24 |
25 | @Override
26 | public void close() {
27 | this.operator.close();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/mujoco-td3.yaml:
--------------------------------------------------------------------------------
1 | mujoco-td3:
2 | # Solve latest versions of the four hardest Mujoco tasks benchmarked in the
3 | # original TD3 paper. Average return over 10 trials at end of 1,000,000
4 | # timesteps (taken from Table 2 of the paper) are given in parens at the end
5 | # of reach environment name.
6 | #
7 | # Paper is at https://arxiv.org/pdf/1802.09477.pdf
8 | env:
9 | grid_search:
10 | - HalfCheetah-v2 # (9,532.99)
11 | - Hopper-v2 # (3,304.75)
12 | - Walker2d-v2 # (4,565.24)
13 | - Ant-v2 # (4,185.06)
14 | run: TD3
15 | stop:
16 | timesteps_total: 1000000
17 | config:
18 | # === Exploration ===
19 | learning_starts: 10000
20 | pure_exploration_steps: 10000
21 |
22 | # === Evaluation ===
23 | evaluation_interval: 5
24 | evaluation_num_episodes: 10
25 |
--------------------------------------------------------------------------------
/rllib/tuned_examples/pong-rainbow.yaml:
--------------------------------------------------------------------------------
1 | pong-deterministic-rainbow:
2 | env: PongDeterministic-v4
3 | run: DQN
4 | stop:
5 | episode_reward_mean: 20
6 | config:
7 | num_atoms: 51
8 | noisy: True
9 | gamma: 0.99
10 | lr: .0001
11 | hiddens: [512]
12 | learning_starts: 10000
13 | buffer_size: 50000
14 | sample_batch_size: 4
15 | train_batch_size: 32
16 | schedule_max_timesteps: 2000000
17 | exploration_final_eps: 0.0
18 | exploration_fraction: .000001
19 | target_network_update_freq: 500
20 | prioritized_replay: True
21 | prioritized_replay_alpha: 0.5
22 | beta_annealing_fraction: 0.2
23 | final_prioritized_replay_beta: 1.0
24 | n_step: 3
25 | gpu: True
26 | model:
27 | grayscale: True
28 | zero_mean: False
29 | dim: 42
30 |
--------------------------------------------------------------------------------
/ci/travis/install-cython-examples.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Cause the script to exit if a single command fails
4 | set -e
5 |
6 | ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE:-$0}")"; pwd)
7 |
8 | echo "PYTHON is $PYTHON"
9 |
10 | cython_examples="$ROOT_DIR/../../doc/examples/cython"
11 |
12 | if [[ "$PYTHON" == "2.7" ]]; then
13 |
14 | pushd $cython_examples
15 | pip install --progress-bar=off scipy
16 | python setup.py install --user
17 | popd
18 |
19 | elif [[ "$PYTHON" == "3.5" ]]; then
20 | export PATH="$HOME/miniconda/bin:$PATH"
21 |
22 | pushd $cython_examples
23 | pip install --progress-bar=off scipy
24 | python setup.py install --user
25 | popd
26 |
27 | elif [[ "$LINT" == "1" ]]; then
28 | export PATH="$HOME/miniconda/bin:$PATH"
29 |
30 | pushd $cython_examples
31 | python setup.py install --user
32 | popd
33 |
34 | else
35 | echo "Unrecognized Python version."
36 | exit 1
37 | fi
38 |
--------------------------------------------------------------------------------
/ci/travis/install-ray.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Cause the script to exit if a single command fails.
4 | set -e
5 |
6 | ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE:-$0}")"; pwd)
7 |
8 | echo "PYTHON is $PYTHON"
9 |
10 | if [[ "$PYTHON" == "2.7" ]]; then
11 |
12 | pushd "$ROOT_DIR/../../python"
13 | python setup.py install --user
14 | popd
15 |
16 | elif [[ "$PYTHON" == "3.5" ]]; then
17 | export PATH="$HOME/miniconda/bin:$PATH"
18 |
19 | pushd "$ROOT_DIR/../../python"
20 | pushd ray/dashboard/client
21 | source $HOME/.nvm/nvm.sh
22 | nvm use node
23 | npm ci
24 | npm run build
25 | popd
26 | python setup.py install --user
27 | popd
28 |
29 | elif [[ "$LINT" == "1" ]]; then
30 | export PATH="$HOME/miniconda/bin:$PATH"
31 |
32 | pushd "$ROOT_DIR/../../python"
33 | python setup.py install --user
34 | popd
35 |
36 | else
37 | echo "Unrecognized Python version."
38 | exit 1
39 | fi
40 |
--------------------------------------------------------------------------------
/python/ray/experimental/serve/context.py:
--------------------------------------------------------------------------------
1 | from enum import IntEnum
2 |
3 | from ray.experimental.serve.exceptions import RayServeException
4 |
5 |
6 | class TaskContext(IntEnum):
7 | """TaskContext constants for queue.enqueue method"""
8 | Web = 1
9 | Python = 2
10 |
11 |
12 | # Global variable will be modified in worker
13 | # web == True: currrently processing a request from web server
14 | # web == False: currently processing a request from python
15 | web = False
16 |
17 | _not_in_web_context_error = """
18 | Accessing the request object outside of the web context. Please use
19 | "serve.context.web" to determine when the function is called within
20 | a web context.
21 | """
22 |
23 |
24 | class FakeFlaskQuest:
25 | def __getattribute__(self, name):
26 | raise RayServeException(_not_in_web_context_error)
27 |
28 | def __setattr__(self, name, value):
29 | raise RayServeException(_not_in_web_context_error)
30 |
--------------------------------------------------------------------------------
/python/ray/experimental/serve/tests/test_persistence.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | import tempfile
4 |
5 | import ray
6 | from ray.experimental import serve
7 |
8 |
9 | def test_new_driver(serve_instance):
10 | script = """
11 | import ray
12 | ray.init(address="auto")
13 |
14 | from ray.experimental import serve
15 | serve.init()
16 |
17 |
18 | def function(flask_request):
19 | return "OK!"
20 |
21 | serve.create_endpoint("driver", "/driver")
22 | serve.create_backend(function, "driver:v1")
23 | serve.link("driver", "driver:v1")
24 | """
25 |
26 | with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
27 | path = f.name
28 | f.write(script)
29 |
30 | proc = subprocess.Popen(["python", path])
31 | return_code = proc.wait(timeout=10)
32 | assert return_code == 0
33 |
34 | handle = serve.get_handle("driver")
35 | assert ray.get(handle.remote()) == "OK!"
36 |
37 | os.remove(path)
38 |
--------------------------------------------------------------------------------
/doc/examples/newsreader/.rayproject/project.yaml:
--------------------------------------------------------------------------------
1 | # This file is generated by `ray project create`.
2 |
3 | name: ray-example-newsreader
4 |
5 | description: "A simple news reader example that uses ray actors to serve requests"
6 | tags: ["ray-example", "flask", "rss", "newsreader"]
7 | documentation: https://ray.readthedocs.io/en/latest/auto_examples/plot_newsreader.html
8 |
9 | cluster: .rayproject/cluster.yaml
10 |
11 | environment:
12 | requirements: .rayproject/requirements.txt
13 |
14 | commands:
15 | - name: run-backend
16 | command: python server.py
17 | config:
18 | port_forward: 5000
19 | - name: run-frontend
20 | command: |
21 | git clone https://github.com/ray-project/qreader
22 | cd qreader
23 | npm install
24 | npm run dev
25 | config:
26 | port_forward: 8080
27 |
28 | output_files: [
29 | # Save the logs from the latest run in snapshots.
30 | "/tmp/ray/session_latest/logs"
31 | ]
32 |
--------------------------------------------------------------------------------
/python/README-building-wheels.md:
--------------------------------------------------------------------------------
1 | # Building manylinux1 wheels
2 |
3 | To cause everything to be rebuilt, this script will delete ALL changes to the
4 | repository, including both changes to tracked files, and ANY untracked files.
5 |
6 | It will also cause all files inside the repository to be owned by root, and
7 | produce .whl files owned by root.
8 |
9 | Inside the root directory (i.e., one level above this python directory), run
10 |
11 | ```
12 | docker run --rm -w /ray -v `pwd`:/ray -ti rayproject/arrow_linux_x86_64_base:latest /ray/python/build-wheel-manylinux1.sh
13 | ```
14 |
15 | The wheel files will be placed in the .whl directory.
16 |
17 | ## Building MacOS wheels
18 |
19 | To build wheels for MacOS, run the following inside the root directory (i.e.,
20 | one level above this python directory).
21 |
22 | ```
23 | ./python/build-wheel-macos.sh
24 | ```
25 |
26 | The script uses `sudo` multiple times, so you may need to type in a password.
27 |
--------------------------------------------------------------------------------
/src/ray/thirdparty/hiredis/win32.h:
--------------------------------------------------------------------------------
1 | #ifndef _WIN32_HELPER_INCLUDE
2 | #define _WIN32_HELPER_INCLUDE
3 | #ifdef _MSC_VER
4 |
5 | #ifndef inline
6 | #define inline __inline
7 | #endif
8 |
9 | #ifndef va_copy
10 | #define va_copy(d,s) ((d) = (s))
11 | #endif
12 |
13 | #ifndef snprintf
14 | #define snprintf c99_snprintf
15 |
16 | __inline int c99_vsnprintf(char* str, size_t size, const char* format, va_list ap)
17 | {
18 | int count = -1;
19 |
20 | if (size != 0)
21 | count = _vsnprintf_s(str, size, _TRUNCATE, format, ap);
22 | if (count == -1)
23 | count = _vscprintf(format, ap);
24 |
25 | return count;
26 | }
27 |
28 | __inline int c99_snprintf(char* str, size_t size, const char* format, ...)
29 | {
30 | int count;
31 | va_list ap;
32 |
33 | va_start(ap, format);
34 | count = c99_vsnprintf(str, size, format, ap);
35 | va_end(ap);
36 |
37 | return count;
38 | }
39 | #endif
40 |
41 | #endif
42 | #endif
--------------------------------------------------------------------------------
/java/runtime/src/main/java/org/ray/runtime/runner/worker/DefaultDriver.java:
--------------------------------------------------------------------------------
1 | package org.ray.runtime.runner.worker;
2 |
3 | import org.ray.api.Ray;
4 |
5 | /**
6 | * The main function of DefaultDriver.
7 | */
8 | public class DefaultDriver {
9 |
10 | //
11 | // " --node-ip-address=" + ip
12 | // + " --redis-address=" + redisAddress
13 | // + " --driver-class" + className
14 | //
15 | public static void main(String[] args) {
16 | try {
17 | System.setProperty("ray.worker.mode", "DRIVER");
18 | Ray.init();
19 |
20 | String driverClass = null;
21 | String driverArgs = null;
22 | Class> cls = Class.forName(driverClass);
23 | String[] argsArray = (driverArgs != null) ? driverArgs.split(",") : (new String[] {});
24 | cls.getMethod("main", String[].class).invoke(null, (Object) argsArray);
25 | } catch (Throwable e) {
26 | e.printStackTrace();
27 | System.exit(-1);
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/java/test/src/main/java/org/ray/api/test/ObjectStoreTest.java:
--------------------------------------------------------------------------------
1 | package org.ray.api.test;
2 |
3 | import com.google.common.collect.ImmutableList;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 | import org.ray.api.Ray;
7 | import org.ray.api.RayObject;
8 | import org.ray.api.id.ObjectId;
9 | import org.testng.Assert;
10 | import org.testng.annotations.Test;
11 |
12 | /**
13 | * Test putting and getting objects.
14 | */
15 | public class ObjectStoreTest extends BaseTest {
16 |
17 | @Test
18 | public void testPutAndGet() {
19 | RayObject obj = Ray.put(1);
20 | Assert.assertEquals(1, (int) obj.get());
21 | }
22 |
23 | @Test
24 | public void testGetMultipleObjects() {
25 | List ints = ImmutableList.of(1, 2, 3, 4, 5);
26 | List ids = ints.stream().map(obj -> Ray.put(obj).getId())
27 | .collect(Collectors.toList());
28 | Assert.assertEquals(ints, Ray.get(ids));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/python/ray/tune/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | from ray.tune.error import TuneError
6 | from ray.tune.tune import run_experiments, run
7 | from ray.tune.experiment import Experiment
8 | from ray.tune.analysis import ExperimentAnalysis, Analysis
9 | from ray.tune.registry import register_env, register_trainable
10 | from ray.tune.trainable import Trainable
11 | from ray.tune.suggest import grid_search
12 | from ray.tune.sample import (function, sample_from, uniform, choice, randint,
13 | randn, loguniform)
14 |
15 | __all__ = [
16 | "Trainable", "TuneError", "grid_search", "register_env",
17 | "register_trainable", "run", "run_experiments", "Experiment", "function",
18 | "sample_from", "track", "uniform", "choice", "randint", "randn",
19 | "loguniform", "progress_reporter", "ExperimentAnalysis", "Analysis"
20 | ]
21 |
--------------------------------------------------------------------------------
/java/streaming/src/main/java/org/ray/streaming/api/function/internal/CollectionSourceFunction.java:
--------------------------------------------------------------------------------
1 | package org.ray.streaming.api.function.internal;
2 |
3 | import java.util.Collection;
4 | import org.ray.streaming.api.function.impl.SourceFunction;
5 |
6 | /**
7 | * The SourceFunction that fetch data from a Java Collection object.
8 | *
9 | * @param Type of the data output by the source.
10 | */
11 | public class CollectionSourceFunction implements SourceFunction {
12 |
13 | private Collection values;
14 |
15 | public CollectionSourceFunction(Collection values) {
16 | this.values = values;
17 | }
18 |
19 | @Override
20 | public void init(int parallel, int index) {
21 | }
22 |
23 | @Override
24 | public void fetch(long batchId, SourceContext ctx) throws Exception {
25 | for (T value : values) {
26 | ctx.collect(value);
27 | }
28 | }
29 |
30 | @Override
31 | public void close() {
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/rllib/optimizers/__init__.py:
--------------------------------------------------------------------------------
1 | from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer
2 | from ray.rllib.optimizers.async_replay_optimizer import AsyncReplayOptimizer
3 | from ray.rllib.optimizers.async_samples_optimizer import AsyncSamplesOptimizer
4 | from ray.rllib.optimizers.async_gradients_optimizer import \
5 | AsyncGradientsOptimizer
6 | from ray.rllib.optimizers.sync_samples_optimizer import SyncSamplesOptimizer
7 | from ray.rllib.optimizers.sync_replay_optimizer import SyncReplayOptimizer
8 | from ray.rllib.optimizers.sync_batch_replay_optimizer import \
9 | SyncBatchReplayOptimizer
10 | from ray.rllib.optimizers.multi_gpu_optimizer import LocalMultiGPUOptimizer
11 |
12 | __all__ = [
13 | "PolicyOptimizer",
14 | "AsyncReplayOptimizer",
15 | "AsyncSamplesOptimizer",
16 | "AsyncGradientsOptimizer",
17 | "SyncSamplesOptimizer",
18 | "SyncReplayOptimizer",
19 | "LocalMultiGPUOptimizer",
20 | "SyncBatchReplayOptimizer",
21 | ]
22 |
--------------------------------------------------------------------------------
/python/ray/includes/common.pxi:
--------------------------------------------------------------------------------
1 | from libcpp cimport bool as c_bool
2 | from libcpp.string cimport string as c_string
3 | from libcpp.vector cimport vector as c_vector
4 |
5 | from ray.includes.common cimport (
6 | CGcsClientOptions,
7 | )
8 |
9 |
10 | cdef class GcsClientOptions:
11 | """Cython wrapper class of C++ `ray::gcs::GcsClientOptions`."""
12 | cdef:
13 | unique_ptr[CGcsClientOptions] inner
14 |
15 | def __init__(self, redis_ip, int redis_port,
16 | redis_password, c_bool is_test_client=False):
17 | if not redis_password:
18 | redis_password = ""
19 | self.inner.reset(
20 | new CGcsClientOptions(redis_ip.encode("ascii"),
21 | redis_port,
22 | redis_password.encode("ascii"),
23 | is_test_client))
24 |
25 | cdef CGcsClientOptions* native(self):
26 | return (self.inner.get())
27 |
--------------------------------------------------------------------------------
/java/example.conf:
--------------------------------------------------------------------------------
1 | # This is an example ray config file.
2 | # To use this file, copy it to your classpath and rename it to 'ray.conf'.
3 |
4 | # For all available config items and default values,
5 | # see 'java/runtime/src/main/resources/ray.default.conf'.
6 | # For config file format, see 'https://github.com/lightbend/config/blob/master/HOCON.md'.
7 |
8 | ray {
9 | // Run mode, available options are:
10 | //
11 | // `SINGLE_PROCESS`: Ray is running in one single Java process, without Raylet backend,
12 | // object store, and GCS. It's useful for debug.
13 | // `CLUSTER`: Ray is running on one or more nodes, with multiple processes.
14 | run-mode = CLUSTER
15 |
16 | // Available resources on this node.
17 | resources: "CPU:4"
18 |
19 | // The address of the redis server to connect, in format `ip:port`.
20 | // If not provided, Ray processes will be started locally, including
21 | // Redis server, Raylet and object store.
22 | redis.address = ""
23 |
24 | }
25 |
--------------------------------------------------------------------------------