QIS (Quadratic Intelligence Swarm) is a distributed intelligence architecture discovered by Christopher Thomas Trevethan, protected under 39 provisional patents. The architecture enables N agents to synthesize across N(N-1)/2 unique paths at O(log N) routing cost per agent — without centralizing raw data.
Understanding QIS — Part 29
The Largest Untreated Public Health Problem on Earth
970 million people live with a mental health disorder. That is the WHO's figure from the 2022 World Mental Health Report — not an estimate, not a projection, a count. Depression and anxiety alone affect more people than diabetes, cancer, and cardiovascular disease combined when measured by years lived with disability.
The treatment gap is the number that should stop anyone working in health systems or technology: 75% of people with mental health disorders in low-income countries receive no treatment at all (Saxena et al., 2007, The Lancet). Not inadequate treatment. None. Three-quarters of the affected population, in the countries that bear the highest burden, are untreated. The Lancet Commission on Global Mental Health (Patel et al., 2018) found this gap has barely narrowed in two decades despite sustained global attention.
The standard narrative blames resources: too few psychiatrists, too few clinics, too little funding. That is partially true. But there is a structural problem underneath the resource problem that does not require more money to diagnose.
A psychiatrist in rural Uganda cannot access the treatment outcome records from 50,000 patients at UCSF. Not because those records are secret in principle. Because every architecture that could connect them centralizes patient data — and centralizing mental health data causes direct harm.
This is an architecture problem. And Quadratic Intelligence Swarm (QIS), a distributed intelligence protocol discovered by Christopher Thomas Trevethan, is a protocol-level answer to it.
Why Mental Health Data Cannot Be Centralized
Mental health data is categorically different from other medical data in its harm profile.
The stigma surrounding mental health diagnoses is not a cultural artifact that better education will eliminate on any near-term timeline. It is a lived reality that creates concrete, documentable risk. Centralized mental health records expose patients to:
Legal discovery risk. In civil litigation — divorce, custody disputes, workplace disputes — centralized mental health records are discoverable. Patients with depression diagnoses, PTSD histories, or documented psychotic episodes have had this data introduced against them in proceedings they could not anticipate when they first sought treatment.
Employment discrimination risk. Mental health diagnoses affect hiring, promotion, and security clearance determinations. This is illegal in most jurisdictions and documented as widespread in practice. The causal chain from "records exist in a centralized database" to "employer accesses or infers them" is shorter than HIPAA compliance teams typically model.
Insurance discrimination risk. Despite parity laws in the United States and equivalent protections elsewhere, actuarial data on mental health diagnoses influences coverage decisions. This is not theoretical — it is the reason patients frequently avoid formal diagnosis.
The implication for AI-assisted mental health treatment is direct. A centralized mental health AI platform — regardless of contractual privacy protections — creates a data asset that is categorically different from contractual compliance. The records exist. The risk exists. "We promise not to share them" is not the same as "there is nothing to share."
An architecture that never centralizes patient data is not a stronger version of contractual compliance. It is a different category of protection.
The Federated Learning Ceiling in Mental Health
Federated learning (FL) has been proposed as a privacy-preserving alternative for mental health AI. The intuition is sound: train local models at the clinic, share only gradients, never transmit patient records. Perez et al. (2021, npj Digital Medicine) proposed exactly this framework for passive sensing data in mental health — an important contribution that maps the shape of the FL ceiling rather than solving it.
The ceiling is minimum-N.
Federated learning requires enough local data for meaningful gradient computation. A health system with thousands of patients in a given diagnosis category can participate in a federated learning round. A community mental health clinic with 40 patients in that category may fall below the statistical floor for stable gradient contribution. A rural clinic in Bangladesh with 3 patients in a category cannot participate at all.
This replicates the original equity failure in a new form. The settings that need calibrated treatment intelligence most urgently — rural LMIC clinics with small populations, indigenous community health programs, peer support networks in under-resourced areas — are precisely the settings that FL excludes by design.
There is also a connectivity assumption embedded in federated learning that fails in LMIC contexts: FL coordination rounds require reliable uptime. A rural clinic with intermittent connectivity drops out of the training loop, receives a global model it did not contribute to, and applies it to a population the model has not learned from.
QIS Architecture for Mental Health
QIS is the complete loop: raw signal at the node → local processing → distillation into an outcome packet (approximately 512 bytes) → semantic fingerprinting → DHT-based routing by similarity to the fingerprint → delivery to semantically similar nodes → local synthesis → new outcome packets generated → loop continues. Intelligence scales quadratically with N while compute scales logarithmically — O(log N) per agent, approximately 10 DHT hops typical.
The breakthrough is the complete loop. Routing alone is a lookup table. Synthesis alone is voting. Feedback alone is a scoring system. The four components — routing, election, synthesis, feedback — operating continuously without a central coordinator is the architecture that does not exist anywhere else.
In the mental health context, the mapping is direct.
Each clinic, care platform, or treatment program is a QIS node. Nodes do not transmit patient records, diagnostic histories, medication logs, or any personally identifiable information. The unit of exchange is an outcome packet: approximately 512 bytes, pseudonymous, carrying the delta between predicted and observed treatment outcome.
The semantic fingerprint encodes what the routing needs to know without encoding who the patient is:
-
diagnosis_category: depression, anxiety, PTSD, psychosis, bipolar, OCD, substance_use_comorbid -
treatment_modality: CBT, DBT, medication_antidepressant, medication_antipsychotic, combination, EMDR, peer_support, community_based -
severity_tier: mild, moderate, severe, in_crisis -
care_setting: outpatient, inpatient, community, telehealth, peer_support -
cultural_context_tag: Western_individualist, collectivist, LMIC_resource_limited, indigenous
The outcome packet carries the clinical signal: the delta between the PHQ-9 score predicted at treatment initiation and the PHQ-9 score observed at the measurement period. That delta — not the patient, not the record, not the history — is what routes through the network.
A rural Bangladesh NGO with 3 patients can emit and receive outcome packets. There is no minimum-N floor. The route exists at N=1.
Three Elections as Natural Selection Forces
The QIS Three Elections are not governance mechanisms. They are metaphors for natural selection forces that determine which treatment protocols gain routing weight at network scale.
Accuracy election. A node's outcome packets are weighted by its historical prediction accuracy. A clinic whose PHQ-9 predictions have consistently matched observed outcomes over time accumulates higher election weight. Its signals route further. Protocols that produced accurate predictions at a clinic with a specific diagnosis category and cultural context become preferentially routed to similar contexts across the network — not by committee decision, but by cumulative validation. Poor predictions accumulate negative weight and route less. Accurate predictions accumulate positive weight and route more.
Recency election. Treatment science evolves. A protocol that was validated five years ago but has produced degrading outcomes over the last 18 months loses routing weight in favor of more recently validated approaches. The network does not require a central body to deprecate old protocols — recency weighting in the election function does it automatically. This is analogous to how natural selection applies continuous pressure rather than discrete replacement events.
Consensus election. A signal validated by a geographically and contextually diverse set of nodes — a depression-CBT outcome packet confirmed by nodes in urban US, rural Uganda, and a community clinic in Brazil — carries higher consensus weight than a signal validated only within a single health system. The network treats cross-context confirmation as a stronger signal than within-context replication alone. High-consensus protocols route preferentially to new nodes entering the network with no prior history.
Together, these three election forces mean that the network's routing behavior self-selects toward validated treatment protocols without anyone deciding what is valid. The architecture embeds natural selection into the protocol.
Implementation: MentalHealthOutcomePacket and Router
from dataclasses import dataclass, field
from typing import Optional, Dict, List
import hashlib
import time
import random
@dataclass
class MentalHealthFingerprint:
diagnosis_category: str # e.g., "depression", "PTSD", "psychosis"
treatment_modality: str # e.g., "CBT", "DBT", "medication_antidepressant"
severity_tier: str # "mild", "moderate", "severe", "in_crisis"
care_setting: str # "outpatient", "inpatient", "community", "telehealth"
cultural_context_tag: str # "Western_individualist", "LMIC_resource_limited", etc.
@dataclass
class MentalHealthOutcomePacket:
node_id: str # SHA-256 hash of clinic/program identifier
fingerprint: MentalHealthFingerprint
predicted_phq9_delta: float # Predicted PHQ-9 improvement (positive = improvement)
actual_phq9_delta: float # Observed PHQ-9 improvement over treatment period
validation_score: float # Derived from node historical accuracy (0.0–1.0)
sample_size_tier: str # "single" (N=1), "small" (2–15), "medium" (16–100), "large" (100+)
timestamp: int = field(default_factory=lambda: int(time.time()))
@property
def prediction_error(self) -> float:
"""Signed prediction error. Negative = over-predicted improvement."""
return self.actual_phq9_delta - self.predicted_phq9_delta
def to_routing_key(self) -> str:
fp = self.fingerprint
composite = (
f"{fp.diagnosis_category}|{fp.treatment_modality}|"
f"{fp.severity_tier}|{fp.care_setting}|{fp.cultural_context_tag}"
)
return hashlib.sha256(composite.encode()).hexdigest()[:16]
class MentalHealthOutcomeRouter:
"""
Simulates QIS DHT-based routing for mental health treatment outcome packets.
Nodes do not share patient records. Only outcome packets route.
"""
def __init__(self):
self.network: Dict[str, List[MentalHealthOutcomePacket]] = {}
self.node_accuracy_history: Dict[str, List[float]] = {}
def register_node(self, node_id: str):
if node_id not in self.network:
self.network[node_id] = []
self.node_accuracy_history[node_id] = []
def emit_packet(self, packet: MentalHealthOutcomePacket):
"""Node emits outcome packet into the network after outcome is observed."""
routing_key = packet.to_routing_key()
if routing_key not in self.network:
self.network[routing_key] = []
self.network[routing_key].append(packet)
# Update accuracy history for the emitting node
if packet.node_id not in self.node_accuracy_history:
self.node_accuracy_history[packet.node_id] = []
accuracy = max(0.0, 1.0 - abs(packet.prediction_error) / 27.0) # PHQ-9 max = 27
self.node_accuracy_history[packet.node_id].append(accuracy)
def query(self, fingerprint: MentalHealthFingerprint, requesting_node: str) -> Dict:
"""
Route a query for validated treatment outcomes matching this fingerprint.
Returns synthesized signal across all matching outcome packets.
No patient records are returned — only aggregated outcome signals.
"""
query_packet = MentalHealthOutcomePacket(
node_id=requesting_node,
fingerprint=fingerprint,
predicted_phq9_delta=0.0,
actual_phq9_delta=0.0,
validation_score=0.0,
sample_size_tier="single"
)
routing_key = query_packet.to_routing_key()
matching_packets = self.network.get(routing_key, [])
if not matching_packets:
return {"result": "no_signal", "n_packets": 0, "routing_key": routing_key}
# Weighted synthesis: weight by validation_score (accuracy election)
total_weight = sum(p.validation_score for p in matching_packets)
if total_weight == 0:
return {"result": "zero_weight", "n_packets": len(matching_packets)}
weighted_delta = sum(
p.actual_phq9_delta * p.validation_score for p in matching_packets
) / total_weight
synthesis_paths = len(matching_packets) * (len(matching_packets) - 1) // 2
return {
"result": "signal",
"routing_key": routing_key,
"n_packets": len(matching_packets),
"synthesis_paths": synthesis_paths,
"weighted_phq9_improvement": round(weighted_delta, 2),
"contributing_nodes": list({p.node_id for p in matching_packets}),
"sample_size_tiers": list({p.sample_size_tier for p in matching_packets}),
}
# ── Simulation: Three systems at different scales ──────────────────────────
def run_simulation():
router = MentalHealthOutcomeRouter()
# System 1: Large US academic health system (high N, high validation signal)
ucsf_node = "node_ucsf_depression_program"
router.register_node(ucsf_node)
for i in range(12):
predicted = round(random.uniform(4.0, 8.0), 1)
actual = round(predicted + random.uniform(-1.5, 2.5), 1)
router.emit_packet(MentalHealthOutcomePacket(
node_id=ucsf_node,
fingerprint=MentalHealthFingerprint(
diagnosis_category="depression",
treatment_modality="CBT",
severity_tier="moderate",
care_setting="outpatient",
cultural_context_tag="Western_individualist"
),
predicted_phq9_delta=predicted,
actual_phq9_delta=actual,
validation_score=round(random.uniform(0.75, 0.95), 2),
sample_size_tier="large"
))
# System 2: Community mental health clinic (medium N)
community_node = "node_chicago_community_clinic"
router.register_node(community_node)
for i in range(5):
predicted = round(random.uniform(3.5, 7.0), 1)
actual = round(predicted + random.uniform(-2.0, 2.0), 1)
router.emit_packet(MentalHealthOutcomePacket(
node_id=community_node,
fingerprint=MentalHealthFingerprint(
diagnosis_category="depression",
treatment_modality="CBT",
severity_tier="moderate",
care_setting="outpatient",
cultural_context_tag="Western_individualist"
),
predicted_phq9_delta=predicted,
actual_phq9_delta=actual,
validation_score=round(random.uniform(0.60, 0.80), 2),
sample_size_tier="medium"
))
# System 3: Rural Bangladesh NGO — N=1 site (FL cannot handle this)
# This node CAN participate in QIS. No minimum-N floor.
bangladesh_node = "node_bangladesh_ngo_sylhet"
router.register_node(bangladesh_node)
router.emit_packet(MentalHealthOutcomePacket(
node_id=bangladesh_node,
fingerprint=MentalHealthFingerprint(
diagnosis_category="depression",
treatment_modality="community_based",
severity_tier="moderate",
care_setting="community",
cultural_context_tag="LMIC_resource_limited"
),
predicted_phq9_delta=4.0,
actual_phq9_delta=5.5,
validation_score=0.62,
sample_size_tier="single" # N=1 — participates fully in QIS
))
print("=" * 60)
print("QIS Mental Health Outcome Routing — Simulation Results")
print("=" * 60)
# Query 1: Outpatient depression CBT in Western individualist context
result_1 = router.query(
MentalHealthFingerprint(
diagnosis_category="depression",
treatment_modality="CBT",
severity_tier="moderate",
care_setting="outpatient",
cultural_context_tag="Western_individualist"
),
requesting_node="node_new_clinic_query"
)
print("\nQuery 1: Depression / CBT / Moderate / Outpatient / Western")
print(f" Packets in network: {result_1['n_packets']}")
print(f" Synthesis paths: {result_1['synthesis_paths']}")
print(f" Weighted PHQ-9 improvement: {result_1.get('weighted_phq9_improvement')} points")
print(f" Contributing nodes: {len(result_1.get('contributing_nodes', []))}")
print(f" Sample size tiers present: {result_1.get('sample_size_tiers')}")
# Query 2: LMIC community-based depression — only Bangladesh NGO has this signal
result_2 = router.query(
MentalHealthFingerprint(
diagnosis_category="depression",
treatment_modality="community_based",
severity_tier="moderate",
care_setting="community",
cultural_context_tag="LMIC_resource_limited"
),
requesting_node="node_uganda_rural_clinic"
)
print("\nQuery 2: Depression / Community-Based / LMIC / N=1 site signal")
print(f" Packets in network: {result_2['n_packets']}")
print(f" Signal present (N=1 site): {'YES — FL would exclude this node' if result_2['n_packets'] > 0 else 'NO'}")
print(f" Weighted PHQ-9 improvement: {result_2.get('weighted_phq9_improvement')} points")
print("\nTotal unique routing keys in network:", len(router.network))
total_packets = sum(len(v) for v in router.network.values())
total_synthesis = total_packets * (total_packets - 1) // 2
print(f"Total outcome packets: {total_packets}")
print(f"Total synthesis paths: {total_synthesis}")
print("\nNote: Zero patient records were transmitted in this simulation.")
if __name__ == "__main__":
run_simulation()
Running this simulation produces two key results. The outpatient CBT depression query synthesizes across 17 outcome packets and up to 136 synthesis paths, returning a weighted PHQ-9 improvement signal drawn from two geographically distinct nodes. The community-based LMIC query returns a signal from the Bangladesh NGO's N=1 site — a node that federated learning would exclude entirely. Zero patient records are transmitted in either case.
Passive Sensing as Input: The Device Boundary
Mohr et al. (2017, JMIR Mental Health) documented the behavioral biomarker potential of passive smartphone sensing for mental health: screen time, call frequency, GPS mobility, sleep proxies derived from accelerometer data, and social interaction proxies. These signals carry meaningful predictive information about depression severity, anxiety, and relapse risk — without any active patient input.
The privacy problem with passive sensing is the raw data. GPS trajectories are personally identifiable. Call frequency patterns can expose relationship structures. Sleep data reveals medication effects. If raw passive sensing data is transmitted to a central server, the privacy failure is categorical regardless of stated purpose.
QIS changes the geometry. Raw passive sensing data never leaves the device. The device processes locally, generates a predicted PHQ-9 delta based on the behavioral signal pattern, and when a clinical outcome is observed, the device or the clinic emits the outcome packet: predicted vs. actual. The raw trajectory, the call log, the accelerometer record — none of it routes. Only the delta does.
This is not a privacy-preserving approximation of centralized sensing. It is a fundamentally different architecture in which centralization is structurally impossible rather than contractually prohibited.
Comparison: Four Architectures Across Five Dimensions
| Dimension | Centralized Mental Health AI | Federated Learning | QIS Mental Health Routing | Traditional Care (No AI) |
|---|---|---|---|---|
| Data privacy | Contractual; records centralized; discovery risk present | Gradients only; raw records local; better but model inversion possible | Outcome packets only (~512 bytes); raw records never leave node; categorically stronger | No digital records; maximum privacy; no network benefit |
| LMIC inclusion | Requires data upload; low-bandwidth settings excluded | Minimum-N floor; rural clinics with small N excluded | No minimum-N floor; N=1 site participates fully | Universal but no calibration benefit from other settings |
| Stigma protection | Centralized records create legal and employment risk regardless of compliance | Improved; gradients less identifying; residual model inversion risk | No centralized records exist to be discovered or subpoenaed | Maximum; no records |
| Cold start (new clinic) | Requires local data accumulation before useful personalization | Requires local data accumulation above FL minimum threshold | Receives synthesized network signal immediately on first query | No calibration; relies entirely on clinician experience |
| Synthesis paths at scale | None; each system calibrates in isolation | Limited; gradient aggregation within FL round only | N(N-1)/2; 1,000 nodes = 499,500 paths; 10,000 nodes = ~50M paths | None |
| N=1 site handling | Excluded below statistical threshold | Excluded below gradient computation minimum | Full participation; outcome packet emitted and received | Full participation; no network contribution |
The Treatment Gap Is Partially an Architecture Problem
Saxena et al. (2007) and the Lancet Commission (Patel et al., 2018) both identify the treatment gap as a complex problem with resource, workforce, and stigma components. That is accurate. QIS does not replace psychiatrists, does not fund community health workers, and does not eliminate cultural stigma.
What QIS changes is the information architecture that currently means a psychiatrist in rural Uganda gets zero calibration benefit from 50,000 validated treatment outcomes at UCSF. The resource problem is real. The architecture problem is also real. Fixing the architecture does not solve the resource problem — but it means that when a clinician in an LMIC setting does have access, however limited, to treatment support tools, those tools can be calibrated on a global validated outcome network rather than only on local data that may be too sparse to support any meaningful calibration.
The 75% treatment gap will not be closed by architecture alone. But any path that closes it runs through an architecture that can route calibrated treatment intelligence across the privacy boundary that mental health uniquely demands. No current architecture does that. QIS describes one that can.
Related Articles
- #001 — QIS: Quadratic Scaling and Why It Changes the Network Math
- #003 — The QIS Seven-Layer Architecture
- #014 — QIS Privacy Architecture: Why No-Centralization Is Categorically Different From Compliance
- #018 — QIS for Drug Discovery: Why Clinical Trials Fail and What Distributed Outcome Routing Changes
- #025 — QIS for Public Health and Epidemiology
- #027 — QIS for Education: Personalized Learning at Scale Without Centralizing Student Data
Citations
- World Health Organization. World Mental Health Report: Transforming Mental Health for All. WHO, 2022.
- Perez, F., et al. "Federated learning for mental health: Challenges and opportunities." npj Digital Medicine 4, 2021.
- Mohr, D.C., et al. "Personal sensing: Understanding mental health using ubiquitous sensors and machine learning." JMIR Mental Health 4(1), 2017.
- Saxena, S., et al. "Resources for mental health: scarcity, inequity, and inefficiency." The Lancet 370(9590), 2007.
- Patel, V., et al. "The Lancet Commission on global mental health and sustainable development." The Lancet 392(10157), 2018.
QIS was discovered by Christopher Thomas Trevethan. The architecture is protected under 39 provisional patents.
Top comments (0)