Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions tests/processors/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,11 @@ cc_test(
:processors
GTest::gtest_main
)

# Python preprocessing and the model-directory boundary use CPU tensors only.
cc_test(
NAME python_image_processor_test
CPU_ONLY
SRCS python_image_processor_test.cpp
DEPS :processors Python::Python GTest::gtest_main
)
121 changes: 121 additions & 0 deletions tests/processors/python_image_processor_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/* Copyright 2026 The xLLM Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://github.com/xLLM-AI/xllm/blob/main/LICENSE

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <gtest/gtest.h>
#include <pybind11/embed.h>
#include <pybind11/stl.h>
#include <torch/torch.h>

#include <array>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "core/framework/config/model_config.h"
#include "core/framework/tokenizer/tokenizer.h"
#include "core/util/scope_guard.h"
#include "processors/multimodal_processor_pipeline.h"
#include "processors/qwen2_vl_image_processor.h"
#include "processors/text_prompt_processor.h"

namespace py = pybind11;

namespace xllm {
namespace {

TEST(PythonImageProcessorTest, ModelDirectoriesRemainLocalToTheirProcessors) {
py::scoped_interpreter interpreter(/*init_signal_handlers=*/false);
py::dict scope;
py::exec(R"PY(
import sys
import types
import torch

module = types.ModuleType("xllm.pybind.multimodal")
module.initialized = []
module.processed = []

def _initialize(model: str) -> None:
module.initialized.append(model)

def _preprocess(images: list[torch.Tensor], model: str) -> dict[str, torch.Tensor]:
module.processed.append(model)
value = {"model-a": 3.0, "model-b": 7.0}[model]
return {
"pixel_values": torch.full((4, 2), value),
"image_grid_thw": torch.tensor([[1, 2, 2]]),
}

module.initialize_image_processor = _initialize
module.preprocess_tensors = _preprocess
sys.modules[module.__name__] = module
)PY",
scope);

auto& config = ModelConfig::get_instance();
const std::string original_model = config.model();
const std::string original_impl = config.model_impl();
ScopeGuard restore_config([&]() {
config.model() = original_model;
config.model_impl() = original_impl;
});
config.model().clear();
config.model_impl() = "python";

ModelArgs args;
args.mm_image_normalize_mean({0.0F, 0.0F, 0.0F})
.mm_image_normalize_std({1.0F, 1.0F, 1.0F});
using Pipeline =
MultimodalProcessor<TextPromptProcessor, Qwen2VLImageProcessor>;
Pipeline first(args,
std::make_shared<Tokenizer>(),
TokenizerArgs{},
/*max_sequence_length=*/0,
/*model_path=*/"model-a");
Pipeline second(args,
std::make_shared<Tokenizer>(),
TokenizerArgs{},
/*max_sequence_length=*/0,
/*model_path=*/"model-b");

MMInputItem image;
image.type = MMType::IMAGE;
image.decode_image = torch::zeros({3, 8, 8}, torch::dtype(torch::kUInt8));
const std::array cases{std::pair{&first, 3.0F},
std::pair{&second, 7.0F},
std::pair{&first, 3.0F}};
for (const auto& [processor, expected] : cases) {
MMData data;
ASSERT_TRUE(processor->process_multimodal(MMInput({image}), data));
const auto& items = data.items<MMItemVec>();
ASSERT_EQ(items.size(), 1u);
EXPECT_TRUE(torch::equal(
std::get<torch::Tensor>(items.front().data().at("pixel_values")),
torch::full({4, 2}, expected)));
EXPECT_TRUE(torch::equal(
std::get<torch::Tensor>(items.front().data().at("image_grid_thw")),
torch::tensor({{1, 2, 2}}, torch::dtype(torch::kInt64))));
}
py::object module = scope["module"];
EXPECT_EQ(module.attr("initialized").cast<std::vector<std::string>>(),
(std::vector<std::string>{"model-a", "model-b"}));
EXPECT_EQ(module.attr("processed").cast<std::vector<std::string>>(),
(std::vector<std::string>{"model-a", "model-b", "model-a"}));
EXPECT_TRUE(config.model().empty());
}

} // namespace
} // namespace xllm
3 changes: 2 additions & 1 deletion xllm/core/distributed_runtime/vlm_master.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,8 @@ VLMMaster::VLMMaster(const Options& options)
std::make_unique<JinjaChatTemplate>(engine->tokenizer_args());
tokenizer_ = engine->tokenizer()->clone();
processor_ =
create_multimodal_processor(model_args_,
create_multimodal_processor(options_.model_path(),
model_args_,
tokenizer_,
options_.max_processor_cache_items(),
engine->tokenizer_args());
Expand Down
1 change: 1 addition & 0 deletions xllm/models/dit/pipelines/pipeline_joyimage_edit_plus.h
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,7 @@ class JoyImageEditPlusPipelineImpl : public torch::nn::Module,
<< "Failed to load JoyImageEditPlus Qwen3-VL tokenizer";
tokenizer_ = std::shared_ptr<Tokenizer>(std::move(tokenizer));
multimodal_processor_ = create_multimodal_processor(
loader->model_root_path(),
text_encoder_model_args_,
tokenizer_,
/*max_cache_items=*/0,
Expand Down
10 changes: 8 additions & 2 deletions xllm/models/model_registry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,7 @@ std::string ModelRegistry::get_model_backend(const std::string& name) {
}

std::unique_ptr<MultimodalProcessorBase> create_multimodal_processor(
const std::string& model_path,
const ModelArgs& model_args,
std::shared_ptr<Tokenizer> tokenizer,
int64_t max_cache_items,
Expand All @@ -678,12 +679,17 @@ std::unique_ptr<MultimodalProcessorBase> create_multimodal_processor(
ModelConfig::get_instance().model_impl()) &&
ModelRegistry::get_model_backend(resolved_name) == "llm") {
return std::make_unique<MultimodalProcessor<TextPromptProcessor>>(
model_args, std::move(tokenizer), tokenizer_args, max_sequence_length);
model_args,
std::move(tokenizer),
tokenizer_args,
max_sequence_length,
model_path);
}
CHECK(multimodal_processor_factory != nullptr)
<< "Missing multimodal processor for model type: " << model_type;
std::unique_ptr<MultimodalProcessorBase> processor =
multimodal_processor_factory(model_args,
multimodal_processor_factory(model_path,
model_args,
std::move(tokenizer),
tokenizer_args,
max_sequence_length);
Expand Down
7 changes: 5 additions & 2 deletions xllm/models/model_registry.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ using DiTModelFactory =

using MultimodalProcessorFactory =
std::function<std::unique_ptr<MultimodalProcessorBase>(
const std::string& model_path,
const ModelArgs& model_args,
std::shared_ptr<Tokenizer> tokenizer,
const TokenizerArgs& tokenizer_args,
Expand Down Expand Up @@ -402,14 +403,16 @@ std::unique_ptr<DiTModel> create_dit_model(const DiTModelContext& context);
const bool VarName##_multimodal_processor_registered = []() { \
ModelRegistry::register_multimodal_processor_factory( \
#ModelType, \
[](const ModelArgs& model_args, \
[](const std::string& model_path, \
const ModelArgs& model_args, \
std::shared_ptr<Tokenizer> tokenizer, \
const TokenizerArgs& tokenizer_args, \
int32_t max_sequence_length) { \
return std::make_unique<ProcessorClass>(model_args, \
std::move(tokenizer), \
tokenizer_args, \
max_sequence_length); \
max_sequence_length, \
model_path); \
}); \
return true; \
}()
Expand Down
1 change: 1 addition & 0 deletions xllm/processors/multimodal_processor.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class MultimodalProcessorBase {
};

std::unique_ptr<MultimodalProcessorBase> create_multimodal_processor(
const std::string& model_path,
const ModelArgs& model_args,
std::shared_ptr<Tokenizer> tokenizer,
int64_t max_cache_items,
Expand Down
22 changes: 20 additions & 2 deletions xllm/processors/multimodal_processor_pipeline.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ limitations under the License.
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

Expand Down Expand Up @@ -72,11 +74,13 @@ class MultimodalProcessor final : public MultimodalProcessorPipeline {
MultimodalProcessor(const ModelArgs& model_args,
std::shared_ptr<Tokenizer> tokenizer,
const TokenizerArgs& tokenizer_args,
int32_t max_sequence_length = 0)
int32_t max_sequence_length = 0,
std::optional<std::string> model_path = std::nullopt)
: MultimodalProcessorPipeline(std::move(tokenizer),
tokenizer_args,
max_sequence_length),
image_processor_(std::make_unique<ImageProcessor>(model_args)),
image_processor_(
create_image_processor(model_args, std::move(model_path))),
video_processor_(std::make_unique<VideoProcessor>(model_args)),
audio_processor_(std::make_unique<AudioProcessor>(model_args)),
prompt_processor_(std::make_unique<PromptProcessor>(model_args)) {}
Expand Down Expand Up @@ -220,6 +224,20 @@ class MultimodalProcessor final : public MultimodalProcessorPipeline {
return true;
}

static std::unique_ptr<ImageProcessor> create_image_processor(
const ModelArgs& model_args,
std::optional<std::string> model_path) {
if constexpr (std::is_constructible_v<ImageProcessor,
const ModelArgs&,
std::string>) {
if (model_path.has_value()) {
return std::make_unique<ImageProcessor>(model_args,
std::move(*model_path));
}
}
return std::make_unique<ImageProcessor>(model_args);
}

std::unique_ptr<ImageProcessor> image_processor_;
std::unique_ptr<VideoProcessor> video_processor_;
std::unique_ptr<AudioProcessor> audio_processor_;
Expand Down
28 changes: 16 additions & 12 deletions xllm/processors/python_image_processor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ limitations under the License.

#include <string>

#include "core/framework/config/model_config.h"
#include "core/util/pybind_helper.h"

namespace py = pybind11;
Expand All @@ -33,23 +32,30 @@ namespace {

// Delegates image preprocessing to Python (HF AutoImageProcessor via
// pybind.multimodal.preprocess_tensors) for the Python model-executor path,
// so no per-model C++ image processor is needed. Initialize the Python loader
// with the owning image processor before the service accepts its first image.
// so no per-model C++ image processor is needed. Share only the Python entry
// point; the owning image processor supplies its model directory on each call.
class PyImagePreprocess final {
public:
static PyImagePreprocess& instance() {
static PyImagePreprocess ins;
return ins;
}

bool run(const std::vector<torch::Tensor>& images,
void initialize(const std::string& model_path) {
py::gil_scoped_acquire gil;
py::module_ mm = py::module_::import("xllm.pybind.multimodal");
mm.attr("initialize_image_processor")(model_path);
}

bool run(const std::string& model_path,
const std::vector<torch::Tensor>& images,
std::vector<MMDataItem>& output_items) {
py::gil_scoped_acquire gil;
try {
// Pass the vector directly: pybind11 (pybind11/stl.h) converts
// std::vector<torch::Tensor> to a Python list at the call site. (Avoids
// both the null-handle default py::list pitfall and an explicit cast.)
py::dict res = preprocess_fn_(images, model_path_);
py::dict res = preprocess_fn_(images, model_path);
Comment thread
XuZhang99 marked this conversation as resolved.
Resolved
// HF returns batched tensors: pixel_values [total_patches, dim],
// image_grid_thw [num_images, 3]. Split per image to match the C++
// ImageProcessor contract (one MMDataItem per input image).
Expand Down Expand Up @@ -86,27 +92,25 @@ class PyImagePreprocess final {
PyImagePreprocess() {
// Processor construction runs outside Python, so imports need the GIL.
py::gil_scoped_acquire gil;
model_path_ = ::xllm::ModelConfig::get_instance().model();
// node0 (master+worker) has already imported the `xllm` package via the
// Python model, so this submodule import is cheap and safe here.
py::module_ mm = py::module_::import("xllm.pybind.multimodal");
mm.attr("initialize_image_processor")(model_path_);
preprocess_fn_ = mm.attr("preprocess_tensors");
}

~PyImagePreprocess() { clear_python_object(preprocess_fn_); }

std::string model_path_;
py::object preprocess_fn_;
};

} // namespace

void initialize_python_image_processor() {
static_cast<void>(PyImagePreprocess::instance());
void initialize_python_image_processor(const std::string& model_path) {
PyImagePreprocess::instance().initialize(model_path);
}
bool process_python_images(const std::vector<torch::Tensor>& images,
bool process_python_images(const std::string& model_path,
const std::vector<torch::Tensor>& images,
std::vector<MMDataItem>& output_items) {
return PyImagePreprocess::instance().run(images, output_items);
return PyImagePreprocess::instance().run(model_path, images, output_items);
}
} // namespace xllm
6 changes: 4 additions & 2 deletions xllm/processors/python_image_processor.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ limitations under the License.
#pragma once
#include <torch/types.h>

#include <string>
#include <vector>

#include "core/framework/multimodal/mm_data_item.h"
namespace xllm {
void initialize_python_image_processor();
bool process_python_images(const std::vector<torch::Tensor>& images,
void initialize_python_image_processor(const std::string& model_path);
bool process_python_images(const std::string& model_path,
const std::vector<torch::Tensor>& images,
std::vector<MMDataItem>& output_items);
} // namespace xllm
12 changes: 9 additions & 3 deletions xllm/processors/qwen2_vl_image_processor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.
#include "processors/qwen2_vl_image_processor.h"

#include <string>
#include <utility>
#include <vector>

#include "core/framework/config/model_config.h"
Expand Down Expand Up @@ -161,7 +162,12 @@ std::optional<Size> smart_resize_tokens(int32_t num_frames,

} // namespace

Qwen2VLImageProcessor::Qwen2VLImageProcessor(const ModelArgs& args) {
Qwen2VLImageProcessor::Qwen2VLImageProcessor(const ModelArgs& args)
: Qwen2VLImageProcessor(args, ModelConfig::get_instance().model()) {}

Qwen2VLImageProcessor::Qwen2VLImageProcessor(const ModelArgs& args,
std::string model_path)
: model_path_(std::move(model_path)) {
image_mean_ = torch::tensor(args.mm_image_normalize_mean(),
torch::dtype(torch::kFloat32));
image_std_ = torch::tensor(args.mm_image_normalize_std(),
Expand Down Expand Up @@ -192,7 +198,7 @@ Qwen2VLImageProcessor::Qwen2VLImageProcessor(const ModelArgs& args) {
}
if (::xllm::ModelConfig::is_python_model_impl(
::xllm::ModelConfig::get_instance().model_impl())) {
initialize_python_image_processor();
initialize_python_image_processor(model_path_);
}
}

Expand Down Expand Up @@ -288,7 +294,7 @@ bool Qwen2VLImageProcessor::process(
// processor; the Python model's encode() consumes the HF output directly.
if (::xllm::ModelConfig::is_python_model_impl(
::xllm::ModelConfig::get_instance().model_impl())) {
if (process_python_images(images, output_items)) {
if (process_python_images(model_path_, images, output_items)) {
return true;
}
// The HF ``Glm5NextImageProcessor`` class only exists in the dev (patched)
Expand Down
Loading
Loading