algo-cli-runtime 0.14.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- algo_cli/__init__.py +3 -0
- algo_cli/__main__.py +7 -0
- algo_cli/_internal/__init__.py +12 -0
- algo_cli/_internal/policy_chain.py +259 -0
- algo_cli/action_registry.py +1047 -0
- algo_cli/agent_blocks.py +550 -0
- algo_cli/agent_pipeline.py +1457 -0
- algo_cli/agent_threads.py +308 -0
- algo_cli/animations.py +316 -0
- algo_cli/cache_admission.py +209 -0
- algo_cli/capability_mask.py +66 -0
- algo_cli/chat_protocol.py +116 -0
- algo_cli/chatgpt_auth.py +510 -0
- algo_cli/chatgpt_client.py +657 -0
- algo_cli/code_rag.py +479 -0
- algo_cli/config.py +651 -0
- algo_cli/context_budget.py +679 -0
- algo_cli/credential_helpers.py +315 -0
- algo_cli/deliberation.py +29 -0
- algo_cli/display.py +1470 -0
- algo_cli/evals/__init__.py +21 -0
- algo_cli/evals/algorithm_effectiveness.py +560 -0
- algo_cli/evals/competitive_harness_rating.py +702 -0
- algo_cli/evals/cot_quality.py +220 -0
- algo_cli/evals/harness_retrieval_benchmark.py +401 -0
- algo_cli/evals/performance_regression.py +136 -0
- algo_cli/evals/scorecard_grading.py +308 -0
- algo_cli/evals/session_distribution.py +84 -0
- algo_cli/execution_guardrails.py +806 -0
- algo_cli/extensions_manifest.py +84 -0
- algo_cli/git_evidence.py +227 -0
- algo_cli/google_workspace.py +407 -0
- algo_cli/google_workspace_auth.py +523 -0
- algo_cli/harness.py +2587 -0
- algo_cli/identity.py +557 -0
- algo_cli/index_compute_lab.py +228 -0
- algo_cli/inference_harness.py +70 -0
- algo_cli/intelligence/__init__.py +1103 -0
- algo_cli/intelligence/acrobat_config.py +307 -0
- algo_cli/intelligence/acrobat_manifests.py +338 -0
- algo_cli/intelligence/acrobat_models.py +195 -0
- algo_cli/intelligence/acrobat_pipeline.py +295 -0
- algo_cli/intelligence/acrobat_runtime.py +302 -0
- algo_cli/intelligence/acrobat_security.py +261 -0
- algo_cli/intelligence/acrobat_workflows.py +226 -0
- algo_cli/intelligence/actionability.py +165 -0
- algo_cli/intelligence/adversarial_audit.py +136 -0
- algo_cli/intelligence/agent_arena.py +92 -0
- algo_cli/intelligence/agent_benchmark.py +236 -0
- algo_cli/intelligence/agent_runtime.py +171 -0
- algo_cli/intelligence/agents_as_tools.py +70 -0
- algo_cli/intelligence/artifact_binding.py +80 -0
- algo_cli/intelligence/autonomous_engineer.py +1976 -0
- algo_cli/intelligence/backpressure.py +99 -0
- algo_cli/intelligence/bloom_filter.py +186 -0
- algo_cli/intelligence/bonferroni.py +66 -0
- algo_cli/intelligence/boundary_compaction.py +98 -0
- algo_cli/intelligence/catalog_verifier.py +172 -0
- algo_cli/intelligence/cavecrew.py +118 -0
- algo_cli/intelligence/changelog.py +176 -0
- algo_cli/intelligence/checkpoint_resume.py +92 -0
- algo_cli/intelligence/circuit_breaker.py +88 -0
- algo_cli/intelligence/clarification_gate.py +101 -0
- algo_cli/intelligence/code_graph.py +180 -0
- algo_cli/intelligence/coderank.py +97 -0
- algo_cli/intelligence/consistent_hash.py +150 -0
- algo_cli/intelligence/consortium_synthesis.py +139 -0
- algo_cli/intelligence/construction/__init__.py +241 -0
- algo_cli/intelligence/construction/common.py +273 -0
- algo_cli/intelligence/construction/documents.py +496 -0
- algo_cli/intelligence/construction/labor_units.py +1395 -0
- algo_cli/intelligence/construction/payments.py +470 -0
- algo_cli/intelligence/construction/risk.py +784 -0
- algo_cli/intelligence/content_extractor.py +132 -0
- algo_cli/intelligence/context_adaptive.py +102 -0
- algo_cli/intelligence/context_ops.py +95 -0
- algo_cli/intelligence/count_min.py +145 -0
- algo_cli/intelligence/cow_state.py +103 -0
- algo_cli/intelligence/critic_loop.py +119 -0
- algo_cli/intelligence/cross_source.py +113 -0
- algo_cli/intelligence/daemon_mode.py +99 -0
- algo_cli/intelligence/dag_orchestration.py +151 -0
- algo_cli/intelligence/deep_research.py +155 -0
- algo_cli/intelligence/degenerate_detector.py +78 -0
- algo_cli/intelligence/delta_report.py +92 -0
- algo_cli/intelligence/discovery_event_log.py +92 -0
- algo_cli/intelligence/document_ingest.py +298 -0
- algo_cli/intelligence/dual_layer_validate.py +151 -0
- algo_cli/intelligence/echo_fidelity.py +73 -0
- algo_cli/intelligence/ema_tuning.py +104 -0
- algo_cli/intelligence/event_log.py +92 -0
- algo_cli/intelligence/evidence_graph.py +114 -0
- algo_cli/intelligence/extension_host.py +162 -0
- algo_cli/intelligence/extension_manifest.py +115 -0
- algo_cli/intelligence/falsification_suite.py +178 -0
- algo_cli/intelligence/finance/__init__.py +169 -0
- algo_cli/intelligence/finance/anomalies.py +135 -0
- algo_cli/intelligence/finance/ap_ar.py +351 -0
- algo_cli/intelligence/finance/cash.py +162 -0
- algo_cli/intelligence/finance/close.py +332 -0
- algo_cli/intelligence/finance/common.py +244 -0
- algo_cli/intelligence/finance/construction.py +135 -0
- algo_cli/intelligence/finance/controls.py +172 -0
- algo_cli/intelligence/finance/evidence.py +119 -0
- algo_cli/intelligence/finance/exceptions.py +157 -0
- algo_cli/intelligence/finance/reconciliations.py +254 -0
- algo_cli/intelligence/finance/revenue.py +109 -0
- algo_cli/intelligence/finance/tax.py +74 -0
- algo_cli/intelligence/finance/workpapers.py +111 -0
- algo_cli/intelligence/finding_record.py +120 -0
- algo_cli/intelligence/flow_dag.py +267 -0
- algo_cli/intelligence/gatherer.py +223 -0
- algo_cli/intelligence/golden_master.py +98 -0
- algo_cli/intelligence/graph_rag.py +195 -0
- algo_cli/intelligence/group_chat.py +143 -0
- algo_cli/intelligence/hash_dedup.py +145 -0
- algo_cli/intelligence/hyperloglog.py +128 -0
- algo_cli/intelligence/incremental_index.py +316 -0
- algo_cli/intelligence/index_store.py +16 -0
- algo_cli/intelligence/iteration_plan.py +133 -0
- algo_cli/intelligence/kernel_plugins.py +167 -0
- algo_cli/intelligence/lesson_catalog.py +135 -0
- algo_cli/intelligence/llm_fallback.py +169 -0
- algo_cli/intelligence/log2_histogram.py +267 -0
- algo_cli/intelligence/lsp_integration.py +147 -0
- algo_cli/intelligence/memory_evolution.py +117 -0
- algo_cli/intelligence/minhash_lsh.py +182 -0
- algo_cli/intelligence/multi_model_score.py +174 -0
- algo_cli/intelligence/multi_tier_grade.py +211 -0
- algo_cli/intelligence/negative_controls.py +113 -0
- algo_cli/intelligence/numeric_clamp.py +63 -0
- algo_cli/intelligence/occ_editor.py +66 -0
- algo_cli/intelligence/output_normalize.py +112 -0
- algo_cli/intelligence/parallel_delegation.py +98 -0
- algo_cli/intelligence/parallel_fanout.py +104 -0
- algo_cli/intelligence/permission_modes.py +105 -0
- algo_cli/intelligence/pre_push_gate.py +68 -0
- algo_cli/intelligence/prefetch.py +171 -0
- algo_cli/intelligence/process_framework.py +217 -0
- algo_cli/intelligence/project_graph.py +387 -0
- algo_cli/intelligence/query_expansion.py +146 -0
- algo_cli/intelligence/ralph_loop.py +117 -0
- algo_cli/intelligence/rate_limiter.py +153 -0
- algo_cli/intelligence/refactor_transaction.py +94 -0
- algo_cli/intelligence/research_workspace.py +108 -0
- algo_cli/intelligence/retraction_ledger.py +72 -0
- algo_cli/intelligence/saga_pattern.py +88 -0
- algo_cli/intelligence/session_fork.py +100 -0
- algo_cli/intelligence/shadow_editor.py +67 -0
- algo_cli/intelligence/shell_session.py +213 -0
- algo_cli/intelligence/source_registry.py +143 -0
- algo_cli/intelligence/spawn_scales.py +99 -0
- algo_cli/intelligence/stat_stability.py +104 -0
- algo_cli/intelligence/structural_validator.py +148 -0
- algo_cli/intelligence/subagent_spawner.py +111 -0
- algo_cli/intelligence/symmetric_verify.py +70 -0
- algo_cli/intelligence/task_classifier.py +129 -0
- algo_cli/intelligence/team_execution.py +122 -0
- algo_cli/intelligence/tiered_access.py +121 -0
- algo_cli/intelligence/utility_registry.py +159 -0
- algo_cli/intuition_engine.py +560 -0
- algo_cli/intuition_injector.py +82 -0
- algo_cli/kernels/__init__.py +5 -0
- algo_cli/kernels/manifest.py +763 -0
- algo_cli/main.py +3903 -0
- algo_cli/memory_candidates.py +541 -0
- algo_cli/memory_echo_veil.py +394 -0
- algo_cli/memory_runtime.py +112 -0
- algo_cli/model_info.py +548 -0
- algo_cli/model_profile.py +160 -0
- algo_cli/model_routing.py +74 -0
- algo_cli/oneshot.py +331 -0
- algo_cli/perf_telemetry.py +389 -0
- algo_cli/plugins.py +245 -0
- algo_cli/private_event_store.py +654 -0
- algo_cli/quantization/__init__.py +24 -0
- algo_cli/quantization/lloyd_max.py +98 -0
- algo_cli/quantization/turbo_quant.py +308 -0
- algo_cli/reasoning/__init__.py +46 -0
- algo_cli/reasoning/combinatorial.py +356 -0
- algo_cli/reasoning/graph_of_thought.py +297 -0
- algo_cli/reasoning/mcts.py +220 -0
- algo_cli/reasoning/neuro_symbolic.py +250 -0
- algo_cli/reasoning/react.py +246 -0
- algo_cli/reasoning/reflexion.py +225 -0
- algo_cli/reasoning/tree_of_thought.py +241 -0
- algo_cli/reasoning_bridge.py +150 -0
- algo_cli/reconciliation.py +284 -0
- algo_cli/reflex.py +385 -0
- algo_cli/resources/docs/ALGO.md +13958 -0
- algo_cli/resources/docs/algo-cli-algorithm-evidence-contract.md +60 -0
- algo_cli/resources/docs/algo-cli-execution-verification-contract.md +59 -0
- algo_cli/resources/docs/algo-cli-memory-lifecycle-contract.md +72 -0
- algo_cli/resources/docs/harness-extension-cleanup-recommendation.md +41 -0
- algo_cli/resources/docs/index-compute-lab-integration.md +32 -0
- algo_cli/resources/docs/inference-harness-loop-blueprint-2026-06.md +55 -0
- algo_cli/resources/docs/main-split-map.md +35 -0
- algo_cli/resources/docs/privacy-and-context.md +48 -0
- algo_cli/resources/docs/reflex-loop-v0.2.md +354 -0
- algo_cli/resources/skills/README.md +26 -0
- algo_cli/resources/skills/algo-cli.md +59 -0
- algo_cli/resources/skills/edit-file-precision.md +49 -0
- algo_cli/resources/skills/harness-search-first.md +47 -0
- algo_cli/resources/skills/memory-recall-ritual.md +51 -0
- algo_cli/resources/skills/qol-algorithms.md +224 -0
- algo_cli/resources/skills/smart-error-recovery.md +56 -0
- algo_cli/resources/skills/tool-selection-cheatsheet.md +65 -0
- algo_cli/retrieval_algorithms.py +127 -0
- algo_cli/runtime_qos.py +236 -0
- algo_cli/runtime_services.py +320 -0
- algo_cli/session_commands.py +95 -0
- algo_cli/session_mode.py +113 -0
- algo_cli/skills.py +430 -0
- algo_cli/slash_dispatch.py +1265 -0
- algo_cli/small_context.py +206 -0
- algo_cli/spawn_budget.py +89 -0
- algo_cli/task_ledger.py +84 -0
- algo_cli/task_router.py +197 -0
- algo_cli/tool_context.py +94 -0
- algo_cli/tool_contract.py +99 -0
- algo_cli/tool_policy.py +357 -0
- algo_cli/tool_runtime.py +647 -0
- algo_cli/tools.py +3056 -0
- algo_cli/url_scheme.py +174 -0
- algo_cli/verify.py +154 -0
- algo_cli/version_manifest.py +178 -0
- algo_cli/vision_screenshot_verify.py +76 -0
- algo_cli/workspace_resolver.py +68 -0
- algo_cli/x_account.py +209 -0
- algo_cli/xai_auth.py +374 -0
- algo_cli/xai_client.py +600 -0
- algo_cli_runtime-0.14.0.dist-info/METADATA +369 -0
- algo_cli_runtime-0.14.0.dist-info/RECORD +237 -0
- algo_cli_runtime-0.14.0.dist-info/WHEEL +4 -0
- algo_cli_runtime-0.14.0.dist-info/entry_points.txt +3 -0
- algo_cli_runtime-0.14.0.dist-info/licenses/LICENSE +21 -0
- ollama_cli/__init__.py +67 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Lloyd-Max optimal scalar quantizer codebook generation.
|
|
2
|
+
|
|
3
|
+
Precomputes quantization boundaries and reconstruction levels for coordinates
|
|
4
|
+
distributed on the unit hypersphere (Beta distribution), as required by
|
|
5
|
+
TurboQuant/PolarQuant for data-oblivious codebooks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Tuple
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
from scipy.stats import beta as beta_dist
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def beta_distribution_pdf(x: np.ndarray, d: int) -> np.ndarray:
|
|
17
|
+
"""Compute the PDF of coordinate distribution on the unit sphere in R^d.
|
|
18
|
+
|
|
19
|
+
Each coordinate of a random unit vector in R^d follows a scaled Beta distribution:
|
|
20
|
+
f(x) = (1/B(1/2, (d-1)/2)) * (1 - x^2)^((d-3)/2) / (2 * sqrt(pi))
|
|
21
|
+
|
|
22
|
+
For high dimensions, this concentrates around 0 (approaches Gaussian).
|
|
23
|
+
"""
|
|
24
|
+
half = (d - 1) / 2.0
|
|
25
|
+
return beta_dist.pdf(x, 0.5, half, loc=0, scale=1)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def precompute_codebook(
|
|
29
|
+
dim: int,
|
|
30
|
+
bits: int = 4,
|
|
31
|
+
*,
|
|
32
|
+
n_grid: int = 10_000,
|
|
33
|
+
max_iter: int = 50,
|
|
34
|
+
tol: float = 1e-8,
|
|
35
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
36
|
+
"""Compute Lloyd-Max optimal quantization codebook for sphere coordinates.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
dim: Dimensionality of the embedding space (determines the Beta shape).
|
|
40
|
+
bits: Number of bits per coordinate (2^bits levels).
|
|
41
|
+
n_grid: Grid points for numerical integration.
|
|
42
|
+
max_iter: Maximum Lloyd iterations.
|
|
43
|
+
tol: Convergence tolerance for boundary shifts.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
(boundaries, levels) where boundaries has 2^bits + 1 entries
|
|
47
|
+
and levels has 2^bits entries.
|
|
48
|
+
"""
|
|
49
|
+
k = 2 ** bits
|
|
50
|
+
half = (dim - 1) / 2.0
|
|
51
|
+
|
|
52
|
+
# PDF of coordinate on unit sphere
|
|
53
|
+
grid = np.linspace(-1, 1, n_grid)
|
|
54
|
+
dx = grid[1] - grid[0]
|
|
55
|
+
pdf = beta_dist.pdf(grid, 0.5, half, loc=0, scale=1)
|
|
56
|
+
pdf = np.nan_to_num(pdf, nan=0.0, posinf=0.0, neginf=0.0)
|
|
57
|
+
|
|
58
|
+
# Initialize boundaries uniformly by CDF
|
|
59
|
+
cdf = np.cumsum(pdf) * dx
|
|
60
|
+
cdf = np.clip(cdf / max(cdf[-1], 1e-12), 0, 1)
|
|
61
|
+
boundaries = np.interp(np.linspace(0, 1, k + 1), cdf, grid)
|
|
62
|
+
|
|
63
|
+
# Lloyd iterations: recompute levels as centroids, recompute boundaries as midpoints
|
|
64
|
+
for _ in range(max_iter):
|
|
65
|
+
levels = np.zeros(k)
|
|
66
|
+
for i in range(k):
|
|
67
|
+
mask = (grid >= boundaries[i]) & (grid < boundaries[i + 1])
|
|
68
|
+
weight = pdf[mask]
|
|
69
|
+
if weight.sum() > tol:
|
|
70
|
+
levels[i] = np.average(grid[mask], weights=weight)
|
|
71
|
+
else:
|
|
72
|
+
levels[i] = (boundaries[i] + boundaries[i + 1]) / 2
|
|
73
|
+
|
|
74
|
+
# New boundaries are midpoints between adjacent levels
|
|
75
|
+
new_boundaries = np.zeros(k + 1)
|
|
76
|
+
new_boundaries[0] = -1.0
|
|
77
|
+
new_boundaries[-1] = 1.0
|
|
78
|
+
for i in range(1, k):
|
|
79
|
+
new_boundaries[i] = (levels[i - 1] + levels[i]) / 2
|
|
80
|
+
|
|
81
|
+
shift = np.max(np.abs(new_boundaries - boundaries))
|
|
82
|
+
boundaries = new_boundaries
|
|
83
|
+
if shift < tol:
|
|
84
|
+
break
|
|
85
|
+
|
|
86
|
+
return boundaries, levels
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# Pre-built codebooks for common dimensions and bit widths
|
|
90
|
+
_CODEBOOK_CACHE: dict[tuple[int, int], tuple] = {}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def get_codebook(dim: int, bits: int = 4) -> Tuple[np.ndarray, np.ndarray]:
|
|
94
|
+
"""Get a cached codebook, computing on first access."""
|
|
95
|
+
key = (dim, bits)
|
|
96
|
+
if key not in _CODEBOOK_CACHE:
|
|
97
|
+
_CODEBOOK_CACHE[key] = precompute_codebook(dim, bits)
|
|
98
|
+
return _CODEBOOK_CACHE[key]
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""TurboQuant MSE + IP vector quantization for agent memory and RAG.
|
|
2
|
+
|
|
3
|
+
Implements:
|
|
4
|
+
- TurboQuantMSE: Random rotation + optimal scalar quantization (PolarQuant)
|
|
5
|
+
- TurboQuantIP: MSE stage + QJL 1-bit residual for unbiased inner-product estimation
|
|
6
|
+
|
|
7
|
+
Based on arXiv:2504.19874 (TurboQuant / PolarQuant).
|
|
8
|
+
Data-oblivious: no training or calibration data needed.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from .lloyd_max import get_codebook
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class TurboQuantMSE:
|
|
24
|
+
"""PolarQuant / TurboQuant-MSE: Rotation + coordinate-wise optimal scalar quantization.
|
|
25
|
+
|
|
26
|
+
Steps:
|
|
27
|
+
1. Apply a fixed random orthogonal rotation R to input vectors.
|
|
28
|
+
2. Quantize each coordinate independently using precomputed Lloyd-Max codebooks
|
|
29
|
+
for the Beta(d/2, 1/2) distribution on the unit sphere.
|
|
30
|
+
3. Dequantize by mapping to reconstruction levels and rotating back.
|
|
31
|
+
|
|
32
|
+
Theoretical MSE bound (unit vectors): D_mse <= (3*pi/2) * 4^(-b)
|
|
33
|
+
"""
|
|
34
|
+
dim: int = 768
|
|
35
|
+
bits: int = 4
|
|
36
|
+
seed: int = 42
|
|
37
|
+
|
|
38
|
+
_rotation: np.ndarray | None = field(default=None, init=False, repr=False)
|
|
39
|
+
_boundaries: np.ndarray | None = field(default=None, init=False, repr=False)
|
|
40
|
+
_levels: np.ndarray | None = field(default=None, init=False, repr=False)
|
|
41
|
+
|
|
42
|
+
def __post_init__(self) -> None:
|
|
43
|
+
self._rotation = self._make_rotation()
|
|
44
|
+
self._boundaries, self._levels = get_codebook(self.dim, self.bits)
|
|
45
|
+
|
|
46
|
+
def _make_rotation(self) -> np.ndarray:
|
|
47
|
+
"""Generate a random orthogonal matrix via QR decomposition."""
|
|
48
|
+
rng = np.random.default_rng(self.seed)
|
|
49
|
+
A = rng.standard_normal((self.dim, self.dim))
|
|
50
|
+
Q, _ = np.linalg.qr(A)
|
|
51
|
+
# Ensure proper rotation (det = +1)
|
|
52
|
+
if np.linalg.det(Q) < 0:
|
|
53
|
+
Q[:, 0] *= -1
|
|
54
|
+
return Q.astype(np.float32)
|
|
55
|
+
|
|
56
|
+
def quantize(self, x: np.ndarray) -> np.ndarray:
|
|
57
|
+
"""Quantize input vectors. x: (n, dim) or (dim,).
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
Integer codes: (n, dim) with values in [0, 2^bits - 1].
|
|
61
|
+
"""
|
|
62
|
+
if x.ndim == 1:
|
|
63
|
+
x = x.reshape(1, -1)
|
|
64
|
+
x = x.astype(np.float32)
|
|
65
|
+
# Step 1: Rotate
|
|
66
|
+
x_rot = x @ self._rotation.T
|
|
67
|
+
# Step 2: Normalize to [-1, 1] range for quantization
|
|
68
|
+
norms = np.linalg.norm(x_rot, axis=1, keepdims=True)
|
|
69
|
+
norms = np.maximum(norms, 1e-8)
|
|
70
|
+
x_normalized = x_rot / norms
|
|
71
|
+
# Step 3: Quantize each coordinate using codebook boundaries
|
|
72
|
+
codes = np.searchsorted(self._boundaries, x_normalized, side="right") - 1
|
|
73
|
+
codes = np.clip(codes, 0, 2**self.bits - 1)
|
|
74
|
+
return codes.squeeze(0) if x.shape[0] == 1 else codes
|
|
75
|
+
|
|
76
|
+
def dequantize(self, codes: np.ndarray, norms: np.ndarray | None = None) -> np.ndarray:
|
|
77
|
+
"""Dequantize codes back to approximate vectors.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
codes: Integer codes (n, dim) or (dim,).
|
|
81
|
+
norms: Optional original norms for rescaling. If None, unit norm assumed.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
Reconstructed vectors (n, dim).
|
|
85
|
+
"""
|
|
86
|
+
if codes.ndim == 1:
|
|
87
|
+
codes = codes.reshape(1, -1)
|
|
88
|
+
# Map codes to reconstruction levels
|
|
89
|
+
level_indices = np.clip(codes, 0, len(self._levels) - 1)
|
|
90
|
+
reconstructed = self._levels[level_indices]
|
|
91
|
+
# Rotate back
|
|
92
|
+
result = reconstructed @ self._rotation
|
|
93
|
+
# Rescale if norms provided
|
|
94
|
+
if norms is not None:
|
|
95
|
+
if norms.ndim == 0:
|
|
96
|
+
norms = norms.reshape(1)
|
|
97
|
+
result = result * norms[:, np.newaxis]
|
|
98
|
+
return result.squeeze(0) if codes.shape[0] == 1 else result
|
|
99
|
+
|
|
100
|
+
def compress(self, x: np.ndarray) -> dict[str, Any]:
|
|
101
|
+
"""Full compress pipeline: quantize + pack metadata.
|
|
102
|
+
|
|
103
|
+
Returns a dict with codes, norms, and config for later decompression.
|
|
104
|
+
"""
|
|
105
|
+
if x.ndim == 1:
|
|
106
|
+
x = x.reshape(1, -1)
|
|
107
|
+
norms = np.linalg.norm(x, axis=1)
|
|
108
|
+
codes = self.quantize(x)
|
|
109
|
+
return {
|
|
110
|
+
"codes": codes,
|
|
111
|
+
"norms": norms,
|
|
112
|
+
"dim": self.dim,
|
|
113
|
+
"bits": self.bits,
|
|
114
|
+
"seed": self.seed,
|
|
115
|
+
"n": x.shape[0],
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
def decompress(self, payload: dict[str, Any]) -> np.ndarray:
|
|
119
|
+
"""Decompress a payload back to approximate vectors."""
|
|
120
|
+
return self.dequantize(payload["codes"], norms=payload["norms"])
|
|
121
|
+
|
|
122
|
+
def mse(self, x: np.ndarray) -> float:
|
|
123
|
+
"""Measure MSE distortion between original and reconstructed vectors."""
|
|
124
|
+
if x.ndim == 1:
|
|
125
|
+
x = x.reshape(1, -1)
|
|
126
|
+
norms = np.linalg.norm(x, axis=1)
|
|
127
|
+
codes = self.quantize(x)
|
|
128
|
+
recon = self.dequantize(codes, norms=norms)
|
|
129
|
+
return float(np.mean((x - recon) ** 2))
|
|
130
|
+
|
|
131
|
+
def compression_ratio(self, n: int = 1) -> float:
|
|
132
|
+
"""Ratio of original bytes to compressed bytes per vector."""
|
|
133
|
+
original_bytes = n * self.dim * 4 # float32
|
|
134
|
+
compressed_bytes = n * self.dim * self.bits / 8 # packed bits
|
|
135
|
+
return original_bytes / max(compressed_bytes, 1)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass
|
|
139
|
+
class TurboQuantIP(TurboQuantMSE):
|
|
140
|
+
"""TurboQuant-IP: MSE quantization + QJL 1-bit residual for inner-product.
|
|
141
|
+
|
|
142
|
+
Two-stage:
|
|
143
|
+
1. PolarQuant/MSE stage with (bits-1) bits per coordinate.
|
|
144
|
+
2. QJL 1-bit sketch of the residual for unbiased IP estimation.
|
|
145
|
+
|
|
146
|
+
The inner-product estimator is unbiased:
|
|
147
|
+
E[<y, Q_ip^{-1}(Q_ip(x))>] = <y, x>
|
|
148
|
+
|
|
149
|
+
Key property: D_prod <= O(||y||^2 * ||x||^2 / 4^bits)
|
|
150
|
+
"""
|
|
151
|
+
qjl_dim: int = 0 # 0 = same as dim; override for reduced sketch size
|
|
152
|
+
|
|
153
|
+
_S: np.ndarray | None = field(default=None, init=False, repr=False)
|
|
154
|
+
|
|
155
|
+
def __post_init__(self) -> None:
|
|
156
|
+
super().__post_init__()
|
|
157
|
+
qjl_dim = self.qjl_dim or self.dim
|
|
158
|
+
rng = np.random.default_rng(self.seed + 1000)
|
|
159
|
+
self._S = np.sign(rng.standard_normal((qjl_dim, self.dim))).astype(np.float32)
|
|
160
|
+
|
|
161
|
+
def quantize_ip(self, x: np.ndarray) -> dict[str, Any]:
|
|
162
|
+
"""Quantize with IP-preservation: MSE stage (b-1 bits) + QJL residual (1 bit).
|
|
163
|
+
|
|
164
|
+
Returns payload with codes, qjl_signs, norms, and config.
|
|
165
|
+
"""
|
|
166
|
+
if x.ndim == 1:
|
|
167
|
+
x = x.reshape(1, -1)
|
|
168
|
+
norms = np.linalg.norm(x, axis=1)
|
|
169
|
+
|
|
170
|
+
# Stage 1: MSE quantization (uses self.bits as configured)
|
|
171
|
+
codes = self.quantize(x)
|
|
172
|
+
recon_mse = self.dequantize(codes, norms=norms)
|
|
173
|
+
|
|
174
|
+
# Stage 2: Compute residual and QJL 1-bit sketch
|
|
175
|
+
residual = x - recon_mse
|
|
176
|
+
qjl_dim = self.qjl_dim or self.dim
|
|
177
|
+
signs = np.sign(self._S @ residual.T).astype(np.int8) # (qjl_dim, n)
|
|
178
|
+
signs = signs.T # (n, qjl_dim)
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
"codes": codes,
|
|
182
|
+
"qjl_signs": signs,
|
|
183
|
+
"norms": norms,
|
|
184
|
+
"dim": self.dim,
|
|
185
|
+
"bits": self.bits,
|
|
186
|
+
"seed": self.seed,
|
|
187
|
+
"qjl_dim": qjl_dim,
|
|
188
|
+
"n": x.shape[0],
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
def dequantize_ip(self, payload: dict[str, Any]) -> np.ndarray:
|
|
192
|
+
"""Dequantize IP payload: MSE reconstruction + QJL residual correction.
|
|
193
|
+
|
|
194
|
+
The QJL dequantization provides an unbiased inner-product estimator:
|
|
195
|
+
Q_jl^{-1}(z) = sqrt(pi/2) / dim * S^T * z
|
|
196
|
+
"""
|
|
197
|
+
codes = payload["codes"]
|
|
198
|
+
norms = payload["norms"]
|
|
199
|
+
qjl_signs = payload["qjl_signs"]
|
|
200
|
+
|
|
201
|
+
# MSE stage reconstruction
|
|
202
|
+
recon_mse = self.dequantize(codes, norms=norms)
|
|
203
|
+
|
|
204
|
+
# QJL residual correction
|
|
205
|
+
qjl_dim = payload.get("qjl_dim", self.dim)
|
|
206
|
+
# Dequantize QJL signs to get unbiased residual estimate
|
|
207
|
+
# E[sign(S*r)] = 0, E[S^T * sign(S*r)] = sqrt(2/pi) * r
|
|
208
|
+
# So: r_hat = sqrt(pi/2) / dim * S^T * signs
|
|
209
|
+
scale = math.sqrt(math.pi / 2) / self.dim
|
|
210
|
+
if qjl_signs.ndim == 1:
|
|
211
|
+
qjl_signs = qjl_signs.reshape(1, -1)
|
|
212
|
+
residual_hat = scale * (qjl_signs.astype(np.float32) @ self._S[:qjl_dim, :].T)
|
|
213
|
+
|
|
214
|
+
return recon_mse + residual_hat
|
|
215
|
+
|
|
216
|
+
def inner_product_error(self, x: np.ndarray, y: np.ndarray) -> float:
|
|
217
|
+
"""Measure inner-product estimation error between quantized and true IP."""
|
|
218
|
+
payload = self.quantize_ip(x)
|
|
219
|
+
recon = self.dequantize_ip(payload)
|
|
220
|
+
true_ip = float(y @ x.T)
|
|
221
|
+
est_ip = float(y @ recon.T)
|
|
222
|
+
return abs(true_ip - est_ip)
|
|
223
|
+
|
|
224
|
+
# ---------------------------------------------------------------------------
|
|
225
|
+
# TurboVec Integration (production-ready drop-in for RAG / agent memory)
|
|
226
|
+
# ---------------------------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
_TURBOVEC_AVAILABLE = False
|
|
229
|
+
try:
|
|
230
|
+
from turbovec import TurboQuantIndex as _TurboQuantIndex # type: ignore[import-untyped]
|
|
231
|
+
_TURBOVEC_AVAILABLE = True
|
|
232
|
+
except ImportError:
|
|
233
|
+
_TurboQuantIndex = None
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def create_vector_index(
|
|
237
|
+
dim: int = 768,
|
|
238
|
+
bits: int = 4,
|
|
239
|
+
*,
|
|
240
|
+
use_turbovec: bool = True,
|
|
241
|
+
) -> "TurboQuantMSE | object":
|
|
242
|
+
"""Create a vector quantization index for agent memory / RAG.
|
|
243
|
+
|
|
244
|
+
Uses TurboVec (Rust-accelerated) when available, falls back to
|
|
245
|
+
our pure-Python TurboQuant implementation otherwise.
|
|
246
|
+
|
|
247
|
+
Args:
|
|
248
|
+
dim: Embedding dimensionality.
|
|
249
|
+
bits: Bits per coordinate (3 or 4 recommended for quality/compression balance).
|
|
250
|
+
use_turbovec: Prefer TurboVec library when installed.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
A TurboQuantIndex (TurboVec) or TurboQuantMSE (pure Python).
|
|
254
|
+
"""
|
|
255
|
+
if use_turbovec and _TURBOVEC_AVAILABLE and _TurboQuantIndex is not None:
|
|
256
|
+
return _TurboQuantIndex(dim=dim, bit_width=bits)
|
|
257
|
+
return TurboQuantMSE(dim=dim, bits=bits)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def compress_embeddings(
|
|
261
|
+
vectors: "np.ndarray",
|
|
262
|
+
dim: int | None = None,
|
|
263
|
+
bits: int = 4,
|
|
264
|
+
*,
|
|
265
|
+
method: str = "mse",
|
|
266
|
+
) -> dict:
|
|
267
|
+
"""Compress an embedding matrix for agent memory storage.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
vectors: Float32 array of shape (n, dim).
|
|
271
|
+
dim: Override dimensionality (defaults to vectors.shape[1]).
|
|
272
|
+
bits: Bits per coordinate.
|
|
273
|
+
method: "mse" for TurboQuant-MSE, "ip" for TurboQuant-IP (inner-product).
|
|
274
|
+
|
|
275
|
+
Returns:
|
|
276
|
+
Compressed payload dict with codes, norms, and config.
|
|
277
|
+
"""
|
|
278
|
+
if dim is None:
|
|
279
|
+
dim = vectors.shape[1]
|
|
280
|
+
|
|
281
|
+
if method == "ip":
|
|
282
|
+
tq = TurboQuantIP(dim=dim, bits=bits)
|
|
283
|
+
return tq.quantize_ip(vectors)
|
|
284
|
+
else:
|
|
285
|
+
tq = TurboQuantMSE(dim=dim, bits=bits)
|
|
286
|
+
return tq.compress(vectors)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def decompress_embeddings(payload: dict, method: str = "mse") -> "np.ndarray":
|
|
290
|
+
"""Decompress a previously compressed embedding payload.
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
payload: Compressed payload from compress_embeddings.
|
|
294
|
+
method: Must match the method used for compression ("mse" or "ip").
|
|
295
|
+
|
|
296
|
+
Returns:
|
|
297
|
+
Reconstructed float32 array of shape (n, dim).
|
|
298
|
+
"""
|
|
299
|
+
if method == "ip":
|
|
300
|
+
dim = payload.get("dim", 768)
|
|
301
|
+
bits = payload.get("bits", 4)
|
|
302
|
+
tq = TurboQuantIP(dim=dim, bits=bits)
|
|
303
|
+
return tq.dequantize_ip(payload)
|
|
304
|
+
else:
|
|
305
|
+
dim = payload.get("dim", 768)
|
|
306
|
+
bits = payload.get("bits", 4)
|
|
307
|
+
tq = TurboQuantMSE(dim=dim, bits=bits)
|
|
308
|
+
return tq.decompress(payload)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Advanced reasoning algorithms for Algo CLI agent harness.
|
|
2
|
+
|
|
3
|
+
Integrates classical and quantum-inspired reasoning methods:
|
|
4
|
+
- ReAct+: Enhanced reasoning-action loops with structured observation parsing
|
|
5
|
+
- Reflexion+: Verbal self-critique with episodic memory and retry
|
|
6
|
+
- Tree-of-Thoughts (ToT): BFS/DFS/MCTS evaluation with backtracking
|
|
7
|
+
- Graph-of-Thoughts (GoT): DAG reasoning with merge/feedback/distill
|
|
8
|
+
- QCR-LLM: Quantum-inspired combinatorial reasoning (HUBO/SA)
|
|
9
|
+
- Neuro-Symbolic: LLM propose + symbolic solver verification
|
|
10
|
+
|
|
11
|
+
All algorithms are local-first and work with Ollama models.
|
|
12
|
+
Quantum-inspired methods use classical simulated annealing by default
|
|
13
|
+
with optional QPU offload via cloud providers.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from .react import ReactLoop, ReactStep, run_react_loop
|
|
17
|
+
from .reflexion import ReflexionLoop, ReflexionEpisode, run_reflexion_loop
|
|
18
|
+
from .tree_of_thought import TreeOfThought, ThoughtNode, run_tot
|
|
19
|
+
from .graph_of_thought import GraphOfThought, ThoughtVertex, run_got
|
|
20
|
+
from .combinatorial import QCRAggregator, HuboProblem, run_qcr_aggregation
|
|
21
|
+
from .neuro_symbolic import NeuroSymbolicVerifier, VerificationResult, run_neuro_symbolic
|
|
22
|
+
from .mcts import MCTSReasoner, MCTSNode, run_mcts
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"ReactLoop",
|
|
26
|
+
"ReactStep",
|
|
27
|
+
"run_react_loop",
|
|
28
|
+
"ReflexionLoop",
|
|
29
|
+
"ReflexionEpisode",
|
|
30
|
+
"run_reflexion_loop",
|
|
31
|
+
"TreeOfThought",
|
|
32
|
+
"ThoughtNode",
|
|
33
|
+
"run_tot",
|
|
34
|
+
"GraphOfThought",
|
|
35
|
+
"ThoughtVertex",
|
|
36
|
+
"run_got",
|
|
37
|
+
"QCRAggregator",
|
|
38
|
+
"HuboProblem",
|
|
39
|
+
"run_qcr_aggregation",
|
|
40
|
+
"NeuroSymbolicVerifier",
|
|
41
|
+
"VerificationResult",
|
|
42
|
+
"run_neuro_symbolic",
|
|
43
|
+
"MCTSReasoner",
|
|
44
|
+
"MCTSNode",
|
|
45
|
+
"run_mcts",
|
|
46
|
+
]
|