Skip to content
Open
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
6 changes: 3 additions & 3 deletions src/twinkle/protocol/types/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,9 @@ class WireInputFeature(DataModel):
feature_attention_mask: Numbers1to4 | None = None
grid_thws: Numbers1to4 | None = None

# The media an encoded multimodal prompt runs with (``input_ids`` are then the engine's ids):
# a multi-turn client uploads them again with every turn, the server keeps no episode.
images: MediaList | None = None
# Samplers receive media references. Some training templates use the same
# images field for a batched tensor.
images: MediaList | Numbers1to4 | None = None
videos: MediaList | None = None
audios: MediaList | None = None

Expand Down
2 changes: 2 additions & 0 deletions src/twinkle/protocol/types/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ class SampleResponseModel(ResponseModel):
"""Mirroring twinkle.data_format.SampleResponse."""
sequences: list[SampledSequenceModel] = Field(..., description='List of sampled sequences')
prompt_token_ids: list[int] | None = Field(None, description='Token IDs of the prompt the sequences continue')
prompt_token_ids_echoed: bool | None = Field(
None, description='Whether the backend returned request IDs before media expansion')
prompt_logprobs: list[float | None] | None = None
topk_prompt_logprobs: list[list[tuple[int, float]] | None] | None = None

Expand Down
5 changes: 5 additions & 0 deletions src/twinkle/server/lifecycle/submit.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ def _as_backend_entry(entry: dict[str, Any]) -> Any:
return Trajectory(**entry)
result = InputFeature(**entry)
media = VLM_TENSOR_FIELDS.intersection(result)
first_image_value = result.get('images')
while isinstance(first_image_value, list) and first_image_value:
first_image_value = first_image_value[0]
if isinstance(first_image_value, (float, int)):
media = media | {'images'}
if media:
import torch
for key in media:
Expand Down
11 changes: 5 additions & 6 deletions src/twinkle/server/sampler/twinkle_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def _build_rollout_rows_and_tags(
return rows, tags


def _to_sample_response_models(responses) -> list[types.SampleResponseModel]:
def _to_sample_response_models(responses, *, prompt_token_ids_echoed: bool = False) -> list[types.SampleResponseModel]:
"""Convert internal sampler responses to the HTTP response schema."""
sample_models = []
for response in responses:
Expand All @@ -139,11 +139,8 @@ def _to_sample_response_models(responses) -> list[types.SampleResponseModel]:
sample_models.append(
types.SampleResponseModel(
sequences=sequences,
# The prompt's own ids, which is what makes a reply served over
# HTTP trainable: paired with a sequence's tokens they are the
# exact ids the model ran on, so a caller never has to re-encode
# the text and hope the tokenizer agrees with itself.
prompt_token_ids=(list(response.prompt_token_ids) if response.prompt_token_ids is not None else None),
prompt_token_ids_echoed=prompt_token_ids_echoed,
prompt_logprobs=response.prompt_logprobs,
topk_prompt_logprobs=response.topk_prompt_logprobs,
))
Expand Down Expand Up @@ -272,7 +269,9 @@ async def generate(adapter_path):
)

responses = await sample_with_weights(self, resolved_uri, generate)
return types.SampleResponseModelList(samples=_to_sample_response_models(responses)).model_dump()
samples = _to_sample_response_models(
responses, prompt_token_ids_echoed=getattr(self, 'sampler_type', None) in ('sglang', 'sglang_async'))
return types.SampleResponseModelList(samples=samples).model_dump()

# Calculate metrics for queue scheduling. The body is wire-validated, so the
# entries are models and ``input_ids`` is absent or a list of ints.
Expand Down
33 changes: 31 additions & 2 deletions src/twinkle_client/rollout/_http_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,43 @@ def sample(self,

def _sample_one(self, item: Any, sampling_params: Any, adapter_uri: Optional[str]) -> SampleResponse:
media = getattr(item, 'media', None)
wire_media = _wire_media(media) if media else {}
if media:
entry = {'input_ids': list(item.engine_input_ids), **_wire_media(media)}
entry = {'input_ids': list(item.engine_input_ids), **wire_media}
if processor_kwargs := getattr(item, 'mm_processor_kwargs', None):
entry['mm_processor_kwargs'] = processor_kwargs
else:
entry = dict(getattr(item, 'feature', item))
responses = self.sampler.sample(
[entry], sampling_params, adapter_name=self.adapter_name, adapter_uri=adapter_uri, token_only=bool(media))
if len(responses) != 1:
raise RuntimeError(f'the server returned {len(responses)} responses for one prompt.')
response = responses[0]
if media:
echoed = getattr(response, 'prompt_token_ids_echoed', None)
request_ids = entry['input_ids']
training_ids = list(item.feature['input_ids'])
prompt_ids = response.prompt_token_ids
# Older SGLang servers echoed the request but omitted the flag.
legacy_echo = echoed is None and prompt_ids == request_ids
expected = request_ids if echoed is True else training_ids
if prompt_ids != expected and not legacy_echo:
prefix = 'request' if echoed is True else 'expanded training prompt'
raise ValueError(f'Remote sampler prompt_token_ids do not match the {prefix}. '
'Check that the training and sampler media processors use the same settings.')
sequences = []
for seq in response.sequences:
tokens = list(seq.tokens)
if media:
completion = self.template.append_completion(item, tokens)
feature = dict(completion.state.feature)
for key, refs in wire_media.items():
if key not in feature or _is_raw_media(feature[key]):
feature[key] = refs
sequences.append(SampledSequence(
stop_reason=seq.stop_reason, tokens=tokens, logprobs=seq.logprobs,
decoded=self.template.decode(tokens), new_input_feature=dict(completion.state.feature),
decoded=self.template.decode(tokens),
new_input_feature=feature,
new_state=completion.state))
else:
sequences.append(SampledSequence(
Expand Down Expand Up @@ -111,6 +131,15 @@ def _wire_media(media: Any) -> Dict[str, List[str]]:
return out


def _is_raw_media(value: Any) -> bool:
entries = value if isinstance(value, (list, tuple)) else [value]
return bool(entries) and all(
isinstance(entry, (str, bytes, bytearray))
or (isinstance(entry, dict) and ('bytes' in entry or 'path' in entry))
or callable(getattr(entry, 'save', None))
for entry in entries)


def _media_ref(value: Any) -> str:
"""A URL passes as is; a local file, raw bytes or a PIL image is uploaded as a ``data:`` URI."""
if isinstance(value, dict) and ('bytes' in value or 'path' in value):
Expand Down
52 changes: 52 additions & 0 deletions tests/sampler/test_vllm_sampler_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
Environment:
TWINKLE_MODEL_ID: model to sample from (default Qwen/Qwen2.5-0.5B-Instruct, small and cache-friendly)
TWINKLE_MAX_MODEL_LEN: max model length (default 512)
TWINKLE_VL_MODEL_DIR: local Qwen3-VL checkpoint for the remote image resize regression
"""
import os

Expand Down Expand Up @@ -130,6 +131,57 @@ def test_sample_from_input_feature_skips_the_template(sampler):
assert all(isinstance(t, int) for t in tokens)


def test_remote_multimodal_prompt_keeps_preprocessed_image():
"""Round-trip a request through the HTTP schema and generate with the real vLLM sampler."""
model_dir = os.environ.get('TWINKLE_VL_MODEL_DIR')
if not model_dir or not os.path.isdir(model_dir):
pytest.skip('Set TWINKLE_VL_MODEL_DIR to a local Qwen3-VL checkpoint.')

from types import SimpleNamespace

from PIL import Image

from swift.dev.builders import build_template
from swift.dev.config import TemplateConfig
from swift.model import get_model_processor
from twinkle.protocol.types.sampler import SampleRequest
from twinkle.sampler.vllm_sampler.vllm_sampler import vLLMSampler
from twinkle.server.lifecycle.submit import to_backend_inputs
from twinkle.server.sampler.twinkle_handlers import _to_sample_response_models
from twinkle_client._request_builder import build_request
from twinkle_client.rollout import HTTPSampler

_, processor = get_model_processor(model_dir, load_model=False)
template = build_template(TemplateConfig(template='qwen3_vl', max_length=2048), processor)
template.max_pixels = 262144
image = Image.new('RGB', (1024, 768))
state = template.encode_prompt({'messages': [{'role': 'user', 'content': '<image>Describe this image.'}],
'images': [image]}, backend='vllm').state
assert state.media.images[0].size != image.size
engine = vLLMSampler(
model_id=model_dir,
engine_args={
'max_model_len': 2048,
'gpu_memory_utilization': 0.35,
'mm_processor_kwargs': {'size': {'shortest_edge': 4096, 'longest_edge': 65536}},
},
)

def sample(inputs, params, **kwargs):
body = build_request(SampleRequest, inputs=inputs, **kwargs)
request = SampleRequest.model_validate_json(body.model_dump_json())
rows = to_backend_inputs(request.inputs)
assert rows[0]['mm_processor_kwargs']['do_resize'] is False
return _to_sample_response_models(engine.sample(rows, sampling_params=params, token_only=request.token_only))

try:
response, = HTTPSampler(SimpleNamespace(sample=sample), template).sample(state, _greedy(max_tokens=2))
assert response.prompt_token_ids == list(state.feature['input_ids'])
assert response.sequences[0].tokens
finally:
engine.shutdown()


def test_sample_batch_returns_one_response_per_input_in_order(sampler):
"""A batch of trajectories yields one response each, so DP slicing and flattening stay aligned."""
trajs = [
Expand Down
77 changes: 77 additions & 0 deletions tests/twinkle_client/test_http_sampler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Copyright (c) ModelScope Contributors. All rights reserved.
from types import SimpleNamespace
from unittest.mock import Mock

import pytest

from twinkle.protocol.types.sampler import SampleResponseModel
from twinkle_client.rollout import HTTPSampler


@pytest.mark.parametrize(('flag', 'prompt', 'accepted'), [
({}, [1, 2], True),
({}, [1, 3, 2], True),
({}, [1, 4, 2], False),
({'prompt_token_ids_echoed': True}, [1, 2], True),
({'prompt_token_ids_echoed': True}, [1, 3, 2], False),
({'prompt_token_ids_echoed': False}, [1, 3, 2], True),
({'prompt_token_ids_echoed': False}, [1, 2], False),
({'prompt_token_ids_echoed': False}, [1, 4, 2], False),
])
def test_multimodal_prompt_validation(flag, prompt, accepted):
image = 'data:image/png;base64,AAA='
visual_tensor = object()
state = SimpleNamespace(
media=SimpleNamespace(images=[image]),
engine_input_ids=[1, 2],
feature={'input_ids': [1, 3, 2]},
mm_processor_kwargs={'do_resize': False},
)
completion = SimpleNamespace(feature={'input_ids': [1, 3, 2, 9], 'images': [visual_tensor]})
template = Mock()
template.append_completion.return_value = SimpleNamespace(state=completion)
template.decode.return_value = 'answer'
response = SampleResponseModel.model_validate({
'prompt_token_ids': prompt,
'sequences': [{'stop_reason': 'length', 'tokens': [9]}],
**flag,
})
http = Mock()
http.sample.return_value = [response]
sampler = HTTPSampler(http, template)

if accepted:
result, = sampler.sample(state)
assert result.sequences[0].new_input_feature['images'] == [visual_tensor]
assert result.sequences[0].new_input_feature['input_ids'] == [1, 3, 2, 9]
else:
with pytest.raises(ValueError, match='prompt_token_ids do not match'):
sampler.sample(state)
template.append_completion.assert_not_called()

wire_input, = http.sample.call_args.args[0]
assert wire_input == {'input_ids': [1, 2], 'images': [image], 'mm_processor_kwargs': {'do_resize': False}}


def test_media_reference_survives_merge_when_template_only_keeps_visual_tensors():
raw_image = {'bytes': None, 'path': 'unread.png'}
image = 'data:image/png;base64,AAA='
pixels = object()
state = SimpleNamespace(
media=SimpleNamespace(images=[image]), engine_input_ids=[1, 2],
feature={'input_ids': [1, 3, 2], 'pixel_values': pixels},
)
template = Mock()
template.append_completion.return_value = SimpleNamespace(
state=SimpleNamespace(feature={'input_ids': [1, 3, 2, 9], 'pixel_values': pixels}))
template.decode.return_value = 'answer'
response = SampleResponseModel(
prompt_token_ids=[1, 3, 2], prompt_token_ids_echoed=False,
sequences=[{'stop_reason': 'length', 'tokens': [9]}])
http = Mock()
http.sample.return_value = [response]

result, = HTTPSampler(http, template).sample(state)
row = {'images': [raw_image], **result.sequences[0].new_input_feature}
assert row['images'] == [image]
assert row['pixel_values'] is pixels
Loading