Skip to main content

LatentPort

LatentPort makes LLM internal states programmable.

Created by Simon P. Villani.

Capture a model's working context, transfer it to another model, compact its attention memory, combine two contexts, or save and branch the state for later use. Transfer and compaction operate directly on inference state. LPCombine continues one cache by replaying the other context.

The interface follows the operation. Select a supported bridge or model when loading; use the same methods to work with its state.

transferred = port.bridge.translate(state)
compacted = state.compact()
combined = state.combine(other, model=model)
branches = state.fork(2)
state.save("saved-state")

Translation and compaction each have their own compatibility requirements. The runtime checks them before proceeding; a shared interface does not make every model pair or sequence of operations compatible.

LatentPort: programmable model state

Website | Get started | Supported transformations | Cookbook | API

License: Apache-2.0 PyPI

State operations

Operation API Purpose
Capture model.capture(context) Read context and retain its complete inference state.
Transfer bridge.translate(state) Transform a source snapshot into the supported target model's state.
Compact state.compact() Reduce attention KV while preserving recurrent memory, convolution state and logical positions.
Combine model.combine(left, right) Continue one cache with the context represented by a second state.
Append model.append(state, text) Process new input from an existing state.
Fork state.fork(2) Create independent descendants of a shared immutable snapshot.
Save / load state.save(path) / lp.State.load(path) Persist and restore state without historical prompt prefill.

LPCombine profiles support ordered combination of two states from the same model and backend.

Combine two states

import latentport as lp

with lp.load_model("latentport/LPCombine-Qwen3.8-27b", backend="nf4") as model:
    left = model.prefill("Nora belongs to team X.\n")
    right = model.prefill("Team X uses the passcode cedar.\n")
    merged = model.combine(left, right)
    with model.session(merged) as session:
        print(session.ask("What is the passcode for Nora's team?").text)

combine() replays the right context after the left cache and returns a new state. Select a profile and use any of its supported backends. State snapshots made with prefill(), or with live(retain_replay=True), retain the tokens for replay.

LPCombine profile Retained-token replay Cache-only replay
Qwen3.8-27b BF16, NF4, GGUF NF4
Qwen3.5-4B BF16, NF4, GGUF BF16, NF4
Qwen3.5-9B BF16, NF4, GGUF BF16, NF4
Gemma-4-31B-it BF16, NF4, GGUF BF16
Qwen3-14B BF16, NF4, GGUF BF16
Qwen3.8-Flash-Next BF16, NF4, GGUF BF16

Use method="cache" to read tokens from a compatible right cache. GGUF uses the usual model_path= argument and native runtime. For a split GGUF checkpoint, keep the shards together and pass the path to a shard. Each profile card specifies which cache layouts it can read.

To combine saved states, run latentport combine LEFT RIGHT OUTPUT with the same model, backend and position settings used to capture them. Add --model-path PATH for local weights or a GGUF file. See LPCombine for compatibility and evaluation.

Get started

Install the lightweight package with Python 3.11 or later:

python -m pip install latentport
latentport doctor

Inference requires CUDA PyTorch and the appropriate backend dependencies. See installation for NF4, BF16 and GGUF setup. GGUF also requires a compatible LatentPort native library. Prebuilt libraries target specific GPU and CUDA configurations; check the guide before downloading models.

Set LATENTPORT_HOME to a directory with enough space for model downloads and caches. The runtime resolves pinned transformation artifacts and compatible base models. Model weights and transformation weights are separate downloads.

Transfer context

Choose bridge_repo from the supported transformations below. This workflow is the same for every supported bridge:

import latentport as lp

history = [("user", "The ticket is red.")]

with lp.load(bridge_repo, backend="nf4") as port:
    state = port.source.capture(history)
    transferred = port.bridge.translate(state)
    answer = port.target.session(transferred).ask("What color is the ticket?")
    print(answer.text)

The source reads the history, translate() creates target state, and the target processes the new question. Changing the bridge repository selects the model pair and trained transformation. It does not change the operation or require manual token slicing. port.handoff() remains an advanced interface for callers that already own an exact target-token suffix.

Use backend="nf4", "bf16" or "gguf" where the selected bridge supports it. Existing base files can be supplied with source_path and target_path. Thinking mode, transfer boundaries and tokenizer compatibility are properties of the selected checkpoint; see its model card and the API contracts.

Conversations

The composite session manages transfer and continuation with the same calls:

with lp.load(bridge_repo, backend="nf4") as port:
    chat = port.composite.session(history)
    answer = chat.ask("What color is the ticket?")
    print(answer.text, end="")
    while not answer.finished:
        answer = chat.generate()
        print(answer.text, end="")
    print()
    print(chat.ask("What evidence supports that answer?").text)

The default cached_handoff policy transfers the initial context once and keeps the target's state for follow-ups. The runtime selects the checkpoint's supported transfer boundary. Some bridges require the target to read the new question; others can transfer its prepared answer state. Neither route replays historical context on the target. A prefix-only bridge with no initial history runs the new question directly on the target because there is no context to transfer.

policy="strict" synchronizes completed answers back to the source and transfers again on subsequent turns. See the cookbook for streaming, answer continuation, branching and MTP requirements.

The same command accepts any supported bridge repository:

python examples/chat.py --repo BRIDGE_REPOSITORY --backend nf4 --context "The ticket is red." --prompt "What color is the ticket?"

Replace BRIDGE_REPOSITORY with a repository from the table below. Use --followup for another turn, or --backend gguf for a compatible native profile.

Compact context

Choose a supported model_id from the table below. The runtime selects the matching learned compaction weights from the state's identity:

with lp.load_model(model_id, backend="nf4") as model:
    state = model.prefill(history)
    compacted = state.compact()
    answer = model.session(compacted).ask("Continue the task.")
    print(answer.text)

The default policy retains one eighth of attention KV at or above 65,536 retained positions. Shorter histories return unchanged unless force=True is supplied. Use ratio=4 for a larger retained budget. Compaction preserves the logical clock and original positions; it does not replace context with a text summary.

For a running session, session.compact(reserve_tokens=...) can make room for an upcoming request within the configured physical capacity. Compaction reduces KV storage, not model-weight memory. See the compaction guide for context sizing, extended positions, backend options and validation receipts.

Reuse, branch and resume

review_state, planning_state = state.fork(2)
state.save("saved-state")
restored = lp.State.load("saved-state")

Prepare context once for several agents, retain a checkpoint before a risky step, or resume a saved session. Snapshots record exact model and runtime identities. Forks share immutable storage; advancing a branch requires its own working state. Snapshots contain prompt-derived tensors and conversation text, so protect them like the original conversation. See persistence and ownership.

Supported transformations

One Python runtime serves the following trained artifacts. This is the current support catalog, not a separate API for each checkpoint.

Operation Supported models Selection
Transfer Qwen3.5-4B to Qwen3.5-9B latentport/LPBridge-Qwen3.5-4b-Qwen3.5-9b as bridge_repo
Transfer Qwen3.5-4B to Qwen3.8-27B latentport/LPBridge-Qwen3.5-4b-Qwen3.8-27b as bridge_repo
Compact Qwen3.5-4B Qwen/Qwen3.5-4B as model_id; selector
Compact Qwen3.5-9B Qwen/Qwen3.5-9B as model_id; selector
Compact Qwen3.8-27B Qwen/Qwen3.8-27B as model_id; selector
Compact Qwen3.8-Flash-Next Qwen/Qwen3.8-Flash-Next as model_id; selector
Compact Gemma 4 31B IT google/gemma-4-31B-it as model_id; selector
Compact Qwen3-14B Qwen/Qwen3-14B as model_id; selector

Each bridge is directional and tied to exact checkpoints. Current bridges require dense source state with complete alignment metadata; compacted and suffix-only source states cannot be transferred. Supported quantizations and execution modes are declared per artifact. An unsupported combination fails explicitly.

Validation and performance

Published measurements describe specific checkpoints, hardware and workloads:

  • At 128K context, 8x compaction reduced attention KV from 4 GiB to 512 MiB on Qwen3.5-4B/9B and from 8 GiB to 1 GiB on Qwen3.8-27B. See compaction results and backend validation for exact configurations.
  • Historical resident transfer measurements reported 2.19x paired initial time-to-first-token speedup at approximately 16K tokens. This is not a general throughput claim or a benchmark for every bridge. See methodology and transfer results.

State copies, model loading, backend scheduling and retained branches affect memory and latency. GPU qualification and CPU contract tests cover different parts of the runtime; consult the records for the profile you intend to use.

Demos and documentation

Report reproducible issues at GitHub Issues. Include python -m latentport doctor, exact model identities and a minimal example with private prompts and credentials removed.

Project

Created by Simon P. Villani, LatentPort is an independent AI research project. It began with LatentPort: Beyond KV Cache, published in September 2026, and now includes learned transfer, compaction and state lifecycle operations. Learned optimisation, combination and automatic policy selection are the next stages of the project.

Original research code | Transformation models | Python package

License

The LatentPort runtime and transformation weights are Apache-2.0. Base models retain their upstream licenses, and llama.cpp retains its MIT license. See LICENSE and the notices supplied with model and native downloads.

Metadata

Release files for latentport 0.4.10

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for latentport 0.4.10
File Size Uploaded Provenance Actions
latentport-0.4.10.tar.gz 6.8 MB Without provenance Details for latentport-0.4.10.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for latentport 0.4.10
File Interpreter ABI Platform Actions
latentport-0.4.10-py3-none-any.whl Python 3 none any Details for latentport-0.4.10-py3-none-any.whl

Total release size: 7.8 MB

Release files / latentport-0.4.10.tar.gz

Download URL latentport-0.4.10.tar.gz
Size 6.8 MB
Tags Source
SHA-256 checksum
How to use checksums
34b16cacd4262a608329dd6b6c4f0dce6de8942a6e7cb70e80af2f9d6e2c7eb8
BLAKE2b-256 checksum
How to use checksums
cfd43ab8d2dd95e9d3be551608281b142c3bafd4db161a03f4effeb578af73d2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Release files / latentport-0.4.10-py3-none-any.whl

Download URL latentport-0.4.10-py3-none-any.whl
Size 1.0 MB
Tags Python 3
SHA-256 checksum
How to use checksums
9e8ea4d4180b9ce9e6190d7ad747090ec192ad0e58df1f186f4e3a7e0224cb56
BLAKE2b-256 checksum
How to use checksums
7325c7231ec8e6858959643201a327951da6cbdadd77ff622e1c244e9d2937a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Security for latentport 0.4.10

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page