file_path
stringlengths 3
280
| file_language
stringclasses 66
values | content
stringlengths 1
1.04M
| repo_name
stringlengths 5
92
| repo_stars
int64 0
154k
| repo_description
stringlengths 0
402
| repo_primary_language
stringclasses 108
values | developer_username
stringlengths 1
25
| developer_name
stringlengths 0
30
| developer_company
stringlengths 0
82
|
|---|---|---|---|---|---|---|---|---|---|
src/ray/util/logging_test.cc
|
C++
|
#include <chrono>
#include <cstdlib>
#include <iostream>
#include "gtest/gtest.h"
#include "ray/util/logging.h"
namespace ray {
int64_t current_time_ms() {
std::chrono::milliseconds ms_since_epoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch());
return ms_since_epoch.count();
}
// This is not really test.
// This file just print some information using the logging macro.
void PrintLog() {
RAY_LOG(DEBUG) << "This is the"
<< " DEBUG"
<< " message";
RAY_LOG(INFO) << "This is the"
<< " INFO message";
RAY_LOG(WARNING) << "This is the"
<< " WARNING message";
RAY_LOG(ERROR) << "This is the"
<< " ERROR message";
RAY_CHECK(true) << "This is a RAY_CHECK"
<< " message but it won't show up";
// The following 2 lines should not run since it will cause program failure.
// RAY_LOG(FATAL) << "This is the FATAL message";
// RAY_CHECK(false) << "This is a RAY_CHECK message but it won't show up";
}
TEST(PrintLogTest, LogTestWithoutInit) {
// Without RayLog::StartRayLog, this should also work.
PrintLog();
}
TEST(PrintLogTest, LogTestWithInit) {
// Test empty app name.
RayLog::StartRayLog("", RayLogLevel::DEBUG, "/tmp/");
PrintLog();
RayLog::ShutDownRayLog();
}
// This test will output large amount of logs to stderr, should be disabled in travis.
TEST(LogPerfTest, PerfTest) {
RayLog::StartRayLog("/fake/path/to/appdire/LogPerfTest", RayLogLevel::ERROR, "/tmp/");
int rounds = 100000;
int64_t start_time = current_time_ms();
for (int i = 0; i < rounds; ++i) {
RAY_LOG(DEBUG) << "This is the "
<< "RAY_DEBUG message";
}
int64_t elapsed = current_time_ms() - start_time;
std::cout << "Testing DEBUG log for " << rounds << " rounds takes " << elapsed << " ms."
<< std::endl;
start_time = current_time_ms();
for (int i = 0; i < rounds; ++i) {
RAY_LOG(ERROR) << "This is the "
<< "RAY_ERROR message";
}
elapsed = current_time_ms() - start_time;
std::cout << "Testing RAY_ERROR log for " << rounds << " rounds takes " << elapsed
<< " ms." << std::endl;
start_time = current_time_ms();
for (int i = 0; i < rounds; ++i) {
RAY_CHECK(i >= 0) << "This is a RAY_CHECK "
<< "message but it won't show up";
}
elapsed = current_time_ms() - start_time;
std::cout << "Testing RAY_CHECK(true) for " << rounds << " rounds takes " << elapsed
<< " ms." << std::endl;
RayLog::ShutDownRayLog();
}
} // namespace ray
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/macros.h
|
C/C++ Header
|
#ifndef RAY_UTIL_MACROS_H
#define RAY_UTIL_MACROS_H
// From Google gutil
#ifndef RAY_DISALLOW_COPY_AND_ASSIGN
#define RAY_DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName &) = delete; \
void operator=(const TypeName &) = delete
#endif
#define RAY_UNUSED(x) (void)x
//
// GCC can be told that a certain branch is not likely to be taken (for
// instance, a CHECK failure), and use that information in static analysis.
// Giving it this information can help it optimize for the common case in
// the absence of better information (ie. -fprofile-arcs).
//
#if defined(__GNUC__)
#define RAY_PREDICT_FALSE(x) (__builtin_expect(x, 0))
#define RAY_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
#define RAY_NORETURN __attribute__((noreturn))
#define RAY_PREFETCH(addr) __builtin_prefetch(addr)
#elif defined(_MSC_VER)
#define RAY_NORETURN __declspec(noreturn)
#define RAY_PREDICT_FALSE(x) x
#define RAY_PREDICT_TRUE(x) x
#define RAY_PREFETCH(addr)
#else
#define RAY_NORETURN
#define RAY_PREDICT_FALSE(x) x
#define RAY_PREDICT_TRUE(x) x
#define RAY_PREFETCH(addr)
#endif
#if (defined(__GNUC__) || defined(__APPLE__))
#define RAY_MUST_USE_RESULT __attribute__((warn_unused_result))
#elif defined(_MSC_VER)
#define RAY_MUST_USE_RESULT
#else
#define RAY_MUST_USE_RESULT
#endif
#endif // RAY_UTIL_MACROS_H
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/ordered_set.h
|
C/C++ Header
|
#ifndef RAY_UTIL_ORDERED_SET_H
#define RAY_UTIL_ORDERED_SET_H
#include <list>
#include <unordered_map>
/// \class ordered_set
///
/// This container has properties of both a deque and a set. It is like a deque
/// in the sense that it maintains the insertion order and allows you to
/// push_back elements and pop_front elements. It is like a set in the sense
/// that it does not allow duplicate entries. Looking up and erasing elements is
/// quick.
template <typename T>
class ordered_set {
private:
using elements_type = std::list<T>;
using positions_type = std::unordered_map<T, typename elements_type::iterator>;
using iterator = typename elements_type::iterator;
using const_iterator = typename elements_type::const_iterator;
public:
ordered_set() {}
ordered_set(const ordered_set &other) = delete;
ordered_set &operator=(const ordered_set &other) = delete;
void push_back(const T &value) {
RAY_CHECK(positions_.find(value) == positions_.end());
auto list_iterator = elements_.insert(elements_.end(), value);
positions_[value] = list_iterator;
}
size_t count(const T &k) const { return positions_.count(k); }
void pop_front() {
positions_.erase(elements_.front());
elements_.pop_front();
}
const T &front() const { return elements_.front(); }
size_t size() const noexcept { return positions_.size(); }
size_t erase(const T &k) {
auto it = positions_.find(k);
RAY_CHECK(it != positions_.end());
elements_.erase(it->second);
return positions_.erase(k);
}
iterator erase(const iterator position) {
positions_.erase(*position);
return elements_.erase(position);
}
iterator begin() noexcept { return elements_.begin(); }
const_iterator begin() const noexcept { return elements_.begin(); }
iterator end() noexcept { return elements_.end(); }
const_iterator end() const noexcept { return elements_.end(); }
private:
elements_type elements_;
positions_type positions_;
};
#endif // RAY_UTIL_ORDERED_SET_H
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/process.h
|
C/C++ Header
|
#ifndef RAY_UTIL_PROCESS_H
#define RAY_UTIL_PROCESS_H
#ifdef __linux__
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <boost/asio/io_service.hpp>
#include <boost/process/args.hpp>
#include <boost/process/child.hpp>
#include <functional>
#include <memory>
#include <utility>
// We only define operators required by the standard library (==, hash).
// We declare but avoid defining the rest so that they're not used by accident.
namespace ray {
typedef boost::process::pid_t pid_t;
class Process : public boost::process::child {
protected:
class ProcessFD {
// This class makes a best-effort attempt to keep a PID alive.
// However, it cannot make any guarantees.
// The kernel might not even support this mechanism.
// See here: https://unix.stackexchange.com/a/181249
#ifdef __linux__
int fd_;
#endif
public:
#ifdef __linux__
~ProcessFD() {
if (fd_ != -1) {
::close(fd_);
}
}
ProcessFD(pid_t pid) : fd_(-1) {
if (pid != -1) {
char path[64];
sprintf(path, "/proc/%d/ns/pid", static_cast<int>(pid));
fd_ = ::open(path, O_RDONLY);
}
}
ProcessFD(ProcessFD &&other) : fd_(std::move(other.fd_)) { other.fd_ = -1; }
ProcessFD(const ProcessFD &other) : fd_(other.fd_ != -1 ? ::dup(other.fd_) : -1) {}
ProcessFD &operator=(ProcessFD other) {
using std::swap;
swap(fd_, other.fd_);
return *this;
}
#else
ProcessFD(pid_t) {}
#endif
};
ProcessFD fd_;
public:
template <typename... T>
explicit Process(T &&... args)
: boost::process::child(std::forward<T>(args)...),
fd_(boost::process::child::id()) {}
};
/// A managed equivalent of a pid_t (to manage the lifetime of each process).
/// TODO(mehrdadn): This hasn't been a great design, but we play along to
/// minimize the changes needed for Windows compatibility.
/// (We used to represent a worker process by just its pid_t, which carries
/// no ownership/lifetime information.)
/// Once this code is running properly, refactor the data structures to create
/// a better ownership structure between the worker processes and the workers.
class ProcessHandle {
std::shared_ptr<Process> proc_;
public:
ProcessHandle(const std::shared_ptr<Process> &proc = std::shared_ptr<Process>())
: proc_(proc) {}
Process *get() const { return proc_.get(); }
explicit operator bool() const { return !!proc_; }
static ProcessHandle FromPid(pid_t pid) {
Process temp(pid);
temp.detach();
return std::make_shared<Process>(std::move(temp));
}
};
} // namespace ray
// Define comparators for process handles:
// - Valid process objects must be distinguished by their IDs.
// - Invalid process objects must be distinguished by their addresses.
namespace std {
template <>
struct equal_to<ray::ProcessHandle> {
bool operator()(const ray::ProcessHandle &x, const ray::ProcessHandle &y) const {
const ray::Process *a = x.get(), *b = y.get();
// See explanation above
return a ? b ? a->valid()
? b->valid() ? equal_to<ray::pid_t>()(a->id(), b->id()) : false
: b->valid() ? false : equal_to<void const *>()(a, b)
: false
: !b;
}
};
template <>
struct hash<ray::ProcessHandle> {
size_t operator()(const ray::ProcessHandle &value) const {
const ray::Process *p = value.get();
// See explanation above
return p ? p->valid() ? hash<ray::pid_t>()(p->id()) : hash<void const *>()(p)
: size_t();
}
};
} // namespace std
#endif
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/sample.h
|
C/C++ Header
|
#ifndef RAY_UTIL_SAMPLE_H
#define RAY_UTIL_SAMPLE_H
#include <random>
#include "absl/time/clock.h"
// Randomly samples num_elements from the elements between first and last using reservoir
// sampling.
template <class Iterator, class T = typename std::iterator_traits<Iterator>::value_type>
void random_sample(Iterator begin, Iterator end, size_t num_elements,
std::vector<T> *out) {
out->resize(0);
if (num_elements == 0) {
return;
}
std::default_random_engine gen(absl::GetCurrentTimeNanos());
size_t current_index = 0;
for (auto it = begin; it != end; it++) {
if (current_index < num_elements) {
out->push_back(*it);
} else {
size_t random_index = std::uniform_int_distribution<size_t>(0, current_index)(gen);
if (random_index < num_elements) {
out->at(random_index) = *it;
}
}
current_index++;
}
return;
}
#endif // RAY_UTIL_SAMPLE_H
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/sample_test.cc
|
C++
|
#include <vector>
#include "gtest/gtest.h"
#include "ray/util/sample.h"
namespace ray {
class RandomSampleTest : public ::testing::Test {
protected:
std::vector<int> *sample;
std::vector<int> *test_vector;
virtual void SetUp() {
sample = new std::vector<int>();
test_vector = new std::vector<int>();
for (int i = 0; i < 10; i++) {
test_vector->push_back(i);
}
}
virtual void TearDown() {
delete sample;
delete test_vector;
}
};
TEST_F(RandomSampleTest, TestEmpty) {
random_sample(test_vector->begin(), test_vector->end(), 0, sample);
ASSERT_EQ(sample->size(), 0);
}
TEST_F(RandomSampleTest, TestSmallerThanSampleSize) {
random_sample(test_vector->begin(), test_vector->end(), test_vector->size() + 1,
sample);
ASSERT_EQ(sample->size(), test_vector->size());
}
TEST_F(RandomSampleTest, TestEqualToSampleSize) {
random_sample(test_vector->begin(), test_vector->end(), test_vector->size(), sample);
ASSERT_EQ(sample->size(), test_vector->size());
}
TEST_F(RandomSampleTest, TestLargerThanSampleSize) {
random_sample(test_vector->begin(), test_vector->end(), test_vector->size() - 1,
sample);
ASSERT_EQ(sample->size(), test_vector->size() - 1);
}
TEST_F(RandomSampleTest, TestEqualOccurrenceChance) {
int trials = 100000;
std::vector<int> occurrences(test_vector->size(), 0);
for (int i = 0; i < trials; i++) {
random_sample(test_vector->begin(), test_vector->end(), test_vector->size() / 2,
sample);
for (int idx : *sample) {
occurrences[idx]++;
}
}
for (int count : occurrences) {
ASSERT_NEAR(trials / 2, count, 0.05 * trials / 2);
}
}
} // namespace ray
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/signal_test.cc
|
C++
|
#include <signal.h>
#include <cstdlib>
#include <iostream>
#include "gtest/gtest.h"
#include "ray/util/logging.h"
#include "ray/util/util.h"
// This test just print some call stack information.
namespace ray {
#ifndef _WIN32
void Sleep() { usleep(100000); }
void TestSendSignal(const std::string &test_name, int signal) {
pid_t pid;
pid = fork();
ASSERT_TRUE(pid >= 0);
if (pid == 0) {
while (true) {
int n = 1000;
while (n--)
;
}
} else {
Sleep();
RAY_LOG(ERROR) << test_name << ": kill pid " << pid
<< " with return value=" << kill(pid, signal);
Sleep();
}
}
TEST(SignalTest, SendTermSignalTest) { TestSendSignal("SendTermSignalTest", SIGTERM); }
TEST(SignalTest, SendBusSignalTest) { TestSendSignal("SendBusSignalTest", SIGBUS); }
TEST(SignalTest, SIGABRT_Test) {
pid_t pid;
pid = fork();
ASSERT_TRUE(pid >= 0);
if (pid == 0) {
// This code will cause SIGABRT sent.
std::abort();
} else {
Sleep();
RAY_LOG(ERROR) << "SIGABRT_Test: kill pid " << pid
<< " with return value=" << kill(pid, SIGKILL);
Sleep();
}
}
TEST(SignalTest, SIGSEGV_Test) {
pid_t pid;
pid = fork();
ASSERT_TRUE(pid >= 0);
if (pid == 0) {
int *pointer = reinterpret_cast<int *>(0x1237896);
*pointer = 100;
} else {
Sleep();
RAY_LOG(ERROR) << "SIGSEGV_Test: kill pid " << pid
<< " with return value=" << kill(pid, SIGKILL);
Sleep();
}
}
TEST(SignalTest, SIGILL_Test) {
pid_t pid;
pid = fork();
ASSERT_TRUE(pid >= 0);
if (pid == 0) {
raise(SIGILL);
} else {
Sleep();
RAY_LOG(ERROR) << "SIGILL_Test: kill pid " << pid
<< " with return value=" << kill(pid, SIGKILL);
Sleep();
}
}
#endif // !_WIN32
} // namespace ray
int main(int argc, char **argv) {
InitShutdownRAII ray_log_shutdown_raii(ray::RayLog::StartRayLog,
ray::RayLog::ShutDownRayLog, argv[0],
ray::RayLogLevel::INFO,
/*log_dir=*/"");
ray::RayLog::InstallFailureSignalHandler();
::testing::InitGoogleTest(&argc, argv);
int failed = RUN_ALL_TESTS();
return failed;
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/test_util.h
|
C/C++ Header
|
#ifndef RAY_UTIL_TEST_UTIL_H
#define RAY_UTIL_TEST_UTIL_H
#include <unistd.h>
#include <string>
#include "gtest/gtest.h"
#include "ray/common/buffer.h"
#include "ray/common/id.h"
#include "ray/common/ray_object.h"
#include "ray/util/util.h"
namespace ray {
// Magic argument to signal to mock_worker we should check message order.
int64_t SHOULD_CHECK_MESSAGE_ORDER = 123450000;
/// Wait until the condition is met, or timeout is reached.
///
/// \param[in] condition The condition to wait for.
/// \param[in] timeout_ms Timeout in milliseconds to wait for for.
/// \return Whether the condition is met.
bool WaitForCondition(std::function<bool()> condition, int timeout_ms) {
int wait_time = 0;
while (true) {
if (condition()) {
return true;
}
// sleep 10ms.
const int wait_interval_ms = 10;
usleep(wait_interval_ms * 1000);
wait_time += wait_interval_ms;
if (wait_time > timeout_ms) {
break;
}
}
return false;
}
// A helper function to return a random task id.
inline TaskID RandomTaskId() {
std::string data(TaskID::Size(), 0);
FillRandom(&data);
return TaskID::FromBinary(data);
}
std::shared_ptr<Buffer> GenerateRandomBuffer() {
auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 gen(seed);
std::uniform_int_distribution<> dis(1, 10);
std::uniform_int_distribution<> value_dis(1, 255);
std::vector<uint8_t> arg1(dis(gen), value_dis(gen));
return std::make_shared<LocalMemoryBuffer>(arg1.data(), arg1.size(), true);
}
std::shared_ptr<RayObject> GenerateRandomObject() {
return std::shared_ptr<RayObject>(new RayObject(GenerateRandomBuffer(), nullptr));
}
/// Path to redis server executable binary.
std::string REDIS_SERVER_EXEC_PATH;
/// Path to redis client executable binary.
std::string REDIS_CLIENT_EXEC_PATH;
/// Path to redis module library.
std::string REDIS_MODULE_LIBRARY_PATH;
/// Port of redis server.
int REDIS_SERVER_PORT;
/// Test helper class, it will start redis server before the test runs,
/// and stop redis server after the test is completed.
class RedisServiceManagerForTest : public ::testing::Test {
public:
static void SetUpTestCase() {
auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 gen(seed);
std::uniform_int_distribution<int> random_gen{2000, 7000};
// Use random port to avoid port conflicts between UTs.
REDIS_SERVER_PORT = random_gen(gen);
std::string start_redis_command =
REDIS_SERVER_EXEC_PATH + " --loglevel warning --loadmodule " +
REDIS_MODULE_LIBRARY_PATH + " --port " + std::to_string(REDIS_SERVER_PORT) + " &";
RAY_LOG(INFO) << "Start redis command is: " << start_redis_command;
RAY_CHECK(system(start_redis_command.c_str()) == 0);
usleep(200 * 1000);
}
static void TearDownTestCase() {
std::string stop_redis_command =
REDIS_CLIENT_EXEC_PATH + " -p " + std::to_string(REDIS_SERVER_PORT) + " shutdown";
RAY_LOG(INFO) << "Stop redis command is: " << stop_redis_command;
RAY_CHECK(system(stop_redis_command.c_str()) == 0);
usleep(100 * 1000);
}
};
} // namespace ray
#endif // RAY_UTIL_TEST_UTIL_H
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/util.h
|
C/C++ Header
|
#ifndef RAY_UTIL_UTIL_H
#define RAY_UTIL_UTIL_H
#include <boost/system/error_code.hpp>
#include <chrono>
#include <iterator>
#include <mutex>
#include <random>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include "ray/common/status.h"
/// Return the number of milliseconds since the steady clock epoch. NOTE: The
/// returned timestamp may be used for accurately measuring intervals but has
/// no relation to wall clock time. It must not be used for synchronization
/// across multiple nodes.
///
/// TODO(rkn): This function appears in multiple places. It should be
/// deduplicated.
///
/// \return The number of milliseconds since the steady clock epoch.
inline int64_t current_time_ms() {
std::chrono::milliseconds ms_since_epoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch());
return ms_since_epoch.count();
}
inline ray::Status boost_to_ray_status(const boost::system::error_code &error) {
switch (error.value()) {
case boost::system::errc::success:
return ray::Status::OK();
default:
return ray::Status::IOError(strerror(error.value()));
}
}
/// A helper function to split a string by whitespaces.
///
/// \param str The string with whitespaces.
///
/// \return A vector that contains strings split by whitespaces.
inline std::vector<std::string> SplitStrByWhitespaces(const std::string &str) {
std::istringstream iss(str);
std::vector<std::string> result(std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>());
return result;
}
class InitShutdownRAII {
public:
/// Type of the Shutdown function.
using ShutdownFunc = void (*)();
/// Create an instance of InitShutdownRAII which will call shutdown
/// function when it is out of scope.
///
/// \param init_func The init function.
/// \param shutdown_func The shutdown function.
/// \param args The arguments for the init function.
template <class InitFunc, class... Args>
InitShutdownRAII(InitFunc init_func, ShutdownFunc shutdown_func, Args &&... args)
: shutdown_(shutdown_func) {
init_func(args...);
}
/// Destructor of InitShutdownRAII which will call the shutdown function.
~InitShutdownRAII() {
if (shutdown_ != nullptr) {
shutdown_();
}
}
private:
ShutdownFunc shutdown_;
};
struct EnumClassHash {
template <typename T>
std::size_t operator()(T t) const {
return static_cast<std::size_t>(t);
}
};
/// unordered_map for enum class type.
template <typename Key, typename T>
using EnumUnorderedMap = std::unordered_map<Key, T, EnumClassHash>;
/// A helper function to fill random bytes into the `data`.
/// Warning: this is not fork-safe, we need to re-seed after that.
template <typename T>
void FillRandom(T *data) {
RAY_CHECK(data != nullptr);
auto randomly_seeded_mersenne_twister = []() {
auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
// To increase the entropy, mix in a number of time samples instead of a single one.
// This avoids the possibility of duplicate seeds for many workers that start in
// close succession.
for (int i = 0; i < 128; i++) {
std::this_thread::sleep_for(std::chrono::microseconds(10));
seed += std::chrono::high_resolution_clock::now().time_since_epoch().count();
}
std::mt19937 seeded_engine(seed);
return seeded_engine;
};
// NOTE(pcm): The right way to do this is to have one std::mt19937 per
// thread (using the thread_local keyword), but that's not supported on
// older versions of macOS (see https://stackoverflow.com/a/29929949)
static std::mutex random_engine_mutex;
std::lock_guard<std::mutex> lock(random_engine_mutex);
static std::mt19937 generator = randomly_seeded_mersenne_twister();
std::uniform_int_distribution<uint32_t> dist(0, std::numeric_limits<uint8_t>::max());
for (int i = 0; i < data->size(); i++) {
(*data)[i] = static_cast<uint8_t>(dist(generator));
}
}
#endif // RAY_UTIL_UTIL_H
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/ray/util/visibility.h
|
C/C++ Header
|
#ifndef RAY_UTIL_VISIBILITY_H
#define RAY_UTIL_VISIBILITY_H
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_MSC_VER)
#pragma warning(disable : 4251)
#else
#pragma GCC diagnostic ignored "-Wattributes"
#endif
#ifdef RAY_STATIC
#define RAY_EXPORT
#elif defined(RAY_EXPORTING)
#define RAY_EXPORT __declspec(dllexport)
#else
#define RAY_EXPORT __declspec(dllimport)
#endif
#define RAY_NO_EXPORT
#else // Not Windows
#ifndef RAY_EXPORT
#define RAY_EXPORT __attribute__((visibility("default")))
#endif
#ifndef RAY_NO_EXPORT
#define RAY_NO_EXPORT __attribute__((visibility("hidden")))
#endif
#endif // Non-Windows
// gcc and clang disagree about how to handle template visibility when you have
// explicit specializations https://llvm.org/bugs/show_bug.cgi?id=24815
#if defined(__clang__)
#define RAY_EXTERN_TEMPLATE extern template class RAY_EXPORT
#else
#define RAY_EXTERN_TEMPLATE extern template class
#endif
// This is a complicated topic, some reading on it:
// http://www.codesynthesis.com/~boris/blog/2010/01/18/dll-export-cxx-templates/
#if defined(_MSC_VER) || defined(__clang__)
#define RAY_TEMPLATE_EXPORT RAY_EXPORT
#else
#define RAY_TEMPLATE_EXPORT
#endif
#endif // RAY_UTIL_VISIBILITY_H
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/arpa/inet.h
|
C/C++ Header
|
#ifndef INET_H
#define INET_H
#endif /* INET_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/getopt.cc
|
C++
|
/*
From:
http://stackoverflow.com/a/17195644/541686
Also posted on:
https://gist.github.com/superwills/5815344
Previously from:
http://www.raspberryginger.com/jbailey/minix/html/lib_2posix_2getopt_8c-source.html
*/
/*
* Copyright (c) 1987, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
int opterr = 1, /* if error message should be printed */
optind = 1, /* index into parent argv vector */
optopt, /* character checked for validity */
optreset; /* reset getopt */
char *optarg; /* argument associated with option */
#define BADCH (int)'?'
#define BADARG (int)':'
static char EMSG[] = "";
/*
* getopt --
* Parse argc/argv argument vector.
*/
int getopt(int nargc, char *const nargv[], const char *ostr) {
static char *place = EMSG; /* option letter processing */
const char *oli; /* option letter list index */
if (optreset || !*place) { /* update scanning pointer */
optreset = 0;
if (optind >= nargc || *(place = nargv[optind]) != '-') {
place = EMSG;
return (-1);
}
if (place[1] && *++place == '-') { /* found "--" */
++optind;
place = EMSG;
return (-1);
}
} /* option letter okay? */
if ((optopt = (int)*place++) == (int)':' || !(oli = strchr(ostr, optopt))) {
/*
* if the user didn't specify '-' as an option,
* assume it means -1.
*/
if (optopt == (int)'-') return (-1);
if (!*place) ++optind;
if (opterr && *ostr != ':') (void)printf("illegal option -- %c\n", optopt);
return (BADCH);
}
if (*++oli != ':') { /* don't need argument */
optarg = NULL;
if (!*place) ++optind;
} else { /* need an argument */
if (*place) /* no white space */
optarg = place;
else if (nargc <= ++optind) { /* no arg */
place = EMSG;
if (*ostr == ':') return (BADARG);
if (opterr) (void)printf("option requires an argument -- %c\n", optopt);
return (BADCH);
} else /* white space */
optarg = nargv[optind];
place = EMSG;
++optind;
}
return (optopt); /* dump back option letter */
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/getopt.h
|
C/C++ Header
|
#ifndef GETOPT_H
#define GETOPT_H
extern char *optarg;
extern int optind, opterr, optopt;
int getopt(int nargc, char *const nargv[], const char *ostr);
#endif /* GETOPT_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/msg.cc
|
C++
|
#include <stdlib.h>
#include <sys/socket.h>
#include <Winsock2.h> // include before other socket headers on Windows
#include <iphlpapi.h>
#include <tcpmib.h>
#pragma comment(lib, "IPHlpAPI.lib")
int socketpair(int domain, int type, int protocol, int sv[2]) {
if ((domain != AF_UNIX && domain != AF_INET) || type != SOCK_STREAM) {
return (int)INVALID_SOCKET;
}
SOCKET sockets[2];
int r = dumb_socketpair(sockets);
sv[0] = (int)sockets[0];
sv[1] = (int)sockets[1];
return r;
}
static DWORD getsockpid(SOCKET client) {
/* http://stackoverflow.com/a/25431340 */
DWORD pid = 0;
struct sockaddr_in Server = {0};
int ServerSize = sizeof(Server);
struct sockaddr_in Client = {0};
int ClientSize = sizeof(Client);
if ((getsockname(client, (struct sockaddr *)&Server, &ServerSize) == 0) &&
(getpeername(client, (struct sockaddr *)&Client, &ClientSize) == 0)) {
struct _MIB_TCPTABLE2 *TcpTable = NULL;
ULONG TcpTableSize = 0;
ULONG result;
do {
result = GetTcpTable2(TcpTable, &TcpTableSize, TRUE);
if (result != ERROR_INSUFFICIENT_BUFFER) {
break;
}
free(TcpTable);
TcpTable = (struct _MIB_TCPTABLE2 *)malloc(TcpTableSize);
} while (TcpTable != NULL);
if (result == NO_ERROR) {
for (DWORD dw = 0; dw < TcpTable->dwNumEntries; ++dw) {
struct _MIB_TCPROW2 *row = &(TcpTable->table[dw]);
if ((row->dwState == 5 /* MIB_TCP_STATE_ESTAB */) &&
(row->dwLocalAddr == Client.sin_addr.s_addr) &&
((row->dwLocalPort & 0xFFFF) == Client.sin_port) &&
(row->dwRemoteAddr == Server.sin_addr.s_addr) &&
((row->dwRemotePort & 0xFFFF) == Server.sin_port)) {
pid = row->dwOwningPid;
break;
}
}
}
free(TcpTable);
}
return pid;
}
ssize_t sendmsg(int sockfd, struct msghdr *msg, int flags) {
ssize_t result = -1;
struct cmsghdr *header = CMSG_FIRSTHDR(msg);
if (header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_RIGHTS) {
/* We're trying to send over a handle of some kind.
* We have to look up which process we're communicating with,
* open a handle to it, and then duplicate our handle into it.
* However, the first two steps cannot be done atomically.
* Therefore, this code HAS A RACE CONDITIONS and is therefore NOT SECURE.
* In the absense of a malicious actor, though, it is exceedingly unlikely
* that the child process closes AND that its process ID is reassigned
* to another existing process.
*/
struct msghdr const old_msg = *msg;
int *const pfd = (int *)CMSG_DATA(header);
msg->msg_control = NULL;
msg->msg_controllen = 0;
WSAPROTOCOL_INFO protocol_info = {0};
/* assume socket if it's a pipe, until proven otherwise */
BOOL is_socket = GetFileType((HANDLE)(SOCKET)(*pfd)) == FILE_TYPE_PIPE;
DWORD const target_pid = getsockpid(sockfd);
HANDLE target_process = NULL;
if (target_pid) {
if (is_socket) {
result = WSADuplicateSocket(*pfd, target_pid, &protocol_info);
if (result == -1 && WSAGetLastError() == WSAENOTSOCK) {
is_socket = FALSE;
}
}
if (!is_socket) {
/* This is a regular handle... fit it into the same struct */
target_process = OpenProcess(PROCESS_DUP_HANDLE, FALSE, target_pid);
if (target_process) {
if (DuplicateHandle(GetCurrentProcess(), (HANDLE)(intptr_t)*pfd, target_process,
(HANDLE *)&protocol_info, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
result = 0;
}
}
}
}
if (result == 0) {
int const nbufs = msg->dwBufferCount + 1;
WSABUF *const bufs = (struct _WSABUF *)_alloca(sizeof(*msg->lpBuffers) * nbufs);
bufs[0].buf = (char *)&protocol_info;
bufs[0].len = sizeof(protocol_info);
memcpy(&bufs[1], msg->lpBuffers, msg->dwBufferCount * sizeof(*msg->lpBuffers));
DWORD nb;
msg->lpBuffers = bufs;
msg->dwBufferCount = nbufs;
GUID wsaid_WSASendMsg = {
0xa441e712, 0x754f, 0x43ca, {0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d}};
typedef INT PASCAL WSASendMsg_t(
SOCKET s, LPWSAMSG lpMsg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
LPWSAOVERLAPPED lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
WSASendMsg_t *WSASendMsg = NULL;
result = WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &wsaid_WSASendMsg,
sizeof(wsaid_WSASendMsg), &WSASendMsg, sizeof(WSASendMsg), &nb,
NULL, 0);
if (result == 0) {
result = (*WSASendMsg)(sockfd, msg, flags, &nb, NULL, NULL) == 0
? (ssize_t)(nb - sizeof(protocol_info))
: 0;
}
}
if (result != 0 && target_process && !is_socket) {
/* we failed to send the handle, and it needs cleaning up! */
HANDLE duplicated_back = NULL;
if (DuplicateHandle(target_process, *(HANDLE *)&protocol_info, GetCurrentProcess(),
&duplicated_back, 0, FALSE, DUPLICATE_CLOSE_SOURCE)) {
CloseHandle(duplicated_back);
}
}
if (target_process) {
CloseHandle(target_process);
}
*msg = old_msg;
}
return result;
}
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) {
int result = -1;
struct cmsghdr *header = CMSG_FIRSTHDR(msg);
if (msg->msg_controllen && flags == 0 /* We can't send flags on Windows... */) {
struct msghdr const old_msg = *msg;
msg->msg_control = NULL;
msg->msg_controllen = 0;
WSAPROTOCOL_INFO protocol_info = {0};
int const nbufs = msg->dwBufferCount + 1;
WSABUF *const bufs = (struct _WSABUF *)_alloca(sizeof(*msg->lpBuffers) * nbufs);
bufs[0].buf = (char *)&protocol_info;
bufs[0].len = sizeof(protocol_info);
memcpy(&bufs[1], msg->lpBuffers, msg->dwBufferCount * sizeof(*msg->lpBuffers));
typedef INT PASCAL WSARecvMsg_t(
SOCKET s, LPWSAMSG lpMsg, LPDWORD lpNumberOfBytesRecvd,
LPWSAOVERLAPPED lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
WSARecvMsg_t *WSARecvMsg = NULL;
DWORD nb;
GUID wsaid_WSARecvMsg = {
0xf689d7c8, 0x6f1f, 0x436b, {0x8a, 0x53, 0xe5, 0x4f, 0xe3, 0x51, 0xc3, 0x22}};
result =
WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &wsaid_WSARecvMsg,
sizeof(wsaid_WSARecvMsg), &WSARecvMsg, sizeof(WSARecvMsg), &nb, NULL, 0);
if (result == 0) {
result = (*WSARecvMsg)(sockfd, msg, &nb, NULL, NULL) == 0
? (ssize_t)(nb - sizeof(protocol_info))
: 0;
}
if (result == 0) {
int *const pfd = (int *)CMSG_DATA(header);
if (protocol_info.iSocketType == 0 && protocol_info.iProtocol == 0) {
*pfd = *(int *)&protocol_info;
} else {
*pfd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
&protocol_info, 0, 0);
}
header->cmsg_level = SOL_SOCKET;
header->cmsg_type = SCM_RIGHTS;
}
*msg = old_msg;
}
return result;
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/netdb.h
|
C/C++ Header
|
#ifndef NETDB_H
#define NETDB_H
#include <ws2tcpip.h>
#endif /* NETDB_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/netinet/in.h
|
C/C++ Header
|
#ifndef IN_H
#define IN_H
#endif /* IN_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/netinet/tcp.h
|
C/C++ Header
|
#ifndef TCP_H
#define TCP_H
#endif /* TCP_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/poll.h
|
C/C++ Header
|
#ifndef POLL_H
#define POLL_H
typedef unsigned long int nfds_t;
int poll(struct pollfd fds[], nfds_t nfds, int timeout);
#endif /* POLL_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/pthread.h
|
C/C++ Header
|
#ifndef _PTHREAD_H
#define _PTHREAD_H 1
#ifndef _INC_WINDOWS
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <Windows.h>
#endif
typedef CRITICAL_SECTION pthread_mutex_t;
#endif /* pthread.h */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/socketpair.cc
|
C++
|
/* socketpair.c
Copyright 2007, 2010 by Nathan C. Myers <ncm@cantrip.org>
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
The name of the author must not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Changes:
* 2014-02-12: merge David Woodhouse, Ger Hobbelt improvements
* git.infradead.org/users/dwmw2/openconnect.git/commitdiff/bdeefa54
* github.com/GerHobbelt/selectable-socketpair
* always init the socks[] to -1/INVALID_SOCKET on error, both on Win32/64
* and UNIX/other platforms
* 2013-07-18: Change to BSD 3-clause license
* 2010-03-31:
* set addr to 127.0.0.1 because win32 getsockname does not always set it.
* 2010-02-25:
* set SO_REUSEADDR option to avoid leaking some windows resource.
* Windows System Error 10049, "Event ID 4226 TCP/IP has reached
* the security limit imposed on the number of concurrent TCP connect
* attempts." Bleah.
* 2007-04-25:
* preserve value of WSAGetLastError() on all error returns.
* 2007-04-22: (Thanks to Matthew Gregan <kinetik@flim.org>)
* s/EINVAL/WSAEINVAL/ fix trivial compile failure
* s/socket/WSASocket/ enable creation of sockets suitable as stdin/stdout
* of a child process.
* add argument make_overlapped
*/
#include <string.h>
#ifdef _WIN32
#include <Windows.h>
#include <io.h>
#include <ws2tcpip.h> /* socklen_t, et al (MSVC20xx) */
#else
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#endif
#ifdef WIN32
/* dumb_socketpair:
* If make_overlapped is nonzero, both sockets created will be usable for
* "overlapped" operations via WSASend etc. If make_overlapped is zero,
* socks[0] (only) will be usable with regular ReadFile etc., and thus
* suitable for use as stdin or stdout of a child process. Note that the
* sockets must be closed with closesocket() regardless.
*/
int dumb_socketpair(SOCKET socks[2]) {
union {
struct sockaddr_in inaddr;
struct sockaddr addr;
} a;
SOCKET listener;
int e;
socklen_t addrlen = sizeof(a.inaddr);
int reuse = 1;
if (socks == 0) {
return SOCKET_ERROR;
}
socks[0] = socks[1] = -1;
listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listener == -1) return SOCKET_ERROR;
memset(&a, 0, sizeof(a));
a.inaddr.sin_family = AF_INET;
a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
a.inaddr.sin_port = 0;
for (;;) {
if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse,
(socklen_t)sizeof(reuse)) == -1)
break;
if (bind(listener, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR) break;
memset(&a, 0, sizeof(a));
if (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR) break;
// win32 getsockname may only set the port number, p=0.0005.
// ( http://msdn.microsoft.com/library/ms738543.aspx ):
a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
a.inaddr.sin_family = AF_INET;
if (listen(listener, 1) == SOCKET_ERROR) break;
socks[0] = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, 0);
if (socks[0] == -1) break;
if (connect(socks[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR) break;
socks[1] = accept(listener, NULL, NULL);
if (socks[1] == -1) break;
closesocket(listener);
return 0;
}
closesocket(listener);
closesocket(socks[0]);
closesocket(socks[1]);
socks[0] = socks[1] = -1;
return SOCKET_ERROR;
}
#else
int dumb_socketpair(int socks[2], int dummy) {
if (socks == 0) {
errno = EINVAL;
return -1;
}
dummy = socketpair(AF_LOCAL, SOCK_STREAM, 0, socks);
if (dummy) socks[0] = socks[1] = -1;
return dummy;
}
#endif
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/strings.h
|
C/C++ Header
|
#ifndef STRINGS_H
#define STRINGS_H
#include <string.h>
static int strcasecmp(const char *s1, const char *s2) { return stricmp(s1, s2); }
static int strncasecmp(const char *s1, const char *s2, size_t n) {
return strnicmp(s1, s2, n);
}
#endif /* STRINGS_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/ioctl.h
|
C/C++ Header
|
#ifndef IOCTL_H
#define IOCTL_H
#endif /* IOCTL_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/mman.h
|
C/C++ Header
|
#ifndef MMAN_H
#define MMAN_H
#include <unistd.h>
#define MAP_SHARED 0x0010 /* share changes */
#define MAP_FAILED ((void *)-1)
#define PROT_READ 0x04 /* pages can be read */
#define PROT_WRITE 0x02 /* pages can be written */
#define PROT_EXEC 0x01 /* pages can be executed */
#ifndef FILE_MAP_ALL_ACCESS
enum { FILE_MAP_ALL_ACCESS = 0xF001F };
#endif
EXTERN_C WINBASEAPI void *WINAPI MapViewOfFile(HANDLE hFileMappingObject,
DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh,
DWORD dwFileOffsetLow,
SIZE_T dwNumberOfBytesToMap);
EXTERN_C WINBASEAPI BOOL WINAPI UnmapViewOfFile(void const *lpBaseAddress);
static void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) {
void *result = (void *)(-1);
if (!addr && prot == MAP_SHARED) {
/* HACK: we're assuming handle sizes can't exceed 32 bits, which is wrong...
* but works for now. */
void *ptr = MapViewOfFile((HANDLE)(intptr_t)fd, FILE_MAP_ALL_ACCESS,
(DWORD)(off >> (CHAR_BIT * sizeof(DWORD))), (DWORD)off,
(SIZE_T)len);
if (ptr) {
result = ptr;
}
}
return result;
}
static int munmap(void *addr, size_t length) {
(void)length;
return UnmapViewOfFile(addr) ? 0 : -1;
}
#endif /* MMAN_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/select.h
|
C/C++ Header
|
#ifndef SELECT_H
#define SELECT_H
#endif /* SELECT_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/socket.h
|
C/C++ Header
|
#ifndef SOCKET_H
#define SOCKET_H
typedef unsigned short sa_family_t;
#include <Winsock2.h>
#include <unistd.h> // ssize_t
#define cmsghdr _WSACMSGHDR
#undef CMSG_DATA
#define CMSG_DATA WSA_CMSG_DATA
#define CMSG_SPACE WSA_CMSG_SPACE
#define CMSG_FIRSTHDR WSA_CMSG_FIRSTHDR
#define CMSG_LEN WSA_CMSG_LEN
#define CMSG_NXTHDR WSA_CMSG_NXTHDR
#define SCM_RIGHTS 1
#define iovec _WSABUF
#define iov_base buf
#define iov_len len
#define msghdr _WSAMSG
#define msg_name name
#define msg_namelen namelen
#define msg_iov lpBuffers
#define msg_iovlen dwBufferCount
#define msg_control Control.buf
#define msg_controllen Control.len
#define msg_flags dwFlags
int dumb_socketpair(SOCKET socks[2]);
ssize_t sendmsg(int sockfd, struct msghdr *msg, int flags);
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
int socketpair(int domain, int type, int protocol, int sv[2]);
#ifdef __cplusplus
namespace {
inline int send(SOCKET s, const void *buf, int len, int flags) {
// Call the const char* overload version
int (*psend)(SOCKET s, const char *buf, int len, int flags) = ::send;
return (*psend)(s, (const char *)buf, len, flags);
}
} // namespace
#endif
#endif /* SOCKET_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/statvfs.h
|
C/C++ Header
|
#ifndef STATVFS_H
#define STATVFS_H 1
#endif
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/syslog.h
|
C/C++ Header
|
#ifndef _SYS_SYSLOG_H
#define _SYS_SYSLOG_H 1
#endif /* sys/syslog.h */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/time.cc
|
C++
|
#include <limits.h>
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz) {
// Free implementation from: https://stackoverflow.com/a/26085827
SYSTEMTIME systime;
GetSystemTime(&systime);
FILETIME filetime;
SystemTimeToFileTime(&systime, &filetime);
unsigned long long const epoch_time_offset = 11644473600ULL * 60 * 60 * 24,
time_high = filetime.dwHighDateTime,
time =
filetime.dwLowDateTime +
(time_high << (CHAR_BIT * sizeof(filetime.dwLowDateTime)));
tv->tv_sec = static_cast<int>((time - epoch_time_offset) / 10000000);
tv->tv_usec = static_cast<int>(systime.wMilliseconds * 1000);
return 0;
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/time.h
|
C/C++ Header
|
#ifndef TIME_H
#define TIME_H
#include <WinSock2.h> // clients require timeval definition
struct timeval;
struct timezone;
#ifdef __cplusplus
extern "C"
#endif
int
gettimeofday(struct timeval *tv, struct timezone *tz);
#endif /* TIME_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/un.h
|
C/C++ Header
|
#ifndef UN_H
#define UN_H
#include <sys/socket.h>
#define UNIX_PATH_MAX 108
typedef struct sockaddr_un {
ADDRESS_FAMILY sun_family;
char sun_path[UNIX_PATH_MAX];
} SOCKADDR_UN, *PSOCKADDR_UN;
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#endif
#endif /* UN_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/wait.cc
|
C++
|
#include <sys/wait.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <Windows.h>
pid_t waitpid(pid_t pid, int *status, int options) {
int result;
if (pid <= 0) {
result = -1;
errno = ECHILD;
} else if (HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, pid)) {
DWORD timeout = status && *status == WNOHANG ? 0 : INFINITE;
if (WaitForSingleObject(process, timeout) != WAIT_FAILED) {
result = 0;
} else {
result = -1;
errno = ECHILD;
}
CloseHandle(process);
} else {
result = -1;
errno = ECHILD;
}
return result;
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/sys/wait.h
|
C/C++ Header
|
#ifndef WAIT_H
#define WAIT_H
#include <unistd.h> // pid_t
#define WNOHANG 1
__declspec(
deprecated("Waiting on a process by ID has an inherent race condition"
" on Windows and is discouraged. "
"Please use a wrapper that keeps the process handle alive"
" and waits on it directly as needed."
"")) pid_t waitpid(pid_t pid, int *status, int options);
#endif /* WAIT_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/syslog.h
|
C/C++ Header
|
#include <sys/syslog.h>
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/unistd.cc
|
C++
|
#include <unistd.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <Windows.h>
int usleep(useconds_t usec) {
Sleep((usec + (1000 - 1)) / 1000);
return 0;
}
unsigned sleep(unsigned seconds) {
Sleep(seconds * 1000);
return 0;
}
int kill(pid_t pid, int sig) {
int result;
if (HANDLE process = OpenProcess(PROCESS_TERMINATE, FALSE, pid)) {
if (sig == SIGKILL) {
if (TerminateProcess(process, ERROR_PROCESS_ABORTED)) {
result = 0;
} else {
result = -1;
errno = EPERM;
}
} else {
result = -1;
errno = EINVAL;
}
CloseHandle(process);
} else {
result = -1;
errno = ESRCH;
}
return result;
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
src/shims/windows/unistd.h
|
C/C++ Header
|
#ifndef UNISTD_H
#define UNISTD_H
#include <getopt.h>
#include <io.h> // open/read/write/close
#ifndef EXTERN_C
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C
#endif
#endif
#ifndef DECLSPEC_IMPORT
#define DECLSPEC_IMPORT __declspec(dllimport)
#endif
#ifndef WINBASEAPI
#define WINBASEAPI DECLSPEC_IMPORT
#endif
#ifndef WINAPI
#define WINAPI __stdcall
#endif
typedef int BOOL;
typedef void *HANDLE;
typedef unsigned long DWORD;
#ifdef _WIN64
typedef unsigned long long UINT_PTR;
typedef unsigned long long ULONG_PTR;
typedef long long ssize_t;
#else
typedef unsigned int UINT_PTR;
typedef unsigned long ULONG_PTR;
typedef int ssize_t;
#endif
typedef int pid_t /* technically unsigned on Windows, but no practical concern */;
enum { SIGKILL = 9 };
typedef ULONG_PTR SIZE_T;
EXTERN_C WINBASEAPI void WINAPI Sleep(DWORD dwMilliseconds);
typedef unsigned int useconds_t;
int usleep(useconds_t usec);
unsigned sleep(unsigned seconds);
__declspec(
deprecated("Killing a process by ID has an inherent race condition on Windows"
" and is HIGHLY discouraged. "
"Furthermore, signals other than SIGKILL are NOT portable. "
"Please use a wrapper that keeps the process handle alive"
" and terminates it directly as needed. "
"For SIGTERM or other signals, a different IPC mechanism may be"
" more appropriate (such as window messages on Windows)."
"")) int kill(pid_t pid, int sig);
#endif /* UNISTD_H */
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/collector/CollectionCollector.java
|
Java
|
package org.ray.streaming.api.collector;
import java.util.List;
import org.ray.streaming.message.Record;
/**
* Combination of multiple collectors.
*
* @param <T> The type of output data.
*/
public class CollectionCollector<T> implements Collector<T> {
private List<Collector> collectorList;
public CollectionCollector(List<Collector> collectorList) {
this.collectorList = collectorList;
}
@Override
public void collect(T value) {
for (Collector collector : collectorList) {
collector.collect(new Record(value));
}
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/collector/Collector.java
|
Java
|
package org.ray.streaming.api.collector;
/**
* The collector that collects data from an upstream operator, and emits data to downstream
* operators.
*
* @param <T> Type of the data to collect.
*/
public interface Collector<T> {
void collect(T value);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/context/RuntimeContext.java
|
Java
|
package org.ray.streaming.api.context;
/**
* Encapsulate the runtime information of a streaming task.
*/
public interface RuntimeContext {
int getTaskId();
int getTaskIndex();
int getParallelism();
Long getBatchId();
Long getMaxBatch();
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/context/StreamingContext.java
|
Java
|
package org.ray.streaming.api.context;
import com.google.common.base.Preconditions;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.atomic.AtomicInteger;
import org.ray.streaming.api.stream.StreamSink;
import org.ray.streaming.jobgraph.JobGraph;
import org.ray.streaming.jobgraph.JobGraphBuilder;
import org.ray.streaming.schedule.JobScheduler;
/**
* Encapsulate the context information of a streaming Job.
*/
public class StreamingContext implements Serializable {
private transient AtomicInteger idGenerator;
/**
* The sinks of this streaming job.
*/
private List<StreamSink> streamSinks;
/**
* The user custom streaming job configuration.
*/
private Map<String, String> jobConfig;
/**
* The logic plan.
*/
private JobGraph jobGraph;
private StreamingContext() {
this.idGenerator = new AtomicInteger(0);
this.streamSinks = new ArrayList<>();
this.jobConfig = new HashMap<>();
}
public static StreamingContext buildContext() {
return new StreamingContext();
}
/**
* Construct job DAG, and execute the job.
*/
public void execute(String jobName) {
JobGraphBuilder jobGraphBuilder = new JobGraphBuilder(this.streamSinks, jobName);
this.jobGraph = jobGraphBuilder.build();
jobGraph.printJobGraph();
ServiceLoader<JobScheduler> serviceLoader = ServiceLoader.load(JobScheduler.class);
Iterator<JobScheduler> iterator = serviceLoader.iterator();
Preconditions.checkArgument(iterator.hasNext(),
"No JobScheduler implementation has been provided.");
JobScheduler jobSchedule = iterator.next();
jobSchedule.schedule(jobGraph, jobConfig);
}
public int generateId() {
return this.idGenerator.incrementAndGet();
}
public void addSink(StreamSink streamSink) {
streamSinks.add(streamSink);
}
public void withConfig(Map<String, String> jobConfig) {
this.jobConfig = jobConfig;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/Function.java
|
Java
|
package org.ray.streaming.api.function;
import java.io.Serializable;
/**
* Interface of streaming functions.
*/
public interface Function extends Serializable {
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/AggregateFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* Interface of aggregate functions.
*
* @param <I> Type of the input data.
* @param <A> Type of the intermediate data.
* @param <O> Type of the output data.
*/
public interface AggregateFunction<I, A, O> extends Function {
A createAccumulator();
void add(I value, A accumulator);
O getResult(A accumulator);
A merge(A a, A b);
void retract(A acc, I value);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/FilterFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* A filter function is a predicate applied individually to each record.
* The predicate decides whether to keep the element, or to discard it.
*
* @param <T> type of the input data.
*/
@FunctionalInterface
public interface FilterFunction<T> extends Function {
/**
* The filter function that evaluates the predicate.
*
* @param value The value to be filtered.
* @return True for values that should be retained, false for values to be filtered out.
*/
boolean filter(T value) throws Exception;
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/FlatMapFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.collector.Collector;
import org.ray.streaming.api.function.Function;
/**
* Interface of flat-map functions.
*
* @param <T> Type of the input data.
* @param <R> Type of the output data.
*/
@FunctionalInterface
public interface FlatMapFunction<T, R> extends Function {
void flatMap(T value, Collector<R> collector);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/JoinFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* Interface of join functions.
*
* @param <T> Type of the left input data.
* @param <O> Type of the right input data.
* @param <R> Type of the output data.
*/
@FunctionalInterface
public interface JoinFunction<T, O, R> extends Function {
R join(T left, O right);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/KeyFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* Interface of key-by functions.
*
* @param <T> Type of the input data.
* @param <K> Type of the key-by field.
*/
@FunctionalInterface
public interface KeyFunction<T, K> extends Function {
K keyBy(T value);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/MapFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* Interface of map functions.
*
* @param <T> type of the input data.
* @param <R> type of the output data.
*/
@FunctionalInterface
public interface MapFunction<T, R> extends Function {
R map(T value);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/ProcessFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* Interface of process functions.
*
* @param <T> Type of the input data.
*/
@FunctionalInterface
public interface ProcessFunction<T> extends Function {
void process(T value);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/ReduceFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* Interface of reduce functions.
*
* @param <T> Type of the input data.
*/
@FunctionalInterface
public interface ReduceFunction<T> extends Function {
T reduce(T oldValue, T newValue);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/SinkFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* Interface of sink functions.
*
* @param <T> Type of the sink data.
*/
@FunctionalInterface
public interface SinkFunction<T> extends Function {
void sink(T value);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/impl/SourceFunction.java
|
Java
|
package org.ray.streaming.api.function.impl;
import org.ray.streaming.api.function.Function;
/**
* Interface of Source functions.
*
* @param <T> Type of the data output by the source.
*/
public interface SourceFunction<T> extends Function {
void init(int parallel, int index);
void run(SourceContext<T> ctx) throws Exception;
void close();
interface SourceContext<T> {
void collect(T element) throws Exception;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/function/internal/CollectionSourceFunction.java
|
Java
|
package org.ray.streaming.api.function.internal;
import java.util.ArrayList;
import java.util.Collection;
import org.ray.streaming.api.function.impl.SourceFunction;
/**
* The SourceFunction that fetch data from a Java Collection object.
*
* @param <T> Type of the data output by the source.
*/
public class CollectionSourceFunction<T> implements SourceFunction<T> {
private Collection<T> values;
public CollectionSourceFunction(Collection<T> values) {
this.values = values;
}
@Override
public void init(int parallel, int index) {
}
@Override
public void run(SourceContext<T> ctx) throws Exception {
for (T value : values) {
ctx.collect(value);
}
// empty collection
values = new ArrayList<>();
}
@Override
public void close() {
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/partition/Partition.java
|
Java
|
package org.ray.streaming.api.partition;
import org.ray.streaming.api.function.Function;
/**
* Interface of the partitioning strategy.
*
* @param <T> Type of the input data.
*/
@FunctionalInterface
public interface Partition<T> extends Function {
/**
* Given a record and downstream partitions, determine which partition(s) should receive the
* record.
*
* @param record The record.
* @param numPartition num of partitions
* @return IDs of the downstream partitions that should receive the record.
*/
int[] partition(T record, int numPartition);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/partition/impl/BroadcastPartition.java
|
Java
|
package org.ray.streaming.api.partition.impl;
import java.util.stream.IntStream;
import org.ray.streaming.api.partition.Partition;
/**
* Broadcast the record to all downstream partitions.
*/
public class BroadcastPartition<T> implements Partition<T> {
private int[] partitions = new int[0];
public BroadcastPartition() {
}
@Override
public int[] partition(T value, int numPartition) {
if (partitions.length != numPartition) {
partitions = IntStream.rangeClosed(0, numPartition - 1).toArray();
}
return partitions;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/partition/impl/KeyPartition.java
|
Java
|
package org.ray.streaming.api.partition.impl;
import org.ray.streaming.api.partition.Partition;
import org.ray.streaming.message.KeyRecord;
/**
* Partition the record by the key.
*
* @param <K> Type of the partition key.
* @param <T> Type of the input record.
*/
public class KeyPartition<K, T> implements Partition<KeyRecord<K, T>> {
private int[] partitions = new int[1];
@Override
public int[] partition(KeyRecord<K, T> keyRecord, int numPartition) {
partitions[0] = Math.abs(keyRecord.getKey().hashCode() % numPartition);
return partitions;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/partition/impl/RoundRobinPartition.java
|
Java
|
package org.ray.streaming.api.partition.impl;
import org.ray.streaming.api.partition.Partition;
/**
* Partition record to downstream tasks in a round-robin matter.
*
* @param <T> Type of the input record.
*/
public class RoundRobinPartition<T> implements Partition<T> {
private int seq;
private int[] partitions = new int[1];
public RoundRobinPartition() {
this.seq = 0;
}
@Override
public int[] partition(T value, int numPartition) {
seq = (seq + 1) % numPartition;
partitions[0] = seq;
return partitions;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/DataStream.java
|
Java
|
package org.ray.streaming.api.stream;
import org.ray.streaming.api.context.StreamingContext;
import org.ray.streaming.api.function.impl.FilterFunction;
import org.ray.streaming.api.function.impl.FlatMapFunction;
import org.ray.streaming.api.function.impl.KeyFunction;
import org.ray.streaming.api.function.impl.MapFunction;
import org.ray.streaming.api.function.impl.SinkFunction;
import org.ray.streaming.api.partition.Partition;
import org.ray.streaming.api.partition.impl.BroadcastPartition;
import org.ray.streaming.operator.StreamOperator;
import org.ray.streaming.operator.impl.FilterOperator;
import org.ray.streaming.operator.impl.FlatMapOperator;
import org.ray.streaming.operator.impl.KeyByOperator;
import org.ray.streaming.operator.impl.MapOperator;
import org.ray.streaming.operator.impl.SinkOperator;
/**
* Represents a stream of data.
*
* This class defines all the streaming operations.
*
* @param <T> Type of data in the stream.
*/
public class DataStream<T> extends Stream<T> {
public DataStream(StreamingContext streamingContext, StreamOperator streamOperator) {
super(streamingContext, streamOperator);
}
public DataStream(DataStream input, StreamOperator streamOperator) {
super(input, streamOperator);
}
/**
* Apply a map function to this stream.
*
* @param mapFunction The map function.
* @param <R> Type of data returned by the map function.
* @return A new DataStream.
*/
public <R> DataStream<R> map(MapFunction<T, R> mapFunction) {
return new DataStream<>(this, new MapOperator(mapFunction));
}
/**
* Apply a flat-map function to this stream.
*
* @param flatMapFunction The FlatMapFunction
* @param <R> Type of data returned by the flatmap function.
* @return A new DataStream
*/
public <R> DataStream<R> flatMap(FlatMapFunction<T, R> flatMapFunction) {
return new DataStream(this, new FlatMapOperator(flatMapFunction));
}
public DataStream<T> filter(FilterFunction<T> filterFunction) {
return new DataStream<T>(this, new FilterOperator(filterFunction));
}
/**
* Apply a union transformation to this stream, with another stream.
*
* @param other Another stream.
* @return A new UnionStream.
*/
public UnionStream<T> union(DataStream<T> other) {
return new UnionStream(this, null, other);
}
/**
* Apply a join transformation to this stream, with another stream.
*
* @param other Another stream.
* @param <O> The type of the other stream data.
* @param <R> The type of the data in the joined stream.
* @return A new JoinStream.
*/
public <O, R> JoinStream<T, O, R> join(DataStream<O> other) {
return new JoinStream<>(this, other);
}
public <R> DataStream<R> process() {
// TODO(zhenxuanpan): Need to add processFunction.
return new DataStream(this, null);
}
/**
* Apply a sink function and get a StreamSink.
*
* @param sinkFunction The sink function.
* @return A new StreamSink.
*/
public DataStreamSink<T> sink(SinkFunction<T> sinkFunction) {
return new DataStreamSink<>(this, new SinkOperator(sinkFunction));
}
/**
* Apply a key-by function to this stream.
*
* @param keyFunction the key function.
* @param <K> The type of the key.
* @return A new KeyDataStream.
*/
public <K> KeyDataStream<K, T> keyBy(KeyFunction<T, K> keyFunction) {
return new KeyDataStream<>(this, new KeyByOperator(keyFunction));
}
/**
* Apply broadcast to this stream.
*
* @return This stream.
*/
public DataStream<T> broadcast() {
this.partition = new BroadcastPartition<>();
return this;
}
/**
* Apply a partition to this stream.
*
* @param partition The partitioning strategy.
* @return This stream.
*/
public DataStream<T> partitionBy(Partition<T> partition) {
this.partition = partition;
return this;
}
/**
* Set parallelism to current transformation.
*
* @param parallelism The parallelism to set.
* @return This stream.
*/
public DataStream<T> setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/DataStreamSink.java
|
Java
|
package org.ray.streaming.api.stream;
import org.ray.streaming.operator.impl.SinkOperator;
/**
* Represents a sink of the DataStream.
*
* @param <T> Type of the input data of this sink.
*/
public class DataStreamSink<T> extends StreamSink<T> {
public DataStreamSink(DataStream<T> input, SinkOperator sinkOperator) {
super(input, sinkOperator);
this.streamingContext.addSink(this);
}
public DataStreamSink<T> setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/DataStreamSource.java
|
Java
|
package org.ray.streaming.api.stream;
import java.util.Collection;
import org.ray.streaming.api.context.StreamingContext;
import org.ray.streaming.api.function.impl.SourceFunction;
import org.ray.streaming.api.function.internal.CollectionSourceFunction;
import org.ray.streaming.api.partition.impl.RoundRobinPartition;
import org.ray.streaming.operator.impl.SourceOperator;
/**
* Represents a source of the DataStream.
*
* @param <T> The type of StreamSource data.
*/
public class DataStreamSource<T> extends DataStream<T> implements StreamSource<T> {
public DataStreamSource(StreamingContext streamingContext, SourceFunction<T> sourceFunction) {
super(streamingContext, new SourceOperator<>(sourceFunction));
super.partition = new RoundRobinPartition<>();
}
/**
* Build a DataStreamSource source from a collection.
*
* @param context Stream context.
* @param values A collection of values.
* @param <T> The type of source data.
* @return A DataStreamSource.
*/
public static <T> DataStreamSource<T> buildSource(
StreamingContext context, Collection<T> values) {
return new DataStreamSource(context, new CollectionSourceFunction(values));
}
public DataStreamSource<T> setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/JoinStream.java
|
Java
|
package org.ray.streaming.api.stream;
import java.io.Serializable;
import org.ray.streaming.api.function.impl.JoinFunction;
import org.ray.streaming.api.function.impl.KeyFunction;
/**
* Represents a DataStream of two joined DataStream.
*
* @param <L> Type of the data in the left stream.
* @param <R> Type of the data in the right stream.
* @param <J> Type of the data in the joined stream.
*/
public class JoinStream<L, R, J> extends DataStream<L> {
public JoinStream(DataStream<L> leftStream, DataStream<R> rightStream) {
super(leftStream, null);
}
/**
* Apply key-by to the left join stream.
*/
public <K> Where<L, R, J, K> where(KeyFunction<L, K> keyFunction) {
return new Where<>(this, keyFunction);
}
/**
* Where clause of the join transformation.
*
* @param <L> Type of the data in the left stream.
* @param <R> Type of the data in the right stream.
* @param <J> Type of the data in the joined stream.
* @param <K> Type of the join key.
*/
class Where<L, R, J, K> implements Serializable {
private JoinStream<L, R, J> joinStream;
private KeyFunction<L, K> leftKeyByFunction;
public Where(JoinStream<L, R, J> joinStream, KeyFunction<L, K> leftKeyByFunction) {
this.joinStream = joinStream;
this.leftKeyByFunction = leftKeyByFunction;
}
public Equal<L, R, J, K> equalLo(KeyFunction<R, K> rightKeyFunction) {
return new Equal<>(joinStream, leftKeyByFunction, rightKeyFunction);
}
}
/**
* Equal clause of the join transformation.
*
* @param <L> Type of the data in the left stream.
* @param <R> Type of the data in the right stream.
* @param <J> Type of the data in the joined stream.
* @param <K> Type of the join key.
*/
class Equal<L, R, J, K> implements Serializable {
private JoinStream<L, R, J> joinStream;
private KeyFunction<L, K> leftKeyByFunction;
private KeyFunction<R, K> rightKeyByFunction;
public Equal(JoinStream<L, R, J> joinStream, KeyFunction<L, K> leftKeyByFunction,
KeyFunction<R, K> rightKeyByFunction) {
this.joinStream = joinStream;
this.leftKeyByFunction = leftKeyByFunction;
this.rightKeyByFunction = rightKeyByFunction;
}
public DataStream<J> with(JoinFunction<L, R, J> joinFunction) {
return (DataStream<J>) joinStream;
}
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/KeyDataStream.java
|
Java
|
package org.ray.streaming.api.stream;
import org.ray.streaming.api.function.impl.AggregateFunction;
import org.ray.streaming.api.function.impl.ReduceFunction;
import org.ray.streaming.api.partition.impl.KeyPartition;
import org.ray.streaming.operator.StreamOperator;
import org.ray.streaming.operator.impl.ReduceOperator;
/**
* Represents a DataStream returned by a key-by operation.
*
* @param <K> Type of the key.
* @param <T> Type of the data.
*/
public class KeyDataStream<K, T> extends DataStream<T> {
public KeyDataStream(DataStream<T> input, StreamOperator streamOperator) {
super(input, streamOperator);
this.partition = new KeyPartition();
}
/**
* Apply a reduce function to this stream.
*
* @param reduceFunction The reduce function.
* @return A new DataStream.
*/
public DataStream<T> reduce(ReduceFunction reduceFunction) {
return new DataStream<>(this, new ReduceOperator(reduceFunction));
}
/**
* Apply an aggregate Function to this stream.
*
* @param aggregateFunction The aggregate function
* @param <A> The type of aggregated intermediate data.
* @param <O> The type of result data.
* @return A new DataStream.
*/
public <A, O> DataStream<O> aggregate(AggregateFunction<T, A, O> aggregateFunction) {
return new DataStream<>(this, null);
}
public KeyDataStream<K, T> setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/Stream.java
|
Java
|
package org.ray.streaming.api.stream;
import java.io.Serializable;
import org.ray.streaming.api.context.StreamingContext;
import org.ray.streaming.api.partition.Partition;
import org.ray.streaming.api.partition.impl.RoundRobinPartition;
import org.ray.streaming.operator.StreamOperator;
import org.ray.streaming.python.PythonOperator;
import org.ray.streaming.python.PythonPartition;
import org.ray.streaming.python.stream.PythonStream;
/**
* Abstract base class of all stream types.
*
* @param <T> Type of the data in the stream.
*/
public abstract class Stream<T> implements Serializable {
protected int id;
protected int parallelism = 1;
protected StreamOperator operator;
protected Stream<T> inputStream;
protected StreamingContext streamingContext;
protected Partition<T> partition;
@SuppressWarnings("unchecked")
public Stream(StreamingContext streamingContext, StreamOperator streamOperator) {
this.streamingContext = streamingContext;
this.operator = streamOperator;
this.id = streamingContext.generateId();
if (streamOperator instanceof PythonOperator) {
this.partition = PythonPartition.RoundRobinPartition;
} else {
this.partition = new RoundRobinPartition<>();
}
}
public Stream(Stream<T> inputStream, StreamOperator streamOperator) {
this.inputStream = inputStream;
this.parallelism = inputStream.getParallelism();
this.streamingContext = this.inputStream.getStreamingContext();
this.operator = streamOperator;
this.id = streamingContext.generateId();
this.partition = selectPartition();
}
@SuppressWarnings("unchecked")
private Partition<T> selectPartition() {
if (inputStream instanceof PythonStream) {
return PythonPartition.RoundRobinPartition;
} else {
return new RoundRobinPartition<>();
}
}
public Stream<T> getInputStream() {
return inputStream;
}
public StreamOperator getOperator() {
return operator;
}
public void setOperator(StreamOperator operator) {
this.operator = operator;
}
public StreamingContext getStreamingContext() {
return streamingContext;
}
public int getParallelism() {
return parallelism;
}
public Stream<T> setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
public int getId() {
return id;
}
public Partition<T> getPartition() {
return partition;
}
public void setPartition(Partition<T> partition) {
this.partition = partition;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/StreamSink.java
|
Java
|
package org.ray.streaming.api.stream;
import org.ray.streaming.operator.StreamOperator;
/**
* Represents a sink of the Stream.
*
* @param <T> Type of the input data of this sink.
*/
public class StreamSink<T> extends Stream<T> {
public StreamSink(Stream<T> inputStream, StreamOperator streamOperator) {
super(inputStream, streamOperator);
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/StreamSource.java
|
Java
|
package org.ray.streaming.api.stream;
/**
* A mark interface that represents a source of the Stream.
*
* @param <T> The type of StreamSource data.
*/
public interface StreamSource<T> {
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/UnionStream.java
|
Java
|
package org.ray.streaming.api.stream;
import java.util.ArrayList;
import java.util.List;
import org.ray.streaming.operator.StreamOperator;
/**
* Represents a union DataStream.
*
* @param <T> The type of union data.
*/
public class UnionStream<T> extends DataStream<T> {
private List<DataStream> unionStreams;
public UnionStream(DataStream input, StreamOperator streamOperator, DataStream<T> other) {
super(input, streamOperator);
this.unionStreams = new ArrayList<>();
this.unionStreams.add(other);
}
public List<DataStream> getUnionStreams() {
return unionStreams;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/jobgraph/JobEdge.java
|
Java
|
package org.ray.streaming.jobgraph;
import java.io.Serializable;
import org.ray.streaming.api.partition.Partition;
/**
* Job edge is connection and partition rules of upstream and downstream execution nodes.
*/
public class JobEdge implements Serializable {
private int srcVertexId;
private int targetVertexId;
private Partition partition;
public JobEdge(int srcVertexId, int targetVertexId, Partition partition) {
this.srcVertexId = srcVertexId;
this.targetVertexId = targetVertexId;
this.partition = partition;
}
public int getSrcVertexId() {
return srcVertexId;
}
public void setSrcVertexId(int srcVertexId) {
this.srcVertexId = srcVertexId;
}
public int getTargetVertexId() {
return targetVertexId;
}
public void setTargetVertexId(int targetVertexId) {
this.targetVertexId = targetVertexId;
}
public Partition getPartition() {
return partition;
}
public void setPartition(Partition partition) {
this.partition = partition;
}
@Override
public String toString() {
return "Edge(" + "from:" + srcVertexId + "-" + targetVertexId + "-" + this.partition.getClass()
+ ")";
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/jobgraph/JobGraph.java
|
Java
|
package org.ray.streaming.jobgraph;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Job graph, the logical plan of streaming job.
*/
public class JobGraph implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(JobGraph.class);
private final String jobName;
private final Map<String, String> jobConfig;
private List<JobVertex> jobVertexList;
private List<JobEdge> jobEdgeList;
private String digraph;
public JobGraph(String jobName, Map<String, String> jobConfig) {
this.jobName = jobName;
this.jobConfig = jobConfig;
this.jobVertexList = new ArrayList<>();
this.jobEdgeList = new ArrayList<>();
}
/**
* Generate direct-graph(made up of a set of vertices and connected by edges)
* by current job graph for simple log printing.
*
* @return Digraph in string type.
*/
public String generateDigraph() {
StringBuilder digraph = new StringBuilder();
digraph.append("digraph ").append(jobName + " ").append(" {");
for (JobEdge jobEdge : jobEdgeList) {
String srcNode = null;
String targetNode = null;
for (JobVertex jobVertex : jobVertexList) {
if (jobEdge.getSrcVertexId() == jobVertex.getVertexId()) {
srcNode = jobVertex.getVertexId() + "-" + jobVertex.getStreamOperator().getName();
} else if (jobEdge.getTargetVertexId() == jobVertex.getVertexId()) {
targetNode = jobVertex.getVertexId() + "-" + jobVertex.getStreamOperator().getName();
}
}
digraph.append(System.getProperty("line.separator"));
digraph.append(srcNode).append(" -> ").append(targetNode);
}
digraph.append(System.getProperty("line.separator")).append("}");
this.digraph = digraph.toString();
return this.digraph;
}
public void addVertex(JobVertex vertex) {
this.jobVertexList.add(vertex);
}
public void addEdge(JobEdge jobEdge) {
this.jobEdgeList.add(jobEdge);
}
public List<JobVertex> getJobVertexList() {
return jobVertexList;
}
public List<JobEdge> getJobEdgeList() {
return jobEdgeList;
}
public String getDigraph() {
return digraph;
}
public String getJobName() {
return jobName;
}
public Map<String, String> getJobConfig() {
return jobConfig;
}
public void printJobGraph() {
if (!LOG.isInfoEnabled()) {
return;
}
LOG.info("Printing job graph:");
for (JobVertex jobVertex : jobVertexList) {
LOG.info(jobVertex.toString());
}
for (JobEdge jobEdge : jobEdgeList) {
LOG.info(jobEdge.toString());
}
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/jobgraph/JobGraphBuilder.java
|
Java
|
package org.ray.streaming.jobgraph;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.ray.streaming.api.stream.DataStream;
import org.ray.streaming.api.stream.Stream;
import org.ray.streaming.api.stream.StreamSink;
import org.ray.streaming.api.stream.StreamSource;
import org.ray.streaming.operator.StreamOperator;
import org.ray.streaming.python.stream.PythonDataStream;
public class JobGraphBuilder {
private JobGraph jobGraph;
private AtomicInteger edgeIdGenerator;
private List<StreamSink> streamSinkList;
public JobGraphBuilder(List<StreamSink> streamSinkList) {
this(streamSinkList, "job-" + System.currentTimeMillis());
}
public JobGraphBuilder(List<StreamSink> streamSinkList, String jobName) {
this(streamSinkList, jobName, new HashMap<>());
}
public JobGraphBuilder(List<StreamSink> streamSinkList, String jobName,
Map<String, String> jobConfig) {
this.jobGraph = new JobGraph(jobName, jobConfig);
this.streamSinkList = streamSinkList;
this.edgeIdGenerator = new AtomicInteger(0);
}
public JobGraph build() {
for (StreamSink streamSink : streamSinkList) {
processStream(streamSink);
}
return this.jobGraph;
}
private void processStream(Stream stream) {
int vertexId = stream.getId();
int parallelism = stream.getParallelism();
StreamOperator streamOperator = stream.getOperator();
JobVertex jobVertex = null;
if (stream instanceof StreamSink) {
jobVertex = new JobVertex(vertexId, parallelism, VertexType.SINK, streamOperator);
Stream parentStream = stream.getInputStream();
int inputVertexId = parentStream.getId();
JobEdge jobEdge = new JobEdge(inputVertexId, vertexId, parentStream.getPartition());
this.jobGraph.addEdge(jobEdge);
processStream(parentStream);
} else if (stream instanceof StreamSource) {
jobVertex = new JobVertex(vertexId, parallelism, VertexType.SOURCE, streamOperator);
} else if (stream instanceof DataStream || stream instanceof PythonDataStream) {
jobVertex = new JobVertex(vertexId, parallelism, VertexType.PROCESS, streamOperator);
Stream parentStream = stream.getInputStream();
int inputVertexId = parentStream.getId();
JobEdge jobEdge = new JobEdge(inputVertexId, vertexId, parentStream.getPartition());
this.jobGraph.addEdge(jobEdge);
processStream(parentStream);
}
this.jobGraph.addVertex(jobVertex);
}
private int getEdgeId() {
return this.edgeIdGenerator.incrementAndGet();
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/jobgraph/JobVertex.java
|
Java
|
package org.ray.streaming.jobgraph;
import com.google.common.base.MoreObjects;
import java.io.Serializable;
import org.ray.streaming.operator.StreamOperator;
/**
* Job vertex is a cell node where logic is executed.
*/
public class JobVertex implements Serializable {
private int vertexId;
private int parallelism;
private VertexType vertexType;
private StreamOperator streamOperator;
public JobVertex(int vertexId, int parallelism, VertexType vertexType,
StreamOperator streamOperator) {
this.vertexId = vertexId;
this.parallelism = parallelism;
this.vertexType = vertexType;
this.streamOperator = streamOperator;
}
public int getVertexId() {
return vertexId;
}
public int getParallelism() {
return parallelism;
}
public StreamOperator getStreamOperator() {
return streamOperator;
}
public VertexType getVertexType() {
return vertexType;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("vertexId", vertexId)
.add("parallelism", parallelism)
.add("vertexType", vertexType)
.add("streamOperator", streamOperator)
.toString();
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/jobgraph/VertexType.java
|
Java
|
package org.ray.streaming.jobgraph;
/**
* Different roles for a node.
*/
public enum VertexType {
MASTER,
SOURCE,
PROCESS,
SINK,
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/message/KeyRecord.java
|
Java
|
package org.ray.streaming.message;
public class KeyRecord<K, T> extends Record<T> {
private K key;
public KeyRecord(K key, T value) {
super(value);
this.key = key;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/message/Message.java
|
Java
|
package org.ray.streaming.message;
import com.google.common.collect.Lists;
import java.io.Serializable;
import java.util.List;
public class Message implements Serializable {
private int taskId;
private long batchId;
private String stream;
private List<Record> recordList;
public Message(int taskId, long batchId, String stream, List<Record> recordList) {
this.taskId = taskId;
this.batchId = batchId;
this.stream = stream;
this.recordList = recordList;
}
public Message(int taskId, long batchId, String stream, Record record) {
this.taskId = taskId;
this.batchId = batchId;
this.stream = stream;
this.recordList = Lists.newArrayList(record);
}
public int getTaskId() {
return taskId;
}
public void setTaskId(int taskId) {
this.taskId = taskId;
}
public long getBatchId() {
return batchId;
}
public void setBatchId(long batchId) {
this.batchId = batchId;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
public List<Record> getRecordList() {
return recordList;
}
public void setRecordList(List<Record> recordList) {
this.recordList = recordList;
}
public Record getRecord(int index) {
return recordList.get(0);
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/message/Record.java
|
Java
|
package org.ray.streaming.message;
import java.io.Serializable;
public class Record<T> implements Serializable {
protected transient String stream;
protected T value;
public Record(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
@Override
public String toString() {
return value.toString();
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/OneInputOperator.java
|
Java
|
package org.ray.streaming.operator;
import org.ray.streaming.message.Record;
public interface OneInputOperator<T> extends Operator {
void processElement(Record<T> record) throws Exception;
default OperatorType getOpType() {
return OperatorType.ONE_INPUT;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/Operator.java
|
Java
|
package org.ray.streaming.operator;
import java.io.Serializable;
import java.util.List;
import org.ray.streaming.api.collector.Collector;
import org.ray.streaming.api.context.RuntimeContext;
public interface Operator extends Serializable {
void open(List<Collector> collectors, RuntimeContext runtimeContext);
void finish();
void close();
OperatorType getOpType();
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/OperatorType.java
|
Java
|
package org.ray.streaming.operator;
public enum OperatorType {
SOURCE,
ONE_INPUT,
TWO_INPUT,
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/StreamOperator.java
|
Java
|
package org.ray.streaming.operator;
import java.util.List;
import org.ray.streaming.api.collector.Collector;
import org.ray.streaming.api.context.RuntimeContext;
import org.ray.streaming.api.function.Function;
import org.ray.streaming.message.KeyRecord;
import org.ray.streaming.message.Record;
public abstract class StreamOperator<F extends Function> implements Operator {
protected String name;
protected F function;
protected List<Collector> collectorList;
protected RuntimeContext runtimeContext;
public StreamOperator(F function) {
this.name = getClass().getSimpleName();
this.function = function;
}
@Override
public void open(List<Collector> collectorList, RuntimeContext runtimeContext) {
this.collectorList = collectorList;
this.runtimeContext = runtimeContext;
}
@Override
public void finish() {
}
@Override
public void close() {
}
protected void collect(Record record) {
for (Collector collector : this.collectorList) {
collector.collect(record);
}
}
protected void collect(KeyRecord keyRecord) {
for (Collector collector : this.collectorList) {
collector.collect(keyRecord);
}
}
public String getName() {
return name;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/TwoInputOperator.java
|
Java
|
package org.ray.streaming.operator;
import org.ray.streaming.message.Record;
public interface TwoInputOperator<T, O> extends Operator {
void processElement(Record<T> record1, Record<O> record2);
default OperatorType getOpType() {
return OperatorType.TWO_INPUT;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/impl/FilterOperator.java
|
Java
|
package org.ray.streaming.operator.impl;
import org.ray.streaming.api.function.impl.FilterFunction;
import org.ray.streaming.message.Record;
import org.ray.streaming.operator.OneInputOperator;
import org.ray.streaming.operator.StreamOperator;
public class FilterOperator<T> extends StreamOperator<FilterFunction<T>> implements
OneInputOperator<T> {
public FilterOperator(FilterFunction<T> filterFunction) {
super(filterFunction);
}
@Override
public void processElement(Record<T> record) throws Exception {
if (this.function.filter(record.getValue())) {
this.collect(record);
}
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/impl/FlatMapOperator.java
|
Java
|
package org.ray.streaming.operator.impl;
import java.util.List;
import org.ray.streaming.api.collector.CollectionCollector;
import org.ray.streaming.api.collector.Collector;
import org.ray.streaming.api.context.RuntimeContext;
import org.ray.streaming.api.function.impl.FlatMapFunction;
import org.ray.streaming.message.Record;
import org.ray.streaming.operator.OneInputOperator;
import org.ray.streaming.operator.StreamOperator;
public class FlatMapOperator<T, R> extends StreamOperator<FlatMapFunction<T, R>> implements
OneInputOperator<T> {
private CollectionCollector collectionCollector;
public FlatMapOperator(FlatMapFunction<T, R> flatMapFunction) {
super(flatMapFunction);
}
@Override
public void open(List<Collector> collectorList, RuntimeContext runtimeContext) {
super.open(collectorList, runtimeContext);
this.collectionCollector = new CollectionCollector(collectorList);
}
@Override
public void processElement(Record<T> record) throws Exception {
this.function.flatMap(record.getValue(), (Collector<R>) collectionCollector);
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/impl/KeyByOperator.java
|
Java
|
package org.ray.streaming.operator.impl;
import org.ray.streaming.api.function.impl.KeyFunction;
import org.ray.streaming.message.KeyRecord;
import org.ray.streaming.message.Record;
import org.ray.streaming.operator.OneInputOperator;
import org.ray.streaming.operator.StreamOperator;
public class KeyByOperator<T, K> extends StreamOperator<KeyFunction<T, K>> implements
OneInputOperator<T> {
public KeyByOperator(KeyFunction<T, K> keyFunction) {
super(keyFunction);
}
@Override
public void processElement(Record<T> record) throws Exception {
K key = this.function.keyBy(record.getValue());
collect(new KeyRecord<>(key, record.getValue()));
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/impl/MapOperator.java
|
Java
|
package org.ray.streaming.operator.impl;
import org.ray.streaming.api.function.impl.MapFunction;
import org.ray.streaming.message.Record;
import org.ray.streaming.operator.OneInputOperator;
import org.ray.streaming.operator.StreamOperator;
public class MapOperator<T, R> extends StreamOperator<MapFunction<T, R>> implements
OneInputOperator<T> {
public MapOperator(MapFunction<T, R> mapFunction) {
super(mapFunction);
}
@Override
public void processElement(Record<T> record) throws Exception {
this.collect(new Record<R>(this.function.map(record.getValue())));
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/impl/ReduceOperator.java
|
Java
|
package org.ray.streaming.operator.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ray.streaming.api.collector.Collector;
import org.ray.streaming.api.context.RuntimeContext;
import org.ray.streaming.api.function.impl.ReduceFunction;
import org.ray.streaming.message.KeyRecord;
import org.ray.streaming.message.Record;
import org.ray.streaming.operator.OneInputOperator;
import org.ray.streaming.operator.StreamOperator;
public class ReduceOperator<K, T> extends StreamOperator<ReduceFunction<T>> implements
OneInputOperator<T> {
private Map<K, T> reduceState;
public ReduceOperator(ReduceFunction<T> reduceFunction) {
super(reduceFunction);
}
@Override
public void open(List<Collector> collectorList, RuntimeContext runtimeContext) {
super.open(collectorList, runtimeContext);
this.reduceState = new HashMap<>();
}
@Override
public void processElement(Record<T> record) throws Exception {
KeyRecord<K, T> keyRecord = (KeyRecord<K, T>) record;
K key = keyRecord.getKey();
T value = keyRecord.getValue();
if (reduceState.containsKey(key)) {
T oldValue = reduceState.get(key);
T newValue = this.function.reduce(oldValue, value);
reduceState.put(key, newValue);
collect(new Record(newValue));
} else {
reduceState.put(key, value);
collect(record);
}
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/impl/SinkOperator.java
|
Java
|
package org.ray.streaming.operator.impl;
import org.ray.streaming.api.function.impl.SinkFunction;
import org.ray.streaming.message.Record;
import org.ray.streaming.operator.OneInputOperator;
import org.ray.streaming.operator.StreamOperator;
public class SinkOperator<T> extends StreamOperator<SinkFunction<T>> implements
OneInputOperator<T> {
public SinkOperator(SinkFunction<T> sinkFunction) {
super(sinkFunction);
}
@Override
public void processElement(Record<T> record) throws Exception {
this.function.sink(record.getValue());
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/operator/impl/SourceOperator.java
|
Java
|
package org.ray.streaming.operator.impl;
import java.util.List;
import org.ray.streaming.api.collector.Collector;
import org.ray.streaming.api.context.RuntimeContext;
import org.ray.streaming.api.function.impl.SourceFunction;
import org.ray.streaming.api.function.impl.SourceFunction.SourceContext;
import org.ray.streaming.message.Record;
import org.ray.streaming.operator.OperatorType;
import org.ray.streaming.operator.StreamOperator;
public class SourceOperator<T> extends StreamOperator<SourceFunction<T>> {
private SourceContextImpl sourceContext;
public SourceOperator(SourceFunction<T> function) {
super(function);
}
@Override
public void open(List<Collector> collectorList, RuntimeContext runtimeContext) {
super.open(collectorList, runtimeContext);
this.sourceContext = new SourceContextImpl(collectorList);
this.function.init(runtimeContext.getParallelism(), runtimeContext.getTaskIndex());
}
public void run() {
try {
this.function.run(this.sourceContext);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public OperatorType getOpType() {
return OperatorType.SOURCE;
}
class SourceContextImpl implements SourceContext<T> {
private List<Collector> collectors;
public SourceContextImpl(List<Collector> collectors) {
this.collectors = collectors;
}
@Override
public void collect(T t) throws Exception {
for (Collector collector : collectors) {
collector.collect(new Record(t));
}
}
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/python/PythonFunction.java
|
Java
|
package org.ray.streaming.python;
import org.ray.streaming.api.function.Function;
/**
* Represents a user defined python function.
*
* <p>Python worker can use information in this class to create a function object.</p>
*
* <p>If this object is constructed from serialized python function,
* python worker can deserialize it to create python function directly.
* If this object is constructed from moduleName and className/functionName,
* python worker will use `importlib` to load python function.</p>
*
* <p>If the python data stream api is invoked from python, `function` will be not null.</p>
* <p>If the python data stream api is invoked from java, `moduleName` and
* `className`/`functionName` will be not null.</p>
* <p>
* TODO serialize to bytes using protobuf
*/
public class PythonFunction implements Function {
public enum FunctionInterface {
SOURCE_FUNCTION("ray.streaming.function.SourceFunction"),
MAP_FUNCTION("ray.streaming.function.MapFunction"),
FLAT_MAP_FUNCTION("ray.streaming.function.FlatMapFunction"),
FILTER_FUNCTION("ray.streaming.function.FilterFunction"),
KEY_FUNCTION("ray.streaming.function.KeyFunction"),
REDUCE_FUNCTION("ray.streaming.function.ReduceFunction"),
SINK_FUNCTION("ray.streaming.function.SinkFunction");
private String functionInterface;
FunctionInterface(String functionInterface) {
this.functionInterface = functionInterface;
}
}
private byte[] function;
private String moduleName;
private String className;
private String functionName;
/**
* FunctionInterface can be used to validate python function,
* and look up operator class from FunctionInterface.
*/
private String functionInterface;
private PythonFunction(byte[] function,
String moduleName,
String className,
String functionName) {
this.function = function;
this.moduleName = moduleName;
this.className = className;
this.functionName = functionName;
}
public void setFunctionInterface(FunctionInterface functionInterface) {
this.functionInterface = functionInterface.functionInterface;
}
/**
* Create a {@link PythonFunction} using python serialized function
*
* @param function serialized python function sent from python driver
*/
public static PythonFunction fromFunction(byte[] function) {
return new PythonFunction(function, null, null, null);
}
/**
* Create a {@link PythonFunction} using <code>moduleName</code> and
* <code>className</code>.
*
* @param moduleName python module name
* @param className python class name
*/
public static PythonFunction fromClassName(String moduleName, String className) {
return new PythonFunction(null, moduleName, className, null);
}
/**
* Create a {@link PythonFunction} using <code>moduleName</code> and
* <code>functionName</code>.
*
* @param moduleName python module name
* @param functionName python function name
*/
public static PythonFunction fromFunctionName(String moduleName, String functionName) {
return new PythonFunction(null, moduleName, null, functionName);
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/python/PythonOperator.java
|
Java
|
package org.ray.streaming.python;
import java.util.List;
import org.ray.streaming.api.context.RuntimeContext;
import org.ray.streaming.operator.OperatorType;
import org.ray.streaming.operator.StreamOperator;
/**
* Represents a {@link StreamOperator} that wraps python {@link PythonFunction}.
*/
@SuppressWarnings("unchecked")
public class PythonOperator extends StreamOperator {
public PythonOperator(PythonFunction function) {
super(function);
}
@Override
public void open(List list, RuntimeContext runtimeContext) {
String msg = String.format("Methods of %s shouldn't be called.", getClass().getSimpleName());
throw new UnsupportedOperationException(msg);
}
@Override
public void finish() {
String msg = String.format("Methods of %s shouldn't be called.", getClass().getSimpleName());
throw new UnsupportedOperationException(msg);
}
@Override
public void close() {
String msg = String.format("Methods of %s shouldn't be called.", getClass().getSimpleName());
throw new UnsupportedOperationException(msg);
}
@Override
public OperatorType getOpType() {
String msg = String.format("Methods of %s shouldn't be called.", getClass().getSimpleName());
throw new UnsupportedOperationException(msg);
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/python/PythonPartition.java
|
Java
|
package org.ray.streaming.python;
import org.ray.streaming.api.partition.Partition;
/**
* Represents a python partition function.
* <p>
* Python worker can create a partition object using information in this
* PythonPartition.
* <p>
* If this object is constructed from serialized python partition,
* python worker can deserialize it to create python partition directly.
* If this object is constructed from moduleName and className/functionName,
* python worker will use `importlib` to load python partition function.
* <p>
* TODO serialize to bytes using protobuf
*/
public class PythonPartition implements Partition {
public static final PythonPartition BroadcastPartition = new PythonPartition(
"ray.streaming.partition", "BroadcastPartition", null);
public static final PythonPartition KeyPartition = new PythonPartition(
"ray.streaming.partition", "KeyPartition", null);
public static final PythonPartition RoundRobinPartition = new PythonPartition(
"ray.streaming.partition", "RoundRobinPartition", null);
private byte[] partition;
private String moduleName;
private String className;
private String functionName;
public PythonPartition(byte[] partition) {
this.partition = partition;
}
public PythonPartition(String moduleName, String className, String functionName) {
this.moduleName = moduleName;
this.className = className;
this.functionName = functionName;
}
@Override
public int[] partition(Object record, int numPartition) {
String msg = String.format("partition method of %s shouldn't be called.",
getClass().getSimpleName());
throw new UnsupportedOperationException(msg);
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/python/stream/PythonDataStream.java
|
Java
|
package org.ray.streaming.python.stream;
import org.ray.streaming.api.context.StreamingContext;
import org.ray.streaming.api.stream.Stream;
import org.ray.streaming.python.PythonFunction;
import org.ray.streaming.python.PythonFunction.FunctionInterface;
import org.ray.streaming.python.PythonOperator;
import org.ray.streaming.python.PythonPartition;
/**
* Represents a stream of data whose transformations will be executed in python.
*/
public class PythonDataStream extends Stream implements PythonStream {
protected PythonDataStream(StreamingContext streamingContext,
PythonOperator pythonOperator) {
super(streamingContext, pythonOperator);
}
protected PythonDataStream(Stream inputStream, PythonOperator pythonOperator) {
super(inputStream, pythonOperator);
}
/**
* Apply a map function to this stream.
*
* @param func The python MapFunction.
* @return A new PythonDataStream.
*/
public PythonDataStream map(PythonFunction func) {
func.setFunctionInterface(FunctionInterface.MAP_FUNCTION);
return new PythonDataStream(this, new PythonOperator(func));
}
/**
* Apply a flat-map function to this stream.
*
* @param func The python FlapMapFunction.
* @return A new PythonDataStream
*/
public PythonDataStream flatMap(PythonFunction func) {
func.setFunctionInterface(FunctionInterface.FLAT_MAP_FUNCTION);
return new PythonDataStream(this, new PythonOperator(func));
}
/**
* Apply a filter function to this stream.
*
* @param func The python FilterFunction.
* @return A new PythonDataStream that contains only the elements satisfying
* the given filter predicate.
*/
public PythonDataStream filter(PythonFunction func) {
func.setFunctionInterface(FunctionInterface.FILTER_FUNCTION);
return new PythonDataStream(this, new PythonOperator(func));
}
/**
* Apply a sink function and get a StreamSink.
*
* @param func The python SinkFunction.
* @return A new StreamSink.
*/
public PythonStreamSink sink(PythonFunction func) {
func.setFunctionInterface(FunctionInterface.SINK_FUNCTION);
return new PythonStreamSink(this, new PythonOperator(func));
}
/**
* Apply a key-by function to this stream.
*
* @param func the python keyFunction.
* @return A new KeyDataStream.
*/
public PythonKeyDataStream keyBy(PythonFunction func) {
func.setFunctionInterface(FunctionInterface.KEY_FUNCTION);
return new PythonKeyDataStream(this, new PythonOperator(func));
}
/**
* Apply broadcast to this stream.
*
* @return This stream.
*/
public PythonDataStream broadcast() {
this.partition = PythonPartition.BroadcastPartition;
return this;
}
/**
* Apply a partition to this stream.
*
* @param partition The partitioning strategy.
* @return This stream.
*/
public PythonDataStream partitionBy(PythonPartition partition) {
this.partition = partition;
return this;
}
/**
* Set parallelism to current transformation.
*
* @param parallelism The parallelism to set.
* @return This stream.
*/
public PythonDataStream setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/python/stream/PythonKeyDataStream.java
|
Java
|
package org.ray.streaming.python.stream;
import org.ray.streaming.api.stream.Stream;
import org.ray.streaming.operator.StreamOperator;
import org.ray.streaming.python.PythonFunction;
import org.ray.streaming.python.PythonFunction.FunctionInterface;
import org.ray.streaming.python.PythonOperator;
import org.ray.streaming.python.PythonPartition;
/**
* Represents a python DataStream returned by a key-by operation.
*/
public class PythonKeyDataStream extends Stream implements PythonStream {
public PythonKeyDataStream(PythonDataStream input, StreamOperator streamOperator) {
super(input, streamOperator);
this.partition = PythonPartition.KeyPartition;
}
/**
* Apply a reduce function to this stream.
*
* @param func The reduce function.
* @return A new DataStream.
*/
public PythonDataStream reduce(PythonFunction func) {
func.setFunctionInterface(FunctionInterface.REDUCE_FUNCTION);
return new PythonDataStream(this, new PythonOperator(func));
}
public PythonKeyDataStream setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/python/stream/PythonStream.java
|
Java
|
package org.ray.streaming.python.stream;
/**
* A marker interface used to identify all python streams.
*/
public interface PythonStream {
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/python/stream/PythonStreamSink.java
|
Java
|
package org.ray.streaming.python.stream;
import org.ray.streaming.api.stream.StreamSink;
import org.ray.streaming.python.PythonOperator;
/**
* Represents a sink of the PythonStream.
*/
public class PythonStreamSink extends StreamSink implements PythonStream {
public PythonStreamSink(PythonDataStream input, PythonOperator sinkOperator) {
super(input, null);
this.streamingContext.addSink(this);
}
public PythonStreamSink setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/python/stream/PythonStreamSource.java
|
Java
|
package org.ray.streaming.python.stream;
import org.ray.streaming.api.context.StreamingContext;
import org.ray.streaming.api.stream.StreamSource;
import org.ray.streaming.python.PythonFunction;
import org.ray.streaming.python.PythonFunction.FunctionInterface;
import org.ray.streaming.python.PythonOperator;
import org.ray.streaming.python.PythonPartition;
/**
* Represents a source of the PythonStream.
*/
public class PythonStreamSource extends PythonDataStream implements StreamSource {
private PythonStreamSource(StreamingContext streamingContext, PythonFunction sourceFunction) {
super(streamingContext, new PythonOperator(sourceFunction));
super.partition = PythonPartition.RoundRobinPartition;
}
public PythonStreamSource setParallelism(int parallelism) {
this.parallelism = parallelism;
return this;
}
public static PythonStreamSource from(StreamingContext streamingContext,
PythonFunction sourceFunction) {
sourceFunction.setFunctionInterface(FunctionInterface.SOURCE_FUNCTION);
return new PythonStreamSource(streamingContext, sourceFunction);
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/schedule/JobScheduler.java
|
Java
|
package org.ray.streaming.schedule;
import java.util.Map;
import org.ray.streaming.jobgraph.JobGraph;
/**
* Interface of the job scheduler.
*/
public interface JobScheduler {
/**
* Assign logical plan to physical execution graph, and schedule job to run.
*
* @param jobGraph The logical plan.
*/
void schedule(JobGraph jobGraph, Map<String, String> conf);
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/main/java/org/ray/streaming/util/Config.java
|
Java
|
package org.ray.streaming.util;
public class Config {
/**
* Maximum number of batches to run in a streaming job.
*/
public static final String STREAMING_BATCH_MAX_COUNT = "streaming.batch.max.count";
/**
* batch frequency in milliseconds
*/
public static final String STREAMING_BATCH_FREQUENCY = "streaming.batch.frequency";
public static final long STREAMING_BATCH_FREQUENCY_DEFAULT = 1000;
public static final String STREAMING_JOB_NAME = "streaming.job.name";
public static final String STREAMING_OP_NAME = "streaming.op_name";
public static final String TASK_JOB_ID = "streaming.task_job_id";
public static final String STREAMING_WORKER_NAME = "streaming.worker_name";
// channel
public static final String CHANNEL_TYPE = "channel_type";
public static final String MEMORY_CHANNEL = "memory_channel";
public static final String NATIVE_CHANNEL = "native_channel";
public static final String DEFAULT_CHANNEL_TYPE = NATIVE_CHANNEL;
public static final String CHANNEL_SIZE = "channel_size";
public static final String CHANNEL_SIZE_DEFAULT = String.valueOf((long)Math.pow(10, 8));
public static final String IS_RECREATE = "streaming.is_recreate";
// return from DataReader.getBundle if only empty message read in this interval.
public static final String TIMER_INTERVAL_MS = "timer_interval_ms";
public static final String READ_TIMEOUT_MS = "read_timeout_ms";
public static final String DEFAULT_READ_TIMEOUT_MS = "10";
public static final String STREAMING_RING_BUFFER_CAPACITY = "streaming.ring_buffer_capacity";
// write an empty message if there is no data to be written in this
// interval.
public static final String STREAMING_EMPTY_MESSAGE_INTERVAL = "streaming.empty_message_interval";
// operator type
public static final String OPERATOR_TYPE = "operator_type";
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-api/src/test/java/org/ray/streaming/jobgraph/JobGraphBuilderTest.java
|
Java
|
package org.ray.streaming.jobgraph;
import com.google.common.collect.Lists;
import java.util.List;
import org.ray.streaming.api.context.StreamingContext;
import org.ray.streaming.api.partition.impl.KeyPartition;
import org.ray.streaming.api.partition.impl.RoundRobinPartition;
import org.ray.streaming.api.stream.DataStream;
import org.ray.streaming.api.stream.DataStreamSource;
import org.ray.streaming.api.stream.StreamSink;
import org.ray.streaming.api.stream.StreamSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class JobGraphBuilderTest {
private static final Logger LOG = LoggerFactory.getLogger(JobGraphBuilderTest.class);
@Test
public void testDataSync() {
JobGraph jobGraph = buildDataSyncJobGraph();
List<JobVertex> jobVertexList = jobGraph.getJobVertexList();
List<JobEdge> jobEdgeList = jobGraph.getJobEdgeList();
Assert.assertEquals(jobVertexList.size(), 2);
Assert.assertEquals(jobEdgeList.size(), 1);
JobEdge jobEdge = jobEdgeList.get(0);
Assert.assertEquals(jobEdge.getPartition().getClass(), RoundRobinPartition.class);
JobVertex sinkVertex = jobVertexList.get(1);
JobVertex sourceVertex = jobVertexList.get(0);
Assert.assertEquals(sinkVertex.getVertexType(), VertexType.SINK);
Assert.assertEquals(sourceVertex.getVertexType(), VertexType.SOURCE);
}
public JobGraph buildDataSyncJobGraph() {
StreamingContext streamingContext = StreamingContext.buildContext();
DataStream<String> dataStream = DataStreamSource.buildSource(streamingContext,
Lists.newArrayList("a", "b", "c"));
StreamSink streamSink = dataStream.sink(x -> LOG.info(x));
JobGraphBuilder jobGraphBuilder = new JobGraphBuilder(Lists.newArrayList(streamSink));
JobGraph jobGraph = jobGraphBuilder.build();
return jobGraph;
}
@Test
public void testKeyByJobGraph() {
JobGraph jobGraph = buildKeyByJobGraph();
List<JobVertex> jobVertexList = jobGraph.getJobVertexList();
List<JobEdge> jobEdgeList = jobGraph.getJobEdgeList();
Assert.assertEquals(jobVertexList.size(), 3);
Assert.assertEquals(jobEdgeList.size(), 2);
JobVertex source = jobVertexList.get(0);
JobVertex map = jobVertexList.get(1);
JobVertex sink = jobVertexList.get(2);
Assert.assertEquals(source.getVertexType(), VertexType.SOURCE);
Assert.assertEquals(map.getVertexType(), VertexType.PROCESS);
Assert.assertEquals(sink.getVertexType(), VertexType.SINK);
JobEdge keyBy2Sink = jobEdgeList.get(0);
JobEdge source2KeyBy = jobEdgeList.get(1);
Assert.assertEquals(keyBy2Sink.getPartition().getClass(), KeyPartition.class);
Assert.assertEquals(source2KeyBy.getPartition().getClass(), RoundRobinPartition.class);
}
public JobGraph buildKeyByJobGraph() {
StreamingContext streamingContext = StreamingContext.buildContext();
DataStream<String> dataStream = DataStreamSource.buildSource(streamingContext,
Lists.newArrayList("1", "2", "3", "4"));
StreamSink streamSink = dataStream.keyBy(x -> x)
.sink(x -> LOG.info(x));
JobGraphBuilder jobGraphBuilder = new JobGraphBuilder(Lists.newArrayList(streamSink));
JobGraph jobGraph = jobGraphBuilder.build();
return jobGraph;
}
@Test
public void testJobGraphViz() {
JobGraph jobGraph = buildKeyByJobGraph();
jobGraph.generateDigraph();
String diGraph = jobGraph.getDigraph();
System.out.println(diGraph);
Assert.assertTrue(diGraph.contains("1-SourceOperator -> 2-KeyByOperator"));
Assert.assertTrue(diGraph.contains("2-KeyByOperator -> 3-SinkOperator"));
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-runtime/src/main/java/org/ray/streaming/runtime/cluster/ResourceManager.java
|
Java
|
package org.ray.streaming.runtime.cluster;
import java.util.ArrayList;
import java.util.List;
import org.ray.api.Ray;
import org.ray.api.RayActor;
import org.ray.streaming.runtime.worker.JobWorker;
/**
* Resource-Manager is used to do the management of resources
*/
public class ResourceManager {
public List<RayActor<JobWorker>> createWorkers(int workerNum) {
List<RayActor<JobWorker>> workers = new ArrayList<>();
for (int i = 0; i < workerNum; i++) {
RayActor<JobWorker> worker = Ray.createActor(JobWorker::new);
workers.add(worker);
}
return workers;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-runtime/src/main/java/org/ray/streaming/runtime/config/Config.java
|
Java
|
package org.ray.streaming.runtime.config;
import java.io.Serializable;
import javax.accessibility.Accessible;
/**
* Basic config interface.
*/
public interface Config extends org.aeonbits.owner.Config, Accessible, Serializable {
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-runtime/src/main/java/org/ray/streaming/runtime/config/StreamingConfig.java
|
Java
|
package org.ray.streaming.runtime.config;
import java.io.Serializable;
import java.util.Map;
/**
* Streaming config including general, master and worker part.
*/
public class StreamingConfig implements Serializable {
public StreamingMasterConfig masterConfig;
public StreamingWorkerConfig workerConfigTemplate;
public StreamingConfig(final Map<String, String> conf) {
masterConfig = new StreamingMasterConfig(conf);
workerConfigTemplate = new StreamingWorkerConfig(conf);
}
public Map<String, String> getMap() {
Map<String, String> wholeConfigMap = masterConfig.configMap;
wholeConfigMap.putAll(workerConfigTemplate.configMap);
return wholeConfigMap;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-runtime/src/main/java/org/ray/streaming/runtime/config/StreamingGlobalConfig.java
|
Java
|
package org.ray.streaming.runtime.config;
import com.google.common.base.Preconditions;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.aeonbits.owner.Config.DefaultValue;
import org.aeonbits.owner.Config.Key;
import org.aeonbits.owner.ConfigFactory;
import org.ray.streaming.runtime.config.global.CommonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Streaming general config. May used by both JobMaster and JobWorker.
*/
public class StreamingGlobalConfig implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(StreamingGlobalConfig.class);
public final CommonConfig commonConfig;
public final Map<String, String> configMap;
public StreamingGlobalConfig(final Map<String, String> conf) {
configMap = new HashMap<>(conf);
commonConfig = ConfigFactory.create(CommonConfig.class, conf);
globalConfig2Map();
}
@Override
public String toString() {
return configMap.toString();
}
private void globalConfig2Map() {
try {
configMap.putAll(config2Map(this.commonConfig));
} catch (Exception e) {
LOG.error("Couldn't convert global config to a map.", e);
}
}
protected Map<String, String> config2Map(org.aeonbits.owner.Config config)
throws ClassNotFoundException {
Map<String, String> result = new HashMap<>();
Class<?> proxyClazz = Class.forName(config.getClass().getName());
Class<?>[] proxyInterfaces = proxyClazz.getInterfaces();
Class<?> configInterface = null;
for (Class<?> proxyInterface : proxyInterfaces) {
if (Config.class.isAssignableFrom(proxyInterface)) {
configInterface = proxyInterface;
break;
}
}
Preconditions.checkArgument(configInterface != null,
"Can not get config interface.");
Method[] methods = configInterface.getMethods();
for (Method method : methods) {
Key ownerKeyAnnotation = method.getAnnotation(Key.class);
String ownerKeyAnnotationValue;
if (ownerKeyAnnotation != null) {
ownerKeyAnnotationValue = ownerKeyAnnotation.value();
Object value;
try {
value = method.invoke(config);
} catch (Exception e) {
LOG.warn("Can not get value by method invoking for config key: {}. "
+ "So use default value instead.", ownerKeyAnnotationValue);
String defaultValue = method.getAnnotation(DefaultValue.class).value();
value = defaultValue;
}
result.put(ownerKeyAnnotationValue, value + "");
}
}
return result;
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
streaming/java/streaming-runtime/src/main/java/org/ray/streaming/runtime/config/StreamingMasterConfig.java
|
Java
|
package org.ray.streaming.runtime.config;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Streaming job master config.
*/
public class StreamingMasterConfig extends StreamingGlobalConfig {
private static final Logger LOG = LoggerFactory.getLogger(StreamingMasterConfig.class);
public StreamingMasterConfig(final Map<String, String> conf) {
super(conf);
}
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.