Skip to content

feat: add on-demand models with shared LoRA and exclusive training - #312

Merged
Yunnglin merged 52 commits into
mainfrom
feat/on-demand-training
Oct 26, 2026
Merged

Yunnglin merged 52 commits into
mainfrom
feat/on-demand-training

Conversation

@Yunnglin

@Yunnglin Yunnglin commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

PR type

  • Bug Fix
  • New Feature
  • Document Updates
  • More Models or Datasets Support

PR information

Changes

  • Start training instances when clients create training handles and release unused devices afterwards. Compatible LoRA handles share an instance; Full training gets an exclusive instance. Support both Transformers and Megatron through the existing YAML entry point.
  • Scale sampling instances according to active requests, route requests to ready instances and remove idle replicas above the configured minimum. Reserve participants during control and Full-weight updates, and replay committed settings before new instances become ready.
  • Manage allocation, startup, timeouts, recovery and confirmed shutdown through shared resource mechanisms. Uncertain completion retains ownership until cleanup is confirmed; controller recovery invalidates old training handles.
  • Carry training identities automatically in the SDK, reject duplicate adapter labels on one client object, and retain explicit checkpoint restore after a handle expires or its controller restarts.
  • Keep execution in server/model and server/sampler, with nested pool/ packages for scheduling. Update configuration examples, user documentation and the related resource/state/SDK tests.

Usage

  1. Upgrade the server and Twinkle SDK together. Keep the existing applications YAML format. In the args of an import_path: model application, configure:

    train_mode: lora
    min_replicas: 0
    max_replicas: 2
    idle_timeout_s: 600
    max_loras: 3
    • min_replicas: 0 defers model loading until the first training request. Set a positive minimum to retain resident instances.
    • max_replicas limits training instances; max_loras limits LoRA handles per instance. Keep device_group and device_mesh for each instance's device count and parallelism. Megatron requires at least two devices per instance.
    • Business idle is controlled by idle_timeout_s. Heartbeats and result polling do not renew it; admitted queued/running operations remain protected. Existing adapter_config.adapter_timeout and adapter_max_lifetime independently control heartbeat loss and absolute lifetime.
    • For Full training, set train_mode: full, remove max_loras, and create the training with config=None. To expose LoRA and Full for the same weights, use separate model applications with different names and routes.
  2. Validate and launch the configuration:

    twinkle-server check-config -c server_config.yaml
    twinkle-server launch --config server_config.yaml
  3. Create and release training through the existing SDK methods; the SDK handles training IDs internally:

    from peft import LoraConfig
    from twinkle import init_twinkle_client
    
    client = init_twinkle_client(base_url="http://localhost:8000", api_key="YOUR_TOKEN")
    model = client.model("ms://Qwen/Qwen3.5-4B")
    model.add_adapter_to_model("demo", LoraConfig(r=8, target_modules="all-linear"))
    # Configure the template, loss and optimizer; train and save checkpoints as usual.
    model.remove_adapter("demo")

    Tinker keeps its existing training-client creation and unload APIs. Save checkpoints regularly; after expiry or controller restart, create a new training handle and explicitly resume the checkpoint. Clients sharing a token also share per_token_model_limit.

  4. To enable sampling scale-out and scale-in, set these fields in the sampler application's args:

    min_replicas: 2
    max_replicas: 4
    target_ongoing_requests: 16
    idle_timeout_s: 600

    This keeps two instances, scales up to four as demand grows, and removes extra instances after 600 idle seconds. Configure devices per instance separately; clients do not choose instance IDs. Reapply custom runtime settings such as templates after a service restart.

  5. Start from the Transformers configuration or Megatron configuration. Auto-generated YAML retains its original application name, layout, environment location and adapter heartbeat configuration, with only the required on-demand fields and device-count validation added.

Dependency and review scope

Experiment results

  • Revision: 7c741d84806cd572adcf0403670c3f7472e5e57a. The current runtime/config integration suite passes 65 CPU cases; fix: correct adapter state reuse and streaming completion #341 independently passes 76 backend CPU cases, including real two-process DDP. Both selected suites have zero failures, errors or skips. Changed source hooks and diff checks pass; GitHub checks must complete on the updated heads.
  • Full acceptance at a02b7595f78d597efb2bf2ccdf85b5f7c3266f52: 1068 distinct selected CPU cases, 17 real PPU pytest executions and a separate two-PPU FSDP slot probe pass. Both SDKs cover training/save/restore/continued optimizer updates on Transformers/Redis and Megatron/Memory; restored logprob differences are zero.
  • Real PPU/Qwen3.5-4B coverage includes four working vLLM engines and 2-to-4-to-2 scaling, updates during reclamation, checkpoint replacement/rebuild, LoRA eviction/reload, timeout isolation and worker/controller recovery. Cleanup verifies owned actors, Serve applications, placement groups, quotas and active state; all eight devices return to the 2 MiB baseline and original services remain healthy.
  • All production files are byte-identical to the previously validated feat: add on-demand models with shared LoRA and exclusive training #312 head 18b9f910; this update changes PR ownership and test placement, adding two CPU reset-contract cases. Previous PPU results are retained for the unchanged execution/probe/config scope; no new hardware run is claimed.
  • Limits: pool Full-checkpoint replacement uses two base-weight path aliases; trained optimizer recovery is covered separately by the backend matrices. The FSDP probe uses a small linear model and does not establish full Qwen FSDP training. PPU/4B results do not establish capacity or throughput for other hardware or larger models.

@Yunnglin
Yunnglin marked this pull request as draft October 14, 2026 00:40
@Yunnglin Yunnglin changed the title feat: 支持小模型按需加载、共享 LoRA 与独占训练 feat: add on-demand models with shared LoRA and exclusive training Oct 14, 2026
@Yunnglin
Yunnglin force-pushed the feat/on-demand-training branch from 7f1cbc1 to 4d8888b Compare October 14, 2026 06:38
@Yunnglin
Yunnglin changed the base branch from main to fix/training-state-restoration October 14, 2026 06:44
@Yunnglin
Yunnglin force-pushed the feat/on-demand-training branch from 4d8888b to 87fd772 Compare October 14, 2026 06:57
Preserve legacy expiration semantics, isolate user initialization failures, and keep recovery nonblocking. Bound retry receipts and reconcile lost completion notifications.
@Yunnglin
Yunnglin force-pushed the feat/on-demand-training branch from 87fd772 to dd96d85 Compare October 15, 2026 02:43
@Yunnglin
Yunnglin changed the base branch from fix/training-state-restoration to main October 15, 2026 02:43
- Split runtime allocation from deployment so the controller persists
  ownership before any worker starts; the driver no longer writes records.
- Make cleanup, close and failure transitions persist-before-mutate, track
  failed instances for sweep retries, fence admission, and exclude failed
  residents when rebuilding minimum replicas.
- Never lose a worker wake-up when enqueue callbacks or queued-status
  writes fail; log background job failures with tracebacks.
- Return 503/Server while the controller is not ready; drop unreleased
  reason codes; reset resident training state before model-id branching.
- Move generic device allocation to server/resources, managed runtime to
  server/model, training records/store to server/state, TaskQueueConfig to
  server/config, and shared proxy/env propagation to the server root, with
  no compatibility re-exports.
- Encapsulate ServerState backend access and batch heartbeat reads outside
  the controller lock.
- Guard all server component dependencies with a strict grimp layer test.
- Require ray[serve]>=2.55 for async deployment constructors.
- Stop tracking local-only docs/design notes.
Fix optimizer metrics, wrapped parameter groups and safe Redis reconnects. Add lifecycle metrics, isolated Redis/GPU acceptance and stress coverage. Move shared probes into tests and untrack local tools.
Integrate 015732e while preserving controller-owned training creation and sequence ledgers. Adapt full-mode regression tests to the catalog/controller path. Verified 434 targeted tests and the complete pre-commit suite.
@Yunnglin
Yunnglin marked this pull request as draft October 23, 2026 08:49
@Yunnglin
Yunnglin marked this pull request as ready for review October 23, 2026 21:56
@Yunnglin
Yunnglin changed the base branch from main to fix/adapter-training-state October 26, 2026 03:48
@Yunnglin
Yunnglin changed the base branch from fix/adapter-training-state to main October 26, 2026 06:12
@Yunnglin
Yunnglin merged commit 6222663 into main Oct 26, 2026
3 of 4 checks passed
tastelikefeet added a commit that referenced this pull request Nov 28, 2026
main carried 17 commits (#311..#291) over merge-base 96dab68. v5 had already ported
everything up to #312 (a4ddc3b) and moved server/client to twinkle_cs, so:

- server/client (src/twinkle/server, twinkle_cs/*, tests/server, tests/twinkle_client):
  kept the v5 tree; the legacy src/twinkle/server path and the old ci_container_test.sh
  stay removed on v5.
- loss: #291 detached DFT weights, #335 Liger CE contract (delegates micro_batch_scale /
  batch_normalizer to CrossEntropyLoss), #334 chunked CE comments, #336 InfoNCE tests.
- model: #343 Torch.empty_cache (auto-merged), #385 fused_lm_rl ported onto the v5 task
  registry (processor/tasks.py + model/tasks.py FusedRL + transformers postprocess),
  #386 NPU fused CE fast path in selective_log_softmax.
- twinkle_agentic: #345 check kinds (hidden_python / sql_query / answer_one_of /
  answer_number / web_receipt / lean) adapted to the episode-scoped Env interface;
  AgenticChallenger gains the _verify_check / _proposal_reward hooks.

Known: cookbook/rsi and tests/cookbook/rsi (#345) are written against main's stateless
Env / AgenticChallenger API and do not run on v5 yet.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants