[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HAFQ11FKVTGQ0FTVMV43J6":3,"skill-same:01M6HAFQ11FKVTGQ0FTVMV43J6":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":14,"repositoryHtmlUrl":52,"repositoryHomepageUrl":6,"ownerHtmlUrl":53,"ownerBlogUrl":54,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M6HAFQ11FKVTGQ0FTVMV43J6","ray",null,"Expert guidance on Ray distributed computing framework for scaling AI and Python  applications. Use for: distributed training, hyperparameter tuning with Ray Tune,  reinforcement learning with Ray RLlib, model serving with Ray Serve, batch inference,  scaling Python applications from single machines to clusters, and Ray Core tasks and actors.","NeuralBlitz\u002FMito","NeuralBlitz","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F79354388?v=4","01M6H8T2TFH477HRS0KTSTKR2E","David Riggs","01M6H8T2YQQDXPYM092P670Z21",0,"MIT","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fray\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"Ray","tuning","for","Hyperparameter Tuning","Batch Inference","scaling","expert","opencode","model","learning","applications","python","data","Distributed Training","distributed-computing","batch","framework","core","tasks","training","2026-11-10 10:12:30",false,"---\nname: ray\ndescription: >\n  Expert guidance on Ray distributed computing framework for scaling AI and Python \n  applications. Use for: distributed training, hyperparameter tuning with Ray Tune, \n  reinforcement learning with Ray RLlib, model serving with Ray Serve, batch inference, \n  scaling Python applications from single machines to clusters, and Ray Core tasks and actors.\nlicense: MIT\ncompatibility: opencode\nmetadata:\n  audience: ml-engineers, data-scientists\n  category: distributed-computing\n  tags: [ray, distributed-computing, machine-learning, scaling]\n---\n\n# Ray — Distributed Computing for AI\n\nCovers: **Ray Core · Distributed Training · Ray Tune · Ray RLlib · Ray Serve · Ray Datasets**\n\n-----\n\n## Understanding Ray\n\n### What is Ray?\n\nRay is a distributed computing framework designed to scale Python applications from a single machine to a large cluster. Originally developed at UC Berkeley's RISELab, Ray provides a unified set of primitives for building distributed applications, making it particularly well-suited for machine learning workloads.\n\nRay addresses the challenge of distributing Python code across multiple machines without requiring developers to become distributed systems experts. It provides a simple API that abstracts away the complexities of cluster management, fault tolerance, and inter-process communication.\n\n**Core Components:**\n\n- **Ray Core** — The foundational distributed computing primitives: tasks, actors, and objects.\n\n- **Ray Tune** — Scalable hyperparameter optimization with support for various search algorithms and schedulers.\n\n- **Ray RLlib** — Reinforcement learning library with distributed training support and many built-in algorithms.\n\n- **Ray Serve** — Scalable model serving framework for building production inference services.\n\n- **Ray Datasets** — Distributed data processing for ML workloads, integrated with popular data formats.\n\n### When to Use Ray\n\n| Use Case | Recommended Ray Component |\n|----------|---------------------------|\n| Parallelizing Python functions | Ray Tasks |\n| Stateful services with shared memory | Ray Actors |\n| Hyperparameter tuning | Ray Tune |\n| Reinforcement learning | Ray RLlib |\n| Model serving | Ray Serve |\n| Large-scale data processing | Ray Datasets |\n| Distributed training | Ray Train |\n\n-----\n\n## Ray Core Fundamentals\n\n### Ray Tasks (Stateless Functions)\n\nRay tasks are stateless functions that can be executed asynchronously across a Ray cluster. They're ideal for parallelizing pure functions that don't require maintaining state between invocations.\n\n```python\nimport ray\nimport time\nfrom typing import List\n\n# Initialize Ray\nray.init()\n\n# Define a function to be executed remotely\n@ray.remote\ndef download_url(url: str) -> str:\n    \"\"\"Simulate downloading content from a URL\"\"\"\n    import random\n    # Simulate network delay\n    time.sleep(random.uniform(0.5, 2.0))\n    return f\"Content from {url}\"\n\n@ray.remote\ndef process_content(content: str) -> int:\n    \"\"\"Process content and return result\"\"\"\n    # Simulate some processing\n    return len(content)\n\n# Execute tasks remotely\nurls = [\n    \"https:\u002F\u002Fexample.com\u002Farticle1\",\n    \"https:\u002F\u002Fexample.com\u002Farticle2\",\n    \"https:\u002F\u002Fexample.com\u002Farticle3\",\n    \"https:\u002F\u002Fexample.com\u002Farticle4\",\n    \"https:\u002F\u002Fexample.com\u002Farticle5\"\n]\n\n# Launch all downloads in parallel\ndownload_futures = [download_url.remote(url) for url in urls]\n\n# Wait for all to complete and get results\ncontents = ray.get(download_futures)\n\n# Chain with processing\nprocess_futures = [process_content.remote(content) for content in contents]\nresults = ray.get(process_futures)\n\nprint(f\"Processed {len(results)} URLs, results: {results}\")\n\n# For larger workflows, use ray.get with timeout\n# results = ray.get(futures, timeout=30)\n```\n\n### Ray Actors (Stateful Services)\n\nRay actors are stateful workers that maintain state across method calls. They're perfect for scenarios where you need shared state, counters, or services that benefit from keeping data in memory.\n\n```python\nimport ray\nfrom dataclasses import dataclass\n\nray.init()\n\n@dataclass\nclass TrainingMetrics:\n    epoch: int\n    loss: float\n    accuracy: float\n\n@ray.remote\nclass ParameterServer:\n    \"\"\"Parameter server for distributed training\"\"\"\n    \n    def __init__(self):\n        self.parameters = {}\n        self.version = 0\n    \n    def get_parameters(self, key: str) -> dict:\n        return self.parameters.get(key, {})\n    \n    def update_parameters(self, key: str, updates: dict):\n        if key not in self.parameters:\n            self.parameters[key] = {}\n        self.parameters[key].update(updates)\n        self.version += 1\n        return self.version\n\n@ray.remote\nclass DataLoader:\n    \"\"\"Distributed data loader actor\"\"\"\n    \n    def __init__(self, data_path: str, batch_size: int = 32):\n        self.data_path = data_path\n        self.batch_size = batch_size\n        self.current_index = 0\n        self.data = self._load_data()\n    \n    def _load_data(self):\n        # Load data (simplified)\n        import numpy as np\n        return np.random.randn(1000, 10)\n    \n    def get_batch(self) -> List[List[float]]:\n        start = self.current_index\n        end = min(start + self.batch_size, len(self.data))\n        \n        if start >= len(self.data):\n            self.current_index = 0\n            start = 0\n            end = min(self.batch_size, len(self.data))\n        \n        batch = self.data[start:end].tolist()\n        self.current_index = end\n        \n        return batch\n    \n    def reset(self):\n        self.current_index = 0\n        return True\n\n# Create actors\nps = ParameterServer.remote()\nloader = DataLoader.remote(\"\u002Fdata\u002Ftrain.csv\", batch_size=32)\n\n# Interact with actors\nray.get(ps.update_parameters.remote(\"model_v1\", {\"weights\": [1, 2, 3]}))\nparams = ray.get(ps.get_parameters.remote(\"model_v1\"))\nbatch = ray.get(loader.get_batch.remote())\n\n# Get actor handle from within another actor\n# Inside another actor:\n# ray.get(loader.get_batch.remote())\n```\n\n### Resource Management\n\n```python\nimport ray\n\nray.init(num_cpus=4, num_gpus=1)\n\n# Specify resource requirements for tasks\n@ray.remote(num_cpus=2, num_gpus=0.5)\ndef train_model_batch(data, config):\n    \"\"\"Train a model on a batch using GPU\"\"\"\n    import torch\n    # Training code here\n    return {\"loss\": 0.5, \"accuracy\": 0.9}\n\n# Use custom resources for specific hardware\n@ray.remote(resources={\"GPU_TYPE_A100\": 1})\ndef run_on_a100():\n    return \"Running on A100 GPU\"\n\n# Actor resource management\n@ray.remote(num_cpus=1, num_gpus=0.25)\nclass GPUWorker:\n    def __init__(self):\n        self.device = \"cuda:0\"\n    \n    def process(self, data):\n        # Process on GPU\n        return len(data)\n\n# Automatic resource allocation with placement groups\nplacement_group = ray.util.placement_group(\n    [{\"CPU\": 2, \"GPU\": 1}],\n    strategy=\"PACK\"\n)\n\n@ray.remote(num_cpus=2, num_gpus=1)\ndef scheduled_task():\n    return \"Running in placement group\"\n\n# Wait for placement group to be ready\nray.get(scheduled_task.options(\n    placement_group=placement_group,\n    placement_group_bundle_index=0\n).remote())\n```\n\n-----\n\n## Ray Tune (Hyperparameter Optimization)\n\n### Basic Configuration\n\n```python\nimport ray\nfrom ray import tune\n\nray.init(num_cpus=4)\n\ndef trainable_function(config: dict):\n    \"\"\"Training function to optimize\"\"\"\n    import time\n    import numpy as np\n    \n    # Extract hyperparameters\n    learning_rate = config.get(\"learning_rate\", 0.01)\n    batch_size = config.get(\"batch_size\", 32)\n    hidden_units = config.get(\"hidden_units\", 64)\n    dropout = config.get(\"dropout\", 0.1)\n    \n    # Simulate training\n    metrics = {\"loss\": 1.0, \"accuracy\": 0.1}\n    \n    for step in range(100):\n        # Simulate training loop\n        loss = np.random.uniform(0.1, 1.0) * (learning_rate \u002F 0.01)\n        accuracy = 1.0 - loss + np.random.uniform(-0.1, 0.1)\n        \n        # Report metrics to Tune\n        tune.report(\n            loss=loss,\n            accuracy=max(0, min(1, accuracy)),\n            step=step,\n            learning_rate=learning_rate\n        )\n        \n        time.sleep(0.1)\n    \n    return {\"loss\": loss, \"accuracy\": accuracy}\n\n# Run basic search\nanalysis = tune.run(\n    trainable_function,\n    config={\n        \"learning_rate\": tune.choice([0.001, 0.01, 0.1]),\n        \"batch_size\": tune.choice([16, 32, 64, 128]),\n        \"hidden_units\": tune.choice([32, 64, 128, 256]),\n        \"dropout\": tune.uniform(0.0, 0.5)\n    },\n    num_samples=20,\n    metric=\"loss\",\n    mode=\"min\",\n    verbose=1\n)\n\n# Get best configuration\nbest_config = analysis.best_config\nbest_loss = analysis.best_result[\"loss\"]\nprint(f\"Best config: {best_config}\")\nprint(f\"Best loss: {best_loss}\")\n```\n\n### Advanced Search Strategies\n\n```python\nfrom ray import tune\nfrom ray.tuners import Tuner\nimport ray\n\nray.init(num_cpus=8)\n\n# Bayesian Optimization with Optuna\ndef optimize_with_optuna(search_space):\n    from ray.tune.search.optuna import OptunaSearch\n    \n    optuna_search = OptunaSearch(\n        metric=\"accuracy\",\n        mode=\"max\",\n        points_to_evaluate=[\n            {\"learning_rate\": 0.01, \"batch_size\": 32}\n        ]\n    )\n    \n    return tune.Tuner(\n        trainable_function,\n        tune_config=tune.TuneConfig(\n            search_alg=optuna_search,\n            num_samples=50,\n            time_budget_s=3600  # 1 hour\n        ),\n        param_space=search_space\n    )\n\n# HyperBand for early stopping\ndef run_with_hyperband(search_space):\n    return tune.Tuner(\n        trainable_function,\n        tune_config=tune.TuneConfig(\n            scheduler=tune.schedulers.HyperBandScheduler(\n                time_attr=\"step\",\n                max_t=100,\n                stop_last_triple=True\n            ),\n            num_samples=100,\n            max_concurrent_trials=8\n        ),\n        param_space=search_space\n    )\n\n# Population-Based Training (PBT)\ndef run_with_pbt(search_space):\n    return tune.Tuner(\n        trainable_function,\n        tune_config=tune.TuneConfig(\n            scheduler=tune.schedulers.PopulationBasedTraining(\n                time_attr=\"step\",\n                perturbation_interval=10,\n                hyperparam_mutations={\n                    \"learning_rate\": tune.loguniform(1e-4, 1e-2),\n                    \"dropout\": tune.uniform(0.0, 0.5)\n                }\n            ),\n            num_samples=20\n        ),\n        param_space=search_space\n    )\n\n# Define search space\nsearch_space = {\n    \"learning_rate\": tune.loguniform(1e-4, 1e-2),\n    \"batch_size\": tune.choice([16, 32, 64, 128]),\n    \"hidden_units\": tune.choice([64, 128, 256, 512]),\n    \"dropout\": tune.uniform(0.0, 0.5),\n    \"optimizer\": tune.choice([\"adam\", \"sgd\", \"rmsprop\"]),\n    \"activation\": tune.choice([\"relu\", \"tanh\", \"gelu\"])\n}\n\n# Run with PBT (often best for neural network tuning)\nanalysis = run_with_pbt(search_space).fit()\n```\n\n### Custom Trainables\n\n```python\nfrom ray import tune\nimport numpy as np\n\nclass CustomTrainable(tune.Trainable):\n    \"\"\"Custom trainable with state management\"\"\"\n    \n    def setup(self, config):\n        \"\"\"Initialize training state\"\"\"\n        self.model = Model(config)\n        self.optimizer = Optimizer(self.model, config[\"learning_rate\"])\n        self.step_count = 0\n        \n        # Load data\n        self.train_data = np.random.randn(1000, 10)\n        self.labels = np.random.randint(0, 2, 1000)\n    \n    def step(self):\n        \"\"\"Execute one training step\"\"\"\n        # Sample batch\n        indices = np.random.choice(len(self.train_data), 32)\n        batch_x = self.train_data[indices]\n        batch_y = self.labels[indices]\n        \n        # Train\n        loss = self.model.train_step(batch_x, batch_y)\n        accuracy = self.model.evaluate(batch_x, batch_y)\n        \n        self.step_count += 1\n        \n        return {\n            \"loss\": loss,\n            \"accuracy\": accuracy,\n            \"step\": self.step_count\n        }\n    \n    def save_checkpoint(self, checkpoint_dir):\n        \"\"\"Save checkpoint\"\"\"\n        path = f\"{checkpoint_dir}\u002Fmodel.npy\"\n        np.save(path, self.model.weights)\n        return path\n    \n    def load_checkpoint(self, checkpoint_path):\n        \"\"\"Load checkpoint\"\"\"\n        self.model.weights = np.load(checkpoint_path)\n\n\nclass Model:\n    def __init__(self, config):\n        self.hidden_units = config.get(\"hidden_units\", 64)\n        self.weights = np.random.randn(10, self.hidden_units)\n    \n    def train_step(self, x, y):\n        \"\"\"Simulate training\"\"\"\n        return np.random.uniform(0.1, 1.0)\n    \n    def evaluate(self, x, y):\n        return np.random.uniform(0.5, 0.95)\n\n\nclass Optimizer:\n    def __init__(self, model, lr):\n        self.model = model\n        self.lr = lr\n\n\n# Run custom trainable\nanalysis = tune.run(\n    CustomTrainable,\n    config={\n        \"learning_rate\": tune.choice([0.001, 0.01, 0.1]),\n        \"hidden_units\": tune.choice([32, 64, 128])\n    },\n    num_samples=10,\n    checkpoint_at_end=True,\n    checkpoint_freq=10\n)\n```\n\n-----\n\n## Ray RLlib (Reinforcement Learning)\n\n### Quick Start with Built-in Algorithms\n\n```python\nimport ray\nimport ray.rllib.algorithms as algo\n\nray.init(num_cpus=4)\n\n# Configure PPO algorithm\nconfig = algo.ppo.PPOConfig()\nconfig = config.environment(\"CartPole-v1\")\nconfig = config.framework(\"torch\")\nconfig = config.rollout_fragment_length(200)\nconfig = config.train_batch_size(4000)\nconfig = config.num_workers(2)\n\n# Build algorithm\nppo = config.build()\n\n# Train for multiple iterations\nfor i in range(50):\n    result = ppo.train()\n    \n    if i % 10 == 0:\n        print(f\"Iteration {i}:\")\n        print(f\"  Episode reward mean: {result['episode_reward_mean']:.2f}\")\n        print(f\"  Episode length mean: {result['episode_len_mean']:.2f}\")\n\n# Evaluate trained agent\nevaluation = ppo.evaluate()\nprint(f\"Evaluation reward: {evaluation['evaluation']['episode_reward_mean']}\")\n\n# Save and restore\nppo.save(\"\u002Ftmp\u002Fcheckpoint\")\nppo.restore(\"\u002Ftmp\u002Fcheckpoint\")\n```\n\n### Custom RL Environment\n\n```python\nimport gymnasium as gym\nfrom gymnasium import spaces\nimport numpy as np\n\nclass WarehouseEnv(gym.Env):\n    \"\"\"Custom warehouse environment for RL\"\"\"\n    \n    metadata = {\"render_modes\": [\"human\"]}\n    \n    def __init__(self, config=None):\n        super().__init__()\n        self.config = config or {}\n        \n        # Define action space: 0=move_left, 1=move_right, 2=move_up, 3=move_down, 4=pickup, 5=dropoff\n        self.action_space = spaces.Discrete(6)\n        \n        # Define observation space\n        self.observation_space = spaces.Box(\n            low=0, high=100, shape=(20,), dtype=np.float32\n        )\n        \n        self.position = [0, 0]\n        self.holding_item = False\n        self.deliveries = 0\n        self.steps = 0\n        self.max_steps = 100\n    \n    def reset(self, seed=None, options=None):\n        super().reset(seed=seed)\n        self.position = [0, 0]\n        self.holding_item = False\n        self.deliveries = 0\n        self.steps = 0\n        \n        obs = self._get_obs()\n        info = {}\n        \n        return obs, info\n    \n    def step(self, action):\n        self.steps += 1\n        \n        # Execute action\n        if action == 0:\n            self.position[0] = max(0, self.position[0] - 1)\n        elif action == 1:\n            self.position[0] = min(9, self.position[0] + 1)\n        elif action == 2:\n            self.position[1] = min(9, self.position[1] + 1)\n        elif action == 3:\n            self.position[1] = max(0, self.position[1] - 1)\n        elif action == 4 and not self.holding_item:\n            self.holding_item = True\n        elif action == 5 and self.holding_item:\n            self.holding_item = False\n            self.deliveries += 1\n        \n        # Calculate reward\n        reward = 1.0 if self.deliveries > 0 else 0.0\n        reward -= 0.01  # Step penalty\n        \n        terminated = self.steps >= self.max_steps\n        truncated = False\n        \n        return self._get_obs(), reward, terminated, truncated, {}\n    \n    def _get_obs(self):\n        obs = np.zeros(20, dtype=np.float32)\n        obs[0] = self.position[0] \u002F 10.0\n        obs[1] = self.position[1] \u002F 10.0\n        obs[2] = float(self.holding_item)\n        obs[3] = self.deliveries \u002F 10.0\n        return obs\n\n\n# Train on custom environment\nfrom ray import tune\nfrom ray.rllib.algorithms import PPOConfig\n\nconfig = (\n    PPOConfig()\n    .environment(WarehouseEnv)\n    .framework(\"torch\")\n    .rollout_fragment_length(200)\n    .train_batch_size(4000)\n)\n\ntune.Tuner(\n    \"PPO\",\n    param_space=config.to_dict(),\n    run_config=tune.RunConfig(stop={\"episode_reward_mean\": 50})\n).fit()\n```\n\n### Multi-Agent Training\n\n```python\nfrom ray.rllib.algorithms import PPOConfig\nfrom ray.rllib.env.multi_agent_env import MultiAgentEnv\nimport numpy as np\n\nclass MultiAgentWarehouse(MultiAgentEnv):\n    def __init__(self, config=None):\n        super().__init__()\n        self.num_agents = 3\n        self.observation_space = spaces.Box(low=0, high=100, shape=(10,))\n        self.action_space = spaces.Discrete(4)\n    \n    def reset(self):\n        return {\n            f\"agent_{i}\": self.observation_space.sample() \n            for i in range(self.num_agents)\n        }\n    \n    def step(self, action_dict):\n        obs = {\n            f\"agent_{i}\": self.observation_space.sample()\n            for i in range(self.num_agents)\n        }\n        \n        rewards = {f\"agent_{i}\": np.random.random() for i in range(self.num_agents)}\n        \n        terminateds = {\"__all__\": False}\n        truncateds = {\"__all__\": False}\n        \n        infos = {f\"agent_{i}\": {} for i in range(self.num_agents)}\n        \n        return obs, rewards, terminateds, truncateds, infos\n\n\nconfig = (\n    PPOConfig()\n    .environment(MultiAgentWarehouse)\n    .framework(\"torch\")\n    .training(train_batch_size=2000)\n    .rollout_fragment_length(100)\n    .multi_agent(\n        policies={\n            \"shared_policy\": (\n                None,\n                self.observation_space,\n                self.action_space,\n                {}\n            )\n        },\n        policy_mapping_fn=lambda agent_id: \"shared_policy\"\n    )\n)\n```\n\n-----\n\n## Ray Serve (Model Serving)\n\n### Basic Deployment\n\n```python\nfrom ray import serve\nimport requests\nfrom transformers import pipeline\n\n# Initialize Ray Serve\nserve.start()\n\n@serve.deployment\nclass TextClassifier:\n    def __init__(self):\n        # Load model in constructor\n        self.classifier = pipeline(\n            \"sentiment-analysis\",\n            model=\"distilbert-base-uncased-finetuned-sst-2-english\"\n        )\n    \n    def __call__(self, request):\n        # Get text from request\n        text = request.query_params.get(\"text\", \"\")\n        \n        # Run inference\n        result = self.classifier(text)[0]\n        \n        return result\n\n# Deploy the model\nTextClassifier.deploy()\n\n# Make requests\nresponse = requests.get(\"http:\u002F\u002Flocalhost:8000\u002FTextClassifier?text=I love Ray!\")\nprint(response.json())\n```\n\n### Complex Deployment with Preprocessing\n\n```python\nfrom ray import serve\nfrom typing import List, Dict\nimport asyncio\n\n@serve.deployment(\n    num_replicas=2,\n    ray_actor_options={\"num_cpus\": 1}\n)\nclass TextPreprocessor:\n    \"\"\"Preprocess text before passing to model\"\"\"\n    \n    def __init__(self):\n        import re\n        self.url_pattern = re.compile(r'https?:\u002F\u002F\\S+')\n        self.email_pattern = re.compile(r'\\S+@\\S+\\.\\S+')\n    \n    async def preprocess(self, text: str) -> str:\n        # Remove URLs\n        text = self.url_pattern.sub('[URL]', text)\n        # Remove emails\n        text = self.email_pattern.sub('[EMAIL]', text)\n        # Lowercase\n        text = text.lower()\n        \n        return text\n    \n    async def batch_preprocess(self, texts: List[str]) -> List[str]:\n        return await asyncio.gather(*[self.preprocess(t) for t in texts])\n\n\n@serve.deployment(\n    num_replicas=2,\n    ray_actor_options={\"num_cpus\": 1, \"num_gpus\": 0.5}\n)\nclass TextModel:\n    \"\"\"Model deployment\"\"\"\n    \n    def __init__(self):\n        import torch\n        from transformers import AutoTokenizer, AutoModel\n        \n        self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n        self.tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n        self.model = AutoModel.from_pretrained(\"bert-base-uncased\").to(self.device)\n        self.model.eval()\n    \n    async def __call__(self, request):\n        import torch\n        \n        text = await request.body()\n        \n        # Tokenize\n        inputs = self.tokenizer(\n            text, \n            return_tensors=\"pt\", \n            padding=True, \n            truncation=True\n        ).to(self.device)\n        \n        # Inference\n        with torch.no_grad():\n            outputs = self.model(**inputs)\n        \n        # Return embedding\n        embedding = outputs.last_hidden_state[:, 0, :].cpu().tolist()\n        \n        return {\"embedding\": embedding}\n\n\n# Chain deployments\nTextPreprocessor.deploy()\nTextModel.deploy(handle_annotation=TextPreprocessor)\n\n\n# Or use ingress with explicit pipeline\n@serve.deployment(route_prefix=\"\u002Fpredict\")\nclass Ingress:\n    def __init__(self):\n        import requests\n        self.preprocessor = serve.get_deployment_handle(\"TextPreprocessor\")\n        self.model = serve.get_deployment_handle(\"TextModel\")\n    \n    async def __call__(self, request):\n        text = await request.body()\n        \n        # Chain calls\n        processed = await self.preprocessor.preprocess.remote(text)\n        result = await self.model.remote(processed)\n        \n        return result\n\nIngress.deploy()\n```\n\n### Model Composition\n\n```python\nfrom ray import serve\nfrom ray.serve.drivers import DefaultAPIDriver\n\n@serve.deployment\nclass Summarizer:\n    def __init__(self):\n        # Load summarization model\n        self.model = load_summarizer()\n    \n    def generate_summary(self, text: str) -> str:\n        return self.model(text)\n\n\n@serve.deployment\nclass SentimentAnalyzer:\n    def __init__(self):\n        # Load sentiment model\n        self.model = load_sentiment_model()\n    \n    def analyze(self, text: str) -> str:\n        return self.model(text)\n\n\n@serve.deployment\nclass AnalysisPipeline:\n    \"\"\"Combined analysis pipeline\"\"\"\n    \n    def __init__(self):\n        self.summarizer = serve.get_deployment_handle(\"Summarizer\")\n        self.sentiment = serve.get_deployment_handle(\"SentimentAnalyzer\")\n    \n    async def analyze(self, text: str) -> Dict:\n        # Run both in parallel\n        summary, sentiment = await asyncio.gather(\n            self.summarizer.generate_summary.remote(text),\n            self.sentiment.analyze.remote(text)\n        )\n        \n        return {\n            \"original_length\": len(text),\n            \"summary\": summary,\n            \"sentiment\": sentiment,\n            \"key_topics\": extract_topics(text)\n        }\n\n# Deploy all\nSummarizer.deploy()\nSentimentAnalyzer.deploy()\nAnalysisPipeline.deploy()\n```\n\n-----\n\n## Ray Datasets\n\n```python\nimport ray\n\nray.init()\n\n# Create dataset from various sources\n# From NumPy\nimport numpy as np\nnumpy_array = np.random.randn(10000, 100)\ndataset = ray.data.from_numpy(numpy_array)\n\n# From pandas\nimport pandas as pd\ndf = pd.DataFrame({\"a\": range(1000), \"b\": range(1000, 2000)})\ndataset = ray.data.from_pandas(df)\n\n# From CSV\ndataset = ray.data.read_csv(\"s3:\u002F\u002Fbucket\u002Fdata\u002F*.csv\")\n\n# From Parquet\ndataset = ray.data.read_parquet(\"s3:\u002F\u002Fbucket\u002Fdata\u002F*.parquet\")\n\n# Transform data\ndef process_batch(batch: pd.DataFrame) -> pd.DataFrame:\n    batch[\"processed\"] = batch[\"a\"] * 2\n    return batch\n\nprocessed = dataset.map_batches(process_batch, batch_size=1000)\n\n# Filter data\nfiltered = dataset.filter(lambda row: row[\"a\"] > 500)\n\n# Shuffle\nshuffled = dataset.random_shuffle()\n\n# Split into train\u002Fval\u002Ftest\ntrain, val, test = shuffled.train_test_split(test_size=0.2)\n\n# Repartition\nrepartitioned = train.repartition(num_blocks=10)\n\n# Materialize to local cluster\nrepartitioned.fully_executed()\n\n# Custom transformations\ndef add_features(row):\n    row[\"new_feature\"] = row[\"a\"] ** 2\n    return row\n\nwith_features = dataset.map(add_features)\n\n# Group by and aggregate\naggregated = dataset.groupby(\"category\").mean()\n\n# Join datasets\ndataset1 = ray.data.from_pandas(pd.DataFrame({\"id\": [1, 2, 3], \"value\": [10, 20, 30]}))\ndataset2 = ray.data.from_pandas(pd.DataFrame({\"id\": [1, 2, 4], \"other\": [\"a\", \"b\", \"c\"]}))\njoined = dataset1.join(dataset2, on=\"id\", how=\"left\")\n```\n\n-----\n\n## Best Practices\n\n### Performance Optimization\n\n1. **Use ObjectRefs efficiently** — Don't get() immediately after each remote() call; batch when possible.\n\n2. **Choose tasks vs actors wisely** — Use tasks for stateless parallelism, actors for stateful services.\n\n3. **Configure resources correctly** — Specify CPU\u002FGPU requirements to enable proper scheduling.\n\n4. **Use placement groups** — For workloads requiring specific hardware configurations.\n\n5. **Monitor with Ray Dashboard** — Use the dashboard to identify bottlenecks.\n\n### Common Pitfalls\n\n1. **Not handling exceptions** — Use try\u002Fexcept within remote functions and propagate errors properly.\n\n2. **Excessive serialization** — Large objects passed between tasks incur serialization overhead. Use shared memory or ObjectRef passing.\n\n3. **Ignoring cluster startup time** — For short jobs, the cluster overhead may outweigh benefits.\n\n4. **Not checkpointing** — For long-running training, implement checkpointing to handle failures.\n\n### Resources\n\n- **Documentation**: docs.ray.io\n- **GitHub**: github.com\u002Fray-project\u002Fray\n- **Community**: discuss.ray.io\n- **Related Skills**: distributed-systems, pytorch, tensorflow, kubernetes\n","# Ray — Distributed Computing for AI\n\nCovers: **Ray Core · Distributed Training · Ray Tune · Ray RLlib · Ray Serve · Ray Datasets**\n\n-----\n\n## Understanding Ray\n\n### What is Ray?\n\nRay is a distributed computing framework designed to scale Python applications from a single machine to a large cluster. Originally developed at UC Berkeley's RISELab, Ray provides a unified set of primitives for building distributed applications, making it particularly well-suited for machine learning workloads.\n\nRay addresses the challenge of distributing Python code across multiple machines without requiring developers to become distributed systems experts. It provides a simple API that abstracts away the complexities of cluster management, fault tolerance, and inter-process communication.\n\n**Core Components:**\n\n- **Ray Core** — The foundational distributed computing primitives: tasks, actors, and objects.\n\n- **Ray Tune** — Scalable hyperparameter optimization with support for various search algorithms and schedulers.\n\n- **Ray RLlib** — Reinforcement learning library with distributed training support and many built-in algorithms.\n\n- **Ray Serve** — Scalable model serving framework for building production inference services.\n\n- **Ray Datasets** — Distributed data processing for ML workloads, integrated with popular data formats.\n\n### When to Use Ray\n\n| Use Case | Recommended Ray Component |\n|----------|---------------------------|\n| Parallelizing Python functions | Ray Tasks |\n| Stateful services with shared memory | Ray Actors |\n| Hyperparameter tuning | Ray Tune |\n| Reinforcement learning | Ray RLlib |\n| Model serving | Ray Serve |\n| Large-scale data processing | Ray Datasets |\n| Distributed training | Ray Train |\n\n-----\n\n## Ray Core Fundamentals\n\n### Ray Tasks (Stateless Functions)\n\nRay tasks are stateless functions that can be executed asynchronously across a Ray cluster. They're ideal for parallelizing pure functions that don't require maintaining state between invocations.\n\n```python\nimport ray\nimport time\nfrom typing import List\n\n# Initialize Ray\nray.init()\n\n# Define a function to be executed remotely\n@ray.remote\ndef download_url(url: str) -> str:\n    \"\"\"Simulate downloading content from a URL\"\"\"\n    import random\n    # Simulate network delay\n    time.sleep(random.uniform(0.5, 2.0))\n    return f\"Content from {url}\"\n\n@ray.remote\ndef process_content(content: str) -> int:\n    \"\"\"Process content and return result\"\"\"\n    # Simulate some processing\n    return len(content)\n\n# Execute tasks remotely\nurls = [\n    \"https:\u002F\u002Fexample.com\u002Farticle1\",\n    \"https:\u002F\u002Fexample.com\u002Farticle2\",\n    \"https:\u002F\u002Fexample.com\u002Farticle3\",\n    \"https:\u002F\u002Fexample.com\u002Farticle4\",\n    \"https:\u002F\u002Fexample.com\u002Farticle5\"\n]\n\n# Launch all downloads in parallel\ndownload_futures = [download_url.remote(url) for url in urls]\n\n# Wait for all to complete and get results\ncontents = ray.get(download_futures)\n\n# Chain with processing\nprocess_futures = [process_content.remote(content) for content in contents]\nresults = ray.get(process_futures)\n\nprint(f\"Processed {len(results)} URLs, results: {results}\")\n\n# For larger workflows, use ray.get with timeout\n# results = ray.get(futures, timeout=30)\n```\n\n### Ray Actors (Stateful Services)\n\nRay actors are stateful workers that maintain state across method calls. They're perfect for scenarios where you need shared state, counters, or services that benefit from keeping data in memory.\n\n```python\nimport ray\nfrom dataclasses import dataclass\n\nray.init()\n\n@dataclass\nclass TrainingMetrics:\n    epoch: int\n    loss: float\n    accuracy: float\n\n@ray.remote\nclass ParameterServer:\n    \"\"\"Parameter server for distributed training\"\"\"\n    \n    def __init__(self):\n        self.parameters = {}\n        self.version = 0\n    \n    def get_parameters(self, key: str) -> dict:\n        return self.parameters.get(key, {})\n    \n    def update_parameters(self, key: str, updates: dict):\n        if key not in self.parameters:\n            self.parameters[key] = {}\n        self.parameters[key].update(updates)\n        self.version += 1\n        return self.version\n\n@ray.remote\nclass DataLoader:\n    \"\"\"Distributed data loader actor\"\"\"\n    \n    def __init__(self, data_path: str, batch_size: int = 32):\n        self.data_path = data_path\n        self.batch_size = batch_size\n        self.current_index = 0\n        self.data = self._load_data()\n    \n    def _load_data(self):\n        # Load data (simplified)\n        import numpy as np\n        return np.random.randn(1000, 10)\n    \n    def get_batch(self) -> List[List[float]]:\n        start = self.current_index\n        end = min(start + self.batch_size, len(self.data))\n        \n        if start >= len(self.data):\n            self.current_index = 0\n            start = 0\n            end = min(self.batch_size, len(self.data))\n        \n        batch = self.data[start:end].tolist()\n        self.current_index = end\n        \n        return batch\n    \n    def reset(self):\n        self.current_index = 0\n        return True\n\n# Create actors\nps = ParameterServer.remote()\nloader = DataLoader.remote(\"\u002Fdata\u002Ftrain.csv\", batch_size=32)\n\n# Interact with actors\nray.get(ps.update_parameters.remote(\"model_v1\", {\"weights\": [1, 2, 3]}))\nparams = ray.get(ps.get_parameters.remote(\"model_v1\"))\nbatch = ray.get(loader.get_batch.remote())\n\n# Get actor handle from within another actor\n# Inside another actor:\n# ray.get(loader.get_batch.remote())\n```\n\n### Resource Management\n\n```python\nimport ray\n\nray.init(num_cpus=4, num_gpus=1)\n\n# Specify resource requirements for tasks\n@ray.remote(num_cpus=2, num_gpus=0.5)\ndef train_model_batch(data, config):\n    \"\"\"Train a model on a batch using GPU\"\"\"\n    import torch\n    # Training code here\n    return {\"loss\": 0.5, \"accuracy\": 0.9}\n\n# Use custom resources for specific hardware\n@ray.remote(resources={\"GPU_TYPE_A100\": 1})\ndef run_on_a100():\n    return \"Running on A100 GPU\"\n\n# Actor resource management\n@ray.remote(num_cpus=1, num_gpus=0.25)\nclass GPUWorker:\n    def __init__(self):\n        self.device = \"cuda:0\"\n    \n    def process(self, data):\n        # Process on GPU\n        return len(data)\n\n# Automatic resource allocation with placement groups\nplacement_group = ray.util.placement_group(\n    [{\"CPU\": 2, \"GPU\": 1}],\n    strategy=\"PACK\"\n)\n\n@ray.remote(num_cpus=2, num_gpus=1)\ndef scheduled_task():\n    return \"Running in placement group\"\n\n# Wait for placement group to be ready\nray.get(scheduled_task.options(\n    placement_group=placement_group,\n    placement_group_bundle_index=0\n).remote())\n```\n\n-----\n\n## Ray Tune (Hyperparameter Optimization)\n\n### Basic Configuration\n\n```python\nimport ray\nfrom ray import tune\n\nray.init(num_cpus=4)\n\ndef trainable_function(config: dict):\n    \"\"\"Training function to optimize\"\"\"\n    import time\n    import numpy as np\n    \n    # Extract hyperparameters\n    learning_rate = config.get(\"learning_rate\", 0.01)\n    batch_size = config.get(\"batch_size\", 32)\n    hidden_units = config.get(\"hidden_units\", 64)\n    dropout = config.get(\"dropout\", 0.1)\n    \n    # Simulate training\n    metrics = {\"loss\": 1.0, \"accuracy\": 0.1}\n    \n    for step in range(100):\n        # Simulate training loop\n        loss = np.random.uniform(0.1, 1.0) * (learning_rate \u002F 0.01)\n        accuracy = 1.0 - loss + np.random.uniform(-0.1, 0.1)\n        \n        # Report metrics to Tune\n        tune.report(\n            loss=loss,\n            accuracy=max(0, min(1, accuracy)),\n            step=step,\n            learning_rate=learning_rate\n        )\n        \n        time.sleep(0.1)\n    \n    return {\"loss\": loss, \"accuracy\": accuracy}\n\n# Run basic search\nanalysis = tune.run(\n    trainable_function,\n    config={\n        \"learning_rate\": tune.choice([0.001, 0.01, 0.1]),\n        \"batch_size\": tune.choice([16, 32, 64, 128]),\n        \"hidden_units\": tune.choice([32, 64, 128, 256]),\n        \"dropout\": tune.uniform(0.0, 0.5)\n    },\n    num_samples=20,\n    metric=\"loss\",\n    mode=\"min\",\n    verbose=1\n)\n\n# Get best configuration\nbest_config = analysis.best_config\nbest_loss = analysis.best_result[\"loss\"]\nprint(f\"Best config: {best_config}\")\nprint(f\"Best loss: {best_loss}\")\n```\n\n### Advanced Search Strategies\n\n```python\nfrom ray import tune\nfrom ray.tuners import Tuner\nimport ray\n\nray.init(num_cpus=8)\n\n# Bayesian Optimization with Optuna\ndef optimize_with_optuna(search_space):\n    from ray.tune.search.optuna import OptunaSearch\n    \n    optuna_search = OptunaSearch(\n        metric=\"accuracy\",\n        mode=\"max\",\n        points_to_evaluate=[\n            {\"learning_rate\": 0.01, \"batch_size\": 32}\n        ]\n    )\n    \n    return tune.Tuner(\n        trainable_function,\n        tune_config=tune.TuneConfig(\n            search_alg=optuna_search,\n            num_samples=50,\n            time_budget_s=3600  # 1 hour\n        ),\n        param_space=search_space\n    )\n\n# HyperBand for early stopping\ndef run_with_hyperband(search_space):\n    return tune.Tuner(\n        trainable_function,\n        tune_config=tune.TuneConfig(\n            scheduler=tune.schedulers.HyperBandScheduler(\n                time_attr=\"step\",\n                max_t=100,\n                stop_last_triple=True\n            ),\n            num_samples=100,\n            max_concurrent_trials=8\n        ),\n        param_space=search_space\n    )\n\n# Population-Based Training (PBT)\ndef run_with_pbt(search_space):\n    return tune.Tuner(\n        trainable_function,\n        tune_config=tune.TuneConfig(\n            scheduler=tune.schedulers.PopulationBasedTraining(\n                time_attr=\"step\",\n                perturbation_interval=10,\n                hyperparam_mutations={\n                    \"learning_rate\": tune.loguniform(1e-4, 1e-2),\n                    \"dropout\": tune.uniform(0.0, 0.5)\n                }\n            ),\n            num_samples=20\n        ),\n        param_space=search_space\n    )\n\n# Define search space\nsearch_space = {\n    \"learning_rate\": tune.loguniform(1e-4, 1e-2),\n    \"batch_size\": tune.choice([16, 32, 64, 128]),\n    \"hidden_units\": tune.choice([64, 128, 256, 512]),\n    \"dropout\": tune.uniform(0.0, 0.5),\n    \"optimizer\": tune.choice([\"adam\", \"sgd\", \"rmsprop\"]),\n    \"activation\": tune.choice([\"relu\", \"tanh\", \"gelu\"])\n}\n\n# Run with PBT (often best for neural network tuning)\nanalysis = run_with_pbt(search_space).fit()\n```\n\n### Custom Trainables\n\n```python\nfrom ray import tune\nimport numpy as np\n\nclass CustomTrainable(tune.Trainable):\n    \"\"\"Custom trainable with state management\"\"\"\n    \n    def setup(self, config):\n        \"\"\"Initialize training state\"\"\"\n        self.model = Model(config)\n        self.optimizer = Optimizer(self.model, config[\"learning_rate\"])\n        self.step_count = 0\n        \n        # Load data\n        self.train_data = np.random.randn(1000, 10)\n        self.labels = np.random.randint(0, 2, 1000)\n    \n    def step(self):\n        \"\"\"Execute one training step\"\"\"\n        # Sample batch\n        indices = np.random.choice(len(self.train_data), 32)\n        batch_x = self.train_data[indices]\n        batch_y = self.labels[indices]\n        \n        # Train\n        loss = self.model.train_step(batch_x, batch_y)\n        accuracy = self.model.evaluate(batch_x, batch_y)\n        \n        self.step_count += 1\n        \n        return {\n            \"loss\": loss,\n            \"accuracy\": accuracy,\n            \"step\": self.step_count\n        }\n    \n    def save_checkpoint(self, checkpoint_dir):\n        \"\"\"Save checkpoint\"\"\"\n        path = f\"{checkpoint_dir}\u002Fmodel.npy\"\n        np.save(path, self.model.weights)\n        return path\n    \n    def load_checkpoint(self, checkpoint_path):\n        \"\"\"Load checkpoint\"\"\"\n        self.model.weights = np.load(checkpoint_path)\n\n\nclass Model:\n    def __init__(self, config):\n        self.hidden_units = config.get(\"hidden_units\", 64)\n        self.weights = np.random.randn(10, self.hidden_units)\n    \n    def train_step(self, x, y):\n        \"\"\"Simulate training\"\"\"\n        return np.random.uniform(0.1, 1.0)\n    \n    def evaluate(self, x, y):\n        return np.random.uniform(0.5, 0.95)\n\n\nclass Optimizer:\n    def __init__(self, model, lr):\n        self.model = model\n        self.lr = lr\n\n\n# Run custom trainable\nanalysis = tune.run(\n    CustomTrainable,\n    config={\n        \"learning_rate\": tune.choice([0.001, 0.01, 0.1]),\n        \"hidden_units\": tune.choice([32, 64, 128])\n    },\n    num_samples=10,\n    checkpoint_at_end=True,\n    checkpoint_freq=10\n)\n```\n\n-----\n\n## Ray RLlib (Reinforcement Learning)\n\n### Quick Start with Built-in Algorithms\n\n```python\nimport ray\nimport ray.rllib.algorithms as algo\n\nray.init(num_cpus=4)\n\n# Configure PPO algorithm\nconfig = algo.ppo.PPOConfig()\nconfig = config.environment(\"CartPole-v1\")\nconfig = config.framework(\"torch\")\nconfig = config.rollout_fragment_length(200)\nconfig = config.train_batch_size(4000)\nconfig = config.num_workers(2)\n\n# Build algorithm\nppo = config.build()\n\n# Train for multiple iterations\nfor i in range(50):\n    result = ppo.train()\n    \n    if i % 10 == 0:\n        print(f\"Iteration {i}:\")\n        print(f\"  Episode reward mean: {result['episode_reward_mean']:.2f}\")\n        print(f\"  Episode length mean: {result['episode_len_mean']:.2f}\")\n\n# Evaluate trained agent\nevaluation = ppo.evaluate()\nprint(f\"Evaluation reward: {evaluation['evaluation']['episode_reward_mean']}\")\n\n# Save and restore\nppo.save(\"\u002Ftmp\u002Fcheckpoint\")\nppo.restore(\"\u002Ftmp\u002Fcheckpoint\")\n```\n\n### Custom RL Environment\n\n```python\nimport gymnasium as gym\nfrom gymnasium import spaces\nimport numpy as np\n\nclass WarehouseEnv(gym.Env):\n    \"\"\"Custom warehouse environment for RL\"\"\"\n    \n    metadata = {\"render_modes\": [\"human\"]}\n    \n    def __init__(self, config=None):\n        super().__init__()\n        self.config = config or {}\n        \n        # Define action space: 0=move_left, 1=move_right, 2=move_up, 3=move_down, 4=pickup, 5=dropoff\n        self.action_space = spaces.Discrete(6)\n        \n        # Define observation space\n        self.observation_space = spaces.Box(\n            low=0, high=100, shape=(20,), dtype=np.float32\n        )\n        \n        self.position = [0, 0]\n        self.holding_item = False\n        self.deliveries = 0\n        self.steps = 0\n        self.max_steps = 100\n    \n    def reset(self, seed=None, options=None):\n        super().reset(seed=seed)\n        self.position = [0, 0]\n        self.holding_item = False\n        self.deliveries = 0\n        self.steps = 0\n        \n        obs = self._get_obs()\n        info = {}\n        \n        return obs, info\n    \n    def step(self, action):\n        self.steps += 1\n        \n        # Execute action\n        if action == 0:\n            self.position[0] = max(0, self.position[0] - 1)\n        elif action == 1:\n            self.position[0] = min(9, self.position[0] + 1)\n        elif action == 2:\n            self.position[1] = min(9, self.position[1] + 1)\n        elif action == 3:\n            self.position[1] = max(0, self.position[1] - 1)\n        elif action == 4 and not self.holding_item:\n            self.holding_item = True\n        elif action == 5 and self.holding_item:\n            self.holding_item = False\n            self.deliveries += 1\n        \n        # Calculate reward\n        reward = 1.0 if self.deliveries > 0 else 0.0\n        reward -= 0.01  # Step penalty\n        \n        terminated = self.steps >= self.max_steps\n        truncated = False\n        \n        return self._get_obs(), reward, terminated, truncated, {}\n    \n    def _get_obs(self):\n        obs = np.zeros(20, dtype=np.float32)\n        obs[0] = self.position[0] \u002F 10.0\n        obs[1] = self.position[1] \u002F 10.0\n        obs[2] = float(self.holding_item)\n        obs[3] = self.deliveries \u002F 10.0\n        return obs\n\n\n# Train on custom environment\nfrom ray import tune\nfrom ray.rllib.algorithms import PPOConfig\n\nconfig = (\n    PPOConfig()\n    .environment(WarehouseEnv)\n    .framework(\"torch\")\n    .rollout_fragment_length(200)\n    .train_batch_size(4000)\n)\n\ntune.Tuner(\n    \"PPO\",\n    param_space=config.to_dict(),\n    run_config=tune.RunConfig(stop={\"episode_reward_mean\": 50})\n).fit()\n```\n\n### Multi-Agent Training\n\n```python\nfrom ray.rllib.algorithms import PPOConfig\nfrom ray.rllib.env.multi_agent_env import MultiAgentEnv\nimport numpy as np\n\nclass MultiAgentWarehouse(MultiAgentEnv):\n    def __init__(self, config=None):\n        super().__init__()\n        self.num_agents = 3\n        self.observation_space = spaces.Box(low=0, high=100, shape=(10,))\n        self.action_space = spaces.Discrete(4)\n    \n    def reset(self):\n        return {\n            f\"agent_{i}\": self.observation_space.sample() \n            for i in range(self.num_agents)\n        }\n    \n    def step(self, action_dict):\n        obs = {\n            f\"agent_{i}\": self.observation_space.sample()\n            for i in range(self.num_agents)\n        }\n        \n        rewards = {f\"agent_{i}\": np.random.random() for i in range(self.num_agents)}\n        \n        terminateds = {\"__all__\": False}\n        truncateds = {\"__all__\": False}\n        \n        infos = {f\"agent_{i}\": {} for i in range(self.num_agents)}\n        \n        return obs, rewards, terminateds, truncateds, infos\n\n\nconfig = (\n    PPOConfig()\n    .environment(MultiAgentWarehouse)\n    .framework(\"torch\")\n    .training(train_batch_size=2000)\n    .rollout_fragment_length(100)\n    .multi_agent(\n        policies={\n            \"shared_policy\": (\n                None,\n                self.observation_space,\n                self.action_space,\n                {}\n            )\n        },\n        policy_mapping_fn=lambda agent_id: \"shared_policy\"\n    )\n)\n```\n\n-----\n\n## Ray Serve (Model Serving)\n\n### Basic Deployment\n\n```python\nfrom ray import serve\nimport requests\nfrom transformers import pipeline\n\n# Initialize Ray Serve\nserve.start()\n\n@serve.deployment\nclass TextClassifier:\n    def __init__(self):\n        # Load model in constructor\n        self.classifier = pipeline(\n            \"sentiment-analysis\",\n            model=\"distilbert-base-uncased-finetuned-sst-2-english\"\n        )\n    \n    def __call__(self, request):\n        # Get text from request\n        text = request.query_params.get(\"text\", \"\")\n        \n        # Run inference\n        result = self.classifier(text)[0]\n        \n        return result\n\n# Deploy the model\nTextClassifier.deploy()\n\n# Make requests\nresponse = requests.get(\"http:\u002F\u002Flocalhost:8000\u002FTextClassifier?text=I love Ray!\")\nprint(response.json())\n```\n\n### Complex Deployment with Preprocessing\n\n```python\nfrom ray import serve\nfrom typing import List, Dict\nimport asyncio\n\n@serve.deployment(\n    num_replicas=2,\n    ray_actor_options={\"num_cpus\": 1}\n)\nclass TextPreprocessor:\n    \"\"\"Preprocess text before passing to model\"\"\"\n    \n    def __init__(self):\n        import re\n        self.url_pattern = re.compile(r'https?:\u002F\u002F\\S+')\n        self.email_pattern = re.compile(r'\\S+@\\S+\\.\\S+')\n    \n    async def preprocess(self, text: str) -> str:\n        # Remove URLs\n        text = self.url_pattern.sub('[URL]', text)\n        # Remove emails\n        text = self.email_pattern.sub('[EMAIL]', text)\n        # Lowercase\n        text = text.lower()\n        \n        return text\n    \n    async def batch_preprocess(self, texts: List[str]) -> List[str]:\n        return await asyncio.gather(*[self.preprocess(t) for t in texts])\n\n\n@serve.deployment(\n    num_replicas=2,\n    ray_actor_options={\"num_cpus\": 1, \"num_gpus\": 0.5}\n)\nclass TextModel:\n    \"\"\"Model deployment\"\"\"\n    \n    def __init__(self):\n        import torch\n        from transformers import AutoTokenizer, AutoModel\n        \n        self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n        self.tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n        self.model = AutoModel.from_pretrained(\"bert-base-uncased\").to(self.device)\n        self.model.eval()\n    \n    async def __call__(self, request):\n        import torch\n        \n        text = await request.body()\n        \n        # Tokenize\n        inputs = self.tokenizer(\n            text, \n            return_tensors=\"pt\", \n            padding=True, \n            truncation=True\n        ).to(self.device)\n        \n        # Inference\n        with torch.no_grad():\n            outputs = self.model(**inputs)\n        \n        # Return embedding\n        embedding = outputs.last_hidden_state[:, 0, :].cpu().tolist()\n        \n        return {\"embedding\": embedding}\n\n\n# Chain deployments\nTextPreprocessor.deploy()\nTextModel.deploy(handle_annotation=TextPreprocessor)\n\n\n# Or use ingress with explicit pipeline\n@serve.deployment(route_prefix=\"\u002Fpredict\")\nclass Ingress:\n    def __init__(self):\n        import requests\n        self.preprocessor = serve.get_deployment_handle(\"TextPreprocessor\")\n        self.model = serve.get_deployment_handle(\"TextModel\")\n    \n    async def __call__(self, request):\n        text = await request.body()\n        \n        # Chain calls\n        processed = await self.preprocessor.preprocess.remote(text)\n        result = await self.model.remote(processed)\n        \n        return result\n\nIngress.deploy()\n```\n\n### Model Composition\n\n```python\nfrom ray import serve\nfrom ray.serve.drivers import DefaultAPIDriver\n\n@serve.deployment\nclass Summarizer:\n    def __init__(self):\n        # Load summarization model\n        self.model = load_summarizer()\n    \n    def generate_summary(self, text: str) -> str:\n        return self.model(text)\n\n\n@serve.deployment\nclass SentimentAnalyzer:\n    def __init__(self):\n        # Load sentiment model\n        self.model = load_sentiment_model()\n    \n    def analyze(self, text: str) -> str:\n        return self.model(text)\n\n\n@serve.deployment\nclass AnalysisPipeline:\n    \"\"\"Combined analysis pipeline\"\"\"\n    \n    def __init__(self):\n        self.summarizer = serve.get_deployment_handle(\"Summarizer\")\n        self.sentiment = serve.get_deployment_handle(\"SentimentAnalyzer\")\n    \n    async def analyze(self, text: str) -> Dict:\n        # Run both in parallel\n        summary, sentiment = await asyncio.gather(\n            self.summarizer.generate_summary.remote(text),\n            self.sentiment.analyze.remote(text)\n        )\n        \n        return {\n            \"original_length\": len(text),\n            \"summary\": summary,\n            \"sentiment\": sentiment,\n            \"key_topics\": extract_topics(text)\n        }\n\n# Deploy all\nSummarizer.deploy()\nSentimentAnalyzer.deploy()\nAnalysisPipeline.deploy()\n```\n\n-----\n\n## Ray Datasets\n\n```python\nimport ray\n\nray.init()\n\n# Create dataset from various sources\n# From NumPy\nimport numpy as np\nnumpy_array = np.random.randn(10000, 100)\ndataset = ray.data.from_numpy(numpy_array)\n\n# From pandas\nimport pandas as pd\ndf = pd.DataFrame({\"a\": range(1000), \"b\": range(1000, 2000)})\ndataset = ray.data.from_pandas(df)\n\n# From CSV\ndataset = ray.data.read_csv(\"s3:\u002F\u002Fbucket\u002Fdata\u002F*.csv\")\n\n# From Parquet\ndataset = ray.data.read_parquet(\"s3:\u002F\u002Fbucket\u002Fdata\u002F*.parquet\")\n\n# Transform data\ndef process_batch(batch: pd.DataFrame) -> pd.DataFrame:\n    batch[\"processed\"] = batch[\"a\"] * 2\n    return batch\n\nprocessed = dataset.map_batches(process_batch, batch_size=1000)\n\n# Filter data\nfiltered = dataset.filter(lambda row: row[\"a\"] > 500)\n\n# Shuffle\nshuffled = dataset.random_shuffle()\n\n# Split into train\u002Fval\u002Ftest\ntrain, val, test = shuffled.train_test_split(test_size=0.2)\n\n# Repartition\nrepartitioned = train.repartition(num_blocks=10)\n\n# Materialize to local cluster\nrepartitioned.fully_executed()\n\n# Custom transformations\ndef add_features(row):\n    row[\"new_feature\"] = row[\"a\"] ** 2\n    return row\n\nwith_features = dataset.map(add_features)\n\n# Group by and aggregate\naggregated = dataset.groupby(\"category\").mean()\n\n# Join datasets\ndataset1 = ray.data.from_pandas(pd.DataFrame({\"id\": [1, 2, 3], \"value\": [10, 20, 30]}))\ndataset2 = ray.data.from_pandas(pd.DataFrame({\"id\": [1, 2, 4], \"other\": [\"a\", \"b\", \"c\"]}))\njoined = dataset1.join(dataset2, on=\"id\", how=\"left\")\n```\n\n-----\n\n## Best Practices\n\n### Performance Optimization\n\n1. **Use ObjectRefs efficiently** — Don't get() immediately after each remote() call; batch when possible.\n\n2. **Choose tasks vs actors wisely** — Use tasks for stateless parallelism, actors for stateful services.\n\n3. **Configure resources correctly** — Specify CPU\u002FGPU requirements to enable proper scheduling.\n\n4. **Use placement groups** — For workloads requiring specific hardware configurations.\n\n5. **Monitor with Ray Dashboard** — Use the dashboard to identify bottlenecks.\n\n### Common Pitfalls\n\n1. **Not handling exceptions** — Use try\u002Fexcept within remote functions and propagate errors properly.\n\n2. **Excessive serialization** — Large objects passed between tasks incur serialization overhead. Use shared memory or ObjectRef passing.\n\n3. **Ignoring cluster startup time** — For short jobs, the cluster overhead may outweigh benefits.\n\n4. **Not checkpointing** — For long-running training, implement checkpointing to handle failures.\n\n### Resources\n\n- **Documentation**: docs.ray.io\n- **GitHub**: github.com\u002Fray-project\u002Fray\n- **Community**: discuss.ray.io\n- **Related Skills**: distributed-systems, pytorch, tensorflow, kubernetes\n",{"name":5,"license":15,"metadata":44,"description":48,"compatibility":26},{"tags":45,"audience":47,"category":33},[5,33,46,24],"machine-learning","ml-engineers, data-scientists","Expert guidance on Ray distributed computing framework for scaling AI and Python  applications. Use for: distributed training, hyperparameter tuning with Ray Tune,  reinforcement learning with Ray RLlib, model serving with Ray Serve, batch inference,  scaling Python applications from single machines to clusters, and Ray Core tasks and actors.\n","main","2ea764e153842704d24a2e9aa4170441a7f03081",".opencode\u002Fskills\u002Fray","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito","https:\u002F\u002Fgithub.com\u002FNeuralBlitz","nuralnexus.org","Independent Multidisciplinary Researcher, Creative Producer, and AI Systems Architect\r\nAn independent creator and research-driven systems designer.","2026-11-12 03:13:05",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add NeuralBlitz\u002FMito --skill ray",{"tool":63,"command":64},"bunx","bunx skills add NeuralBlitz\u002FMito --skill ray",{"tool":66,"command":67},"pnpm","pnpm dlx skills add NeuralBlitz\u002FMito --skill ray","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fray\u002FSKILL.md",true,[],[72,88,101,114,122,137],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":39},"01M6HAZSAQK1S27CEZYAYJTQDX","wireless-communications","Wireless systems, mobile networks, and 5G\u002F6G","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwireless-communications\u002FSKILL.md",[],[79,80,81,82,83,84,85,86,26,87],"communications","wireless communications","wireless","systems","engineering","networks","5G","students","mobile",{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":39},"01M6HAZFX6E8NK3WZWDX5YCKYY","websockets","WebSocket implementation and best practices","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwebassembly\u002Fwebsockets\u002FSKILL.md",[],[90,95,96,97,26,98,99,100],"websocket implementation","time","implementation","real-time","websocket","best practices",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":39},"01M6HAZ6DAXBQ7QHXXM1EM7715","vulnerability-auditing","Vulnerability assessment and auditing","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvulnerability-auditing\u002FSKILL.md",[],[108,109,110,111,26,112,113],"vulnerability","vulnerability auditing","security","vulnerability assessment","cybersecurity","assessment",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":39},"01M6HAZ3FKF3CS9Z3J96RVE2ZE","vulnerability-assessment","Finding and assessing security vulnerabilities","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvue\u002Fvulnerability-assessment\u002FSKILL.md",[],[111,108,113,110,121,26],"vulnerabilities",{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":39},"01M6HAYSHM6HKRKEHFP0SGZQX7","vlsi-design","Very-Large-Scale Integration circuit design and semiconductor engineering","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvlsi-design\u002FSKILL.md",[],[129,130,131,132,133,83,134,26,135,86,136],"vlsi design","VLSI","design","hardware","integration","computer","scale","circuit",{"skillNo":138,"name":139,"nameZh":6,"description":140,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":141,"categories":142,"keywords":143,"publishedAt":39},"01M6HAYPQ30FFE2JXD7WQJ8R6C","unsupervised","Unsupervised learning concepts","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvisualization\u002Funsupervised\u002FSKILL.md",[],[139,28,26,144,145,146,147,46],"intelligence","unsupervised learning","machine","concepts"]