"""Gradio composition and bounded callbacks.""" import base64 from pathlib import Path import gradio as gr from .data_loader import load_catalog from .provenance import source_url from .research_catalog import COMPONENTS, RESEARCH, RESOURCES, SOURCES, memory_scenario, ref from .visualizations import architecture, capacity_chart, copy_chart, copy_population, empty_figure, evidence_table ROOT = Path(__file__).resolve().parents[1] CSS = (ROOT / "assets/style.css").read_text() METRICS = {"Median timing · measured (ms)": "time_ms", "Bandwidth · derived (GB/s)": "bandwidth_gb_s"} TIMERS = {"CUDA events · device": "events", "Host monotonic · end-to-end": "host"} DIRECTIONS = {"Host to device": "h2d", "Device to host": "d2h"} def architecture_detail(selected): if selected not in COMPONENTS: raise gr.Error("Select a documented component.") description, path = COMPONENTS[selected] return architecture(selected), f"### {selected}\n{description}\n\n{ref('cachalot', path, 'Pinned architecture source')}" def scenario(cache, record): try: slots, percent = memory_scenario(cache, record, 15360) except ValueError as error: raise gr.Error(str(error)) from None return capacity_chart(slots, 15360), f"**{slots:,} slots · {percent:.2f}% capacity coverage.** Derived arithmetic inside a hypothetical scenario. Capacity coverage is not cache hit rate." def build_app(): catalog = load_catalog() dataset = catalog.datasets.get("cuda-s1-baseline") mark = base64.b64encode((ROOT / "assets/cachalot-mark.svg").read_bytes()).decode() with gr.Blocks(title="Cachalot Research Observatory", analytics_enabled=False) as demo: gr.HTML(f'''
Cachalot mark
Forera AI / Research systems

Cachalot Research Observatory

Investigating how large mixture-of-experts models move through small memory systems. Architecture, published experiments, and the evidence behind them.

READ-ONLY RESEARCH COMPANIONCPU-ONLY SPACESOURCE SNAPSHOT · 31 OCT 2026
''') with gr.Tabs(): with gr.Tab("Overview", id="overview"): gr.Markdown("## The bytes are the challenge\nMoE routing activates a small part of a much larger model. Keeping selected experts available becomes a problem of memory capacity, locality, data movement and scheduling.") gr.HTML('''
01 / Execution

Cachalot

Alpha inference engine for Apple Silicon. MLX and Metal execute the resident model while a bounded expert cache streams missing experts from SSD.

02 / Observation

Cachalot Lab

Native macOS environment for runtime health, scoped telemetry, local inference workflows and experimentation. Advanced research surfaces follow evidence contracts.

03 / Public evidence

This observatory

Forera AI’s public, read-only research companion. Reviewed source snapshots and published measurements remain usable without a local runtime or GPU.

''') gr.Markdown(f"""### Working capabilities and research objectives The documented Apple Silicon runtime includes DeepSeek V4.1 Flash, GLM-5.3-Flash and MiniMax-M3 paths. Capabilities and quality limits differ by model; source documentation is authoritative. CUDA work is a separate experimental lane. Lab currently supplies native health, cache/read evidence, saved inference workflows, optional energy evidence and sampled DeepSeek decode aggregates. Durable run comparisons, full event timelines, sweeps and validated counterfactuals remain roadmap work. {ref('cachalot','README.md','Runtime capabilities')} · {ref('cachalot-lab','README.md','Lab capabilities')} · {ref('cachalot-lab','docs/PLAN.md','Lab roadmap')} ### Inspected versions **Cachalot {catalog.manifest.get('sources', {}).get('cachalot', {}).get('version', 'unavailable')}** at `{SOURCES['cachalot'][:12]}` · **Lab {catalog.manifest.get('sources', {}).get('cachalot-lab', {}).get('version', 'unavailable')}** at `{SOURCES['cachalot-lab'][:12]}`. These are version-file readings at the inspected commits, not live latest-release claims. {ref('cachalot','pyproject.toml','Runtime version file')} · {ref('cachalot-lab','package.json','Lab version file')} """) gr.HTML('
Measured: instrument observations. Derived: arithmetic with stated inputs. Illustrative: architecture relationships. Hypothetical: user-selected assumptions. Missing evidence stays unavailable.
') with gr.Tab("Architecture", id="architecture"): gr.Markdown("## Follow the data path\n**Illustrative architecture · DeepSeek path.** Lines show logical relationships, not measured bandwidth, execution order or latency contribution. Use the selector for component responsibilities; hover for labels.") select = gr.Dropdown(list(COMPONENTS), value="Expert cache", label="Inspect component", allow_custom_value=False) plot = gr.Plot(architecture(), label="Documented architecture") detail = gr.Markdown(architecture_detail("Expert cache")[1]) select.change(architecture_detail, select, [plot, detail], api_name=False) gr.Markdown(f"""**Unified memory matters.** The documented Mac loader can read SSD data into GPU-visible slots directly. A discrete NVIDIA GPU adds host/device transfer boundaries. Do not interpret this picture as a CUDA implementation. {ref('cachalot','README.md','Runtime architecture')} · {ref('cachalot','docs/SEAMS.md','Policy and execution seams')} · {ref('cachalot-lab','docs/ARCHITECTURE.md','Native Lab architecture')}""") with gr.Tab("Benchmarks", id="benchmarks"): gr.Markdown("## Published evidence, bounded comparisons\n**Selected historical baseline · S1, 18 October 2026.** Transfer and kernel microbenchmarks on one RTX 5090 VM. No model, no inference, no tokens/s. The chart compares copy sizes within this run only.") for error in catalog.errors: gr.Markdown(f"**Evidence unavailable:** {error}") if dataset: run, machine = dataset["run"], dataset["machine"] gr.Markdown(f"""**Hardware:** {machine['gpu']['framework_view']['name']}, PCIe Gen 5 ×16, KVM, 23.46 GiB host RAM. **Software:** Python {machine['host']['python']}, PyTorch {machine['software']['torch']['version']}, driver {machine['software']['driver']['driver_version']}. **Collection:** `{run['created_utc']}` · instrument `{run['instrument']['version']}` · execution source `{run['code']['git']['sha']}`. **Model / quantization:** not applicable; fp16/uint8 stand-ins. **Runtime version:** experiment record reports 0.66.15; this is not an inference runtime benchmark. """) gr.HTML('
Historical correction: later trials found pinned-buffer backing and allocation patterns can change copy rates. S1 values remain as recorded; they are not a universal link limit. Device timing and host elapsed timing remain separate populations.
') with gr.Row(): metric = gr.Dropdown(list(METRICS), value=next(iter(METRICS)), label="Measurement type") timer = gr.Dropdown(list(TIMERS), value=next(iter(TIMERS)), label="Timing scope") direction = gr.Dropdown(list(DIRECTIONS), value=next(iter(DIRECTIONS)), label="Transfer direction") def explore(metric_choice, timer_choice, direction_choice): if metric_choice not in METRICS or timer_choice not in TIMERS or direction_choice not in DIRECTIONS: raise gr.Error("Select a supported comparison.") args = (METRICS[metric_choice], TIMERS[timer_choice], DIRECTIONS[direction_choice]) rows = copy_population(dataset, *args) missing = sum(row.get('value') is None for row in rows) return copy_chart(dataset, *args), evidence_table(rows), f"**{len(rows)} rows in this selection · {missing} unavailable.** Controls excluded. Unknown values are gaps; lines only guide the eye. No interpolation or cross-run pooling." initial = explore(next(iter(METRICS)), next(iter(TIMERS)), next(iter(DIRECTIONS))) chart = gr.Plot(initial[0], label="Copy-size comparison") summary = gr.Markdown(initial[2]) table = gr.Dataframe(initial[1], interactive=False, label="Selected source rows · exact units and uncertainty", max_height=340) for control in (metric, timer, direction): control.change(explore, [metric, timer, direction], [chart, table, summary], api_name=False) gr.Markdown("### Provenance and limits\n" + "\n".join(f"- {item}" for item in dataset['metadata']['limitations'])) gr.Markdown(f"{ref('cachalot','docs/CUDA-S1-RESULTS.md','S1 report and correction')} · {ref('cachalot','docs/CUDA-PIN-IDLE-RESULTS.md','Later host-idle findings')} · {ref('cachalot','benchmarks/cuda/suite.py','Result producer')}") with gr.Accordion("All source rows and integrity metadata", open=False): gr.Markdown("326 published rows: 110 measured timing summaries, 187 derived metrics, 29 unavailable timing cells. n=30 per reported timing; p50/p95 are sample quantiles. Bootstrap intervals concern the median, not a prediction interval. No raw per-iteration samples are included for this run.") gr.Dataframe(evidence_table(dataset['rows']), interactive=False, label="Complete imported baseline", max_height=360) gr.JSON({"run": run, "machine": machine, "catalog": dataset['metadata']}, label="Public source manifests and SHA-256 checksums") else: gr.Plot(empty_figure()) gr.Markdown("### Awaiting reviewed publication\nRequired: immutable source commit, sanitized machine/run manifests, units, workload, timing scope, sample population and successful correctness gates. No values are synthesized.") gr.Markdown(f"### Model inference datasets\n**Unavailable in this curated release.** The runtime publishes narrative results and benchmark producers; this explorer imports only the inspected S1 contract. It does not turn narrative ranges, local traces, examples or test fixtures into new measurements. {ref('cachalot','benchmarks/decode_throughput.py','Native decode producer')} · {ref('cachalot','README.md','Runtime reports')}") with gr.Tab("Memory & streaming", id="memory"): gr.Markdown(f"""## Capacity is not locality **Architectural explanation.** The resident trunk, attention/KV state and expert working set share a finite memory budget. A missing expert must be read; useful prefetch can overlap some work, while unused prefetch can add traffic. Cache capacity alone does not predict reuse, cache misses or token latency. {ref('cachalot','README.md','Architecture and memory design')} ### Hypothetical slot calculator **Not a trace, benchmark or performance prediction.** Start with an editable 48 GiB cache and a rounded 9.49 MiB expert record, following a documented DeepSeek research configuration. Assume 15,360 equal-size experts; ignore slot metadata, alignment, allocator overhead, KV growth, pressure and cache admission. The real effective capacity can differ. {ref('cachalot','docs/CUDA-RESEARCH-PLAN.md','Sizing reference')} """) with gr.Row(): cache = gr.Slider(0, 256, value=48, step=1, label="Hypothetical expert budget (GiB)") record = gr.Slider(1, 128, value=9.49, step=.01, label="Assumed uniform expert record (MiB)") capacity, capacity_note = scenario(48, 9.49) capacity_plot = gr.Plot(capacity, label="Hypothetical capacity") capacity_text = gr.Markdown(capacity_note) for control in (cache, record): control.release(scenario, [cache, record], [capacity_plot, capacity_text], api_name=False) gr.Markdown(f"""**Calculation:** slots = min(total experts, floor(cache GiB × 1024 / record MiB)); capacity coverage = slots / total experts. GiB and MiB are binary; benchmark GB/s is decimal. ### What the available telemetry can establish Runtime read counters concern expert-store activity. Whole-drive and whole-Mac activity include other work. Summed read durations can overlap and exceed wall time. Sampled DeepSeek token means preserve sampling and dropped-event limits; they do not supply a complete per-request dependency timeline. **Live memory pressure, expert reuse traces, cache misses and prefetch outcomes:** unavailable here. No connection to private or local telemetry is attempted. {ref('cachalot-lab','runtime-contract/telemetry.yaml','Supported telemetry semantics')} · {ref('cachalot-lab','runtime-contract/observability-proposal.md','Proposed event contract')} """) with gr.Tab("CUDA research", id="cuda"): gr.Markdown("## A different memory hierarchy\nDiscrete GPUs introduce VRAM capacity, host staging and host-to-device transfers. The research asks which routing/locality observations transfer across platforms and which costs depend on the hardware, driver and schedule.") for item in RESEARCH: gr.Markdown(f"### {item['track']} · {item['status']}\n{item['scope']}\n\n{item['source']}") gr.Markdown(f"""### Open engineering questions - How do expert residency and workload locality change transfer demand? - When does useful prefetch hide transfer time, and when does scheduling interfere with compute? - How do host-buffer state, allocation order and host activity affect staging cost? - What controlled workloads and correctness gates permit a cross-platform comparison? Published trials also cover V100 and L40S regimes; this curated explorer does not pool those measurements with S1. The original plan/scaffold introductions predate the later measurements. Dated result reports take precedence for what ran; neither establishes a shipped CUDA inference backend. {ref('cachalot','docs/CUDA-RESEARCH-PLAN.md','Research programme and gates')} · {ref('cachalot','docs/CUDA-PIN-PATTERN-AUDIT.md','Interpretation audit')} CloudRift supports the NVIDIA CUDA research track through sponsored GPU-compute access. [CloudRift](https://www.cloudrift.ai/). Support does not imply endorsement of experimental conclusions. """) with gr.Tab("Reproducibility", id="reproducibility"): gr.Markdown("## Reconstruct the claim\nThis observatory loads only bundled, reviewed evidence. It makes no upstream request at startup; GitHub or Hub outages do not replace evidence with generated data.") for repo, sha in SOURCES.items(): gr.Markdown(f"**{repo}** · default branch `main` · [`{sha}`](https://github.com/forera-ai/{repo}/commit/{sha}) · inspected 2026-10-31.") gr.Markdown(f"""### S1 methodology The published run uses five warm-ups and 30 timed iterations per cell. Device timing uses CUDA events; host scope uses a monotonic timer. Copies require round-trip equality and matmul requires a float32 CPU reference. Failed correctness gates suppress timing. Timer overhead greater than 10% of the cell median produces an unavailable value. All imported run gates passed; this Space validates those recorded gates, not the physical experiment again. The original execution source is `af4ed4b` (REVISION file; runtime 0.66.15 according to the registered record). The publication snapshot is a different, full commit pinned above. Instrument identity is `N1-scaffold-1`; the source manifests preserve run ID, sample counts, seed, caps, hardware and software. The expert-like projection shape is derived, uses fp16 weights, and is not the quantized inference kernel. **Model identifiers:** none applies to S1. The runtime overview's primary documented checkpoint is [deepseek-ai/DeepSeek-V4.1-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash); no checkpoint is downloaded by this app. Do not attach that model's throughput or quantization to the S1 stand-ins. **Reproduction hardware:** a separate Linux NVIDIA host with compatible CUDA PyTorch is required for original GPU experiments. The observatory itself needs Python 3.12 and CPU only. Provisioning or executing GPU trials is outside this application. {ref('cachalot','docs/CUDA-S1-EXPERIMENT-RECORD.md','Registered predictions and stop rules')} · {ref('cachalot','benchmarks/cuda/SESSION-RUNBOOK.md','Original runbook')} · {ref('cachalot','benchmarks/cuda/cuda_bench.py','CLI producer')} · {ref('cachalot','benchmarks/cuda/manifest.py','Source artifact contract')} ### Publication and compatibility rules Each dataset must name its source commit/files, collection context, hardware, workload, units, limitations and successful gates. SHA-256 and source manifest content IDs are checked before rendering. Unknown units, mixed runs, failed gates, non-finite values, changed hashes or unsafe paths withhold the dataset with an explicit message. Only ordinary copy cells from the same run, direction, metric and timer scope enter each chart. Pinned and pageable backing are explicit comparison variables; repeated control cells remain in the raw table. Missing values are never zero. Derived bandwidth is bytes divided by median time, not model throughput. No cross-run winner, causal inference, interpolation or critical-path reconstruction is offered. """) with gr.Tab("Resources", id="resources"): gr.Markdown("## Source, methods, collaboration\n" + "\n\n".join(f"[{name}]({url})" for name, url in RESOURCES.items())) gr.Markdown(f"### Documentation\n{ref('cachalot','docs/RESEARCH-DIRECTION.md','Research charter')} · {ref('cachalot-lab','docs/PRODUCT_DIRECTION.md','Lab product direction')} · {ref('cachalot-lab','docs/RUNTIME_SYNC.md','Source-reviewed runtime compatibility')}") gr.Markdown("### Attribution\nCachalot mark and imported evidence: Forera AI and contributors, from the pinned public repositories under MIT. Their copyright notice and license are retained in this Space. This is an independent public companion to the native application; it does not host the inference engine.") gr.HTML('') return demo