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
1 change: 1 addition & 0 deletions src/twinkle/protocol/types/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,4 @@ class TaskEnvelope(ResponseModel):
queue_state: QueueState | None = None
queue_state_reason: str | None = None
progress: UploadProgress | None = None
execution_finished: bool | None = None # tracked backend work has stopped
10 changes: 9 additions & 1 deletion src/twinkle/protocol/types/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"""
from __future__ import annotations

from pydantic import Field, JsonValue
from hmac import digest
from pydantic import UUID4, Field, JsonValue
from typing import Any, Dict, List, Literal, Optional, Tuple

from .base import ResponseModel, StrictRequest, passthrough
Expand All @@ -38,11 +39,18 @@ class SampleRequest(StrictRequest):
inputs: WireInputBatch = Field(..., description='Trajectory or InputFeature entries to sample from')
sampling_params: dict[str, JsonValue] | None = Field(
None, description='Sampling parameters (max_tokens, temperature, num_samples, etc.)')
client_sample_id: UUID4 | None = None
adapter_name: str = Field('', description='Adapter name for LoRA inference')
adapter_uri: str | None = Field(None, description='Adapter URI (twinkle:// path or local path) for LoRA inference')
token_only: bool = Field(
False, description='Return sampled tokens/logprobs only; encoded inputs are engine ids, media alongside')

def tracked_request_id(self, token: str) -> str | None:
if self.client_sample_id is None:
return None
identity = digest(token.encode(), self.client_sample_id.bytes, 'sha256')
return f'req_sample_{identity.hex()}'


class SampledSequenceModel(ResponseModel):
"""A single sampled sequence, mirroring twinkle.data_format.SampledSequence."""
Expand Down
1 change: 1 addition & 0 deletions src/twinkle/server/lifecycle/envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ def envelope_from_record(
queue_state=record.get('queue_state'),
queue_state_reason=record.get('queue_state_reason'),
progress=record.get('progress'),
execution_finished=record.get('execution_finished'),
)
if status in ('failed', 'cancelled'):
return TaskEnvelope(
Expand Down
17 changes: 15 additions & 2 deletions src/twinkle/server/sampler/twinkle_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from __future__ import annotations

import asyncio
import hashlib
import json
import uuid
from collections.abc import Callable, Mapping
Expand Down Expand Up @@ -277,12 +278,24 @@ async def generate(adapter_path):
# 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.
input_tokens = sum(len(getattr(entry, 'input_ids', None) or ()) for entry in body.inputs)
return await self.submit_concurrent_and_peek(
request_id = body.tracked_request_id(token)
schedule = {}
if request_id is not None:
fingerprint = hashlib.sha256(f'{request.url.path}\n{body.model_dump_json()}'.encode()).hexdigest()
schedule = dict(request_id=request_id, submission_fingerprint=fingerprint, track_execution=True)

reply = await self.submit_concurrent_and_peek(
_task,
token=token,
input_tokens=input_tokens,
task_type='sample',
execution_scope=request_execution_scope(request))
execution_scope=request_execution_scope(request),
**schedule)
if request_id is not None:
record = await self.state.get_future(request_id)
if record is not None and record.get('submission_fingerprint') != fingerprint:
raise RequestRejectedError('client_sample_id is already bound to a different sampler request')
return reply

@app.post('/twinkle/sample_to_data_plane', response_model=types.TaskEnvelope)
async def sample_to_data_plane(
Expand Down
9 changes: 9 additions & 0 deletions src/twinkle/server/state/future_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ def report_progress(existing: dict | None, *, progress: dict) -> dict | None:
snapshot = {**progress, 'sequence': previous.get('sequence', 0) + 1}
return {**existing, 'progress': snapshot}

@staticmethod
def finish_execution(existing: dict | None) -> dict | None:
if existing is None or existing.get('execution_finished') is not False:
return None
return {**existing, 'execution_finished': True}

@staticmethod
def cancel(existing: dict | None, *, failure: dict, now: str) -> dict | None:
"""Atomic transform: cancel iff the task has not started (pending/queued).
Expand Down Expand Up @@ -227,6 +233,9 @@ async def report_progress(self, request_id: str, progress: dict[str, Any]) -> No
await self._backend.update_atomic(
self._make_key(request_id), functools.partial(FutureTransitions.report_progress, progress=progress))

async def mark_execution_finished(self, request_id: str) -> None:
await self._backend.update_atomic(self._make_key(request_id), FutureTransitions.finish_execution)

async def cancel_if_pending(self, request_id: str) -> str | None:
"""Cancel a task iff it has not started; return the resulting status.

Expand Down
1 change: 1 addition & 0 deletions src/twinkle/server/state/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class FutureRecord(BaseModel):
queue_state_reason: str | None = None
progress: dict[str, Any] | None = None
submission_fingerprint: str | None = None
execution_finished: bool | None = None
# Replica ownership and deadline are fixed when the record is created.
replica_id: str | None = None
absolute_deadline: float | None = None
Expand Down
3 changes: 3 additions & 0 deletions src/twinkle/server/state/server_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,9 @@ async def report_future_progress(self, request_id: str, progress: dict[str, Any]
async def create_pending_future(self, request_id: str, **fields: Any) -> bool:
return await self._future_mgr.create_pending(request_id, **fields)

async def mark_future_execution_finished(self, request_id: str) -> None:
await self._future_mgr.mark_execution_finished(request_id)

async def assert_future_owner(self, request_id: str, token: str) -> None:
record = await self._future_mgr.get(request_id)
owner = record.owner_token if record is not None else None
Expand Down
17 changes: 15 additions & 2 deletions src/twinkle/server/task_queue/mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ async def schedule_concurrent_task(
request_id: str | None = None,
execution_scope: ExecutionScope | None = None,
submission_fingerprint: str | None = None,
track_execution: bool = False,
) -> dict[str, Any]:
"""Schedule a compute task that runs now instead of in serial order.

Expand Down Expand Up @@ -386,7 +387,8 @@ async def schedule_concurrent_task(
self._queue_key(model_id=model_id, token=token),
replica_id=getattr(self, 'replica_id', None),
absolute_deadline=self._future_deadline(),
submission_fingerprint=submission_fingerprint)
submission_fingerprint=submission_fingerprint,
track_execution=track_execution)
if started:
logger.info(f'[TaskQueue] Task {request_id} started concurrently, type={task_type or "unknown"}, '
f'model_id={model_id}, input_tokens={input_tokens}')
Expand All @@ -400,7 +402,18 @@ async def schedule_concurrent_task(
async def submit_concurrent_and_peek(self, coro_factory: Callable[[], Coroutine],
**schedule_kwargs) -> TaskEnvelope:
"""Concurrent compute submission with the existing Twinkle future envelope."""
ref = await self.schedule_concurrent_task(coro_factory, **schedule_kwargs)
admission = self.schedule_concurrent_task(coro_factory, **schedule_kwargs)
if schedule_kwargs.get('track_execution'):
# Once the tracked request is admitted it must be queryable even if the POST disconnects.
submission = asyncio.create_task(admission)
try:
ref = await asyncio.shield(submission)
except asyncio.CancelledError:
self._queue_tasks.add(submission)
submission.add_done_callback(self._queue_task_done)
raise
else:
ref = await admission
return await self._peek_terminal(ref['request_id'], fallback_status='pending')

async def _peek_terminal(self, request_id: str, *, fallback_status: str) -> TaskEnvelope:
Expand Down
11 changes: 8 additions & 3 deletions src/twinkle/server/task_queue/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,8 @@ async def _execute_task(self, task: QueuedTask, queue_key: str, q: asyncio.Queue
q.task_done()

async def submit_detached(self, task: QueuedTask, queue_key: str, *, replica_id: str | None,
absolute_deadline: float, submission_fingerprint: str | None = None) -> bool:
absolute_deadline: float, submission_fingerprint: str | None = None,
track_execution: bool = False) -> bool:
"""Own admission, future persistence and startup as one lifecycle."""
self.reserve_detached()
wrote_status = False
Expand All @@ -360,14 +361,16 @@ async def submit_detached(self, task: QueuedTask, queue_key: str, *, replica_id:
replica_id=replica_id,
absolute_deadline=absolute_deadline,
owner_token=task.token)
if track_execution:
fields['execution_finished'] = False
if submission_fingerprint is None:
await self._state.store_future_status(task.request_id, TaskStatus.PENDING.value, **fields)
elif not await self._state.create_pending_future(
task.request_id, submission_fingerprint=submission_fingerprint, **fields):
self.release_detached()
return False
wrote_status = True
self.run_detached(task, queue_key)
self.run_detached(task, queue_key, track_execution=track_execution)
return True
except BaseException:
self.release_detached()
Expand All @@ -389,7 +392,7 @@ def reserve_detached(self) -> None:
def release_detached(self) -> None:
self._detached_reserved -= 1

def run_detached(self, task: QueuedTask, queue_key: str) -> None:
def run_detached(self, task: QueuedTask, queue_key: str, *, track_execution: bool = False) -> None:
"""Start ``task`` now, beside the serial loop instead of in its turn.

For backends that batch concurrent requests themselves (vLLM). The task
Expand Down Expand Up @@ -425,6 +428,8 @@ async def run():
break
if not execution.cancelled():
execution.exception()
if track_execution:
await self._state.mark_future_execution_finished(task.request_id)

running = asyncio.create_task(run())
self._detached_tasks[running] = task
Expand Down
43 changes: 41 additions & 2 deletions src/twinkle_client/_future.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ def resolve(
total_timeout: float = _DEFAULT_TOTAL_TIMEOUT,
transport: ClientTransport | None = None,
on_progress: Callable[[UploadProgress], None] | None = None,
on_terminal: Callable[[TaskEnvelope], None] | None = None,
) -> Any:
"""Block until ``submit``'s task reaches a terminal state, then return its result.

Expand All @@ -146,9 +147,14 @@ def report_progress(envelope: TaskEnvelope) -> None:
cursor = progress.sequence
on_progress(progress)

def unwrap(envelope: TaskEnvelope):
if on_terminal is not None:
on_terminal(envelope)
return _unwrap(envelope, model_cls)

if submit.status in TERMINAL_STATUSES:
report_progress(submit)
return _unwrap(submit, model_cls) # same call as the retrieve path
return unwrap(submit)

resolved_transport = capture_transport(transport)
deadline = time.monotonic() + total_timeout
Expand Down Expand Up @@ -186,7 +192,7 @@ def report_progress(envelope: TaskEnvelope) -> None:
continue
report_progress(reply)
if reply.status in TERMINAL_STATUSES:
return _unwrap(reply, model_cls) # same call as the submit path
return unwrap(reply)
_log_queue_state(reply)
poll_request_id = uuid.uuid4().hex
except (KeyboardInterrupt, SystemExit):
Expand All @@ -209,3 +215,36 @@ def resolve_response(
# Older servers reject unknown retrieve fields and omit progress in submit replies.
on_progress=on_progress if 'progress' in payload else None,
)


def submit_tracked_task(transport, url, body, model_cls, on_outcome_unknown, *, request_id=None):
"""Notify the caller only when a submitted task may still be running."""
try:
response = transport.post_model(url, body)
except (requests.ConnectTimeout, requests.exceptions.InvalidHeader, requests.exceptions.InvalidURL,
requests.exceptions.InvalidSchema, requests.exceptions.MissingSchema):
raise
except requests.HTTPError as exc:
status = _status_of(exc)
if status is None or status in (408, 499) or status >= 500:
on_outcome_unknown(request_id)
raise
except (requests.RequestException, KeyboardInterrupt, SystemExit):
on_outcome_unknown(request_id)
raise

def record_terminal(envelope):
if envelope.status == 'failed' and envelope.execution_finished is False:
on_outcome_unknown(envelope.request_id)

try:
submit = TaskEnvelope.model_validate(response.json())
request_id = submit.request_id
result = resolve(submit, model_cls=None, transport=transport, on_terminal=record_terminal)
except (TaskFailedError, TaskCancelledError):
raise
except BaseException:
on_outcome_unknown(request_id)
raise
# Response-model validation is local. The remote operation has ended.
return model_cls.model_validate(result) if model_cls is not None else result
8 changes: 8 additions & 0 deletions src/twinkle_client/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,14 @@ def get_checkpoint_twinkle_path(self, run_id: str, checkpoint_id: str) -> str:
"""
return self.get_checkpoint_path(run_id, checkpoint_id).twinkle_path

def retrieve_task(self, request_id: str):
"""Retrieve a task envelope with a short, bounded wait for reconciliation."""
from twinkle.protocol.types.lifecycle import TaskEnvelope

response = self._transport.post(self._get_url('/retrieve_future'), json_data={'request_id': request_id},
timeout=2)
return TaskEnvelope.model_validate(response.json())

def delete_checkpoint(self, run_id: str, checkpoint_id: str) -> DeleteCheckpointResponse:
"""
Delete a checkpoint.
Expand Down
18 changes: 15 additions & 3 deletions src/twinkle_client/rollout/_http_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from __future__ import annotations
import base64
import threading
from contextlib import nullcontext
from functools import partial
from io import BytesIO
from typing import Any, Dict, List, Optional

Expand Down Expand Up @@ -30,6 +32,8 @@ def __init__(self, sampler, template, *, adapter_name: str = ''):
self.template = template
self.adapter_name = adapter_name
self.adapter_path: Optional[str] = None
self.adapter_lease = None
self.on_adapter_task_unknown = None

def sample(self,
inputs: Any,
Expand All @@ -42,18 +46,26 @@ def sample(self,
del session_id
if adapter_path and use_base_model:
raise ValueError('adapter_path and use_base_model=True ask for opposite weights.')
adapter_uri = None if use_base_model else (adapter_path or self.adapter_path)
items = inputs if isinstance(inputs, list) else [inputs]
return [self._sample_one(item, sampling_params, adapter_uri) for item in items]
if self.adapter_lease is not None and not use_base_model:
scope = self.adapter_lease(adapter_path or None)
else:
scope = nullcontext(None if use_base_model else (adapter_path or self.adapter_path))
with scope as adapter_uri:
return [self._sample_one(item, sampling_params, adapter_uri) for item in items]

def _sample_one(self, item: Any, sampling_params: Any, adapter_uri: Optional[str]) -> SampleResponse:
media = getattr(item, 'media', None)
if media:
entry = {'input_ids': list(item.engine_input_ids), **_wire_media(media)}
else:
entry = dict(getattr(item, 'feature', item))
options = {}
if adapter_uri is not None and self.on_adapter_task_unknown is not None:
options['on_outcome_unknown'] = partial(self.on_adapter_task_unknown, adapter_uri)
responses = self.sampler.sample(
[entry], sampling_params, adapter_name=self.adapter_name, adapter_uri=adapter_uri, token_only=bool(media))
[entry], sampling_params, adapter_name=self.adapter_name, adapter_uri=adapter_uri,
token_only=bool(media), **options)
if len(responses) != 1:
raise RuntimeError(f'the server returned {len(responses)} responses for one prompt.')
response = responses[0]
Expand Down
23 changes: 14 additions & 9 deletions src/twinkle_client/sampler/vllm_sampler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
from dataclasses import asdict
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from uuid import uuid4

from twinkle.data_format import InputFeature, SamplingParams, Trajectory
from twinkle.protocol.json_utils import json_safe
Expand Down Expand Up @@ -86,6 +87,7 @@ def sample(
session_id: Optional[str] = None,
num_samples: int = 1,
token_only: bool = False,
on_outcome_unknown=None,
) -> List[SampleResponseModel]:
"""Sample from the model.

Expand All @@ -111,15 +113,18 @@ def sample(
"""
if adapter_uri is None:
adapter_uri = adapter_path if adapter_path is not None else getattr(self, 'adapter_uri', None)
response = self._transport.post_model(
f'{self.server_url}/sample',
build_request(
SampleRequest,
inputs=_json_safe(inputs),
sampling_params=self._sampling_params(sampling_params, num_samples),
adapter_name=adapter_name,
adapter_uri=adapter_uri,
token_only=token_only))
url = f'{self.server_url}/sample'
body = build_request(
SampleRequest, inputs=_json_safe(inputs), sampling_params=self._sampling_params(sampling_params, num_samples),
adapter_name=adapter_name, adapter_uri=adapter_uri, token_only=token_only,
client_sample_id=uuid4() if on_outcome_unknown is not None else None)
if on_outcome_unknown is not None:
from twinkle_client._future import submit_tracked_task

request_id = body.tracked_request_id(self._transport.context.api_key)
return submit_tracked_task(
self._transport, url, body, SampleResponseModelList, on_outcome_unknown, request_id=request_id).samples
response = self._transport.post_model(url, body)
return self._await_task(response, SampleResponseModelList).samples

@staticmethod
Expand Down
Loading
Loading