Entropic 2.11.1
Local-first agentic inference engine
Loading...
Searching...
No Matches
orchestrator.h
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
23#pragma once
24
34
35#include <chrono>
36#include <functional>
37#include <memory>
38#include <mutex>
39#include <string>
40#include <unordered_map>
41#include <unordered_set>
42#include <vector>
43
44struct llama_context; // Forward declaration for adapter management
45struct llama_model; // Forward declaration for speculative compat (v2.1.11)
46
47namespace entropic {
48
54 std::string tier_name;
55 std::string previous_tier;
56 std::string model_raw;
57 std::string swap_action = "none";
58 double routing_ms = 0.0;
59 std::string adapter_name;
60 double adapter_swap_ms = 0.0;
61};
62
75 std::optional<float> temperature;
76 std::optional<int> max_output_tokens;
77 std::optional<float> top_p;
78 std::optional<int> top_k;
79 std::optional<float> min_p;
80 std::optional<float> presence_penalty;
81 std::optional<float> frequency_penalty;
82 std::optional<float> repeat_penalty;
83 std::optional<bool> enable_thinking;
84 std::optional<std::string> tool_call_mode;
85};
86
100ENTROPIC_EXPORT void apply_tier_sampler_overrides(
101 GenerationParams& params,
102 const TierSamplerOverrides& ov);
103
113public:
120 bool initialize(const ParsedConfig& config);
121
126 void shutdown();
127
151
152 /* ── Generation ──────────────────────────────────────── */
153
163 const std::vector<Message>& messages,
164 const GenerationParams& params,
165 const std::string& tier_name = "");
166
177 const std::vector<Message>& messages,
178 const GenerationParams& params,
179 std::atomic<bool>& cancel,
180 const std::string& tier_name = "");
181
199 std::vector<GenerationResult> generate_batch(
200 const std::vector<std::vector<Message>>& messages_list,
201 const std::vector<GenerationParams>& params_list,
202 const std::vector<std::string>& tiers,
203 std::atomic<bool>& cancel);
204
210 const std::vector<Message>& messages,
211 const GenerationParams& params,
212 std::function<void(std::string_view)> on_token,
213 std::atomic<bool>& cancel,
214 const std::string& tier_name = "");
215
216 /* ── Routing ─────────────────────────────────────────── */
217
224 std::string route(const std::vector<Message>& messages);
225
226 /* ── Queries ─────────────────────────────────────────── */
227
233
238 std::string last_used_tier() const;
239
244 std::vector<std::string> loaded_models() const;
245
250 std::vector<std::string> available_models() const;
251
256 bool can_handoff(const std::string& from, const std::string& to) const;
257
262 ChatAdapter* get_adapter(const std::string& tier_name) const;
263
270 InferenceBackend* get_backend(const std::string& tier_name) const;
271
278 AdapterManager& adapter_manager() { return lora_manager_; }
279
286 GrammarRegistry& grammar_registry() { return grammar_registry_; }
287
294 ProfileRegistry& profile_registry() { return profile_registry_; }
295
302 ThroughputTracker& throughput_tracker() { return throughput_tracker_; }
303
310 size_t load_grammars_from(const std::filesystem::path& grammar_dir);
311
323
337 bool has_vision_capable_tier() const;
338
345 bool compatible = false;
346 std::string diagnostic;
347 };
348
366
380 void set_speculative_enabled(bool enabled) {
381 config_.inference.speculative.enabled = enabled;
382 }
383
384 /* ── VRAM-aware tier residency (v2.2.4, gh#57) ────────── */
385
392 enum class ResidencyEvent : int {
393 Loaded = 0,
394 Evicted = 1,
395 ActivationSwap = 2,
396 };
397
412 using ResidencyObserverFn = std::function<void(
413 ResidencyEvent event,
414 const std::string& tier_name,
415 const std::string& model_path,
416 size_t footprint)>;
417
428
440 std::string residency_snapshot_json() const;
441
453 size_t vram_budget_bytes() const { return vram_budget_bytes_; }
454
466 size_t tier_footprint_bytes(const std::string& tier_name) const;
467
479 entropic_error_t last_residency_error() const { return last_residency_error_; }
480
486 void clear_last_residency_error() { last_residency_error_ = ENTROPIC_OK; }
487
503 std::string select_vision_tier() const;
504
524 const std::string& tier_name) {
525 apply_tier_sampler_defaults(params, tier_name);
526 }
527
528private:
529 /* ── Model pool (one backend per unique path) ────────── */
530 std::unordered_map<std::string, std::shared_ptr<InferenceBackend>> model_pool_;
531
532 /* ── Tier → backend mapping (many-to-one) ────────────── */
533 std::unordered_map<std::string, std::shared_ptr<InferenceBackend>> tiers_;
534
535 /* ── Per-tier adapters (one-to-one, identity-specific) ── */
536 std::unordered_map<std::string, std::unique_ptr<ChatAdapter>> adapters_;
537
538 /* ── Secondary models (router, draft, future thinking) ── */
549 SecondaryModelLoader secondary_loader_;
550
551 /* ── Routing state ───────────────────────────────────── */
552 std::unordered_map<std::string, std::string> tier_map_;
553 std::unordered_map<std::string, std::unordered_set<std::string>> handoff_rules_;
554 std::string default_tier_;
555 std::string loaded_main_tier_;
556 RoutingResult last_routing_result_;
557 std::vector<std::string> tier_history_;
558
559 mutable std::mutex swap_mutex_;
560
561 ParsedConfig config_;
562
563 /* ── Residency tracking (v2.2.4, gh#57) ──────────────── */
564
574 mutable std::unordered_map<std::string, size_t> tier_footprint_bytes_;
575
582 std::unordered_map<std::string, long long> tier_last_activation_ms_;
583
588 std::chrono::steady_clock::time_point start_time_{std::chrono::steady_clock::now()};
589
599 size_t vram_budget_bytes_{0};
600
605 ResidencyObserverFn residency_observer_;
606
611 entropic_error_t last_residency_error_{ENTROPIC_OK};
612
633 size_t estimate_footprint_bytes(const std::string& tier_name) const;
634
643 void log_fit_recommendation(const std::string& tier_name) const;
644
669 static size_t resolve_vram_budget_bytes();
670
681 void fire_residency_observer(
682 ResidencyEvent event,
683 const std::string& tier_name,
684 const std::string& model_path,
685 size_t footprint);
686
687 /* ── LoRA adapter management (v1.9.2) ────────────────── */
688 AdapterManager lora_manager_;
689
690 /* ── Grammar registry (v1.9.3) ────────────────────────── */
691 GrammarRegistry grammar_registry_;
692
693 /* ── Profile registry (v2.0.0) ───────────────────────── */
694 ProfileRegistry profile_registry_;
695
696 /* ── Throughput tracker (v2.0.0) ─────────────────────── */
697 ThroughputTracker throughput_tracker_;
698
699 /* ── Internal ────────────────────────────────────────── */
700
705 InferenceBackend* get_model(const std::string& tier_name);
706
714 void record_activation_reuse(const std::string& tier_name);
715
723 bool residency_admits(const std::string& tier_name);
724
731 InferenceBackend* activate_and_track(
732 const std::string& tier_name,
733 const std::shared_ptr<InferenceBackend>& backend);
734
742 GenerationResult build_no_model_error(const std::string& tier_name);
743
748 void deactivate_current_if_needed(InferenceBackend* incoming);
749
762 void ensure_tier_lora(const std::string& tier_name,
763 InferenceBackend* result);
764
775 void unload_or_warm_current(InferenceBackend* current);
776
781 std::pair<std::string, std::string> classify_task(
782 const std::vector<Message>& messages);
783
790 bool deactivate_if_active(llama_context* ctx);
791
803 double ensure_adapter_for_tier(
804 const std::string& tier_name, llama_context* ctx);
805
810 void preload_adapters();
811
819 bool create_tier_backends(const ParsedConfig& config);
820
827 void build_routing_tables(const ParsedConfig& config);
828
836 bool activate_default_tier(const ParsedConfig& config);
837
844 void activate_router(const ParsedConfig& config);
845
861 void activate_draft(const ParsedConfig& config);
862
867 void load_bundled_grammars();
868
875 void resolve_grammar_key(GenerationParams& params,
876 const std::string& tier_name);
877
890 void apply_tier_sampler_defaults(GenerationParams& params,
891 const std::string& tier_name);
892
908 GenerationParams resolve_and_stage(InferenceBackend* model,
909 const GenerationParams& params,
910 const std::string& tier_name);
911
922 std::string resolve_speculative_pair(
923 llama_model*& target_out, llama_model*& draft_out) const;
924
934 bool try_speculative_route(
935 InferenceBackend* model,
936 const std::vector<Message>& messages,
937 const GenerationParams& params,
938 const std::string& tier_name,
939 GenerationResult& result);
940
951 GenerationResult run_generate_dispatch(
952 InferenceBackend* model,
953 const std::vector<Message>& messages,
954 const GenerationParams& params,
955 const std::string& tier_name);
956
966 bool try_speculative_route_streaming(
967 InferenceBackend* model,
968 const std::vector<Message>& messages,
969 const GenerationParams& params,
970 const std::string& tier_name,
971 std::function<void(std::string_view)> on_token,
972 std::atomic<bool>& cancel,
973 GenerationResult& result);
974
985 bool try_mtp_route(
986 InferenceBackend* model,
987 const std::vector<Message>& messages,
988 const GenerationParams& params,
989 std::function<void(std::string_view)> on_token,
990 std::atomic<bool>& cancel,
991 GenerationResult& result);
992
1002 bool resolve_mtp_effective(const std::string& tier_name) const;
1003};
1004
1005} // namespace entropic
ChatAdapter concrete base class.
AdapterManager — LoRA adapter lifecycle and hot-swap.
LoRA adapter lifecycle manager.
Concrete base class for chat format adapters (80% logic).
Centralized grammar registry for named GBNF grammars.
Concrete base class for inference backends (80% logic).
Definition backend.h:69
Multi-model lifecycle and routing orchestrator.
size_t vram_budget_bytes() const
Engine-tracked VRAM budget in bytes (0 = unknown).
SpeculativeCompatInfo check_speculative_compat() const
Check whether the currently-configured target/draft pair is compatible for speculative decoding.
std::vector< std::string > available_models() const
All configured tier names.
size_t load_grammars_from(const std::filesystem::path &grammar_dir)
Load grammars from an explicit directory path.
GrammarRegistry & grammar_registry()
Access the grammar registry.
GenerationResult generate_streaming(const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view)> on_token, std::atomic< bool > &cancel, const std::string &tier_name="")
Streaming generation.
void apply_tier_sampler_defaults_for_test(GenerationParams &params, const std::string &tier_name)
Test-only forwarder to the private per-tier sampler default application (gh#94, audit task #71).
std::vector< std::string > loaded_models() const
Currently loaded model tier names.
bool initialize(const ParsedConfig &config)
Initialize from parsed config.
bool has_vision_capable_tier() const
Return true if any configured tier declares the "vision" capability (gh#41, v2.1.8).
size_t tier_footprint_bytes(const std::string &tier_name) const
Estimated VRAM footprint for a given tier in bytes.
AdapterManager & adapter_manager()
Access the LoRA adapter manager.
void shutdown()
Shutdown — unload all models.
RoutingResult last_routing_result() const
Last routing result.
std::function< void(ResidencyEvent event, const std::string &tier_name, const std::string &model_path, size_t footprint)> ResidencyObserverFn
Residency observer callback type (internal C++ form).
GenerationResult generate(const std::vector< Message > &messages, const GenerationParams &params, const std::string &tier_name="")
Generate using routed or explicit tier.
void clear_last_residency_error()
Clear last_residency_error().
void clear_all_prompt_caches()
Invalidate prompt/KV caches across every pooled backend.
entropic_error_t last_residency_error() const
Last residency-related error code, or ENTROPIC_OK if none.
std::string route(const std::vector< Message > &messages)
Route to tier using router model.
ChatAdapter * get_adapter(const std::string &tier_name) const
Get adapter for a tier.
void set_residency_observer(ResidencyObserverFn cb)
Register a residency observer.
std::string last_used_tier() const
Last used tier name.
~ModelOrchestrator()
Destructor — invokes shutdown() and AdapterManager::unload_all().
std::vector< GenerationResult > generate_batch(const std::vector< std::vector< Message > > &messages_list, const std::vector< GenerationParams > &params_list, const std::vector< std::string > &tiers, std::atomic< bool > &cancel)
Same-prefix batch generation on a shared resident model (gh#98).
std::string select_vision_tier() const
Pick the canonical vision-capable tier name (gh#41).
ProfileRegistry & profile_registry()
Access the GPU resource profile registry.
ThroughputTracker & throughput_tracker()
Access the throughput tracker.
void set_speculative_enabled(bool enabled)
Runtime toggle for the speculative-decoding path.
bool can_handoff(const std::string &from, const std::string &to) const
Check if handoff is permitted.
std::string residency_snapshot_json() const
Serialize the current residency set as a JSON string.
ResidencyEvent
Residency observer event codes — mirror the C ABI enum entropic_residency_event_t exactly (LOADED=0,...
InferenceBackend * get_backend(const std::string &tier_name) const
Get the inference backend for a tier (for evaluation APIs).
Centralized registry for named GPU resource profiles.
Role-keyed lifecycle manager for non-primary models.
EWMA-based throughput tracker for generation budgeting.
Configuration structs with defaults.
Error types for cross-.so error reporting.
entropic_error_t
Error codes returned by all C API functions.
Definition error.h:37
@ ENTROPIC_OK
Success.
Definition error.h:38
GrammarRegistry — named grammar management and validation.
InferenceBackend concrete base class.
Activate model on GPU (WARM → ACTIVE).
ENTROPIC_EXPORT void apply_tier_sampler_overrides(GenerationParams &params, const TierSamplerOverrides &ov)
Apply per-tier sampler overrides to params.
ProfileRegistry – named GPU resource profile management.
Unified lifecycle for non-primary inference backends.
Generation parameters for a single inference call.
Definition config.h:313
Result of a single generation call.
SpeculativeConfig speculative
Speculative decoding (gh#36)
Definition config.h:974
Result of a speculative-decoding compatibility check.
bool compatible
true when speculative may proceed
std::string diagnostic
Reason on failure (empty on ok)
Full parsed configuration.
Definition config.h:985
InferenceConfig inference
Inference-side knobs (currently speculative decoding only).
Definition config.h:1051
Result metadata from a routing decision.
std::string adapter_name
Active adapter (empty = base model) (v1.9.2)
double routing_ms
Total routing time.
std::string model_raw
Raw model output (e.g. "2")
std::string tier_name
Selected tier.
std::string swap_action
"none", "reused", "loaded"
std::string previous_tier
Previous tier (empty if first)
double adapter_swap_ms
Adapter swap latency (v1.9.2)
bool enabled
Master switch (off by default)
Definition config.h:933
Per-tier sampler overrides parsed from identity frontmatter.
std::optional< float > top_p
gh#85
std::optional< float > temperature
gh#82
std::optional< float > min_p
gh#85
std::optional< float > presence_penalty
gh#85
std::optional< std::string > tool_call_mode
gh#103
std::optional< float > frequency_penalty
gh#85
std::optional< int > top_k
gh#85
std::optional< bool > enable_thinking
gh#86
std::optional< float > repeat_penalty
gh#86
std::optional< int > max_output_tokens
gh#82
ThroughputTracker – real-time throughput measurement and prediction.