页面简介
Batch LLM inference with ray.data.llm: vLLM and SGLang engines or hosted endpoints, multi-GPU scaling, and vision, video, and audio models.
正文摘录
Working with LLMs# Use the ray.data.llm module to run scalable batch inference on Ray Data datasets. The module can run a vLLM or SGLang inference engine directly, query OpenAI-compatible endpoints through HttpRequestProcessorConfig, or send requests to a Ray Serve deployment through ServeDeploymentProcessorConfig. To get started, see the following sections: Quickstart: Run your first batch inference job. Architecture: Understand the processor pipeline. Scaling: Scale your LLM stage to multiple replicas. For common use cases, see the following sections: Text generation: Generate chat completions with LLMs. Embeddings: Generate text embeddings. Classification: Run content classifiers and sentiment analyzers. Multimodality: Run batch inference with vision language models (VLMs) and omni-modal models on multimodal data. OpenAI-compatible endpoints: Query deployed models. Serve deployments: Share vLLM engines across processors. Custom tokenizers: Use vLLM tokenizers for models that Hugging Face doesn’t support. To troubleshoot and tune your pipeline, see the following sections: Troubleshooting: Resolve GPU memory and model loading issues. Advanced configuration: Configure parallelism, per-stage tuning, LoRA, and batch concurrency. Quickstart: Run batch inference with vLLM# This example shows the minimal setup to run vLLM batch inference on a dataset. Note This quickstart requires a GPU because vLLM is GPU-accelerated. First, install Ray Data with LLM support: pip install -U "ray[data, llm]>=2.53.0" The following minimal example runs batch inference: import ray from ray.data.llm import vLLMEngineProcessorConfig, build_processor # Initialize Ray ray.init() # simple dataset ds = ray.data.from_items([ {"prompt": "What is machine learning?"}, {"prompt": "Explain neural networks in one sentence."}, ]) # Minimal vLLM configuration config = vLLMEngineProcessorConfig( model_source="Qwen/Qwen3.5-0.8B", concurrency=1, # 1 vLLM engine replica batch_size=32, # 32 samples per batch engine_kwargs={ "max_model_len": 4096, # Fit into test GPU memory } ) # Build processor # preprocess: converts input row to format expected by vLLM (OpenAI chat format) # postprocess: extracts generated text from vLLM output processor = build_processor( config, preprocess=lambda row: { "messages": [{"role": "user", "content": row["prompt"]}], "sampling_params": {"temperature": 0.7, "max_tokens": 100}, }, postprocess=lambda row: { "prompt": row["prompt"], "response": row["generated_text"], }, ) # inference ds = processor(ds) # iterate through the results for result in ds.iter_rows(): print(f"Q: {result['prompt']}") print(f"A: {result['response']}\n") # Alternative ways to get results: # results = ds.take(10) # Get first 10 results # ds.show(limit=5) # Print first 5 results # ds.write_parquet("output.parquet") # Save to file This example does the following: Creates a simple dataset with prompts. Configures a vLLM processor with minimal settings. Builds a processor that converts prompts to OpenAI chat format during preprocessing and extracts the generated text during postprocessing. Runs inference on the dataset. Iterates through the results. The processor expects input rows with a prompt field and outputs rows with both prompt and response fields. Consume the results with iter_rows(), take(), or show(), or save them to files with write_parquet(). For more configuration options and features, see the following sections. How does the processor pipeline work?# Ray Data LLM transforms your data through a multi-stage processor pipeline that runs LLM inference. Understanding this architecture helps you optimize performance and debug issues. Input Dataset | v - Preprocess (Custom Function) - PrepareMultimodal (Optional, for VLM / Omni models) - ChatTemplate (Applies chat template to messages) - Tokenize (Optional -- converts text to token IDs) - LLM Engine (vLLM/SGLang inference on GPU) - Detokenize (Optional -- converts token IDs back to text) - Postprocess (Custom Function) | v Output Dataset Each stage does the following: Preprocess: Your custom function that transforms input rows into the format that downstream stages expect, typically OpenAI chat format with messages. PrepareMultimodal: Extracts and prepares multimodal inputs. Enable it with prepare_multimodal_stage=True. ChatTemplate: Applies the model’s chat template to convert messages into a prompt string. Tokenize: Converts the prompt string into token IDs for the model. LLM Engine: The inference stage that runs vLLM or SGLang on GPU or TPU accelerators. Detokenize: Converts output token IDs back to readable text. Postprocess: Your custom function that extracts and formats the final output. Each stage runs as a separate Ray actor pool, so you can scale and allocate resources for each stage independently. By default, all CPU and GPU stages use autoscaling actor pools, except the ServeDeployment stage, which uses a fixed pool. Scale to multiple GPUs# To scale the LLM stage horizontally to multiple GPU replicas, set the concurrency parameter: config = vLLMEngineProcessorConfig( model_source="Qwen/Qwen3.5-0.8B", engine_kwargs={ "enable_chunked_prefill": True, "max_num_batched_tokens": 4096, "max_model_len": 16384, }, concurrency=10, batch_size=64, ) Each replica runs an independent inference engine. Set concurrency to match the number of available GPUs or GPU nodes. By default, when you set concurrency to an integer n, GPU stages autoscale from 1 to n actors. To use a fixed pool of n actors, set concurrency to (n, n). config = vLLMEngineProcessorConfig( model_source="Qwen/Qwen3.5-0.8B", engine_kwargs={ "enable_chunked_prefill": True, "max_num_batched_tokens": 4096, "max_model_len": 16384, }, concurrency=(10, 10), batch_size=64, ) Generate text# Use vLLMEngineProcessorConfig or SGLangEngineProcessorConfig for chat completions and text generation tasks. The key configuration options include the following: model_source: The Hugging Face model ID or the path to the model weights. concurrency: The number of vLLM engine replicas, typically one per GPU node. batch_size: The number of rows per batch. Reduce it if you hit memory limits. # Basic vLLM configuration config = vLLMEngineProcessorConfig( model_source="Qwen/Qwen3.5-0.8B", engine_kwargs={ "enable_chunked_prefill": True, "max_num_batched_tokens": 4096, # Reduce if CUDA OOM occurs "max_model_len": 4096, # Constrain to fit test GPU memory }, concurrency=1, batch_size=64, ) For gated models that require authentication, pass your Hugging Face token through runtime_env: # Configuration with Hugging Face token config_with_token = vLLMEngineProcessorConfig( model_source="Qwen/Qwen3.5-0.8B", runtime_env={"env_vars": {"HF_TOKEN": "your_huggingface_token"}}, concurrency=1, batch_size=64, ) Run batch inference on multimodal data# Ray Data LLM also supports batch inference with vision language models and omni-modal models on multimodal data. To run multimodal batch inference, make the following two changes to the previous example: Set prepare_multimodal_stage=True in the vLLMEngineProcessorConfig. Prepare multimodal data inside the preprocessor. Run image batch inference with a vision language model# First, load a vision dataset: """ Load vision dataset from Hugging Face. This function loads the LMMs-Eval-Lite dataset which contains: - Images with associated questions - Multiple choice answers - Various visual reasoning tasks """ try: from huggingface_hub import HfFileSystem # Load "LMMs-Eval-Lite" dataset from Hugging Face using HfFileSystem path = "hf://datasets/lmms-lab/LMMs-Eval-Lite/coco2017_cap_val/" fs = HfFileSystem() vision_dataset = ray.data.read_parquet(path, filesystem=fs) return vision_dataset except ImportError: print( "huggingface_hub package not available. Install with: pip install huggingface_hub" ) return None except Exception as e: print(f"Error loading dataset: {e}") return None Next, configure the VLM processor with the essential settings: vision_processor_config = vLLMEngineProcessorConfig( model_source="Qwen/Qwen2.5-VL-3B-Instruct", engine_kwargs=dict( tensor_parallel_size=1, pipeline_parallel_size=1, max_model_len=4096, trust_remote_code=True, limit_mm_per_prompt={"image": 1}, ), batch_size=16, concurrency=1, prepare_multimodal_stage=True, ) Define preprocessing and postprocessing functions that convert dataset rows into the format the VLM expects and extract the model responses. In the preprocessor, structure image data as part of an OpenAI-compatible message. You can pass either an image URL or a PIL.Image.Image object. """Supported image input formats: image URL, PIL Image object""" { "messages": [ { "role": "system", "content": "Provide a detailed description of the image." }, { "role": "user", "content": [ {"type": "text", "text": "Describe what happens in this image."}, # Option 1: Provide image URL {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}, # Option 2: Provide PIL Image object {"type": "image_pil", "image_pil": PIL.Image.open("path/to/image.jpg")} ] }, ] } def vision_preprocess(row: dict) -> dict: """ Preprocessing function for vision-language model inputs. Converts dataset rows into the format expected by the VLM: - System prompt for analysis instructions - User message with text and image content - Multiple choice formatting - Sampling parameters """ choice_indices = ["A", "B", "C", "D", "E", "F", "G", "H"] return { "messages": [ { "role": "system", "content": ( "Analyze the image and question carefully, using step-by-step reasoning. " "First, describe any image provided in detail. Then, present your reasoning. " "And finally your final answer in this format: Final Answer: <answer> " "where <answer> is: The single correct letter choice A, B, C, D, E, F, etc. when options are provided. " "Only include the letter. Your direct answer if no options are given, as a single phrase or number. " "IMPORTANT: Remember, to end your answer with Final Answer: <answer>." ), }, { "role": "user", "content": [ {"type