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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,25 @@ rp flash dev main.py # live dev session: edit, re-run, logs stream back
rp flash deploy # deploy production endpoints
```

To run a worker image you already built, declare it with `app.worker_image`.
The image's own handler serves the jobs, and `args` replaces its start command
(leave it out to keep the image's own). Keyword arguments become the job input:

```python
echo = app.worker_image(
name="echo",
image="runpod/mock-worker:latest",
args="python3 -u /handler.py --generator",
gpu="ADA_24",
workers=(0, 3),
)

echo.remote(mock_return="hello")
```

`rp flash dev`, `rp flash deploy` and `rp flash undeploy` manage it like any
other queue resource.

Recurring schedules are not supported by `runpod.apps`. For periodic jobs, use
an external scheduler to invoke a deployed queue function with `.spawn()`.

Expand Down
3 changes: 2 additions & 1 deletion runpod/apps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
RemoteExecutionError,
ScheduleNotSupported,
)
from .handles import ApiHandle, FunctionHandle
from .handles import ApiHandle, FunctionHandle, WorkerImageHandle
from .job import Job
from .markers import delete, get, init, patch, post, put
from .model import Model
Expand Down Expand Up @@ -46,6 +46,7 @@
"ResourceKind",
"ResourceSpec",
"RouteSpec",
"WorkerImageHandle",
"ScheduleNotSupported",
"current_context",
"delete",
Expand Down
76 changes: 72 additions & 4 deletions runpod/apps/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from .context import Context, current_context
from .errors import EndpointNotFound, InvalidResourceError
from .gpu import GpuLike
from .handles import ApiHandle, FunctionHandle
from .handles import ApiHandle, FunctionHandle, WorkerImageHandle
from .spec import (
DEFAULT_SCALER_VALUE,
ResourceKind,
Expand All @@ -32,6 +32,8 @@
from .targets import InvocationTarget, PodTarget, SentinelTarget
from .volume import Volume

Handle = FunctionHandle | ApiHandle | WorkerImageHandle

DEFAULT_ENV = "default"

_REGISTRY: list["App"] = []
Expand Down Expand Up @@ -61,16 +63,16 @@
self.name = name
self.env = env
self._source_file = Path(sys._getframe(1).f_code.co_filename).resolve()
self._resources: dict[str, FunctionHandle | ApiHandle] = {}
self._resources: dict[str, Handle] = {}
self._dev_events: object | None = None
self._dev_targets: dict[str, InvocationTarget] = {}
_REGISTRY.append(self)

@property
def resources(self) -> dict[str, FunctionHandle | ApiHandle]:
def resources(self) -> dict[str, Handle]:
return dict(self._resources)

def _register(self, name: str, handle: FunctionHandle | ApiHandle) -> None:
def _register(self, name: str, handle: Handle) -> None:
if name in self._resources:
raise InvalidResourceError(
f"duplicate resource name '{name}' in app '{self.name}'"
Expand Down Expand Up @@ -141,6 +143,72 @@

return decorator

def worker_image(
self,
*,
name: str,
image: str,
args: str | None = None,
gpu: GpuLike | list[GpuLike] | None = None,
cpu: str | list[str] | None = None,
gpu_count: int = 1,
workers: int | tuple[int, int] | None = None,
idle_timeout: int = 60,
mounts: Mapping[str, Volume] | None = None,
env: dict[str, Any] | None = None,
datacenter: str | list[str] | None = None,
registry_auth: str | None = None,
max_concurrency: int = 1,
execution_timeout_ms: int = 0,
flashboot: bool = True,
scaler_type: str | None = None,
scaler_value: int = DEFAULT_SCALER_VALUE,
min_cuda_version: str | None = None,
container_disk_gb: int | None = None,
) -> WorkerImageHandle:
"""declare a queue endpoint that runs a prebuilt worker image.

the image's own handler serves jobs; nothing from this project
runs on the worker. args replaces the image's start command
(the container's docker args); omit it to keep the image's own.

mock = app.worker_image(
name="mock-worker",
image="runpod/mock-worker:latest",
args="python3 -u /handler.py --generator",
gpu="ADA_24",
)
mock.remote(mock_return="hello")

calls send their keyword arguments as the job input.
"""
spec = ResourceSpec(
kind=ResourceKind.QUEUE,
name=name,
gpu=gpu,
cpu=cpu,
gpu_count=gpu_count,
workers=workers,
idle_timeout=idle_timeout,
mounts=mounts,
env=env,
datacenter=datacenter,
image=image,
registry_auth=registry_auth,
max_concurrency=max_concurrency,
execution_timeout_ms=execution_timeout_ms,
flashboot=flashboot,
scaler_type=scaler_type,
scaler_value=scaler_value,
min_cuda_version=min_cuda_version,
container_disk_gb=container_disk_gb,
image_only=True,
docker_args=args,
)
handle = WorkerImageHandle(self, spec)
self._register(spec.name, handle)
return handle

def task(
self,
*,
Expand Down
5 changes: 4 additions & 1 deletion runpod/apps/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,10 @@ def _deployed_endpoint_input(
if spec.flashboot:
payload["flashBootType"] = "FLASHBOOT"

if spec.image:
if spec.image_only:
# a prebuilt worker image runs its own handler, not the runtime
payload["template"]["dockerArgs"] = spec.docker_args or ""
elif spec.image:
# custom images install the runtime before attaching the artifact
payload["template"]["env"].append(
{"key": "RUNPOD_RUNTIME_KIND", "value": spec.kind.value}
Expand Down
11 changes: 9 additions & 2 deletions runpod/apps/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,11 @@ def _endpoint_input(
# nested .remote() calls from inside a dev worker need
# credentials and the dev-session marker to resolve
# sibling dev endpoints by name
# prebuilt worker images run third-party handlers that
# make no nested calls, so they never get the account key
*(
[{"key": "RUNPOD_API_KEY", "value": key}]
if (key := _client_api_key())
if not spec.image_only and (key := _client_api_key())
else []
),
{"key": "RUNPOD_DEV_APP", "value": app.name},
Expand All @@ -173,7 +175,10 @@ def _endpoint_input(
if spec.flashboot:
payload["flashBootType"] = "FLASHBOOT"

if spec.image:
if spec.image_only:
# a prebuilt worker image runs its own handler, not the runtime
payload["template"]["dockerArgs"] = spec.docker_args or ""
elif spec.image:
# custom images install and start the independently released runtime
payload["template"]["env"].append(
{"key": "RUNPOD_RUNTIME_KIND", "value": spec.kind.value}
Expand Down Expand Up @@ -339,6 +344,7 @@ async def start(self) -> None:
spec.name,
events=self.events,
api=self.api,
raw=spec.image_only,
)

self._emit("session_started")
Expand Down Expand Up @@ -428,6 +434,7 @@ async def refresh(self, apps: list[App]) -> None:
handle.spec.name,
events=self.events,
api=self.api,
raw=handle.spec.image_only,
)

spec = handle.spec
Expand Down
29 changes: 29 additions & 0 deletions runpod/apps/handles.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def load_model(): ... # worker startup hook
from .job import Job
from .markers import INIT_ATTR, is_init, route_of
from .spec import ResourceKind, ResourceSpec, RouteSpec
from .stubs import Queue

if TYPE_CHECKING:
from .app import App
Expand Down Expand Up @@ -467,3 +468,31 @@ def __repr__(self) -> str:
f"<ApiHandle api:{self.spec.name} routes={n_routes} "
f"app={self._app.name!r}>"
)


class WorkerImageHandle(Queue):
"""handle for a prebuilt worker image deployed as a queue endpoint.

the image runs its own handler, so calls send plain job input the
way the queue client does, and resolve through the owning app so the
same handle reaches a dev session or a deployed environment.
"""

def __init__(self, app: "App", spec: ResourceSpec):
super().__init__(app=app.name, name=spec.name, env=app.env)
self._app = app
self.spec = spec

def _clone(self) -> "WorkerImageHandle":
return WorkerImageHandle(self._app, self.spec)

async def _resolve_target(self):
if in_discovery():
raise DiscoveryInvocationError(self.spec.name)
return await self._app._resolve(self.spec)

def __repr__(self) -> str:
return (
f"<WorkerImageHandle {self._app.name}/{self.spec.name} "
f"image={self.spec.image!r}>"
)
29 changes: 29 additions & 0 deletions runpod/apps/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ class ResourceSpec:
container_disk_gb: int | None = None
routes: list[RouteSpec] = field(default_factory=list)
asgi_factory: str | None = None
image_only: bool = False
docker_args: str | None = None

def __post_init__(self) -> None:
self.validate()
Expand Down Expand Up @@ -304,6 +306,7 @@ def validate(self) -> None:
f"available on queue and api resources; tasks download "
f"weights themselves"
)
self._validate_image_only()
if self.schedule is not None and (
not isinstance(self.schedule, str) or not self.schedule
):
Expand All @@ -325,6 +328,28 @@ def validate(self) -> None:
)
seen.add(key)

def _validate_image_only(self) -> None:
"""image-only resources run a prebuilt worker image's own handler."""
if not self.image_only:
if self.docker_args is not None:
raise InvalidResourceError(
f"resource '{self.name}': args are only supported on "
f"worker image resources"
)
return
if self.kind is not ResourceKind.QUEUE:
raise InvalidResourceError(
f"resource '{self.name}': worker image resources are queue endpoints"
)
if not isinstance(self.image, str) or not self.image.strip():
raise InvalidResourceError(
f"resource '{self.name}': worker image resources need an image"
)
if self.docker_args is not None and not isinstance(self.docker_args, str):
raise InvalidResourceError(
f"resource '{self.name}': args must be a string start command"
)

@property
def is_cpu(self) -> bool:
return self.cpu is not None
Expand Down Expand Up @@ -410,4 +435,8 @@ def to_manifest(self, *, include_env: bool = True) -> dict[str, Any]:
]
if self.asgi_factory:
data["asgiFactory"] = self.asgi_factory
if self.image_only:
data["imageOnly"] = True
if self.docker_args:
data["dockerArgs"] = self.docker_args
return data
21 changes: 14 additions & 7 deletions runpod/apps/stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,20 @@ def with_options(
new_options = build_job_options(
webhook, execution_timeout, ttl, low_priority, s3_config
)
clone = Queue(
clone = self._clone()
clone._job_options = merge_job_options(self._job_options, new_options)
return clone

def _clone(self) -> "Queue":
return Queue(
app=self.app_name,
name=self.resource_name,
id=self.resource_id,
env=self.env,
)
clone._job_options = merge_job_options(self._job_options, new_options)
return clone

async def _resolve_target(self):
return self._target()

def _payload(self, kwargs: dict) -> dict:
payload = {"input": kwargs or {"__empty": True}}
Expand All @@ -102,15 +108,16 @@ def _payload(self, kwargs: dict) -> dict:
return payload

async def _remote_async(self, **kwargs: Any) -> Any:
return await self._target().invoke(self._payload(kwargs))
target = await self._resolve_target()
return await target.invoke(self._payload(kwargs))

async def _spawn_async(self, **kwargs: Any) -> Job:
target = self._target()
target = await self._resolve_target()
data = await target.submit(self._payload(kwargs))
return Job(data, target)

async def _stream_async(self, **kwargs: Any) -> AsyncIterator[Any]:
target = self._target()
target = await self._resolve_target()
data = await target.submit(self._payload(kwargs))
stream = target.stream_job(data["id"])
try:
Expand All @@ -122,7 +129,7 @@ async def _stream_async(self, **kwargs: Any) -> AsyncIterator[Any]:
async def _job_async(self, job_id: str) -> Job:
return Job(
{"id": job_id, "status": "UNKNOWN"},
self._target(),
await self._resolve_target(),
)

def __repr__(self) -> str:
Expand Down
6 changes: 6 additions & 0 deletions runpod/apps/targets.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,11 +679,15 @@ def __init__(
resource_name: str = "",
events: object | None = None,
api=None,
raw: bool = False,
):
self.endpoint_id = endpoint_id
self.resource_name = resource_name
self.events = events
self.api = api
# raw endpoints run a prebuilt worker image's own handler, so
# job output is returned as the worker produced it
self.raw = raw
self._client = QueueClient(endpoint_id, _headers)
self._source_target: Any | None = None
self._source_resource: str = ""
Expand Down Expand Up @@ -753,6 +757,8 @@ def build_payload(

def unwrap(self, data: dict[str, Any]) -> Any:
output = unwrap_job_output(data)
if self.raw:
return output
Comment on lines +760 to +761
# the live handler is a generator handler, so job output is an
# aggregated list: one plain response for normal functions,
# __stream__-marked chunk envelopes for generator functions
Expand Down
Loading
Loading