mellea.backends.adapters.adapter
Adapter classes for adding fine-tuned modules to inference backends.
The primary public surface is :func:AdapterMixin.resolve_adapter (find or lazily
register an adapter by capability name) and :meth:AdapterMixin._find_adapter
(look up a registered adapter). :class:AdapterMixin is mixed into backends that
support runtime adapter loading and unloading.
Adapter and LocalHFAdapter are the legacy adapter ABCs retained for
third-party backends; the composed Adapter dataclass in ._core is the
current adapter surface. get_adapter_for_intrinsic is deprecated; prefer
resolve_adapter.
Functions
FUNC get_adapter_for_intrinsic
get_adapter_for_intrinsic(intrinsic_name: str, intrinsic_adapter_types: list[AdapterType] | tuple[AdapterType, ...], available_adapters: dict[str, T]) -> T | None
Find an adapter from a dict of available adapters based on the adapter function name and its allowed adapter types.
Args:
intrinsic_name: The name of the adapter function, e.g."answerability".intrinsic_adapter_types: The adapter types allowed for this adapter function, e.g.[AdapterType.ALORA, AdapterType.LORA].available_adapters: The available adapters to choose from; mapsadapter.qualified_nameto the adapter object.
Returns:
- T | None: The first matching adapter found, or
Noneif no match exists.
FUNC validate_prompt_config
validate_prompt_config(config: dict) -> None
Raise if a prompt io.yaml config is not usable for a prompt fallback.
instruction is optional in the io.yaml schema but required for a prompt
fallback, which injects it at rewrite time.
Args:
config: The parsed prompt io.yaml mapping.name: The adapter function name, for the error message.source: Where the config came from (repo/slot/path), for the error message.
Raises:
ValueError:configlacks a non-emptyinstruction.
Classes
CLASS Adapter
An adapter that can be added to a single backend.
An adapter can only be registered with one backend at a time. Use
adapter.qualified_name when referencing the adapter after adding it.
Args:
name: Human-readable name of the adapter.adapter_type: Enum describing the adapter type (e.g.AdapterType.LORAorAdapterType.ALORA).
Attributes:
qualified_name: Unique name used for loading and lookup; formed as"<name>_<adapter_type.value>".backend: The backend this adapter has been added to, orNoneif not yet added.path: Filesystem path to the adapter weights; set when the adapter is added to a backend.
CLASS LocalHFAdapter
Abstract adapter subclass for locally loaded Hugging Face model backends.
Subclasses must implement get_local_hf_path to return the filesystem path
from which adapter weights should be loaded given a base model name.
Methods:
FUNC get_local_hf_path
get_local_hf_path(self, base_model_name: str) -> str
Return the local filesystem path from which adapter weights should be loaded.
Args:
base_model_name: The base model name; typically the last component of the Hugging Face model ID (e.g."granite-4.0-micro").
Returns:
- Filesystem path to the adapter weights directory.
CLASS AdapterMixin
Mixin class for backends capable of utilizing adapters.
Three verbs are universal across every adapter reality (LocalFile/PEFT,
Embedded/Granite Switch, ServerMediated): base_model_name,
add_adapter, and list_adapters. The remaining five verbs are
reality-specific; a concrete backend overrides only the verb(s) matching
its own reality; the others keep raising NotImplementedError.
Attributes:
base_model_name: The short model name used to identify adapter variants (e.g."granite-3.3-8b-instruct"for"ibm-granite/granite-3.3-8b-instruct").
Methods:
FUNC base_model_name
base_model_name(self) -> str
Return the short model name used for adapter variant lookup.
Returns:
- The base model name (e.g.
"granite-3.3-8b-instruct").
FUNC add_adapter
add_adapter(self, adapter: AdapterInput) -> None
Register an adapter with this backend so it can be loaded later.
The adapter must not already have been added to a different backend.
Concrete backends accept the full AdapterInput union but raise
TypeError for adapter realities they do not implement (e.g. a PEFT
backend rejects an embedded adapter), so a statically valid call may
still be rejected at runtime.
config is the raw io.yaml mapping for a composed Adapter/
_AdapterCore whose weights is an EmbeddedBinding or
ServerMediatedBinding. Those realities do not retain the raw
configuration required by the legacy rewriter, so it must be supplied
at registration rather than being fetched lazily like a
LocalFileBinding's io.yaml.
Args:
adapter: The adapter to register with this backend.config: Raw io.yaml config for a composedEmbeddedBindingorServerMediatedBindingadapter. Ignored (and rejected) for every other adapter reality.
Raises:
TypeError: Ifadapterbelongs to a reality this backend does not support, orconfigis given for a reality other than a composedEmbeddedBindingorServerMediatedBindingadapter.ValueError: Ifadapter.weightsis anEmbeddedBindingorServerMediatedBindingandconfigis not given — registering it without a config would make it discoverable but permanently unable to generate.
FUNC list_adapters
list_adapters(self) -> list[str]
Return the qualified names of all adapters registered with this backend.
Returns:
- list[str]: Qualified adapter names for all adapters that have been
registered via
add_adapter.
FUNC load_peft_adapter
load_peft_adapter(self, adapter_qualified_name: str) -> None
Load a previously registered PEFT adapter into the underlying model.
LocalFile/PEFT reality only (e.g. a locally hosted Hugging Face
model). The adapter must have been registered via add_adapter
before calling this method.
Args:
adapter_qualified_name: Theadapter.qualified_nameof the adapter to load.
Raises:
NotImplementedError: If this backend's adapter reality is not LocalFile/PEFT.
FUNC unload_peft_adapter
unload_peft_adapter(self, adapter_qualified_name: str) -> None
Unload a previously loaded PEFT adapter from the underlying model.
LocalFile/PEFT reality only (e.g. a locally hosted Hugging Face model).
Args:
adapter_qualified_name: Theadapter.qualified_nameof the adapter to unload.
Raises:
NotImplementedError: If this backend's adapter reality is not LocalFile/PEFT.
FUNC remove_adapter
remove_adapter(self, adapter_qualified_name: str) -> None
Deregister a previously added adapter, freeing its qualified name for reuse.
The inverse of add_adapter(). LocalFile/PEFT bindings call this from
LocalFileBinding.release() after unloading their weights. Embedded
backends use it to clear their registration and cached configuration;
their weights are already part of the served model, so there is no
unload step.
Args:
adapter_qualified_name: Theadapter.qualified_nameof the adapter to deregister.
Raises:
NotImplementedError: If this backend's adapter reality does not support deregistration.
FUNC activate_peft_adapter
activate_peft_adapter(self, adapter_qualified_name: str) -> None
Switch a previously loaded PEFT adapter on for subsequent generation.
LocalFile/PEFT reality only (e.g. a locally hosted Hugging Face
model). The adapter must have been loaded via load_peft_adapter
before calling this method.
Args:
adapter_qualified_name: Theadapter.qualified_nameof the adapter to activate.
Raises:
NotImplementedError: If this backend's adapter reality is not LocalFile/PEFT.
FUNC deactivate_peft_adapter
deactivate_peft_adapter(self, adapter_qualified_name: str) -> None
Switch off any active PEFT adapter so generation uses the base model.
LocalFile/PEFT reality only (e.g. a locally hosted Hugging Face model).
Args:
adapter_qualified_name: Theadapter.qualified_nameof the adapter to deactivate. Accepted for symmetry withactivate_peft_adapter; the underlying primitive clears all active PEFT adapters regardless of name.
Raises:
NotImplementedError: If this backend's adapter reality is not LocalFile/PEFT.
FUNC resolve_adapter
resolve_adapter(self, name: str) -> _AdapterCore
Find or lazily register an adapter by capability name.
Default implementation preserves Phase 0 behaviour, using the internal
_added_adapters dict that concrete backends maintain. Override in
Phase 2 (see epic #929) to implement proper lifecycle management.
Args:
name: Capability name (e.g."answerability").
Returns:
- The registered adapter with the given capability.
Raises:
ValueError: If the backend has no model ID, or (for a backend that supports composed adapters) if no trained adapter and no prompt fallback exists fornameon the backend's base model.KeyError: If the adapter cannot be found after registration.
FUNC adapter_scope
adapter_scope(self, adapter: '_AdapterCore | None')
Context manager wrapping adapter activation and deactivation.
A no-op when adapter is None. Otherwise: activates
adapter.weights, yields, then always deactivates; even if the with
body raises. Each phase fires ADAPTER_FUNCTION_PHASE_COMPLETE, and
ADAPTER_FUNCTION_INVOCATION_COMPLETE fires on the way out, carrying the
overall outcome.
This method fires hooks only; it does not open spans. Span production is a
plugin's job (see #1464 for the rule and #1466 for the adapter-function
spans), and the ADAPTER_FUNCTION_* family currently has no start hook for
a plugin to open a span on. Hook dispatch goes through
_run_async_in_thread (no timeout): the dispatching call blocks the
calling thread, but the hook coroutine itself runs on the shared
_EventLoopHandler event-loop thread. A subscriber that blocks on
something the dispatching thread is holding deadlocks rather than
merely stalls; e.g. on LocalHFBackend, an intrinsic caller holds
_generation_lock across the whole scope, so a subscriber that
re-enters any _generation_lock path blocks the event-loop thread
while its owner waits on that same event loop, and reentrance cannot
bridge the gap. Even without such re-entry, a slow or blocking-mode
ADAPTER_FUNCTION_* subscriber delays whatever holds this scope open.
deactivate() is guarded on activate()'s own side effect having
completed, not on the activate phase's hook dispatch also succeeding.
If a plugin subscribed to ADAPTER_FUNCTION_PHASE_COMPLETE raises after
activate() already flipped the adapter on, deactivate() still runs —
telemetry must not be able to strand the adapter active.
Not atomic across the whole scope by itself: _adapter_activation_lock()
is held only inside each of activate()/deactivate()'s own verb calls
(see LocalFileBinding.activate), not for the with body in between.
Two concurrent adapter_scope() calls on one backend can therefore
interleave; one thread's body can run while a different adapter is
active, activated by another thread's call; unless the caller closes
that gap itself. Widening this method's own lock to span the whole
scope was tried and reverted: it deadlocks the moment the body does
real async generation from the thread that opened the scope, because
that work runs on the shared event-loop thread while this thread holds
the lock; a same-thread RLock doesn't help across threads.
LocalHFBackend._generate_composed_local_file_with_adapter_scope is the
reference
example of a caller that does close the gap for its own call site: it
holds _generation_lock around the entire scope, which is safe there
only because the scope body is fully synchronous end to end and
does no async generation work on the event loop (its only loop
traffic during the scope is the hook dispatches described above —
one-way submissions, not re-entry into this backend); concurrent
invocations simply land on different threads and serialise on the
lock, rather than one thread holding it while another does async work
on the loop. A caller whose
body awaits work that re-enters generation on another thread must not
widen a lock this way; that reproduces the deadlock above.
A caller composing adapter_scope() with LocalHFBackend's standard
(non-intrinsic) generation path still silently ignores it: that path
(_generate_with_adapter_lock) always deactivates any adapter before
generating, so wrapping generate_from_context() in adapter_scope()
activates the adapter, generates against the base model anyway, then
deactivates. Pre-existing, not specific to the intrinsic path this
method now supports.
AdapterFunctionMetricsPlugin in
mellea/telemetry/metrics_plugins.py emits the adapter-function
metrics; their instruments and attributes are defined in
mellea/telemetry/metrics.py.
Args:
adapter: The adapter to activate, orNone(no-op).
Raises:
TypeError:adapter.weightsis not aWeightsBinding(e.g. anEmbeddedBinding, which has no activate()/deactivate() to scope; call itsapply_activation()directly instead).BaseException: An error raised by activation, thewithbody, or deactivation. If both the body and deactivation fail, the body error remains primary and the deactivation error is chained.