-
Notifications
You must be signed in to change notification settings - Fork 322
Expand file tree
/
Copy pathapi.py
More file actions
1378 lines (1087 loc) · 49 KB
/
api.py
File metadata and controls
1378 lines (1087 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import os
import random
import signal
import threading
import time
from contextlib import asynccontextmanager, suppress
from datetime import datetime, timedelta, timezone
from typing import Annotated, Any, AsyncGenerator, ClassVar, Literal
from uuid import uuid4
import fastapi
import psutil
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse, StreamingResponse
from pydantic import (
Base64Bytes,
BaseModel,
Discriminator,
Field,
Tag,
model_validator,
)
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import TimeoutError as SATimeoutError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import SQLModel, func, select
from sqlmodel.ext.asyncio.session import AsyncSession
from skyrl.tinker import types
from skyrl.tinker.config import EngineConfig, add_model, config_to_argv
from skyrl.tinker.db_models import (
CheckpointDB,
CheckpointStatus,
FutureDB,
ModelDB,
RequestStatus,
SamplingSessionDB,
SessionDB,
enable_sqlite_wal,
get_async_database_url,
)
from skyrl.tinker.extra import (
ExternalInferenceClient,
SkyRLTrainInferenceForwardingClient,
)
from skyrl.utils.log import get_uvicorn_log_config, logger
from skyrl.utils.storage import download_file
# Validation patterns for train_run_ids, model_ids and checkpoint_ids
ID_PATTERN = r"^[a-zA-Z0-9_-]+$"
ID_MAX_LENGTH = 255
API_SERVER_STARTUP_ARGS = ["-m", "skyrl.tinker.api"]
# Timeout for graceful shutdown when engine crashes
SHUTDOWN_TIMEOUT_SECONDS = 10
def _get_parent_uv_run_args(parent_cmd: list[str]) -> list[str]:
"""Extract parent `uv run <uv run args>` flags for the engine launch given the parent process's startup command
`uv run` starts this Python API process as a child. To recover the original
`uv run <uv run args> ...` flags, we inspect the parent process command line
and extract all the uv run args before the script argument.
"""
# the API server startup command can be
# uv run <uv run args> -m skyrl.tinker.api
# or uv run <uv run args> python -m skyrl.tinker.api
# or uv run <uv run args> -- python -m skyrl.tinker.api
stop_strings = ["--", "python"]
detected = False
for i in range(len(parent_cmd) - 1):
if parent_cmd[i] in stop_strings or parent_cmd[i : i + len(API_SERVER_STARTUP_ARGS)] == API_SERVER_STARTUP_ARGS:
detected = True
break
if not detected or i < 2:
raise ValueError(
f"Unable to parse tinker API server startup command: {parent_cmd}. "
"Ensure that the tinker API server was started with `uv run <uv run args> -m skyrl.tinker.api`"
)
parent_cmd = parent_cmd[2:i] # ignore uv run
return parent_cmd
def _build_uv_run_cmd_engine(parent_cmd: list[str], engine_config: BaseModel) -> list[str]:
"""Builds uv run command for the engine
Args:
parent_cmd: The command for the parent process starting the engine
engine_config: Engine configuration
Returns:
cmd: The uv run command for the tinker engine
"""
cmd = ["uv", "run"]
parent_flags = _get_parent_uv_run_args(parent_cmd)
logger.debug(f"Detected API server uv run flags: {parent_flags}")
cmd.extend(parent_flags)
# NOTE: uv deduplicates extras so we can unconditionally add the tinker extra
cmd.extend(["--extra", "tinker", "--extra", engine_config.backend])
cmd.extend(["-m", "skyrl.tinker.engine"])
cmd.extend(config_to_argv(engine_config))
return cmd
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifespan event handler for startup and shutdown."""
db_url = get_async_database_url(app.state.engine_config.database_url)
app.state.db_engine = create_async_engine(db_url, echo=False)
enable_sqlite_wal(app.state.db_engine.sync_engine)
async with app.state.db_engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
# Setup external inference client if configured.
#
# Three cases:
# 1. external_inference_url set: forward sample requests to a fully
# external vLLM (existing behavior).
# 2. backend in (megatron, fsdp) and colocate_all=False: install
# SkyRLTrainInferenceForwardingClient so sample requests go directly
# to the SkyRL-Train-managed vLLM, bypassing the engine's serial loop.
# 3. otherwise (JAX, colocated SkyRL-Train, etc.): route everything
# through the engine subprocess.
#
# The colocated path stays on the engine because vLLM is asleep during
# training and only the engine's synchronous sample path knows how to
# wake it (save_weights_for_sampler → broadcast → sample).
backend_name = app.state.engine_config.backend
backend_cfg = app.state.engine_config.backend_config or {}
# SkyRL-Train default is colocate_all=True; only opt into forwarding
# when the operator explicitly sets it to False.
is_colocated = bool(backend_cfg.get("trainer.placement.colocate_all", True))
if app.state.engine_config.external_inference_url:
app.state.external_inference_client = ExternalInferenceClient(app.state.engine_config, app.state.db_engine)
logger.info(f"External engine configured: {app.state.engine_config.external_inference_url}")
elif backend_name in ("megatron", "fsdp") and not is_colocated:
app.state.external_inference_client = SkyRLTrainInferenceForwardingClient(
app.state.engine_config, app.state.db_engine
)
logger.info(
"SkyRL-Train inference forwarding client enabled for non-colocated backend=%s",
backend_name,
)
else:
app.state.external_inference_client = None
logger.info("Using internal engine for inference")
# Build subprocess command with engine config parameters.
parent_cmd = psutil.Process(os.getppid()).cmdline()
cmd = _build_uv_run_cmd_engine(parent_cmd, app.state.engine_config)
background_engine = await asyncio.create_subprocess_exec(*cmd)
app.state.background_engine = background_engine
logger.info(f"Started background engine with PID {background_engine.pid}: {' '.join(cmd)}")
shutting_down = False
async def monitor_engine():
"""Monitor engine process and exit API server if it crashes."""
exit_code = await background_engine.wait()
if not shutting_down:
logger.error(f"Background engine crashed with exit code {exit_code}, exiting API server")
# Start a background timer that force-exits after timeout.
# Using a thread instead of asyncio task because SIGTERM handling
# may wait for pending asyncio tasks to complete before exiting.
def force_exit():
logger.warning("Graceful shutdown timed out, forcing exit")
os._exit(1)
timer = threading.Timer(SHUTDOWN_TIMEOUT_SECONDS, force_exit)
timer.daemon = True
timer.start()
# Request graceful shutdown. Uvicorn will stop accepting new
# connections and wait for active requests to complete.
# If shutdown doesn't complete in time, force_exit() will terminate.
os.kill(os.getpid(), signal.SIGTERM)
monitor_task = asyncio.create_task(monitor_engine())
yield
shutting_down = True
monitor_task.cancel()
# Close the forwarding client's persistent httpx connection pool if we
# installed one. Cheap no-op when external_inference_client doesn't own
# an httpx client (ExternalInferenceClient creates one per call).
inference_client = getattr(app.state, "external_inference_client", None)
aclose = getattr(inference_client, "aclose", None)
if aclose is not None:
with suppress(Exception):
await aclose()
logger.info(f"Stopping background engine (PID {app.state.background_engine.pid})")
with suppress(ProcessLookupError):
background_engine.terminate()
try:
await asyncio.wait_for(background_engine.wait(), timeout=5)
except asyncio.TimeoutError:
logger.warning(f"Background engine (PID {background_engine.pid}) did not terminate gracefully, killing")
background_engine.kill()
await background_engine.wait()
logger.info("Background engine stopped")
app = FastAPI(title="Tinker API Mock", version="0.0.1", lifespan=lifespan)
async def get_session(request: Request) -> AsyncGenerator[AsyncSession, None]:
"""Dependency to get a database session."""
async with AsyncSession(request.app.state.db_engine) as session:
yield session
async def get_model(session: AsyncSession, model_id: str) -> ModelDB:
"""Fetch a model by ID, raising 404 if not found."""
statement = select(ModelDB).where(ModelDB.model_id == model_id)
result = await session.exec(statement)
model = result.first()
if not model:
raise HTTPException(status_code=404, detail="Model not found")
return model
async def create_future(
session: AsyncSession,
request_type: types.RequestType,
model_id: str | None,
request_data: BaseModel,
) -> int:
"""Create a FutureDB entry and return its auto-generated request_id."""
future_db = FutureDB(
request_type=request_type,
model_id=model_id,
request_data=request_data.model_dump(mode="json"),
status=RequestStatus.PENDING,
)
session.add(future_db)
await session.flush() # Flush to generate auto-increment request_id
assert future_db.request_id
return future_db.request_id
async def create_checkpoint(
session: AsyncSession,
model_id: str,
checkpoint_id: str,
checkpoint_type: types.CheckpointType,
):
"""Create a pending CheckpointDB entry, relying on database constraints for validation."""
checkpoint_db = CheckpointDB(
model_id=model_id,
checkpoint_id=checkpoint_id,
checkpoint_type=checkpoint_type,
status=CheckpointStatus.PENDING,
)
session.add(checkpoint_db)
try:
await session.flush()
except IntegrityError:
await session.rollback()
# Determine which constraint failed by checking if the model exists
statement = select(ModelDB).where(ModelDB.model_id == model_id)
result = await session.exec(statement)
if not result.first():
raise HTTPException(status_code=404, detail=f"Model '{model_id}' not found")
else:
raise HTTPException(
status_code=409, detail=f"Checkpoint '{checkpoint_id}' already exists for model '{model_id}'"
)
class LoRAConfig(BaseModel):
rank: int
seed: int | None = Field(
default=None, description="Seed for LoRA weight initialization. If None, a random seed is used."
)
class CreateModelRequest(BaseModel):
session_id: str
base_model: str
lora_config: LoRAConfig
model_role: str = "policy"
class CreateModelResponse(BaseModel):
model_id: str
base_model: str
lora_config: LoRAConfig | None = None
status: str = "created"
request_id: str
class UnloadModelRequest(BaseModel):
model_id: str
type: str | None = None
class UnloadModelResponse(BaseModel):
request_id: str
model_id: str
class ModelData(BaseModel):
base_model: str
lora_config: LoRAConfig | None = None
model_name: str | None = None
class ModelInfoResponse(BaseModel):
model_id: str
status: str
model_data: ModelData
class Checkpoint(BaseModel):
checkpoint_id: str
checkpoint_type: Literal["training", "sampler"]
time: datetime
tinker_path: str
class TrainingRun(BaseModel):
training_run_id: str
base_model: str
model_owner: str = "default"
is_lora: bool = True
corrupted: bool = False
lora_rank: int | None = None
last_request_time: datetime
last_checkpoint: Checkpoint | None = None
last_sampler_checkpoint: Checkpoint | None = None
user_metadata: dict[str, str] | None = None
class EncodedTextChunk(BaseModel):
type: Literal["encoded_text"] = "encoded_text"
tokens: list[int]
def to_types(self) -> types.EncodedTextChunk:
return types.EncodedTextChunk(tokens=self.tokens)
class ImageChunk(BaseModel):
type: Literal["image"] = "image"
data: Base64Bytes
format: Literal["png", "jpeg"]
expected_tokens: int | None = None
def to_types(self) -> types.ImageChunk:
return types.ImageChunk.model_construct(
data=self.data,
format=self.format,
expected_tokens=self.expected_tokens,
)
class ImageAssetPointerChunk(BaseModel):
type: Literal["image_asset_pointer"] = "image_asset_pointer"
format: Literal["png", "jpeg"]
location: str = Field(min_length=1)
expected_tokens: int | None = None
def to_types(self) -> types.ImageAssetPointerChunk:
return types.ImageAssetPointerChunk(
format=self.format,
location=self.location,
expected_tokens=self.expected_tokens,
)
def _get_model_chunk_type(v: Any) -> str:
if isinstance(v, dict):
if "type" in v:
return v["type"]
is_encoded_text = "tokens" in v
is_image_asset_pointer = "location" in v
is_image = "data" in v
if sum([is_encoded_text, is_image_asset_pointer, is_image]) > 1:
raise ValueError(
"Ambiguous model chunk type: must be exactly one of 'encoded_text', 'image_asset_pointer', or 'image'"
)
if is_encoded_text:
return "encoded_text"
if is_image_asset_pointer:
return "image_asset_pointer"
if is_image:
return "image"
return getattr(v, "type", "encoded_text")
ModelInputChunk = Annotated[
Annotated[EncodedTextChunk, Tag("encoded_text")]
| Annotated[ImageAssetPointerChunk, Tag("image_asset_pointer")]
| Annotated[ImageChunk, Tag("image")],
Discriminator(_get_model_chunk_type),
]
class ModelInput(BaseModel):
chunks: list[ModelInputChunk]
def to_types(self) -> types.ModelInput:
return types.ModelInput(chunks=[chunk.to_types() for chunk in self.chunks])
class TensorData(BaseModel):
data: list[int] | list[float]
def to_types(self) -> types.TensorData:
return types.TensorData(data=self.data)
class Datum(BaseModel):
loss_fn_inputs: dict[str, TensorData]
model_input: ModelInput
def to_types(self) -> types.Datum:
inp = self.loss_fn_inputs
if "weights" not in inp:
weights = types.TensorData(data=[1.0] * len(inp["target_tokens"].data))
else:
weights = inp["weights"].to_types()
return types.Datum(
loss_fn_inputs=types.LossFnInputs(
target_tokens=inp["target_tokens"].to_types(),
weights=weights,
advantages=inp["advantages"].to_types() if "advantages" in inp else types.TensorData(data=[]),
logprobs=inp["logprobs"].to_types() if "logprobs" in inp else types.TensorData(data=[]),
values=inp["values"].to_types() if "values" in inp else types.TensorData(data=[]),
returns=inp["returns"].to_types() if "returns" in inp else types.TensorData(data=[]),
),
model_input=self.model_input.to_types(),
)
class ForwardBackwardInput(BaseModel):
_ALLOWED_KEYS_BY_LOSS_FN: ClassVar[dict[str, set[str]]] = {
"cross_entropy": set(),
"importance_sampling": set(),
"ppo": {"clip_low_threshold", "clip_high_threshold", "value_clip"},
"cispo": {"clip_low_threshold", "clip_high_threshold"},
"ppo_critic": {"value_clip"},
}
data: list[Datum]
loss_fn: Literal["cross_entropy", "importance_sampling", "ppo", "cispo", "ppo_critic"]
loss_fn_config: dict[str, float] | None = None
@model_validator(mode="after")
def validate_loss_fn_config_keys(self):
"""Validate loss_fn_config keys based on the selected loss function."""
if self.loss_fn_config is None:
return self
allowed_keys = self._ALLOWED_KEYS_BY_LOSS_FN[self.loss_fn]
invalid_keys = sorted(set(self.loss_fn_config.keys()) - allowed_keys)
if invalid_keys:
if allowed_keys:
raise ValueError(
f"Invalid loss_fn_config keys for loss_fn='{self.loss_fn}': {invalid_keys}. "
f"Allowed keys: {sorted(allowed_keys)}."
)
raise ValueError(
f"loss_fn='{self.loss_fn}' does not accept loss_fn_config keys. " f"Received: {invalid_keys}."
)
return self
def to_types(self) -> types.ForwardBackwardInput:
return types.ForwardBackwardInput(
data=[datum.to_types() for datum in self.data],
loss_fn=self.loss_fn,
loss_fn_config=self.loss_fn_config,
)
class ForwardBackwardRequest(BaseModel):
model_id: str
forward_backward_input: ForwardBackwardInput
class ForwardRequest(BaseModel):
model_id: str
forward_input: ForwardBackwardInput
class AdamParams(BaseModel):
learning_rate: float = Field(default=1e-4, ge=0.0)
beta1: float = Field(default=0.9, ge=0.0, lt=1.0)
beta2: float = Field(default=0.95, ge=0.0, lt=1.0)
eps: float = Field(default=1e-12, gt=0.0)
weight_decay: float = Field(default=0.0, ge=0.0)
def to_types(self) -> types.AdamParams:
return types.AdamParams(
learning_rate=self.learning_rate,
beta1=self.beta1,
beta2=self.beta2,
eps=self.eps,
weight_decay=self.weight_decay,
)
class OptimStepRequest(BaseModel):
model_id: str
adam_params: AdamParams
class SaveWeightsForSamplerRequest(BaseModel):
model_id: str
path: str | None = Field(default=None, pattern=ID_PATTERN, max_length=ID_MAX_LENGTH)
sampling_session_seq_id: int | None = None
seq_id: int | None = None
type: Literal["save_weights_for_sampler"] = "save_weights_for_sampler"
@model_validator(mode="after")
def check_path_or_ids(self):
if not self.path and (self.sampling_session_seq_id is None or self.seq_id is None):
raise ValueError("Either 'path' or both 'sampling_session_seq_id' and 'seq_id' must be provided")
return self
class SamplingParams(BaseModel):
max_tokens: int | None = None
seed: int | None = None
stop: list[int] | list[str] | None = None
temperature: float = 1
top_k: int = -1
top_p: float = 1
def to_types(self) -> types.SamplingParams:
if self.max_tokens is None:
raise HTTPException(status_code=400, detail="max_tokens is currently required")
if self.max_tokens <= 0:
raise HTTPException(status_code=400, detail="max_tokens must be a positive number")
# Generate a random seed if not provided
seed = self.seed if self.seed is not None else random.randint(0, 2**31 - 1)
# Determine if stop values are token IDs (int) or strings
stop_tokens = None
stop_strings = None
if self.stop:
if all(isinstance(s, int) for s in self.stop):
stop_tokens = list(self.stop)
elif all(isinstance(s, str) for s in self.stop):
stop_strings = list(self.stop)
else:
raise HTTPException(
status_code=400,
detail="stop must be either all integers (token IDs) or all strings, not mixed",
)
return types.SamplingParams(
temperature=self.temperature,
max_tokens=self.max_tokens,
seed=seed,
stop_tokens=stop_tokens,
stop_strings=stop_strings,
top_k=self.top_k,
top_p=self.top_p,
)
class SampleRequest(BaseModel):
num_samples: int = 1
prompt: ModelInput
sampling_params: SamplingParams
base_model: str | None = None
model_path: str | None = None
sampling_session_id: str | None = None
seq_id: int | None = None
prompt_logprobs: bool | None = None
topk_prompt_logprobs: int = 0
type: Literal["sample"] = "sample"
@model_validator(mode="after")
def validate_model_source(self):
"""Valid if:
- sampling_session_id is provided AND seq_id is provided
- OR exactly one of base_model or model_path is provided
"""
if self.sampling_session_id is not None:
if self.seq_id is None:
raise ValueError("'seq_id' must be provided when 'sampling_session_id' is used")
return self
if (self.base_model is None) == (self.model_path is None):
raise ValueError(
"When 'sampling_session_id' is not provided, exactly one of 'base_model' or 'model_path' must be provided"
)
return self
class SaveWeightsRequest(BaseModel):
model_id: str
path: str = Field(..., pattern=ID_PATTERN, max_length=ID_MAX_LENGTH)
type: Literal["save_weights"] | None = None
class LoadWeightsRequest(BaseModel):
model_id: str
path: str
type: Literal["load_weights"] | None = None
class FutureResponse(BaseModel):
future_id: str
status: str = "pending"
request_id: str
class TelemetryEvent(BaseModel):
event: str
event_id: str
event_session_index: int
severity: str
timestamp: str
properties: dict[str, Any] | None = None
class TelemetryRequest(BaseModel):
events: list[TelemetryEvent]
platform: str
sdk_version: str
session_id: str
class TelemetryResponse(BaseModel):
status: Literal["accepted"] = "accepted"
class HealthResponse(BaseModel):
status: Literal["ok"]
class CreateSessionRequest(BaseModel):
tags: list[str]
user_metadata: dict[str, Any] | None = None
sdk_version: str
type: Literal["create_session"] = "create_session"
class CreateSessionResponse(BaseModel):
type: Literal["create_session"] = "create_session"
info_message: str | None = None
warning_message: str | None = None
error_message: str | None = None
session_id: str
class SessionHeartbeatRequest(BaseModel):
session_id: str
type: Literal["session_heartbeat"] = "session_heartbeat"
class SessionHeartbeatResponse(BaseModel):
type: Literal["session_heartbeat"] = "session_heartbeat"
class CreateSamplingSessionRequest(BaseModel):
session_id: str
sampling_session_seq_id: int
base_model: str | None = None
model_path: str | None = None
type: Literal["create_sampling_session"] = "create_sampling_session"
class CreateSamplingSessionResponse(BaseModel):
type: Literal["create_sampling_session"] = "create_sampling_session"
sampling_session_id: str
class SupportedModel(BaseModel):
model_name: str
class GetServerCapabilitiesResponse(BaseModel):
supported_models: list[SupportedModel]
class ListCheckpointsResponse(BaseModel):
checkpoints: list[Checkpoint]
class Cursor(BaseModel):
offset: int
limit: int
total_count: int
class TrainingRunsResponse(BaseModel):
training_runs: list[TrainingRun]
cursor: Cursor
class WeightsInfoRequest(BaseModel):
tinker_path: str
class WeightsInfoResponse(BaseModel):
"""Minimal information for loading public checkpoints."""
# from: https://github.com/thinking-machines-lab/tinker/blob/main/src/tinker/types/weights_info_response.py
base_model: str
is_lora: bool
lora_rank: int | None = None
class ClientConfigResponse(BaseModel):
pjwt_auth_enabled: bool = False
@app.post("/api/v1/client/config", response_model=ClientConfigResponse)
async def client_config():
"""Stub for tinker SDK client_config handshake."""
return ClientConfigResponse()
@app.get("/api/v1/healthz", response_model=HealthResponse)
async def healthz():
"""Checks if the API server is ready."""
return HealthResponse(status="ok")
@app.post("/api/v1/create_session", response_model=CreateSessionResponse)
async def create_session(request: CreateSessionRequest, session: AsyncSession = Depends(get_session)):
"""Create a new session + persist in DB"""
session_id = f"session_{uuid4().hex[:8]}"
session_db = SessionDB(
session_id=session_id,
tags=request.tags,
user_metadata=request.user_metadata or {},
sdk_version=request.sdk_version,
status="active",
)
session.add(session_db)
await session.commit()
return CreateSessionResponse(session_id=session_id)
@app.post("/api/v1/session_heartbeat", response_model=SessionHeartbeatResponse)
async def session_heartbeat(request: SessionHeartbeatRequest, session: AsyncSession = Depends(get_session)):
"""Heartbeat for an active session to keep it alive."""
session_db = await session.get(SessionDB, request.session_id)
if session_db is None:
raise HTTPException(status_code=404, detail="Session not found")
session_db.last_heartbeat_at = datetime.now(timezone.utc)
session_db.heartbeat_count += 1
await session.commit()
return SessionHeartbeatResponse()
@app.post("/api/v1/create_sampling_session", response_model=CreateSamplingSessionResponse)
async def create_sampling_session(request: CreateSamplingSessionRequest, session: AsyncSession = Depends(get_session)):
"""Create a new sampling session within an existing session."""
session_db = await session.get(SessionDB, request.session_id)
if session_db is None:
raise HTTPException(status_code=404, detail="Session not found")
# Exactly one of base_model or model_path must be provided
if (request.base_model is None) == (request.model_path is None):
raise HTTPException(status_code=400, detail="Exactly one of base_model or model_path must be provided")
sampling_session_id = f"sampling_{uuid4().hex[:8]}"
sampling_db = SamplingSessionDB(
sampling_session_id=sampling_session_id,
session_id=request.session_id,
sampling_session_seq_id=request.sampling_session_seq_id,
base_model=request.base_model,
model_path=request.model_path,
)
session.add(sampling_db)
await session.commit()
return CreateSamplingSessionResponse(sampling_session_id=sampling_session_id)
@app.post("/api/v1/create_model", response_model=CreateModelResponse)
async def create_model(request: CreateModelRequest, session: AsyncSession = Depends(get_session)):
"""Create a new model, optionally with a LoRA adapter."""
# Validate session exists
session_db = await session.get(SessionDB, request.session_id)
if session_db is None:
raise HTTPException(status_code=404, detail="Session not found")
model_id = f"model_{uuid4().hex[:8]}"
# alpha = 32 seems to be the tinker default (see https://thinkingmachines.ai/blog/lora/)
# Generate a random seed if not provided
seed = request.lora_config.seed if request.lora_config.seed is not None else random.randint(0, 2**31 - 1)
lora_config = types.LoraConfig(rank=request.lora_config.rank, alpha=32.0, seed=seed)
request_id = await create_future(
session=session,
request_type=types.RequestType.CREATE_MODEL,
model_id=model_id,
request_data=types.CreateModelInput(lora_config=lora_config, model_role=request.model_role),
)
model_db = ModelDB(
model_id=model_id,
base_model=request.base_model,
lora_config=lora_config.model_dump(),
status="created",
request_id=request_id,
session_id=request.session_id,
)
session.add(model_db)
await session.commit()
return CreateModelResponse(
model_id=model_id,
base_model=request.base_model,
lora_config=request.lora_config,
status="created",
request_id=str(request_id),
)
@app.post("/api/v1/unload_model", response_model=UnloadModelResponse)
async def unload_model(request: UnloadModelRequest, session: AsyncSession = Depends(get_session)):
"""Unload a model and free all associated resources."""
# Validate model exists
model_db = await session.get(ModelDB, request.model_id)
if model_db is None:
raise HTTPException(status_code=404, detail="Model not found")
# Update model status
model_db.status = "unloading"
# Create future request
request_id = await create_future(
session=session,
request_type=types.RequestType.UNLOAD_MODEL,
model_id=request.model_id,
request_data=types.UnloadModelInput(),
)
await session.commit()
return UnloadModelResponse(request_id=str(request_id), model_id=request.model_id)
class GetInfoRequest(BaseModel):
model_id: str
type: str | None = None
@app.post("/api/v1/get_info", response_model=ModelInfoResponse)
async def get_model_info(request: GetInfoRequest, session: AsyncSession = Depends(get_session)):
"""Retrieve information about the current model."""
model = await get_model(session, request.model_id)
lora_config = types.LoraConfig.model_validate(model.lora_config)
model_data = ModelData(
base_model=model.base_model, lora_config=LoRAConfig(rank=lora_config.rank), model_name=model.base_model
)
return ModelInfoResponse(model_id=model.model_id, status=model.status, model_data=model_data)
@app.get("/api/v1/training_runs/{model_id}", response_model=TrainingRun)
async def get_training_run(model_id: str, session: AsyncSession = Depends(get_session)):
"""Get training run for session resumption."""
model = await get_model(session, model_id)
lora_config = types.LoraConfig.model_validate(model.lora_config)
return TrainingRun(
training_run_id=model.model_id,
base_model=model.base_model,
model_owner="default",
is_lora=True,
corrupted=False,
lora_rank=lora_config.rank,
# TODO: Once we track modified_at timestamps, update this
last_request_time=model.created_at,
last_checkpoint=None,
last_sampler_checkpoint=None,
user_metadata=None,
)
@app.post("/api/v1/forward_backward", response_model=FutureResponse)
async def forward_backward(request: ForwardBackwardRequest, session: AsyncSession = Depends(get_session)):
"""Compute and accumulate gradients."""
await get_model(session, request.model_id)
request_id = await create_future(
session=session,
request_type=types.RequestType.FORWARD_BACKWARD,
model_id=request.model_id,
request_data=request.forward_backward_input.to_types(),
)
await session.commit()
return FutureResponse(future_id=str(request_id), status="pending", request_id=str(request_id))
@app.post("/api/v1/forward", response_model=FutureResponse)
async def forward(request: ForwardRequest, session: AsyncSession = Depends(get_session)):
"""Forward pass to obtain logprobs without accumulating gradients"""
await get_model(session, request.model_id)
request_id = await create_future(
session=session,
request_type=types.RequestType.FORWARD,
model_id=request.model_id,
request_data=request.forward_input.to_types(),
)
await session.commit()
return FutureResponse(future_id=str(request_id), status="pending", request_id=str(request_id))
@app.post("/api/v1/optim_step", response_model=FutureResponse)
async def optim_step(request: OptimStepRequest, session: AsyncSession = Depends(get_session)):
"""Update model using accumulated gradients."""
await get_model(session, request.model_id)
request_id = await create_future(
session=session,
request_type=types.RequestType.OPTIM_STEP,
model_id=request.model_id,
request_data=types.OptimStepInput(adam_params=request.adam_params.to_types()),
)
await session.commit()
return FutureResponse(future_id=str(request_id), status="pending", request_id=str(request_id))
@app.post("/api/v1/load_weights", response_model=FutureResponse)
async def load_weights(request: LoadWeightsRequest, req: Request, session: AsyncSession = Depends(get_session)):
"""Loads weights and training state."""
await get_model(session, request.model_id)
path = types.TinkerPath.parse(request.path)
if (
not path
or path.kind != "weights"
or not (source_model_id := path.primary_id)
or not (checkpoint_id := path.secondary_id)
):
raise HTTPException(
status_code=400, detail="request.path must be in format tinker://source_model_id/weights/checkpoint_id"
)
await validate_checkpoint(req, source_model_id, checkpoint_id, types.CheckpointType.TRAINING, session)
request_id = await create_future(
session=session,
request_type=types.RequestType.LOAD_WEIGHTS,
model_id=request.model_id,
request_data=types.LoadWeightsInput(source_model_id=source_model_id, checkpoint_id=checkpoint_id),
)
await session.commit()
return FutureResponse(future_id=str(request_id), status="pending", request_id=str(request_id))
@app.post("/api/v1/save_weights", response_model=FutureResponse)
async def save_weights(request: SaveWeightsRequest, session: AsyncSession = Depends(get_session)):
"""Saves weights and training state."""
# Create pending checkpoint entry (validates model exists)
await create_checkpoint(
session=session,
model_id=request.model_id,
checkpoint_id=request.path,
checkpoint_type=types.CheckpointType.TRAINING,
)
request_id = await create_future(
session=session,
request_type=types.RequestType.SAVE_WEIGHTS,
model_id=request.model_id,
request_data=types.SaveWeightsInput(path=request.path),
)
await session.commit()
return FutureResponse(future_id=str(request_id), status="pending", request_id=str(request_id))
@app.post("/api/v1/save_weights_for_sampler", response_model=FutureResponse)
async def save_weights_for_sampler(request: SaveWeightsForSamplerRequest, session: AsyncSession = Depends(get_session)):
"""Saves weights in a format compatible with sampling/inference servers."""
# Get the model (validates it exists and gives us the session_id)
model = await get_model(session, request.model_id)