Runtime¶
Runtime archive, deduplication, caching, and scheduling.
- class nlp_shap.runtime.CoalitionDedupRegistry[source]¶
Bases:
objectTrack coalition keys that already required backend execution.
- class nlp_shap.runtime.CoalitionJob(coalition_key: str, snapshot_id: str, snapshot: ConversationSnapshot, absence_policy: str, mask_words: bytes, mask_n_bits: int, model_id: str, utility: float, prefix_hash: str = '')[source]¶
Bases:
objectOne coalition evaluation request routed through the scheduler.
- snapshot: ConversationSnapshot¶
Conversation snapshot passed to the backend for generation.
- class nlp_shap.runtime.CoalitionProgress(*args, **kwargs)[source]¶
Bases:
ProtocolSync hooks notified as coalition jobs are planned and finished.
- class nlp_shap.runtime.CoalitionRecord(record_id: int, snapshot_id: str, coalition_key: str, mask: PackedMask, absence_policy: str, model_id: str, generation_text: str, utility: float, elapsed_ms: float, cache_hit: bool)[source]¶
Bases:
objectOne persisted coalition evaluation row.
- mask: PackedMask¶
Packed coalition mask bytes and original bit length.
- class nlp_shap.runtime.CoalitionRecordDraft(snapshot_id: str, coalition_key: str, mask: PackedMask, absence_policy: str, model_id: str, generation_text: str, utility: float, elapsed_ms: float, cache_hit: bool)[source]¶
Bases:
objectInput payload used when appending a coalition record.
- mask: PackedMask¶
Packed coalition mask bytes and original bit length.
- class nlp_shap.runtime.HotResultStore(maxsize: int | None = 128, _values: OrderedDict[str, str]=<factory>)[source]¶
Bases:
objectIn-memory LRU store for recently generated coalition outputs.
- class nlp_shap.runtime.InMemoryObservabilitySink(spans: list[SpanRecord] = <factory>)[source]¶
Bases:
objectCollect span records in memory for tests and diagnostics.
- spans: list[SpanRecord]¶
- class nlp_shap.runtime.InferenceScheduler(max_inflight: int, generation: GenerationConfig, store: HotResultStore, dedup: CoalitionDedupRegistry | None = None, archive: RunArchive | None = None, pending_limit: int | None = None, progress: CoalitionProgress | None = None)[source]¶
Bases:
objectExecute coalition jobs with bounded concurrency and optional deduplication.
- async run(jobs: Sequence[CoalitionJob], generate: Callable[[ConversationSnapshot], Awaitable[str]]) SchedulerMetrics[source]¶
Execute coalition jobs and return scheduler counters.
- async run_iter(jobs: Iterable[CoalitionJob], generate: Callable[[ConversationSnapshot], Awaitable[str]], total: int | None = None) SchedulerMetrics[source]¶
Execute jobs from an iterable without creating all coroutines upfront.
- async run_stream(jobs: AsyncIterator[CoalitionJob], generate: Callable[[ConversationSnapshot], Awaitable[str]]) SchedulerMetrics[source]¶
Execute jobs from an async iterator with bounded pending tasks.
- class nlp_shap.runtime.NullCoalitionProgress[source]¶
Bases:
objectNo-op progress sink used when callers omit a progress callback.
- class nlp_shap.runtime.NullObservabilitySink[source]¶
Bases:
objectNo-op observability sink used when telemetry is disabled.
- class nlp_shap.runtime.ObservabilitySink(*args, **kwargs)[source]¶
Bases:
ProtocolProtocol for recording explain pipeline stage spans.
- class nlp_shap.runtime.PerfSummary(total_ms: float, generation_ms: float, scoring_ms: float, aggregation_ms: float)[source]¶
Bases:
objectWall-clock breakdown for one explain or reanalyze run.
- class nlp_shap.runtime.PrefixCacheManager[source]¶
Bases:
objectStore and reuse transformer
past_key_valuesfor shared prefixes.- get_prefix(token_ids: Sequence[int]) tuple[Any | None, int][source]¶
Return cached KV state and the longest matching prefix length.
- lookup(token_ids: Sequence[int]) tuple[Any | None, int][source]¶
Return cached KV state and update hit or miss counters.
- get_at_length(token_ids: Sequence[int], length: int) Any | None[source]¶
Return cached KV state for an exact prefix length.
- class nlp_shap.runtime.RunArchive(root: Path, manifest: RunManifest, flush_every: int = 50)[source]¶
Bases:
objectPersist coalition records to SQLite with generation text stored as blobs.
- classmethod open(root: Path, manifest: RunManifest, flush_every: int = 50) Self[source]¶
Create a run archive directory and open its SQLite database.
- classmethod load(root: Path) Self[source]¶
Open an existing run archive without rewriting its manifest.
- write_base_generation(text: str) None[source]¶
Persist the grand-coalition reference generation before coalition rows.
- append(draft: CoalitionRecordDraft) int[source]¶
Append one coalition record and return its archive identifier.
- history_lazy() Iterator[CoalitionRecord][source]¶
Iterate coalition records one row at a time without bulk preloading.
- class nlp_shap.runtime.SchedulerMetrics(requested: int, executed: int, deduplicated: int, cache_hits: int, kv_cache_hits: int = 0)[source]¶
Bases:
objectCounters collected while executing coalition jobs.
- class nlp_shap.runtime.SpanRecord(name: str, duration_ms: float)[source]¶
Bases:
objectOne completed pipeline stage span.
- nlp_shap.runtime.build_coalition_key(snapshot_id: str, player_ids: tuple[str, ...], mask_present: tuple[bool, ...], absence_policy: str, model_id: str, generation: GenerationConfig) str[source]¶
Build a stable SHA256 coalition key for deduplication.
- nlp_shap.runtime.build_snapshot_prefix_hash(snapshot: ConversationSnapshot) str[source]¶
Hash the shared text prefix excluding the final whitespace token.
- nlp_shap.runtime.dedup_enabled(config: DedupConfig, generation: GenerationConfig) bool[source]¶
Return whether coalition deduplication should be active.
- nlp_shap.runtime.group_jobs_for_prefix_cache(jobs: list[T], *, key: Callable[[T], str]) list[T][source]¶
Sort jobs so coalitions with the same prefix hash run adjacently.
SQLite-backed run archive for coalition evaluation history.
- nlp_shap.runtime.archive.BASE_GENERATION_FILE = 'base_generation.txt'¶
Filename for the grand-coalition reference generation at the archive root.
- class nlp_shap.runtime.archive.CoalitionRecord(record_id: int, snapshot_id: str, coalition_key: str, mask: PackedMask, absence_policy: str, model_id: str, generation_text: str, utility: float, elapsed_ms: float, cache_hit: bool)[source]¶
Bases:
objectOne persisted coalition evaluation row.
- mask: PackedMask¶
Packed coalition mask bytes and original bit length.
- class nlp_shap.runtime.archive.CoalitionRecordDraft(snapshot_id: str, coalition_key: str, mask: PackedMask, absence_policy: str, model_id: str, generation_text: str, utility: float, elapsed_ms: float, cache_hit: bool)[source]¶
Bases:
objectInput payload used when appending a coalition record.
- mask: PackedMask¶
Packed coalition mask bytes and original bit length.
- class nlp_shap.runtime.archive.RunArchive(root: Path, manifest: RunManifest, flush_every: int = 50)[source]¶
Bases:
objectPersist coalition records to SQLite with generation text stored as blobs.
- classmethod open(root: Path, manifest: RunManifest, flush_every: int = 50) Self[source]¶
Create a run archive directory and open its SQLite database.
- classmethod load(root: Path) Self[source]¶
Open an existing run archive without rewriting its manifest.
- write_base_generation(text: str) None[source]¶
Persist the grand-coalition reference generation before coalition rows.
- append(draft: CoalitionRecordDraft) int[source]¶
Append one coalition record and return its archive identifier.
- history_lazy() Iterator[CoalitionRecord][source]¶
Iterate coalition records one row at a time without bulk preloading.
Coalition deduplication keys and registry.
- nlp_shap.runtime.dedup.dedup_enabled(config: DedupConfig, generation: GenerationConfig) bool[source]¶
Return whether coalition deduplication should be active.
- nlp_shap.runtime.dedup.build_coalition_key(snapshot_id: str, player_ids: tuple[str, ...], mask_present: tuple[bool, ...], absence_policy: str, model_id: str, generation: GenerationConfig) str[source]¶
Build a stable SHA256 coalition key for deduplication.
- class nlp_shap.runtime.dedup.CoalitionDedupRegistry[source]¶
Bases:
objectTrack coalition keys that already required backend execution.
Hot LRU cache for coalition generation results.
- class nlp_shap.runtime.store.HotResultStore(maxsize: int | None = 128, _values: OrderedDict[str, str]=<factory>)[source]¶
Bases:
objectIn-memory LRU store for recently generated coalition outputs.
Async coalition inference scheduling with deduplication.
- nlp_shap.runtime.scheduler.GenerateFn¶
Async callable that returns generated text for one snapshot.
alias of
Callable[[ConversationSnapshot],Awaitable[str]]
- class nlp_shap.runtime.scheduler.SchedulerMetrics(requested: int, executed: int, deduplicated: int, cache_hits: int, kv_cache_hits: int = 0)[source]¶
Bases:
objectCounters collected while executing coalition jobs.
- class nlp_shap.runtime.scheduler.CoalitionJob(coalition_key: str, snapshot_id: str, snapshot: ConversationSnapshot, absence_policy: str, mask_words: bytes, mask_n_bits: int, model_id: str, utility: float, prefix_hash: str = '')[source]¶
Bases:
objectOne coalition evaluation request routed through the scheduler.
- snapshot: ConversationSnapshot¶
Conversation snapshot passed to the backend for generation.
- class nlp_shap.runtime.scheduler.InferenceScheduler(max_inflight: int, generation: GenerationConfig, store: HotResultStore, dedup: CoalitionDedupRegistry | None = None, archive: RunArchive | None = None, pending_limit: int | None = None, progress: CoalitionProgress | None = None)[source]¶
Bases:
objectExecute coalition jobs with bounded concurrency and optional deduplication.
- async run(jobs: Sequence[CoalitionJob], generate: Callable[[ConversationSnapshot], Awaitable[str]]) SchedulerMetrics[source]¶
Execute coalition jobs and return scheduler counters.
- async run_iter(jobs: Iterable[CoalitionJob], generate: Callable[[ConversationSnapshot], Awaitable[str]], total: int | None = None) SchedulerMetrics[source]¶
Execute jobs from an iterable without creating all coroutines upfront.
- async run_stream(jobs: AsyncIterator[CoalitionJob], generate: Callable[[ConversationSnapshot], Awaitable[str]]) SchedulerMetrics[source]¶
Execute jobs from an async iterator with bounded pending tasks.
Optional synchronous progress callbacks for coalition execution.
- class nlp_shap.runtime.progress.CoalitionProgress(*args, **kwargs)[source]¶
Bases:
ProtocolSync hooks notified as coalition jobs are planned and finished.